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/Attrs.inc"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
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 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
533 E = ImpCastExprToType(E, Context.getPointerType(Ty),
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
548 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
658 if (T->canDecayToPointerType())
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
666 !T->isMemberPointerType()))
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
718 Context.getTargetInfo().getCXXABI().isMicrosoft())
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
729 Cleanup.setExprNeedsCleanups(true);
730
732 Cleanup.setExprNeedsCleanups(true);
733
735 return ExprError();
736
737 // C++ [conv.lval]p3:
738 // If T is cv std::nullptr_t, the result is a null pointer constant.
739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
742
743 // C11 6.3.2.1p2:
744 // ... if the lvalue has atomic type, the value has the non-atomic version
745 // of the type of the lvalue ...
746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747 T = Atomic->getValueType().getUnqualifiedType();
748 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
749 nullptr, VK_PRValue, FPOptionsOverride());
750 }
751
752 return Res;
753}
754
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
763}
764
766 QualType Ty = E->getType();
767 ExprResult Res = E;
768 // Only do implicit cast for a function type, but not for a pointer
769 // to function type.
770 if (Ty->isFunctionType()) {
771 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
772 CK_FunctionToPointerDecay);
773 if (Res.isInvalid())
774 return ExprError();
775 }
776 Res = DefaultLvalueConversion(Res.get());
777 if (Res.isInvalid())
778 return ExprError();
779 return Res.get();
780}
781
782/// UsualUnaryFPConversions - Promotes floating-point types according to the
783/// current language semantics.
785 QualType Ty = E->getType();
786 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
787
788 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
789 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
790 (getLangOpts().getFPEvalMethod() !=
792 PP.getLastFPEvalPragmaLocation().isValid())) {
793 switch (EvalMethod) {
794 default:
795 llvm_unreachable("Unrecognized float evaluation method");
796 break;
798 llvm_unreachable("Float evaluation method should be set by now");
799 break;
801 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
802 // Widen the expression to double.
803 return Ty->isComplexType()
805 Context.getComplexType(Context.DoubleTy),
806 CK_FloatingComplexCast)
807 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
808 break;
810 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
811 // Widen the expression to long double.
812 return Ty->isComplexType()
814 E, Context.getComplexType(Context.LongDoubleTy),
815 CK_FloatingComplexCast)
816 : ImpCastExprToType(E, Context.LongDoubleTy,
817 CK_FloatingCast);
818 break;
819 }
820 }
821
822 // Half FP have to be promoted to float unless it is natively supported
823 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
824 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
825
826 return E;
827}
828
829/// UsualUnaryConversions - Performs various conversions that are common to most
830/// operators (C99 6.3). The conversions of array and function types are
831/// sometimes suppressed. For example, the array->pointer conversion doesn't
832/// apply if the array is an argument to the sizeof or address (&) operators.
833/// In these instances, this routine should *not* be called.
835 // First, convert to an r-value.
837 if (Res.isInvalid())
838 return ExprError();
839
840 // Promote floating-point types.
841 Res = UsualUnaryFPConversions(Res.get());
842 if (Res.isInvalid())
843 return ExprError();
844 E = Res.get();
845
846 QualType Ty = E->getType();
847 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
848
849 // Try to perform integral promotions if the object has a theoretically
850 // promotable type.
852 // C99 6.3.1.1p2:
853 //
854 // The following may be used in an expression wherever an int or
855 // unsigned int may be used:
856 // - an object or expression with an integer type whose integer
857 // conversion rank is less than or equal to the rank of int
858 // and unsigned int.
859 // - A bit-field of type _Bool, int, signed int, or unsigned int.
860 //
861 // If an int can represent all values of the original type, the
862 // value is converted to an int; otherwise, it is converted to an
863 // unsigned int. These are called the integer promotions. All
864 // other types are unchanged by the integer promotions.
865
866 QualType PTy = Context.isPromotableBitField(E);
867 if (!PTy.isNull()) {
868 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
869 return E;
870 }
871 if (Context.isPromotableIntegerType(Ty)) {
872 QualType PT = Context.getPromotedIntegerType(Ty);
873 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
874 return E;
875 }
876 }
877 return E;
878}
879
880/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
881/// do not have a prototype. Arguments that have type float or __fp16
882/// are promoted to double. All other argument types are converted by
883/// UsualUnaryConversions().
885 QualType Ty = E->getType();
886 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
887
889 if (Res.isInvalid())
890 return ExprError();
891 E = Res.get();
892
893 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
894 // promote to double.
895 // Note that default argument promotion applies only to float (and
896 // half/fp16); it does not apply to _Float16.
897 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
898 if (BTy && (BTy->getKind() == BuiltinType::Half ||
899 BTy->getKind() == BuiltinType::Float)) {
900 if (getLangOpts().OpenCL &&
901 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
902 if (BTy->getKind() == BuiltinType::Half) {
903 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
904 }
905 } else {
906 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
907 }
908 }
909 if (BTy &&
910 getLangOpts().getExtendIntArgs() ==
912 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
913 Context.getTypeSizeInChars(BTy) <
914 Context.getTypeSizeInChars(Context.LongLongTy)) {
915 E = (Ty->isUnsignedIntegerType())
916 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
917 .get()
918 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
919 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
920 "Unexpected typesize for LongLongTy");
921 }
922
923 // C++ performs lvalue-to-rvalue conversion as a default argument
924 // promotion, even on class types, but note:
925 // C++11 [conv.lval]p2:
926 // When an lvalue-to-rvalue conversion occurs in an unevaluated
927 // operand or a subexpression thereof the value contained in the
928 // referenced object is not accessed. Otherwise, if the glvalue
929 // has a class type, the conversion copy-initializes a temporary
930 // of type T from the glvalue and the result of the conversion
931 // is a prvalue for the temporary.
932 // FIXME: add some way to gate this entire thing for correctness in
933 // potentially potentially evaluated contexts.
937 E->getExprLoc(), E);
938 if (Temp.isInvalid())
939 return ExprError();
940 E = Temp.get();
941 }
942
943 // C++ [expr.call]p7, per CWG722:
944 // An argument that has (possibly cv-qualified) type std::nullptr_t is
945 // converted to void* ([conv.ptr]).
946 // (This does not apply to C23 nullptr)
948 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
949
950 return E;
951}
952
954 if (Ty->isIncompleteType()) {
955 // C++11 [expr.call]p7:
956 // After these conversions, if the argument does not have arithmetic,
957 // enumeration, pointer, pointer to member, or class type, the program
958 // is ill-formed.
959 //
960 // Since we've already performed null pointer conversion, array-to-pointer
961 // decay and function-to-pointer decay, the only such type in C++ is cv
962 // void. This also handles initializer lists as variadic arguments.
963 if (Ty->isVoidType())
964 return VarArgKind::Invalid;
965
966 if (Ty->isObjCObjectType())
967 return VarArgKind::Invalid;
968 return VarArgKind::Valid;
969 }
970
972 return VarArgKind::Invalid;
973
974 if (Context.getTargetInfo().getTriple().isWasm() &&
976 return VarArgKind::Invalid;
977 }
978
979 if (Ty.isCXX98PODType(Context))
980 return VarArgKind::Valid;
981
982 // C++11 [expr.call]p7:
983 // Passing a potentially-evaluated argument of class type (Clause 9)
984 // having a non-trivial copy constructor, a non-trivial move constructor,
985 // or a non-trivial destructor, with no corresponding parameter,
986 // is conditionally-supported with implementation-defined semantics.
989 if (!Record->hasNonTrivialCopyConstructor() &&
990 !Record->hasNonTrivialMoveConstructor() &&
991 !Record->hasNonTrivialDestructor())
993
994 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
995 return VarArgKind::Valid;
996
997 if (Ty->isObjCObjectType())
998 return VarArgKind::Invalid;
999
1000 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1001 return VarArgKind::Valid;
1002
1003 if (getLangOpts().MSVCCompat)
1005
1006 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1007 return VarArgKind::Valid;
1008
1009 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1010 // permitted to reject them. We should consider doing so.
1011 return VarArgKind::Undefined;
1012}
1013
1015 // Don't allow one to pass an Objective-C interface to a vararg.
1016 const QualType &Ty = E->getType();
1017 VarArgKind VAK = isValidVarArgType(Ty);
1018
1019 // Complain about passing non-POD types through varargs.
1020 switch (VAK) {
1023 E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1025 [[fallthrough]];
1026 case VarArgKind::Valid:
1027 if (Ty->isRecordType()) {
1028 // This is unlikely to be what the user intended. If the class has a
1029 // 'c_str' member function, the user probably meant to call that.
1030 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1031 PDiag(diag::warn_pass_class_arg_to_vararg)
1032 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1033 }
1034 break;
1035
1038 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1039 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1040 << getLangOpts().CPlusPlus11 << Ty << CT);
1041 break;
1042
1045 Diag(E->getBeginLoc(),
1046 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1047 << Ty << CT;
1048 else if (Ty->isObjCObjectType())
1049 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1050 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1051 << Ty << CT);
1052 else
1053 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1054 << isa<InitListExpr>(E) << Ty << CT;
1055 break;
1056 }
1057}
1058
1060 FunctionDecl *FDecl) {
1061 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1062 // Strip the unbridged-cast placeholder expression off, if applicable.
1063 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1064 (CT == VariadicCallType::Method ||
1065 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1066 E = ObjC().stripARCUnbridgedCast(E);
1067
1068 // Otherwise, do normal placeholder checking.
1069 } else {
1070 ExprResult ExprRes = CheckPlaceholderExpr(E);
1071 if (ExprRes.isInvalid())
1072 return ExprError();
1073 E = ExprRes.get();
1074 }
1075 }
1076
1078 if (ExprRes.isInvalid())
1079 return ExprError();
1080
1081 // Copy blocks to the heap.
1082 if (ExprRes.get()->getType()->isBlockPointerType())
1083 maybeExtendBlockObject(ExprRes);
1084
1085 E = ExprRes.get();
1086
1087 // Diagnostics regarding non-POD argument types are
1088 // emitted along with format string checking in Sema::CheckFunctionCall().
1090 // Turn this into a trap.
1091 CXXScopeSpec SS;
1092 SourceLocation TemplateKWLoc;
1093 UnqualifiedId Name;
1094 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1095 E->getBeginLoc());
1096 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1097 /*HasTrailingLParen=*/true,
1098 /*IsAddressOfOperand=*/false);
1099 if (TrapFn.isInvalid())
1100 return ExprError();
1101
1102 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1103 E->getEndLoc());
1104 if (Call.isInvalid())
1105 return ExprError();
1106
1107 ExprResult Comma =
1108 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1109 if (Comma.isInvalid())
1110 return ExprError();
1111 return Comma.get();
1112 }
1113
1114 if (!getLangOpts().CPlusPlus &&
1116 diag::err_call_incomplete_argument))
1117 return ExprError();
1118
1119 return E;
1120}
1121
1122/// Convert complex integers to complex floats and real integers to
1123/// real floats as required for complex arithmetic. Helper function of
1124/// UsualArithmeticConversions()
1125///
1126/// \return false if the integer expression is an integer type and is
1127/// successfully converted to the (complex) float type.
1129 ExprResult &ComplexExpr,
1130 QualType IntTy,
1131 QualType ComplexTy,
1132 bool SkipCast) {
1133 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1134 if (SkipCast) return false;
1135 if (IntTy->isIntegerType()) {
1136 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1137 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1138 } else {
1139 assert(IntTy->isComplexIntegerType());
1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1141 CK_IntegralComplexToFloatingComplex);
1142 }
1143 return false;
1144}
1145
1146// This handles complex/complex, complex/float, or float/complex.
1147// When both operands are complex, the shorter operand is converted to the
1148// type of the longer, and that is the type of the result. This corresponds
1149// to what is done when combining two real floating-point operands.
1150// The fun begins when size promotion occur across type domains.
1151// From H&S 6.3.4: When one operand is complex and the other is a real
1152// floating-point type, the less precise type is converted, within it's
1153// real or complex domain, to the precision of the other type. For example,
1154// when combining a "long double" with a "double _Complex", the
1155// "double _Complex" is promoted to "long double _Complex".
1157 QualType ShorterType,
1158 QualType LongerType,
1159 bool PromotePrecision) {
1160 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1161 QualType Result =
1162 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1163
1164 if (PromotePrecision) {
1165 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1166 Shorter =
1167 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1168 } else {
1169 if (LongerIsComplex)
1170 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1171 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1172 }
1173 }
1174 return Result;
1175}
1176
1177/// Handle arithmetic conversion with complex types. Helper function of
1178/// UsualArithmeticConversions()
1180 ExprResult &RHS, QualType LHSType,
1181 QualType RHSType, bool IsCompAssign) {
1182 // Handle (complex) integer types.
1183 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1184 /*SkipCast=*/false))
1185 return LHSType;
1186 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1187 /*SkipCast=*/IsCompAssign))
1188 return RHSType;
1189
1190 // Compute the rank of the two types, regardless of whether they are complex.
1191 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1192 if (Order < 0)
1193 // Promote the precision of the LHS if not an assignment.
1194 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1195 /*PromotePrecision=*/!IsCompAssign);
1196 // Promote the precision of the RHS unless it is already the same as the LHS.
1197 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1198 /*PromotePrecision=*/Order > 0);
1199}
1200
1201/// Handle arithmetic conversion from integer to float. Helper function
1202/// of UsualArithmeticConversions()
1204 ExprResult &IntExpr,
1205 QualType FloatTy, QualType IntTy,
1206 bool ConvertFloat, bool ConvertInt) {
1207 if (IntTy->isIntegerType()) {
1208 if (ConvertInt)
1209 // Convert intExpr to the lhs floating point type.
1210 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1211 CK_IntegralToFloating);
1212 return FloatTy;
1213 }
1214
1215 // Convert both sides to the appropriate complex float.
1216 assert(IntTy->isComplexIntegerType());
1217 QualType result = S.Context.getComplexType(FloatTy);
1218
1219 // _Complex int -> _Complex float
1220 if (ConvertInt)
1221 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1222 CK_IntegralComplexToFloatingComplex);
1223
1224 // float -> _Complex float
1225 if (ConvertFloat)
1226 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1227 CK_FloatingRealToComplex);
1228
1229 return result;
1230}
1231
1232/// Handle arithmethic conversion with floating point types. Helper
1233/// function of UsualArithmeticConversions()
1235 ExprResult &RHS, QualType LHSType,
1236 QualType RHSType, bool IsCompAssign) {
1237 bool LHSFloat = LHSType->isRealFloatingType();
1238 bool RHSFloat = RHSType->isRealFloatingType();
1239
1240 // N1169 4.1.4: If one of the operands has a floating type and the other
1241 // operand has a fixed-point type, the fixed-point operand
1242 // is converted to the floating type [...]
1243 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1244 if (LHSFloat)
1245 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1246 else if (!IsCompAssign)
1247 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1248 return LHSFloat ? LHSType : RHSType;
1249 }
1250
1251 // If we have two real floating types, convert the smaller operand
1252 // to the bigger result.
1253 if (LHSFloat && RHSFloat) {
1254 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1255 if (order > 0) {
1256 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1257 return LHSType;
1258 }
1259
1260 assert(order < 0 && "illegal float comparison");
1261 if (!IsCompAssign)
1262 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1263 return RHSType;
1264 }
1265
1266 if (LHSFloat) {
1267 // Half FP has to be promoted to float unless it is natively supported
1268 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1269 LHSType = S.Context.FloatTy;
1270
1271 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1272 /*ConvertFloat=*/!IsCompAssign,
1273 /*ConvertInt=*/ true);
1274 }
1275 assert(RHSFloat);
1276 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1277 /*ConvertFloat=*/ true,
1278 /*ConvertInt=*/!IsCompAssign);
1279}
1280
1281/// Diagnose attempts to convert between __float128, __ibm128 and
1282/// long double if there is no support for such conversion.
1283/// Helper function of UsualArithmeticConversions().
1284static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1285 QualType RHSType) {
1286 // No issue if either is not a floating point type.
1287 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1288 return false;
1289
1290 // No issue if both have the same 128-bit float semantics.
1291 auto *LHSComplex = LHSType->getAs<ComplexType>();
1292 auto *RHSComplex = RHSType->getAs<ComplexType>();
1293
1294 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1295 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1296
1297 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1298 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1299
1300 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1301 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1302 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1303 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1304 return false;
1305
1306 return true;
1307}
1308
1309typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1310
1311namespace {
1312/// These helper callbacks are placed in an anonymous namespace to
1313/// permit their use as function template parameters.
1314ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1315 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1316}
1317
1318ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1320 CK_IntegralComplexCast);
1321}
1322}
1323
1324/// Handle integer arithmetic conversions. Helper function of
1325/// UsualArithmeticConversions()
1326template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1328 ExprResult &RHS, QualType LHSType,
1329 QualType RHSType, bool IsCompAssign) {
1330 // The rules for this case are in C99 6.3.1.8
1331 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1332 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1333 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1334 if (LHSSigned == RHSSigned) {
1335 // Same signedness; use the higher-ranked type
1336 if (order >= 0) {
1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338 return LHSType;
1339 } else if (!IsCompAssign)
1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341 return RHSType;
1342 } else if (order != (LHSSigned ? 1 : -1)) {
1343 // The unsigned type has greater than or equal rank to the
1344 // signed type, so use the unsigned type
1345 if (RHSSigned) {
1346 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1347 return LHSType;
1348 } else if (!IsCompAssign)
1349 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1350 return RHSType;
1351 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1352 // The two types are different widths; if we are here, that
1353 // means the signed type is larger than the unsigned type, so
1354 // use the signed type.
1355 if (LHSSigned) {
1356 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1357 return LHSType;
1358 } else if (!IsCompAssign)
1359 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1360 return RHSType;
1361 } else {
1362 // The signed type is higher-ranked than the unsigned type,
1363 // but isn't actually any bigger (like unsigned int and long
1364 // on most 32-bit systems). Use the unsigned type corresponding
1365 // to the signed type.
1366 QualType result =
1367 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1368 RHS = (*doRHSCast)(S, RHS.get(), result);
1369 if (!IsCompAssign)
1370 LHS = (*doLHSCast)(S, LHS.get(), result);
1371 return result;
1372 }
1373}
1374
1375/// Handle conversions with GCC complex int extension. Helper function
1376/// of UsualArithmeticConversions()
1378 ExprResult &RHS, QualType LHSType,
1379 QualType RHSType,
1380 bool IsCompAssign) {
1381 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1382 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1383
1384 if (LHSComplexInt && RHSComplexInt) {
1385 QualType LHSEltType = LHSComplexInt->getElementType();
1386 QualType RHSEltType = RHSComplexInt->getElementType();
1387 QualType ScalarType =
1389 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1390
1391 return S.Context.getComplexType(ScalarType);
1392 }
1393
1394 if (LHSComplexInt) {
1395 QualType LHSEltType = LHSComplexInt->getElementType();
1396 QualType ScalarType =
1398 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1400 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1401 CK_IntegralRealToComplex);
1402
1403 return ComplexType;
1404 }
1405
1406 assert(RHSComplexInt);
1407
1408 QualType RHSEltType = RHSComplexInt->getElementType();
1409 QualType ScalarType =
1411 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1413
1414 if (!IsCompAssign)
1415 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1416 CK_IntegralRealToComplex);
1417 return ComplexType;
1418}
1419
1420/// Return the rank of a given fixed point or integer type. The value itself
1421/// doesn't matter, but the values must be increasing with proper increasing
1422/// rank as described in N1169 4.1.1.
1423static unsigned GetFixedPointRank(QualType Ty) {
1424 const auto *BTy = Ty->getAs<BuiltinType>();
1425 assert(BTy && "Expected a builtin type.");
1426
1427 switch (BTy->getKind()) {
1428 case BuiltinType::ShortFract:
1429 case BuiltinType::UShortFract:
1430 case BuiltinType::SatShortFract:
1431 case BuiltinType::SatUShortFract:
1432 return 1;
1433 case BuiltinType::Fract:
1434 case BuiltinType::UFract:
1435 case BuiltinType::SatFract:
1436 case BuiltinType::SatUFract:
1437 return 2;
1438 case BuiltinType::LongFract:
1439 case BuiltinType::ULongFract:
1440 case BuiltinType::SatLongFract:
1441 case BuiltinType::SatULongFract:
1442 return 3;
1443 case BuiltinType::ShortAccum:
1444 case BuiltinType::UShortAccum:
1445 case BuiltinType::SatShortAccum:
1446 case BuiltinType::SatUShortAccum:
1447 return 4;
1448 case BuiltinType::Accum:
1449 case BuiltinType::UAccum:
1450 case BuiltinType::SatAccum:
1451 case BuiltinType::SatUAccum:
1452 return 5;
1453 case BuiltinType::LongAccum:
1454 case BuiltinType::ULongAccum:
1455 case BuiltinType::SatLongAccum:
1456 case BuiltinType::SatULongAccum:
1457 return 6;
1458 default:
1459 if (BTy->isInteger())
1460 return 0;
1461 llvm_unreachable("Unexpected fixed point or integer type");
1462 }
1463}
1464
1465/// handleFixedPointConversion - Fixed point operations between fixed
1466/// point types and integers or other fixed point types do not fall under
1467/// usual arithmetic conversion since these conversions could result in loss
1468/// of precsision (N1169 4.1.4). These operations should be calculated with
1469/// the full precision of their result type (N1169 4.1.6.2.1).
1471 QualType RHSTy) {
1472 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1473 "Expected at least one of the operands to be a fixed point type");
1474 assert((LHSTy->isFixedPointOrIntegerType() ||
1475 RHSTy->isFixedPointOrIntegerType()) &&
1476 "Special fixed point arithmetic operation conversions are only "
1477 "applied to ints or other fixed point types");
1478
1479 // If one operand has signed fixed-point type and the other operand has
1480 // unsigned fixed-point type, then the unsigned fixed-point operand is
1481 // converted to its corresponding signed fixed-point type and the resulting
1482 // type is the type of the converted operand.
1483 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1485 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1487
1488 // The result type is the type with the highest rank, whereby a fixed-point
1489 // conversion rank is always greater than an integer conversion rank; if the
1490 // type of either of the operands is a saturating fixedpoint type, the result
1491 // type shall be the saturating fixed-point type corresponding to the type
1492 // with the highest rank; the resulting value is converted (taking into
1493 // account rounding and overflow) to the precision of the resulting type.
1494 // Same ranks between signed and unsigned types are resolved earlier, so both
1495 // types are either signed or both unsigned at this point.
1496 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1497 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1498
1499 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1500
1502 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1503
1504 return ResultTy;
1505}
1506
1507/// Check that the usual arithmetic conversions can be performed on this pair of
1508/// expressions that might be of enumeration type.
1510 SourceLocation Loc,
1511 ArithConvKind ACK) {
1512 // C++2a [expr.arith.conv]p1:
1513 // If one operand is of enumeration type and the other operand is of a
1514 // different enumeration type or a floating-point type, this behavior is
1515 // deprecated ([depr.arith.conv.enum]).
1516 //
1517 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1518 // Eventually we will presumably reject these cases (in C++23 onwards?).
1520 R = RHS->getEnumCoercedType(Context);
1521 bool LEnum = L->isUnscopedEnumerationType(),
1522 REnum = R->isUnscopedEnumerationType();
1523 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1524 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1525 (REnum && L->isFloatingType())) {
1526 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1528 ? diag::warn_arith_conv_enum_float_cxx20
1529 : diag::warn_arith_conv_enum_float)
1530 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1531 << L << R;
1532 } else if (!IsCompAssign && LEnum && REnum &&
1533 !Context.hasSameUnqualifiedType(L, R)) {
1534 unsigned DiagID;
1535 // In C++ 26, usual arithmetic conversions between 2 different enum types
1536 // are ill-formed.
1538 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1539 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1540 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1541 // If either enumeration type is unnamed, it's less likely that the
1542 // user cares about this, but this situation is still deprecated in
1543 // C++2a. Use a different warning group.
1544 DiagID = getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_anon_enum_types;
1547 } else if (ACK == ArithConvKind::Conditional) {
1548 // Conditional expressions are separated out because they have
1549 // historically had a different warning flag.
1550 DiagID = getLangOpts().CPlusPlus20
1551 ? diag::warn_conditional_mixed_enum_types_cxx20
1552 : diag::warn_conditional_mixed_enum_types;
1553 } else if (ACK == ArithConvKind::Comparison) {
1554 // Comparison expressions are separated out because they have
1555 // historically had a different warning flag.
1556 DiagID = getLangOpts().CPlusPlus20
1557 ? diag::warn_comparison_mixed_enum_types_cxx20
1558 : diag::warn_comparison_mixed_enum_types;
1559 } else {
1560 DiagID = getLangOpts().CPlusPlus20
1561 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1562 : diag::warn_arith_conv_mixed_enum_types;
1563 }
1564 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1565 << (int)ACK << L << R;
1566 }
1567}
1568
1570 Expr *RHS, SourceLocation Loc,
1571 ArithConvKind ACK) {
1572 QualType LHSType = LHS->getType().getUnqualifiedType();
1573 QualType RHSType = RHS->getType().getUnqualifiedType();
1574
1575 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1576 !RHSType->isUnicodeCharacterType())
1577 return;
1578
1579 if (ACK == ArithConvKind::Comparison) {
1580 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1581 return;
1582
1583 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1584 if (T->isChar8Type())
1585 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1586 if (T->isChar16Type())
1587 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1588 assert(T->isChar32Type());
1589 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1590 };
1591
1592 Expr::EvalResult LHSRes, RHSRes;
1593 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1595 SemaRef.isConstantEvaluatedContext());
1596 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1598 SemaRef.isConstantEvaluatedContext());
1599
1600 // Don't warn if the one known value is a representable
1601 // in the type of both expressions.
1602 if (LHSSuccess != RHSuccess) {
1603 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1604 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1605 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1606 return;
1607 }
1608
1609 if (!LHSSuccess || !RHSuccess) {
1610 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1611 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1612 << RHSType;
1613 return;
1614 }
1615
1616 llvm::APSInt LHSValue(32);
1617 LHSValue = LHSRes.Val.getInt();
1618 llvm::APSInt RHSValue(32);
1619 RHSValue = RHSRes.Val.getInt();
1620
1621 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1622 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1623 if (LHSSafe && RHSSafe)
1624 return;
1625
1626 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1627 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1628 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1629 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1630 return;
1631 }
1632
1633 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1634 return;
1635
1636 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1637 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1638 << RHSType;
1639}
1640
1641/// UsualArithmeticConversions - Performs various conversions that are common to
1642/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1643/// routine returns the first non-arithmetic type found. The client is
1644/// responsible for emitting appropriate error diagnostics.
1646 SourceLocation Loc,
1647 ArithConvKind ACK) {
1648
1649 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1650
1651 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1652
1653 if (ACK != ArithConvKind::CompAssign) {
1654 LHS = UsualUnaryConversions(LHS.get());
1655 if (LHS.isInvalid())
1656 return QualType();
1657 }
1658
1659 RHS = UsualUnaryConversions(RHS.get());
1660 if (RHS.isInvalid())
1661 return QualType();
1662
1663 // For conversion purposes, we ignore any qualifiers.
1664 // For example, "const float" and "float" are equivalent.
1665 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1666 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1667
1668 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1669 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1670 LHSType = AtomicLHS->getValueType();
1671
1672 // If both types are identical, no conversion is needed.
1673 if (Context.hasSameType(LHSType, RHSType))
1674 return Context.getCommonSugaredType(LHSType, RHSType);
1675
1676 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1677 // The caller can deal with this (e.g. pointer + int).
1678 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1679 return QualType();
1680
1681 // Apply unary and bitfield promotions to the LHS's type.
1682 QualType LHSUnpromotedType = LHSType;
1683 if (Context.isPromotableIntegerType(LHSType))
1684 LHSType = Context.getPromotedIntegerType(LHSType);
1685 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1686 if (!LHSBitfieldPromoteTy.isNull())
1687 LHSType = LHSBitfieldPromoteTy;
1688 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1689 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1690
1691 // If both types are identical, no conversion is needed.
1692 if (Context.hasSameType(LHSType, RHSType))
1693 return Context.getCommonSugaredType(LHSType, RHSType);
1694
1695 // At this point, we have two different arithmetic types.
1696
1697 // Diagnose attempts to convert between __ibm128, __float128 and long double
1698 // where such conversions currently can't be handled.
1699 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1700 return QualType();
1701
1702 // Handle complex types first (C99 6.3.1.8p1).
1703 if (LHSType->isComplexType() || RHSType->isComplexType())
1704 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1706
1707 // Now handle "real" floating types (i.e. float, double, long double).
1708 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1709 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1711
1712 // Handle GCC complex int extension.
1713 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1714 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1716
1717 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1718 return handleFixedPointConversion(*this, LHSType, RHSType);
1719
1720 // Finally, we have two differing integer types.
1722 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1723}
1724
1725//===----------------------------------------------------------------------===//
1726// Semantic Analysis for various Expression Types
1727//===----------------------------------------------------------------------===//
1728
1729
1731 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1732 bool PredicateIsExpr, void *ControllingExprOrType,
1733 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1734 unsigned NumAssocs = ArgTypes.size();
1735 assert(NumAssocs == ArgExprs.size());
1736
1737 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1738 for (unsigned i = 0; i < NumAssocs; ++i) {
1739 if (ArgTypes[i])
1740 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1741 else
1742 Types[i] = nullptr;
1743 }
1744
1745 // If we have a controlling type, we need to convert it from a parsed type
1746 // into a semantic type and then pass that along.
1747 if (!PredicateIsExpr) {
1748 TypeSourceInfo *ControllingType;
1749 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1750 &ControllingType);
1751 assert(ControllingType && "couldn't get the type out of the parser");
1752 ControllingExprOrType = ControllingType;
1753 }
1754
1756 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1757 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1758 delete [] Types;
1759 return ER;
1760}
1761
1763 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1764 bool PredicateIsExpr, void *ControllingExprOrType,
1766 unsigned NumAssocs = Types.size();
1767 assert(NumAssocs == Exprs.size());
1768 assert(ControllingExprOrType &&
1769 "Must have either a controlling expression or a controlling type");
1770
1771 Expr *ControllingExpr = nullptr;
1772 TypeSourceInfo *ControllingType = nullptr;
1773 if (PredicateIsExpr) {
1774 // Decay and strip qualifiers for the controlling expression type, and
1775 // handle placeholder type replacement. See committee discussion from WG14
1776 // DR423.
1780 reinterpret_cast<Expr *>(ControllingExprOrType));
1781 if (R.isInvalid())
1782 return ExprError();
1783 ControllingExpr = R.get();
1784 } else {
1785 // The extension form uses the type directly rather than converting it.
1786 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1787 if (!ControllingType)
1788 return ExprError();
1789 }
1790
1791 bool TypeErrorFound = false,
1792 IsResultDependent = ControllingExpr
1793 ? ControllingExpr->isTypeDependent()
1794 : ControllingType->getType()->isDependentType(),
1795 ContainsUnexpandedParameterPack =
1796 ControllingExpr
1797 ? ControllingExpr->containsUnexpandedParameterPack()
1798 : ControllingType->getType()->containsUnexpandedParameterPack();
1799
1800 // The controlling expression is an unevaluated operand, so side effects are
1801 // likely unintended.
1802 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1803 ControllingExpr->HasSideEffects(Context, false))
1804 Diag(ControllingExpr->getExprLoc(),
1805 diag::warn_side_effects_unevaluated_context);
1806
1807 for (unsigned i = 0; i < NumAssocs; ++i) {
1808 if (Exprs[i]->containsUnexpandedParameterPack())
1809 ContainsUnexpandedParameterPack = true;
1810
1811 if (Types[i]) {
1812 if (Types[i]->getType()->containsUnexpandedParameterPack())
1813 ContainsUnexpandedParameterPack = true;
1814
1815 if (Types[i]->getType()->isDependentType()) {
1816 IsResultDependent = true;
1817 } else {
1818 // We relax the restriction on use of incomplete types and non-object
1819 // types with the type-based extension of _Generic. Allowing incomplete
1820 // objects means those can be used as "tags" for a type-safe way to map
1821 // to a value. Similarly, matching on function types rather than
1822 // function pointer types can be useful. However, the restriction on VM
1823 // types makes sense to retain as there are open questions about how
1824 // the selection can be made at compile time.
1825 //
1826 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1827 // complete object type other than a variably modified type."
1828 // C2y removed the requirement that an expression form must
1829 // use a complete type, though it's still as-if the type has undergone
1830 // lvalue conversion. We support this as an extension in C23 and
1831 // earlier because GCC does so.
1832 unsigned D = 0;
1833 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1834 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1835 : diag::ext_assoc_type_incomplete;
1836 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1837 D = diag::err_assoc_type_nonobject;
1838 else if (Types[i]->getType()->isVariablyModifiedType())
1839 D = diag::err_assoc_type_variably_modified;
1840 else if (ControllingExpr) {
1841 // Because the controlling expression undergoes lvalue conversion,
1842 // array conversion, and function conversion, an association which is
1843 // of array type, function type, or is qualified can never be
1844 // reached. We will warn about this so users are less surprised by
1845 // the unreachable association. However, we don't have to handle
1846 // function types; that's not an object type, so it's handled above.
1847 //
1848 // The logic is somewhat different for C++ because C++ has different
1849 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1850 // If T is a non-class type, the type of the prvalue is the cv-
1851 // unqualified version of T. Otherwise, the type of the prvalue is T.
1852 // The result of these rules is that all qualified types in an
1853 // association in C are unreachable, and in C++, only qualified non-
1854 // class types are unreachable.
1855 //
1856 // NB: this does not apply when the first operand is a type rather
1857 // than an expression, because the type form does not undergo
1858 // conversion.
1859 unsigned Reason = 0;
1860 QualType QT = Types[i]->getType();
1861 if (QT->isArrayType())
1862 Reason = 1;
1863 else if (QT.hasQualifiers() &&
1864 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1865 Reason = 2;
1866
1867 if (Reason)
1868 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1869 diag::warn_unreachable_association)
1870 << QT << (Reason - 1);
1871 }
1872
1873 if (D != 0) {
1874 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1875 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1876 if (getDiagnostics().getDiagnosticLevel(
1877 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1879 TypeErrorFound = true;
1880 }
1881
1882 // C11 6.5.1.1p2 "No two generic associations in the same generic
1883 // selection shall specify compatible types."
1884 for (unsigned j = i+1; j < NumAssocs; ++j)
1885 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1886 Context.typesAreCompatible(Types[i]->getType(),
1887 Types[j]->getType())) {
1888 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1889 diag::err_assoc_compatible_types)
1890 << Types[j]->getTypeLoc().getSourceRange()
1891 << Types[j]->getType()
1892 << Types[i]->getType();
1893 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1894 diag::note_compat_assoc)
1895 << Types[i]->getTypeLoc().getSourceRange()
1896 << Types[i]->getType();
1897 TypeErrorFound = true;
1898 }
1899 }
1900 }
1901 }
1902 if (TypeErrorFound)
1903 return ExprError();
1904
1905 // If we determined that the generic selection is result-dependent, don't
1906 // try to compute the result expression.
1907 if (IsResultDependent) {
1908 if (ControllingExpr)
1909 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1910 Types, Exprs, DefaultLoc, RParenLoc,
1911 ContainsUnexpandedParameterPack);
1912 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1913 Exprs, DefaultLoc, RParenLoc,
1914 ContainsUnexpandedParameterPack);
1915 }
1916
1917 SmallVector<unsigned, 1> CompatIndices;
1918 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1919 // Look at the canonical type of the controlling expression in case it was a
1920 // deduced type like __auto_type. However, when issuing diagnostics, use the
1921 // type the user wrote in source rather than the canonical one.
1922 for (unsigned i = 0; i < NumAssocs; ++i) {
1923 if (!Types[i])
1924 DefaultIndex = i;
1925 else if (ControllingExpr &&
1926 Context.typesAreCompatible(
1927 ControllingExpr->getType().getCanonicalType(),
1928 Types[i]->getType()))
1929 CompatIndices.push_back(i);
1930 else if (ControllingType &&
1931 Context.typesAreCompatible(
1932 ControllingType->getType().getCanonicalType(),
1933 Types[i]->getType()))
1934 CompatIndices.push_back(i);
1935 }
1936
1937 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1938 TypeSourceInfo *ControllingType) {
1939 // We strip parens here because the controlling expression is typically
1940 // parenthesized in macro definitions.
1941 if (ControllingExpr)
1942 ControllingExpr = ControllingExpr->IgnoreParens();
1943
1944 SourceRange SR = ControllingExpr
1945 ? ControllingExpr->getSourceRange()
1946 : ControllingType->getTypeLoc().getSourceRange();
1947 QualType QT = ControllingExpr ? ControllingExpr->getType()
1948 : ControllingType->getType();
1949
1950 return std::make_pair(SR, QT);
1951 };
1952
1953 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1954 // type compatible with at most one of the types named in its generic
1955 // association list."
1956 if (CompatIndices.size() > 1) {
1957 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1958 SourceRange SR = P.first;
1959 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1960 << SR << P.second << (unsigned)CompatIndices.size();
1961 for (unsigned I : CompatIndices) {
1962 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1963 diag::note_compat_assoc)
1964 << Types[I]->getTypeLoc().getSourceRange()
1965 << Types[I]->getType();
1966 }
1967 return ExprError();
1968 }
1969
1970 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1971 // its controlling expression shall have type compatible with exactly one of
1972 // the types named in its generic association list."
1973 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1974 CompatIndices.size() == 0) {
1975 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1976 SourceRange SR = P.first;
1977 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1978 return ExprError();
1979 }
1980
1981 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1982 // type name that is compatible with the type of the controlling expression,
1983 // then the result expression of the generic selection is the expression
1984 // in that generic association. Otherwise, the result expression of the
1985 // generic selection is the expression in the default generic association."
1986 unsigned ResultIndex =
1987 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1988
1989 if (ControllingExpr) {
1991 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1992 ContainsUnexpandedParameterPack, ResultIndex);
1993 }
1995 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1996 ContainsUnexpandedParameterPack, ResultIndex);
1997}
1998
2000 switch (Kind) {
2001 default:
2002 llvm_unreachable("unexpected TokenKind");
2003 case tok::kw___func__:
2004 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2005 case tok::kw___FUNCTION__:
2007 case tok::kw___FUNCDNAME__:
2008 return PredefinedIdentKind::FuncDName; // [MS]
2009 case tok::kw___FUNCSIG__:
2010 return PredefinedIdentKind::FuncSig; // [MS]
2011 case tok::kw_L__FUNCTION__:
2012 return PredefinedIdentKind::LFunction; // [MS]
2013 case tok::kw_L__FUNCSIG__:
2014 return PredefinedIdentKind::LFuncSig; // [MS]
2015 case tok::kw___PRETTY_FUNCTION__:
2017 }
2018}
2019
2020/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2021/// to determine the value of a PredefinedExpr. This can be either a
2022/// block, lambda, captured statement, function, otherwise a nullptr.
2025 DC = DC->getParent();
2026 return cast_or_null<Decl>(DC);
2027}
2028
2029/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2030/// location of the token and the offset of the ud-suffix within it.
2032 unsigned Offset) {
2033 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2034 S.getLangOpts());
2035}
2036
2037/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2038/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2040 IdentifierInfo *UDSuffix,
2041 SourceLocation UDSuffixLoc,
2042 ArrayRef<Expr*> Args,
2043 SourceLocation LitEndLoc) {
2044 assert(Args.size() <= 2 && "too many arguments for literal operator");
2045
2046 QualType ArgTy[2];
2047 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2048 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2049 if (ArgTy[ArgIdx]->isArrayType())
2050 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2051 }
2052
2053 DeclarationName OpName =
2055 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2056 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2057
2058 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2059 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2060 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2061 /*AllowStringTemplatePack*/ false,
2062 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2063 return ExprError();
2064
2065 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2066}
2067
2069 // StringToks needs backing storage as it doesn't hold array elements itself
2070 std::vector<Token> ExpandedToks;
2071 if (getLangOpts().MicrosoftExt)
2072 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2073
2074 StringLiteralParser Literal(StringToks, PP,
2076 if (Literal.hadError)
2077 return ExprError();
2078
2079 SmallVector<SourceLocation, 4> StringTokLocs;
2080 for (const Token &Tok : StringToks)
2081 StringTokLocs.push_back(Tok.getLocation());
2082
2083 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2085 false, {}, StringTokLocs);
2086
2087 if (!Literal.getUDSuffix().empty()) {
2088 SourceLocation UDSuffixLoc =
2089 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2090 Literal.getUDSuffixOffset());
2091 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2092 }
2093
2094 return Lit;
2095}
2096
2097std::vector<Token>
2099 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2100 // local macros that expand to string literals that may be concatenated.
2101 // These macros are expanded here (in Sema), because StringLiteralParser
2102 // (in Lex) doesn't know the enclosing function (because it hasn't been
2103 // parsed yet).
2104 assert(getLangOpts().MicrosoftExt);
2105
2106 // Note: Although function local macros are defined only inside functions,
2107 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2108 // expansion of macros into empty string literals without additional checks.
2109 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2110 if (!CurrentDecl)
2111 CurrentDecl = Context.getTranslationUnitDecl();
2112
2113 std::vector<Token> ExpandedToks;
2114 ExpandedToks.reserve(Toks.size());
2115 for (const Token &Tok : Toks) {
2117 assert(tok::isStringLiteral(Tok.getKind()));
2118 ExpandedToks.emplace_back(Tok);
2119 continue;
2120 }
2121 if (isa<TranslationUnitDecl>(CurrentDecl))
2122 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2123 // Stringify predefined expression
2124 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2125 << Tok.getKind();
2126 SmallString<64> Str;
2127 llvm::raw_svector_ostream OS(Str);
2128 Token &Exp = ExpandedToks.emplace_back();
2129 Exp.startToken();
2130 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2131 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2132 OS << 'L';
2133 Exp.setKind(tok::wide_string_literal);
2134 } else {
2135 Exp.setKind(tok::string_literal);
2136 }
2137 OS << '"'
2139 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2140 << '"';
2141 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2142 }
2143 return ExpandedToks;
2144}
2145
2148 assert(!StringToks.empty() && "Must have at least one string!");
2149
2150 // StringToks needs backing storage as it doesn't hold array elements itself
2151 std::vector<Token> ExpandedToks;
2152 if (getLangOpts().MicrosoftExt)
2153 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2154
2155 StringLiteralParser Literal(StringToks, PP);
2156 if (Literal.hadError)
2157 return ExprError();
2158
2159 SmallVector<SourceLocation, 4> StringTokLocs;
2160 for (const Token &Tok : StringToks)
2161 StringTokLocs.push_back(Tok.getLocation());
2162
2163 QualType CharTy = Context.CharTy;
2165 if (Literal.isWide()) {
2166 CharTy = Context.getWideCharType();
2168 } else if (Literal.isUTF8()) {
2169 if (getLangOpts().Char8)
2170 CharTy = Context.Char8Ty;
2171 else if (getLangOpts().C23)
2172 CharTy = Context.UnsignedCharTy;
2174 } else if (Literal.isUTF16()) {
2175 CharTy = Context.Char16Ty;
2177 } else if (Literal.isUTF32()) {
2178 CharTy = Context.Char32Ty;
2180 } else if (Literal.isPascal()) {
2181 CharTy = Context.UnsignedCharTy;
2182 }
2183
2184 // Warn on u8 string literals before C++20 and C23, whose type
2185 // was an array of char before but becomes an array of char8_t.
2186 // In C++20, it cannot be used where a pointer to char is expected.
2187 // In C23, it might have an unexpected value if char was signed.
2188 if (Kind == StringLiteralKind::UTF8 &&
2190 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2191 : !getLangOpts().C23)) {
2192 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2193 ? diag::warn_cxx20_compat_utf8_string
2194 : diag::warn_c23_compat_utf8_string);
2195
2196 // Create removals for all 'u8' prefixes in the string literal(s). This
2197 // ensures C++20/C23 compatibility (but may change the program behavior when
2198 // built by non-Clang compilers for which the execution character set is
2199 // not always UTF-8).
2200 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2201 SourceLocation RemovalDiagLoc;
2202 for (const Token &Tok : StringToks) {
2203 if (Tok.getKind() == tok::utf8_string_literal) {
2204 if (RemovalDiagLoc.isInvalid())
2205 RemovalDiagLoc = Tok.getLocation();
2207 Tok.getLocation(),
2208 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2210 }
2211 }
2212 Diag(RemovalDiagLoc, RemovalDiag);
2213 }
2214
2215 QualType StrTy =
2216 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2217
2218 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2220 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2221 if (Literal.getUDSuffix().empty())
2222 return Lit;
2223
2224 // We're building a user-defined literal.
2225 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2226 SourceLocation UDSuffixLoc =
2227 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2228 Literal.getUDSuffixOffset());
2229
2230 // Make sure we're allowed user-defined literals here.
2231 if (!UDLScope)
2232 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2233
2234 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2235 // operator "" X (str, len)
2236 QualType SizeType = Context.getSizeType();
2237
2238 DeclarationName OpName =
2239 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2240 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2241 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2242
2243 QualType ArgTy[] = {
2244 Context.getArrayDecayedType(StrTy), SizeType
2245 };
2246
2247 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2248 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2249 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2250 /*AllowStringTemplatePack*/ true,
2251 /*DiagnoseMissing*/ true, Lit)) {
2252
2253 case LOLR_Cooked: {
2254 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2255 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2256 StringTokLocs[0]);
2257 Expr *Args[] = { Lit, LenArg };
2258
2259 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2260 }
2261
2262 case LOLR_Template: {
2263 TemplateArgumentListInfo ExplicitArgs;
2264 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2265 TemplateArgumentLocInfo ArgInfo(Lit);
2266 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2267 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2268 &ExplicitArgs);
2269 }
2270
2272 TemplateArgumentListInfo ExplicitArgs;
2273
2274 unsigned CharBits = Context.getIntWidth(CharTy);
2275 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2276 llvm::APSInt Value(CharBits, CharIsUnsigned);
2277
2278 TemplateArgument TypeArg(CharTy);
2279 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2280 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2281
2282 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2283 Value = Lit->getCodeUnit(I);
2284 TemplateArgument Arg(Context, Value, CharTy);
2286 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2287 }
2288 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2289 &ExplicitArgs);
2290 }
2291 case LOLR_Raw:
2293 llvm_unreachable("unexpected literal operator lookup result");
2294 case LOLR_Error:
2295 return ExprError();
2296 }
2297 llvm_unreachable("unexpected literal operator lookup result");
2298}
2299
2302 SourceLocation Loc,
2303 const CXXScopeSpec *SS) {
2304 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2305 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2306}
2307
2310 const DeclarationNameInfo &NameInfo,
2311 const CXXScopeSpec *SS, NamedDecl *FoundD,
2312 SourceLocation TemplateKWLoc,
2313 const TemplateArgumentListInfo *TemplateArgs) {
2316 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2317 TemplateArgs);
2318}
2319
2320// CUDA/HIP: Check whether a captured reference variable is referencing a
2321// host variable in a device or host device lambda.
2323 VarDecl *VD) {
2324 if (!S.getLangOpts().CUDA || !VD->hasInit())
2325 return false;
2326 assert(VD->getType()->isReferenceType());
2327
2328 // Check whether the reference variable is referencing a host variable.
2329 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2330 if (!DRE)
2331 return false;
2332 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2333 if (!Referee || !Referee->hasGlobalStorage() ||
2334 Referee->hasAttr<CUDADeviceAttr>())
2335 return false;
2336
2337 // Check whether the current function is a device or host device lambda.
2338 // Check whether the reference variable is a capture by getDeclContext()
2339 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2340 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2341 if (MD && MD->getParent()->isLambda() &&
2342 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2343 VD->getDeclContext() != MD)
2344 return true;
2345
2346 return false;
2347}
2348
2350 // A declaration named in an unevaluated operand never constitutes an odr-use.
2352 return NOUR_Unevaluated;
2353
2354 // C++2a [basic.def.odr]p4:
2355 // A variable x whose name appears as a potentially-evaluated expression e
2356 // is odr-used by e unless [...] x is a reference that is usable in
2357 // constant expressions.
2358 // CUDA/HIP:
2359 // If a reference variable referencing a host variable is captured in a
2360 // device or host device lambda, the value of the referee must be copied
2361 // to the capture and the reference variable must be treated as odr-use
2362 // since the value of the referee is not known at compile time and must
2363 // be loaded from the captured.
2364 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2365 if (VD->getType()->isReferenceType() &&
2366 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2368 VD->isUsableInConstantExpressions(Context))
2369 return NOUR_Constant;
2370 }
2371
2372 // All remaining non-variable cases constitute an odr-use. For variables, we
2373 // need to wait and see how the expression is used.
2374 return NOUR_None;
2375}
2376
2379 const DeclarationNameInfo &NameInfo,
2380 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2381 SourceLocation TemplateKWLoc,
2382 const TemplateArgumentListInfo *TemplateArgs) {
2383 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2384 NeedToCaptureVariable(D, NameInfo.getLoc());
2385
2387 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2388 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2390
2391 // C++ [except.spec]p17:
2392 // An exception-specification is considered to be needed when:
2393 // - in an expression, the function is the unique lookup result or
2394 // the selected member of a set of overloaded functions.
2395 //
2396 // We delay doing this until after we've built the function reference and
2397 // marked it as used so that:
2398 // a) if the function is defaulted, we get errors from defining it before /
2399 // instead of errors from computing its exception specification, and
2400 // b) if the function is a defaulted comparison, we can use the body we
2401 // build when defining it as input to the exception specification
2402 // computation rather than computing a new body.
2403 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2404 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2405 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2406 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2407 }
2408 }
2409
2410 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2412 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2414
2415 const auto *FD = dyn_cast<FieldDecl>(D);
2416 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2417 FD = IFD->getAnonField();
2418 if (FD) {
2419 UnusedPrivateFields.remove(FD);
2420 // Just in case we're building an illegal pointer-to-member.
2421 if (FD->isBitField())
2423 }
2424
2425 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2426 // designates a bit-field.
2427 if (const auto *BD = dyn_cast<BindingDecl>(D))
2428 if (const auto *BE = BD->getBinding())
2429 E->setObjectKind(BE->getObjectKind());
2430
2431 return E;
2432}
2433
2434void
2437 DeclarationNameInfo &NameInfo,
2438 const TemplateArgumentListInfo *&TemplateArgs) {
2440 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2441 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2442
2443 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2444 Id.TemplateId->NumArgs);
2445 translateTemplateArguments(TemplateArgsPtr, Buffer);
2446
2447 TemplateName TName = Id.TemplateId->Template.get();
2449 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2450 TemplateArgs = &Buffer;
2451 } else {
2452 NameInfo = GetNameFromUnqualifiedId(Id);
2453 TemplateArgs = nullptr;
2454 }
2455}
2456
2458 // During a default argument instantiation the CurContext points
2459 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2460 // function parameter list, hence add an explicit check.
2461 bool isDefaultArgument =
2462 !CodeSynthesisContexts.empty() &&
2463 CodeSynthesisContexts.back().Kind ==
2465 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2466 bool isInstance = CurMethod && CurMethod->isInstance() &&
2467 R.getNamingClass() == CurMethod->getParent() &&
2468 !isDefaultArgument;
2469
2470 // There are two ways we can find a class-scope declaration during template
2471 // instantiation that we did not find in the template definition: if it is a
2472 // member of a dependent base class, or if it is declared after the point of
2473 // use in the same class. Distinguish these by comparing the class in which
2474 // the member was found to the naming class of the lookup.
2475 unsigned DiagID = diag::err_found_in_dependent_base;
2476 unsigned NoteID = diag::note_member_declared_at;
2478 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2479 : diag::err_found_later_in_class;
2480 } else if (getLangOpts().MSVCCompat) {
2481 DiagID = diag::ext_found_in_dependent_base;
2482 NoteID = diag::note_dependent_member_use;
2483 }
2484
2485 if (isInstance) {
2486 // Give a code modification hint to insert 'this->'.
2487 Diag(R.getNameLoc(), DiagID)
2488 << R.getLookupName()
2489 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2491 } else {
2492 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2493 // they're not shadowed).
2494 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2495 }
2496
2497 for (const NamedDecl *D : R)
2498 Diag(D->getLocation(), NoteID);
2499
2500 // Return true if we are inside a default argument instantiation
2501 // and the found name refers to an instance member function, otherwise
2502 // the caller will try to create an implicit member call and this is wrong
2503 // for default arguments.
2504 //
2505 // FIXME: Is this special case necessary? We could allow the caller to
2506 // diagnose this.
2507 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2508 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2509 return true;
2510 }
2511
2512 // Tell the callee to try to recover.
2513 return false;
2514}
2515
2518 TemplateArgumentListInfo *ExplicitTemplateArgs,
2519 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2520 DeclarationName Name = R.getLookupName();
2522
2523 unsigned diagnostic = diag::err_undeclared_var_use;
2524 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2528 diagnostic = diag::err_undeclared_use;
2529 diagnostic_suggest = diag::err_undeclared_use_suggest;
2530 }
2531
2532 // If the original lookup was an unqualified lookup, fake an
2533 // unqualified lookup. This is useful when (for example) the
2534 // original lookup would not have found something because it was a
2535 // dependent name.
2536 DeclContext *DC =
2537 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2538 while (DC) {
2539 if (isa<CXXRecordDecl>(DC)) {
2540 if (ExplicitTemplateArgs) {
2542 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2543 /*EnteringContext*/ false, TemplateNameIsRequired,
2544 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2545 return true;
2546 } else {
2547 LookupQualifiedName(R, DC);
2548 }
2549
2550 if (!R.empty()) {
2551 // Don't give errors about ambiguities in this lookup.
2553
2554 // If there's a best viable function among the results, only mention
2555 // that one in the notes.
2556 OverloadCandidateSet Candidates(R.getNameLoc(),
2558 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2560 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2561 OR_Success) {
2562 R.clear();
2563 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2564 R.resolveKind();
2565 }
2566
2568 }
2569
2570 R.clear();
2571 }
2572
2573 DC = DC->getLookupParent();
2574 }
2575
2576 // We didn't find anything, so try to correct for a typo.
2577 TypoCorrection Corrected;
2578 if (S && (Corrected =
2580 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2581 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2582 bool DroppedSpecifier =
2583 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2584 R.setLookupName(Corrected.getCorrection());
2585
2586 bool AcceptableWithRecovery = false;
2587 bool AcceptableWithoutRecovery = false;
2588 NamedDecl *ND = Corrected.getFoundDecl();
2589 if (ND) {
2590 if (Corrected.isOverloaded()) {
2594 for (NamedDecl *CD : Corrected) {
2595 if (FunctionTemplateDecl *FTD =
2596 dyn_cast<FunctionTemplateDecl>(CD))
2598 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2599 Args, OCS);
2600 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2601 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2603 Args, OCS);
2604 }
2605 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2606 case OR_Success:
2607 ND = Best->FoundDecl;
2608 Corrected.setCorrectionDecl(ND);
2609 break;
2610 default:
2611 // FIXME: Arbitrarily pick the first declaration for the note.
2612 Corrected.setCorrectionDecl(ND);
2613 break;
2614 }
2615 }
2616 R.addDecl(ND);
2617 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2620 if (!Record)
2624 }
2625
2626 auto *UnderlyingND = ND->getUnderlyingDecl();
2627 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2628 isa<FunctionTemplateDecl>(UnderlyingND);
2629 // FIXME: If we ended up with a typo for a type name or
2630 // Objective-C class name, we're in trouble because the parser
2631 // is in the wrong place to recover. Suggest the typo
2632 // correction, but don't make it a fix-it since we're not going
2633 // to recover well anyway.
2634 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2635 getAsTypeTemplateDecl(UnderlyingND) ||
2636 isa<ObjCInterfaceDecl>(UnderlyingND);
2637 } else {
2638 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2639 // because we aren't able to recover.
2640 AcceptableWithoutRecovery = true;
2641 }
2642
2643 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2644 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2645 ? diag::note_implicit_param_decl
2646 : diag::note_previous_decl;
2647 if (SS.isEmpty())
2648 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2649 PDiag(NoteID), AcceptableWithRecovery);
2650 else
2651 diagnoseTypo(Corrected,
2652 PDiag(diag::err_no_member_suggest)
2653 << Name << computeDeclContext(SS, false)
2654 << DroppedSpecifier << NameRange,
2655 PDiag(NoteID), AcceptableWithRecovery);
2656
2657 // Tell the callee whether to try to recover.
2658 return !AcceptableWithRecovery;
2659 }
2660 }
2661 R.clear();
2662
2663 // Emit a special diagnostic for failed member lookups.
2664 // FIXME: computing the declaration context might fail here (?)
2665 if (!SS.isEmpty()) {
2666 Diag(R.getNameLoc(), diag::err_no_member)
2667 << Name << computeDeclContext(SS, false) << NameRange;
2668 return true;
2669 }
2670
2671 // Give up, we can't recover.
2672 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2673 return true;
2674}
2675
2676/// In Microsoft mode, if we are inside a template class whose parent class has
2677/// dependent base classes, and we can't resolve an unqualified identifier, then
2678/// assume the identifier is a member of a dependent base class. We can only
2679/// recover successfully in static methods, instance methods, and other contexts
2680/// where 'this' is available. This doesn't precisely match MSVC's
2681/// instantiation model, but it's close enough.
2682static Expr *
2684 DeclarationNameInfo &NameInfo,
2685 SourceLocation TemplateKWLoc,
2686 const TemplateArgumentListInfo *TemplateArgs) {
2687 // Only try to recover from lookup into dependent bases in static methods or
2688 // contexts where 'this' is available.
2689 QualType ThisType = S.getCurrentThisType();
2690 const CXXRecordDecl *RD = nullptr;
2691 if (!ThisType.isNull())
2692 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2693 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2694 RD = MD->getParent();
2695 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2696 return nullptr;
2697
2698 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2699 // is available, suggest inserting 'this->' as a fixit.
2700 SourceLocation Loc = NameInfo.getLoc();
2701 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2702 DB << NameInfo.getName() << RD;
2703
2704 if (!ThisType.isNull()) {
2705 DB << FixItHint::CreateInsertion(Loc, "this->");
2707 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2708 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2709 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2710 }
2711
2712 // Synthesize a fake NNS that points to the derived class. This will
2713 // perform name lookup during template instantiation.
2714 CXXScopeSpec SS;
2715 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2716 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2718 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2719 TemplateArgs);
2720}
2721
2724 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2725 bool HasTrailingLParen, bool IsAddressOfOperand,
2727 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2728 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2729 "cannot be direct & operand and have a trailing lparen");
2730 if (SS.isInvalid())
2731 return ExprError();
2732
2733 TemplateArgumentListInfo TemplateArgsBuffer;
2734
2735 // Decompose the UnqualifiedId into the following data.
2736 DeclarationNameInfo NameInfo;
2737 const TemplateArgumentListInfo *TemplateArgs;
2738 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2739
2740 DeclarationName Name = NameInfo.getName();
2742 SourceLocation NameLoc = NameInfo.getLoc();
2743
2744 if (II && II->isEditorPlaceholder()) {
2745 // FIXME: When typed placeholders are supported we can create a typed
2746 // placeholder expression node.
2747 return ExprError();
2748 }
2749
2750 // This specially handles arguments of attributes appertains to a type of C
2751 // struct field such that the name lookup within a struct finds the member
2752 // name, which is not the case for other contexts in C.
2753 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2754 // See if this is reference to a field of struct.
2755 LookupResult R(*this, NameInfo, LookupMemberName);
2756 // LookupName handles a name lookup from within anonymous struct.
2757 if (LookupName(R, S)) {
2758 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2759 QualType type = VD->getType().getNonReferenceType();
2760 // This will eventually be translated into MemberExpr upon
2761 // the use of instantiated struct fields.
2762 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2763 }
2764 }
2765 }
2766
2767 // Perform the required lookup.
2768 LookupResult R(*this, NameInfo,
2772 if (TemplateKWLoc.isValid() || TemplateArgs) {
2773 // Lookup the template name again to correctly establish the context in
2774 // which it was found. This is really unfortunate as we already did the
2775 // lookup to determine that it was a template name in the first place. If
2776 // this becomes a performance hit, we can work harder to preserve those
2777 // results until we get here but it's likely not worth it.
2778 AssumedTemplateKind AssumedTemplate;
2779 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2780 /*EnteringContext=*/false, TemplateKWLoc,
2781 &AssumedTemplate))
2782 return ExprError();
2783
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2790 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2791
2792 // If the result might be in a dependent base class, this is a dependent
2793 // id-expression.
2795 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2796 IsAddressOfOperand, TemplateArgs);
2797
2798 // If this reference is in an Objective-C method, then we need to do
2799 // some special Objective-C lookup, too.
2800 if (IvarLookupFollowUp) {
2801 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2802 if (E.isInvalid())
2803 return ExprError();
2804
2805 if (Expr *Ex = E.getAs<Expr>())
2806 return Ex;
2807 }
2808 }
2809
2810 if (R.isAmbiguous())
2811 return ExprError();
2812
2813 // This could be an implicitly declared function reference if the language
2814 // mode allows it as a feature.
2815 if (R.empty() && HasTrailingLParen && II &&
2816 getLangOpts().implicitFunctionsAllowed()) {
2817 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2818 if (D) R.addDecl(D);
2819 }
2820
2821 // Determine whether this name might be a candidate for
2822 // argument-dependent lookup.
2823 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2824
2825 if (R.empty() && !ADL) {
2826 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2827 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2828 TemplateKWLoc, TemplateArgs))
2829 return E;
2830 }
2831
2832 // Don't diagnose an empty lookup for inline assembly.
2833 if (IsInlineAsmIdentifier)
2834 return ExprError();
2835
2836 // If this name wasn't predeclared and if this is not a function
2837 // call, diagnose the problem.
2838 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2839 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2840 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2841 "Typo correction callback misconfigured");
2842 if (CCC) {
2843 // Make sure the callback knows what the typo being diagnosed is.
2844 CCC->setTypoName(II);
2845 if (SS.isValid())
2846 CCC->setTypoNNS(SS.getScopeRep());
2847 }
2848 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2849 // a template name, but we happen to have always already looked up the name
2850 // before we get here if it must be a template name.
2851 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2852 {}, nullptr))
2853 return ExprError();
2854
2855 assert(!R.empty() &&
2856 "DiagnoseEmptyLookup returned false but added no results");
2857
2858 // If we found an Objective-C instance variable, let
2859 // LookupInObjCMethod build the appropriate expression to
2860 // reference the ivar.
2861 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2862 R.clear();
2863 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2864 // In a hopelessly buggy code, Objective-C instance variable
2865 // lookup fails and no expression will be built to reference it.
2866 if (!E.isInvalid() && !E.get())
2867 return ExprError();
2868 return E;
2869 }
2870 }
2871
2872 // This is guaranteed from this point on.
2873 assert(!R.empty() || ADL);
2874
2875 // Check whether this might be a C++ implicit instance member access.
2876 // C++ [class.mfct.non-static]p3:
2877 // When an id-expression that is not part of a class member access
2878 // syntax and not used to form a pointer to member is used in the
2879 // body of a non-static member function of class X, if name lookup
2880 // resolves the name in the id-expression to a non-static non-type
2881 // member of some class C, the id-expression is transformed into a
2882 // class member access expression using (*this) as the
2883 // postfix-expression to the left of the . operator.
2884 //
2885 // But we don't actually need to do this for '&' operands if R
2886 // resolved to a function or overloaded function set, because the
2887 // expression is ill-formed if it actually works out to be a
2888 // non-static member function:
2889 //
2890 // C++ [expr.ref]p4:
2891 // Otherwise, if E1.E2 refers to a non-static member function. . .
2892 // [t]he expression can be used only as the left-hand operand of a
2893 // member function call.
2894 //
2895 // There are other safeguards against such uses, but it's important
2896 // to get this right here so that we don't end up making a
2897 // spuriously dependent expression if we're inside a dependent
2898 // instance method.
2899 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2900 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2901 S);
2902
2903 if (TemplateArgs || TemplateKWLoc.isValid()) {
2904
2905 // In C++1y, if this is a variable template id, then check it
2906 // in BuildTemplateIdExpr().
2907 // The single lookup result must be a variable template declaration.
2911 assert(R.getAsSingle<TemplateDecl>() &&
2912 "There should only be one declaration found.");
2913 }
2914
2915 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2916 }
2917
2918 return BuildDeclarationNameExpr(SS, R, ADL);
2919}
2920
2922 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2923 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2924 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2925 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2926
2927 if (R.isAmbiguous())
2928 return ExprError();
2929
2931 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2932 NameInfo, /*TemplateArgs=*/nullptr);
2933
2934 if (R.empty()) {
2935 // Don't diagnose problems with invalid record decl, the secondary no_member
2936 // diagnostic during template instantiation is likely bogus, e.g. if a class
2937 // is invalid because it's derived from an invalid base class, then missing
2938 // members were likely supposed to be inherited.
2940 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2941 if (CD->isInvalidDecl())
2942 return ExprError();
2943 Diag(NameInfo.getLoc(), diag::err_no_member)
2944 << NameInfo.getName() << DC << SS.getRange();
2945 return ExprError();
2946 }
2947
2948 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2949 QualType ET;
2950 TypeLocBuilder TLB;
2951 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
2952 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
2953 SS.getScopeRep(), TagD,
2954 /*OwnsTag=*/false);
2955 auto TL = TLB.push<TagTypeLoc>(ET);
2957 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2958 TL.setNameLoc(NameInfo.getLoc());
2959 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
2960 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
2961 SS.getScopeRep(), TypedefD);
2962 TLB.push<TypedefTypeLoc>(ET).set(
2963 /*ElaboratedKeywordLoc=*/SourceLocation(),
2964 SS.getWithLocInContext(Context), NameInfo.getLoc());
2965 } else {
2966 // FIXME: What else can appear here?
2967 ET = SemaRef.Context.getTypeDeclType(TD);
2968 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
2969 assert(SS.isEmpty());
2970 }
2971
2972 // Diagnose a missing typename if this resolved unambiguously to a type in
2973 // a dependent context. If we can recover with a type, downgrade this to
2974 // a warning in Microsoft compatibility mode.
2975 unsigned DiagID = diag::err_typename_missing;
2976 if (RecoveryTSI && getLangOpts().MSVCCompat)
2977 DiagID = diag::ext_typename_missing;
2978 SourceLocation Loc = SS.getBeginLoc();
2979 auto D = Diag(Loc, DiagID);
2980 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2981
2982 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2983 // context.
2984 if (!RecoveryTSI)
2985 return ExprError();
2986
2987 // Only issue the fixit if we're prepared to recover.
2988 D << FixItHint::CreateInsertion(Loc, "typename ");
2989
2990 // Recover by pretending this was an elaborated type.
2991 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2992
2993 return ExprEmpty();
2994 }
2995
2996 // If necessary, build an implicit class member access.
2997 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2999 /*TemplateKWLoc=*/SourceLocation(),
3000 R, /*TemplateArgs=*/nullptr,
3001 /*S=*/nullptr);
3002
3003 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3004}
3005
3007 NestedNameSpecifier Qualifier,
3008 NamedDecl *FoundDecl,
3009 NamedDecl *Member) {
3010 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3011 if (!RD)
3012 return From;
3013
3014 QualType DestRecordType;
3015 QualType DestType;
3016 QualType FromRecordType;
3017 QualType FromType = From->getType();
3018 bool PointerConversions = false;
3019 if (isa<FieldDecl>(Member)) {
3020 DestRecordType = Context.getCanonicalTagType(RD);
3021 auto FromPtrType = FromType->getAs<PointerType>();
3022 DestRecordType = Context.getAddrSpaceQualType(
3023 DestRecordType, FromPtrType
3024 ? FromType->getPointeeType().getAddressSpace()
3025 : FromType.getAddressSpace());
3026
3027 if (FromPtrType) {
3028 DestType = Context.getPointerType(DestRecordType);
3029 FromRecordType = FromPtrType->getPointeeType();
3030 PointerConversions = true;
3031 } else {
3032 DestType = DestRecordType;
3033 FromRecordType = FromType;
3034 }
3035 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3036 if (!Method->isImplicitObjectMemberFunction())
3037 return From;
3038
3039 DestType = Method->getThisType().getNonReferenceType();
3040 DestRecordType = Method->getFunctionObjectParameterType();
3041
3042 if (FromType->getAs<PointerType>()) {
3043 FromRecordType = FromType->getPointeeType();
3044 PointerConversions = true;
3045 } else {
3046 FromRecordType = FromType;
3047 DestType = DestRecordType;
3048 }
3049
3050 LangAS FromAS = FromRecordType.getAddressSpace();
3051 LangAS DestAS = DestRecordType.getAddressSpace();
3052 if (FromAS != DestAS) {
3053 QualType FromRecordTypeWithoutAS =
3054 Context.removeAddrSpaceQualType(FromRecordType);
3055 QualType FromTypeWithDestAS =
3056 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3057 if (PointerConversions)
3058 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3059 From = ImpCastExprToType(From, FromTypeWithDestAS,
3060 CK_AddressSpaceConversion, From->getValueKind())
3061 .get();
3062 }
3063 } else {
3064 // No conversion necessary.
3065 return From;
3066 }
3067
3068 if (DestType->isDependentType() || FromType->isDependentType())
3069 return From;
3070
3071 // If the unqualified types are the same, no conversion is necessary.
3072 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3073 return From;
3074
3075 SourceRange FromRange = From->getSourceRange();
3076 SourceLocation FromLoc = FromRange.getBegin();
3077
3078 ExprValueKind VK = From->getValueKind();
3079
3080 // C++ [class.member.lookup]p8:
3081 // [...] Ambiguities can often be resolved by qualifying a name with its
3082 // class name.
3083 //
3084 // If the member was a qualified name and the qualified referred to a
3085 // specific base subobject type, we'll cast to that intermediate type
3086 // first and then to the object in which the member is declared. That allows
3087 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3088 //
3089 // class Base { public: int x; };
3090 // class Derived1 : public Base { };
3091 // class Derived2 : public Base { };
3092 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3093 //
3094 // void VeryDerived::f() {
3095 // x = 17; // error: ambiguous base subobjects
3096 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3097 // }
3098 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3099 QualType QType = QualType(Qualifier.getAsType(), 0);
3100 assert(QType->isRecordType() && "lookup done with non-record type");
3101
3102 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3103
3104 // In C++98, the qualifier type doesn't actually have to be a base
3105 // type of the object type, in which case we just ignore it.
3106 // Otherwise build the appropriate casts.
3107 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3108 CXXCastPath BasePath;
3109 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3110 FromLoc, FromRange, &BasePath))
3111 return ExprError();
3112
3113 if (PointerConversions)
3114 QType = Context.getPointerType(QType);
3115 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3116 VK, &BasePath).get();
3117
3118 FromType = QType;
3119 FromRecordType = QRecordType;
3120
3121 // If the qualifier type was the same as the destination type,
3122 // we're done.
3123 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3124 return From;
3125 }
3126 }
3127
3128 CXXCastPath BasePath;
3129 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3130 FromLoc, FromRange, &BasePath,
3131 /*IgnoreAccess=*/true))
3132 return ExprError();
3133
3134 // Propagate qualifiers to base subobjects as per:
3135 // C++ [basic.type.qualifier]p1.2:
3136 // A volatile object is [...] a subobject of a volatile object.
3137 Qualifiers FromTypeQuals = FromType.getQualifiers();
3138 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3139 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3140
3141 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3142 &BasePath);
3143}
3144
3146 const LookupResult &R,
3147 bool HasTrailingLParen) {
3148 // Only when used directly as the postfix-expression of a call.
3149 if (!HasTrailingLParen)
3150 return false;
3151
3152 // Never if a scope specifier was provided.
3153 if (SS.isNotEmpty())
3154 return false;
3155
3156 // Only in C++ or ObjC++.
3157 if (!getLangOpts().CPlusPlus)
3158 return false;
3159
3160 // Turn off ADL when we find certain kinds of declarations during
3161 // normal lookup:
3162 for (const NamedDecl *D : R) {
3163 // C++0x [basic.lookup.argdep]p3:
3164 // -- a declaration of a class member
3165 // Since using decls preserve this property, we check this on the
3166 // original decl.
3167 if (D->isCXXClassMember())
3168 return false;
3169
3170 // C++0x [basic.lookup.argdep]p3:
3171 // -- a block-scope function declaration that is not a
3172 // using-declaration
3173 // NOTE: we also trigger this for function templates (in fact, we
3174 // don't check the decl type at all, since all other decl types
3175 // turn off ADL anyway).
3176 if (isa<UsingShadowDecl>(D))
3177 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3178 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3179 return false;
3180
3181 // C++0x [basic.lookup.argdep]p3:
3182 // -- a declaration that is neither a function or a function
3183 // template
3184 // And also for builtin functions.
3185 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3186 // But also builtin functions.
3187 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3188 return false;
3189 } else if (!isa<FunctionTemplateDecl>(D))
3190 return false;
3191 }
3192
3193 return true;
3194}
3195
3196
3197/// Diagnoses obvious problems with the use of the given declaration
3198/// as an expression. This is only actually called for lookups that
3199/// were not overloaded, and it doesn't promise that the declaration
3200/// will in fact be used.
3202 bool AcceptInvalid) {
3203 if (D->isInvalidDecl() && !AcceptInvalid)
3204 return true;
3205
3206 if (isa<TypedefNameDecl>(D)) {
3207 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3208 return true;
3209 }
3210
3211 if (isa<ObjCInterfaceDecl>(D)) {
3212 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3213 return true;
3214 }
3215
3216 if (isa<NamespaceDecl>(D)) {
3217 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3218 return true;
3219 }
3220
3221 return false;
3222}
3223
3224// Certain multiversion types should be treated as overloaded even when there is
3225// only one result.
3227 assert(R.isSingleResult() && "Expected only a single result");
3228 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3229 return FD &&
3230 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3231}
3232
3234 LookupResult &R, bool NeedsADL,
3235 bool AcceptInvalidDecl) {
3236 // If this is a single, fully-resolved result and we don't need ADL,
3237 // just build an ordinary singleton decl ref.
3238 if (!NeedsADL && R.isSingleResult() &&
3242 R.getRepresentativeDecl(), nullptr,
3243 AcceptInvalidDecl);
3244
3245 // We only need to check the declaration if there's exactly one
3246 // result, because in the overloaded case the results can only be
3247 // functions and function templates.
3249 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3250 AcceptInvalidDecl))
3251 return ExprError();
3252
3253 // Otherwise, just build an unresolved lookup expression. Suppress
3254 // any lookup-related diagnostics; we'll hash these out later, when
3255 // we've picked a target.
3257
3260 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3261 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3262
3263 return ULE;
3264}
3265
3267 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3268 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3269 bool AcceptInvalidDecl) {
3270 assert(D && "Cannot refer to a NULL declaration");
3271 assert(!isa<FunctionTemplateDecl>(D) &&
3272 "Cannot refer unambiguously to a function template");
3273
3274 SourceLocation Loc = NameInfo.getLoc();
3275 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3276 // Recovery from invalid cases (e.g. D is an invalid Decl).
3277 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3278 // diagnostics, as invalid decls use int as a fallback type.
3279 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3280 }
3281
3282 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3283 // Specifically diagnose references to class templates that are missing
3284 // a template argument list.
3285 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3286 return ExprError();
3287 }
3288
3289 // Make sure that we're referring to a value.
3291 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3292 Diag(D->getLocation(), diag::note_declared_at);
3293 return ExprError();
3294 }
3295
3296 // Check whether this declaration can be used. Note that we suppress
3297 // this check when we're going to perform argument-dependent lookup
3298 // on this function name, because this might not be the function
3299 // that overload resolution actually selects.
3300 if (DiagnoseUseOfDecl(D, Loc))
3301 return ExprError();
3302
3303 auto *VD = cast<ValueDecl>(D);
3304
3305 // Only create DeclRefExpr's for valid Decl's.
3306 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3307 return ExprError();
3308
3309 // Handle members of anonymous structs and unions. If we got here,
3310 // and the reference is to a class member indirect field, then this
3311 // must be the subject of a pointer-to-member expression.
3312 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3313 IndirectField && !IndirectField->isCXXClassMember())
3315 IndirectField);
3316
3317 QualType type = VD->getType();
3318 if (type.isNull())
3319 return ExprError();
3320 ExprValueKind valueKind = VK_PRValue;
3321
3322 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3323 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3324 // is expanded by some outer '...' in the context of the use.
3325 type = type.getNonPackExpansionType();
3326
3327 switch (D->getKind()) {
3328 // Ignore all the non-ValueDecl kinds.
3329#define ABSTRACT_DECL(kind)
3330#define VALUE(type, base)
3331#define DECL(type, base) case Decl::type:
3332#include "clang/AST/DeclNodes.inc"
3333 llvm_unreachable("invalid value decl kind");
3334
3335 // These shouldn't make it here.
3336 case Decl::ObjCAtDefsField:
3337 llvm_unreachable("forming non-member reference to ivar?");
3338
3339 // Enum constants are always r-values and never references.
3340 // Unresolved using declarations are dependent.
3341 case Decl::EnumConstant:
3342 case Decl::UnresolvedUsingValue:
3343 case Decl::OMPDeclareReduction:
3344 case Decl::OMPDeclareMapper:
3345 valueKind = VK_PRValue;
3346 break;
3347
3348 // Fields and indirect fields that got here must be for
3349 // pointer-to-member expressions; we just call them l-values for
3350 // internal consistency, because this subexpression doesn't really
3351 // exist in the high-level semantics.
3352 case Decl::Field:
3353 case Decl::IndirectField:
3354 case Decl::ObjCIvar:
3355 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3356 "building reference to field in C?");
3357
3358 // These can't have reference type in well-formed programs, but
3359 // for internal consistency we do this anyway.
3360 type = type.getNonReferenceType();
3361 valueKind = VK_LValue;
3362 break;
3363
3364 // Non-type template parameters are either l-values or r-values
3365 // depending on the type.
3366 case Decl::NonTypeTemplateParm: {
3367 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3368 type = reftype->getPointeeType();
3369 valueKind = VK_LValue; // even if the parameter is an r-value reference
3370 break;
3371 }
3372
3373 // [expr.prim.id.unqual]p2:
3374 // If the entity is a template parameter object for a template
3375 // parameter of type T, the type of the expression is const T.
3376 // [...] The expression is an lvalue if the entity is a [...] template
3377 // parameter object.
3378 if (type->isRecordType()) {
3379 type = type.getUnqualifiedType().withConst();
3380 valueKind = VK_LValue;
3381 break;
3382 }
3383
3384 // For non-references, we need to strip qualifiers just in case
3385 // the template parameter was declared as 'const int' or whatever.
3386 valueKind = VK_PRValue;
3387 type = type.getUnqualifiedType();
3388 break;
3389 }
3390
3391 case Decl::Var:
3392 case Decl::VarTemplateSpecialization:
3393 case Decl::VarTemplatePartialSpecialization:
3394 case Decl::Decomposition:
3395 case Decl::Binding:
3396 case Decl::OMPCapturedExpr:
3397 // In C, "extern void blah;" is valid and is an r-value.
3398 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3399 type->isVoidType()) {
3400 valueKind = VK_PRValue;
3401 break;
3402 }
3403 [[fallthrough]];
3404
3405 case Decl::ImplicitParam:
3406 case Decl::ParmVar: {
3407 // These are always l-values.
3408 valueKind = VK_LValue;
3409 type = type.getNonReferenceType();
3410
3411 // FIXME: Does the addition of const really only apply in
3412 // potentially-evaluated contexts? Since the variable isn't actually
3413 // captured in an unevaluated context, it seems that the answer is no.
3414 if (!isUnevaluatedContext()) {
3415 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3416 if (!CapturedType.isNull())
3417 type = CapturedType;
3418 }
3419 break;
3420 }
3421
3422 case Decl::Function: {
3423 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3424 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3425 type = Context.BuiltinFnTy;
3426 valueKind = VK_PRValue;
3427 break;
3428 }
3429 }
3430
3431 const FunctionType *fty = type->castAs<FunctionType>();
3432
3433 // If we're referring to a function with an __unknown_anytype
3434 // result type, make the entire expression __unknown_anytype.
3435 if (fty->getReturnType() == Context.UnknownAnyTy) {
3436 type = Context.UnknownAnyTy;
3437 valueKind = VK_PRValue;
3438 break;
3439 }
3440
3441 // Functions are l-values in C++.
3442 if (getLangOpts().CPlusPlus) {
3443 valueKind = VK_LValue;
3444 break;
3445 }
3446
3447 // C99 DR 316 says that, if a function type comes from a
3448 // function definition (without a prototype), that type is only
3449 // used for checking compatibility. Therefore, when referencing
3450 // the function, we pretend that we don't have the full function
3451 // type.
3452 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3453 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3454 fty->getExtInfo());
3455
3456 // Functions are r-values in C.
3457 valueKind = VK_PRValue;
3458 break;
3459 }
3460
3461 case Decl::CXXDeductionGuide:
3462 llvm_unreachable("building reference to deduction guide");
3463
3464 case Decl::MSProperty:
3465 case Decl::MSGuid:
3466 case Decl::TemplateParamObject:
3467 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3468 // capture in OpenMP, or duplicated between host and device?
3469 valueKind = VK_LValue;
3470 break;
3471
3472 case Decl::UnnamedGlobalConstant:
3473 valueKind = VK_LValue;
3474 break;
3475
3476 case Decl::CXXMethod:
3477 // If we're referring to a method with an __unknown_anytype
3478 // result type, make the entire expression __unknown_anytype.
3479 // This should only be possible with a type written directly.
3480 if (const FunctionProtoType *proto =
3481 dyn_cast<FunctionProtoType>(VD->getType()))
3482 if (proto->getReturnType() == Context.UnknownAnyTy) {
3483 type = Context.UnknownAnyTy;
3484 valueKind = VK_PRValue;
3485 break;
3486 }
3487
3488 // C++ methods are l-values if static, r-values if non-static.
3489 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3490 valueKind = VK_LValue;
3491 break;
3492 }
3493 [[fallthrough]];
3494
3495 case Decl::CXXConversion:
3496 case Decl::CXXDestructor:
3497 case Decl::CXXConstructor:
3498 valueKind = VK_PRValue;
3499 break;
3500 }
3501
3502 auto *E =
3503 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3504 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3505 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3506 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3507 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3508 // diagnostics).
3509 if (VD->isInvalidDecl() && E)
3510 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3511 return E;
3512}
3513
3514static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3516 Target.resize(CharByteWidth * (Source.size() + 1));
3517 char *ResultPtr = &Target[0];
3518 const llvm::UTF8 *ErrorPtr;
3519 bool success =
3520 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3521 (void)success;
3522 assert(success);
3523 Target.resize(ResultPtr - &Target[0]);
3524}
3525
3528 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3529 if (!currentDecl) {
3530 Diag(Loc, diag::ext_predef_outside_function);
3531 currentDecl = Context.getTranslationUnitDecl();
3532 }
3533
3534 QualType ResTy;
3535 StringLiteral *SL = nullptr;
3536 if (cast<DeclContext>(currentDecl)->isDependentContext())
3537 ResTy = Context.DependentTy;
3538 else {
3539 // Pre-defined identifiers are of type char[x], where x is the length of
3540 // the string.
3541 bool ForceElaboratedPrinting =
3542 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3543 auto Str =
3544 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3545 unsigned Length = Str.length();
3546
3547 llvm::APInt LengthI(32, Length + 1);
3550 ResTy =
3551 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3552 SmallString<32> RawChars;
3553 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3554 Str, RawChars);
3555 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3557 /*IndexTypeQuals*/ 0);
3559 /*Pascal*/ false, ResTy, Loc);
3560 } else {
3561 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3562 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3564 /*IndexTypeQuals*/ 0);
3566 /*Pascal*/ false, ResTy, Loc);
3567 }
3568 }
3569
3570 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3571 SL);
3572}
3573
3577
3579 SmallString<16> CharBuffer;
3580 bool Invalid = false;
3581 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3582 if (Invalid)
3583 return ExprError();
3584
3585 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3586 PP, Tok.getKind());
3587 if (Literal.hadError())
3588 return ExprError();
3589
3590 QualType Ty;
3591 if (Literal.isWide())
3592 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3593 else if (Literal.isUTF8() && getLangOpts().C23)
3594 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3595 else if (Literal.isUTF8() && getLangOpts().Char8)
3596 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3597 else if (Literal.isUTF16())
3598 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3599 else if (Literal.isUTF32())
3600 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3601 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3602 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3603 else
3604 Ty = Context.CharTy; // 'x' -> char in C++;
3605 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3606
3608 if (Literal.isWide())
3610 else if (Literal.isUTF16())
3612 else if (Literal.isUTF32())
3614 else if (Literal.isUTF8())
3616
3617 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3618 Tok.getLocation());
3619
3620 if (Literal.getUDSuffix().empty())
3621 return Lit;
3622
3623 // We're building a user-defined literal.
3624 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3625 SourceLocation UDSuffixLoc =
3626 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3627
3628 // Make sure we're allowed user-defined literals here.
3629 if (!UDLScope)
3630 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3631
3632 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3633 // operator "" X (ch)
3634 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3635 Lit, Tok.getLocation());
3636}
3637
3639 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3641 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3642 Context.IntTy, Loc);
3643}
3644
3646 QualType Ty, SourceLocation Loc) {
3647 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3648
3649 using llvm::APFloat;
3650 APFloat Val(Format);
3651
3652 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3653 if (RM == llvm::RoundingMode::Dynamic)
3654 RM = llvm::RoundingMode::NearestTiesToEven;
3655 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3656
3657 // Overflow is always an error, but underflow is only an error if
3658 // we underflowed to zero (APFloat reports denormals as underflow).
3659 if ((result & APFloat::opOverflow) ||
3660 ((result & APFloat::opUnderflow) && Val.isZero())) {
3661 unsigned diagnostic;
3662 SmallString<20> buffer;
3663 if (result & APFloat::opOverflow) {
3664 diagnostic = diag::warn_float_overflow;
3665 APFloat::getLargest(Format).toString(buffer);
3666 } else {
3667 diagnostic = diag::warn_float_underflow;
3668 APFloat::getSmallest(Format).toString(buffer);
3669 }
3670
3671 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3672 }
3673
3674 bool isExact = (result == APFloat::opOK);
3675 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3676}
3677
3678bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3679 assert(E && "Invalid expression");
3680
3681 if (E->isValueDependent())
3682 return false;
3683
3684 QualType QT = E->getType();
3685 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3686 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3687 return true;
3688 }
3689
3690 llvm::APSInt ValueAPS;
3692
3693 if (R.isInvalid())
3694 return true;
3695
3696 // GCC allows the value of unroll count to be 0.
3697 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3698 // "The values of 0 and 1 block any unrolling of the loop."
3699 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3700 // '#pragma unroll' cases.
3701 bool ValueIsPositive =
3702 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3703 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3704 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3705 << toString(ValueAPS, 10) << ValueIsPositive;
3706 return true;
3707 }
3708
3709 return false;
3710}
3711
3713 // Fast path for a single digit (which is quite common). A single digit
3714 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3715 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3716 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3717 return ActOnIntegerConstant(Tok.getLocation(), Val);
3718 }
3719
3720 SmallString<128> SpellingBuffer;
3721 // NumericLiteralParser wants to overread by one character. Add padding to
3722 // the buffer in case the token is copied to the buffer. If getSpelling()
3723 // returns a StringRef to the memory buffer, it should have a null char at
3724 // the EOF, so it is also safe.
3725 SpellingBuffer.resize(Tok.getLength() + 1);
3726
3727 // Get the spelling of the token, which eliminates trigraphs, etc.
3728 bool Invalid = false;
3729 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3730 if (Invalid)
3731 return ExprError();
3732
3733 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3734 PP.getSourceManager(), PP.getLangOpts(),
3735 PP.getTargetInfo(), PP.getDiagnostics());
3736 if (Literal.hadError)
3737 return ExprError();
3738
3739 if (Literal.hasUDSuffix()) {
3740 // We're building a user-defined literal.
3741 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3742 SourceLocation UDSuffixLoc =
3743 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3744
3745 // Make sure we're allowed user-defined literals here.
3746 if (!UDLScope)
3747 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3748
3749 QualType CookedTy;
3750 if (Literal.isFloatingLiteral()) {
3751 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3752 // long double, the literal is treated as a call of the form
3753 // operator "" X (f L)
3754 CookedTy = Context.LongDoubleTy;
3755 } else {
3756 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3757 // unsigned long long, the literal is treated as a call of the form
3758 // operator "" X (n ULL)
3759 CookedTy = Context.UnsignedLongLongTy;
3760 }
3761
3762 DeclarationName OpName =
3763 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3764 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3765 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3766
3767 SourceLocation TokLoc = Tok.getLocation();
3768
3769 // Perform literal operator lookup to determine if we're building a raw
3770 // literal or a cooked one.
3771 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3772 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3773 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3774 /*AllowStringTemplatePack*/ false,
3775 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3777 // Lookup failure for imaginary constants isn't fatal, there's still the
3778 // GNU extension producing _Complex types.
3779 break;
3780 case LOLR_Error:
3781 return ExprError();
3782 case LOLR_Cooked: {
3783 Expr *Lit;
3784 if (Literal.isFloatingLiteral()) {
3785 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3786 } else {
3787 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3788 if (Literal.GetIntegerValue(ResultVal))
3789 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3790 << /* Unsigned */ 1;
3791 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3792 Tok.getLocation());
3793 }
3794 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3795 }
3796
3797 case LOLR_Raw: {
3798 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3799 // literal is treated as a call of the form
3800 // operator "" X ("n")
3801 unsigned Length = Literal.getUDSuffixOffset();
3802 QualType StrTy = Context.getConstantArrayType(
3803 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3804 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3805 Expr *Lit =
3806 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3808 /*Pascal*/ false, StrTy, TokLoc);
3809 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3810 }
3811
3812 case LOLR_Template: {
3813 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3814 // template), L is treated as a call fo the form
3815 // operator "" X <'c1', 'c2', ... 'ck'>()
3816 // where n is the source character sequence c1 c2 ... ck.
3817 TemplateArgumentListInfo ExplicitArgs;
3818 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3819 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3820 llvm::APSInt Value(CharBits, CharIsUnsigned);
3821 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3822 Value = TokSpelling[I];
3823 TemplateArgument Arg(Context, Value, Context.CharTy);
3825 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3826 }
3827 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3828 }
3830 llvm_unreachable("unexpected literal operator lookup result");
3831 }
3832 }
3833
3834 Expr *Res;
3835
3836 if (Literal.isFixedPointLiteral()) {
3837 QualType Ty;
3838
3839 if (Literal.isAccum) {
3840 if (Literal.isHalf) {
3841 Ty = Context.ShortAccumTy;
3842 } else if (Literal.isLong) {
3843 Ty = Context.LongAccumTy;
3844 } else {
3845 Ty = Context.AccumTy;
3846 }
3847 } else if (Literal.isFract) {
3848 if (Literal.isHalf) {
3849 Ty = Context.ShortFractTy;
3850 } else if (Literal.isLong) {
3851 Ty = Context.LongFractTy;
3852 } else {
3853 Ty = Context.FractTy;
3854 }
3855 }
3856
3857 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3858
3859 bool isSigned = !Literal.isUnsigned;
3860 unsigned scale = Context.getFixedPointScale(Ty);
3861 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3862
3863 llvm::APInt Val(bit_width, 0, isSigned);
3864 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3865 bool ValIsZero = Val.isZero() && !Overflowed;
3866
3867 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3868 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3869 // Clause 6.4.4 - The value of a constant shall be in the range of
3870 // representable values for its type, with exception for constants of a
3871 // fract type with a value of exactly 1; such a constant shall denote
3872 // the maximal value for the type.
3873 --Val;
3874 else if (Val.ugt(MaxVal) || Overflowed)
3875 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3876
3878 Tok.getLocation(), scale);
3879 } else if (Literal.isFloatingLiteral()) {
3880 QualType Ty;
3881 if (Literal.isHalf){
3882 if (getLangOpts().HLSL ||
3883 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3884 Ty = Context.HalfTy;
3885 else {
3886 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3887 return ExprError();
3888 }
3889 } else if (Literal.isFloat)
3890 Ty = Context.FloatTy;
3891 else if (Literal.isLong)
3892 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3893 else if (Literal.isFloat16)
3894 Ty = Context.Float16Ty;
3895 else if (Literal.isFloat128)
3896 Ty = Context.Float128Ty;
3897 else if (getLangOpts().HLSL)
3898 Ty = Context.FloatTy;
3899 else
3900 Ty = Context.DoubleTy;
3901
3902 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3903
3904 if (Ty == Context.DoubleTy) {
3905 if (getLangOpts().SinglePrecisionConstants) {
3906 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3907 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3908 }
3909 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3910 "cl_khr_fp64", getLangOpts())) {
3911 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3912 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3914 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3915 }
3916 }
3917 } else if (!Literal.isIntegerLiteral()) {
3918 return ExprError();
3919 } else {
3920 QualType Ty;
3921
3922 // 'z/uz' literals are a C++23 feature.
3923 if (Literal.isSizeT)
3924 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3926 ? diag::warn_cxx20_compat_size_t_suffix
3927 : diag::ext_cxx23_size_t_suffix
3928 : diag::err_cxx23_size_t_suffix);
3929
3930 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3931 // but we do not currently support the suffix in C++ mode because it's not
3932 // entirely clear whether WG21 will prefer this suffix to return a library
3933 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3934 // literals are a C++ extension.
3935 if (Literal.isBitInt)
3936 PP.Diag(Tok.getLocation(),
3937 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3938 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3939 : diag::ext_c23_bitint_suffix);
3940
3941 // Get the value in the widest-possible width. What is "widest" depends on
3942 // whether the literal is a bit-precise integer or not. For a bit-precise
3943 // integer type, try to scan the source to determine how many bits are
3944 // needed to represent the value. This may seem a bit expensive, but trying
3945 // to get the integer value from an overly-wide APInt is *extremely*
3946 // expensive, so the naive approach of assuming
3947 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3948 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3949 if (Literal.isBitInt)
3950 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3951 Literal.getLiteralDigits(), Literal.getRadix());
3952 if (Literal.MicrosoftInteger) {
3953 if (Literal.MicrosoftInteger == 128 &&
3954 !Context.getTargetInfo().hasInt128Type())
3955 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3956 << Literal.isUnsigned;
3957 BitsNeeded = Literal.MicrosoftInteger;
3958 }
3959
3960 llvm::APInt ResultVal(BitsNeeded, 0);
3961
3962 if (Literal.GetIntegerValue(ResultVal)) {
3963 // If this value didn't fit into uintmax_t, error and force to ull.
3964 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3965 << /* Unsigned */ 1;
3966 Ty = Context.UnsignedLongLongTy;
3967 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3968 "long long is not intmax_t?");
3969 } else {
3970 // If this value fits into a ULL, try to figure out what else it fits into
3971 // according to the rules of C99 6.4.4.1p5.
3972
3973 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3974 // be an unsigned int.
3975 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3976
3977 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3978 // suffix for portability of code with C++, but both `l` and `ll` are
3979 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3980 // same.
3981 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3982 Literal.isLong = true;
3983 Literal.isLongLong = false;
3984 }
3985
3986 // Check from smallest to largest, picking the smallest type we can.
3987 unsigned Width = 0;
3988
3989 // Microsoft specific integer suffixes are explicitly sized.
3990 if (Literal.MicrosoftInteger) {
3991 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3992 Width = 8;
3993 Ty = Context.CharTy;
3994 } else {
3995 Width = Literal.MicrosoftInteger;
3996 Ty = Context.getIntTypeForBitwidth(Width,
3997 /*Signed=*/!Literal.isUnsigned);
3998 }
3999 }
4000
4001 // Bit-precise integer literals are automagically-sized based on the
4002 // width required by the literal.
4003 if (Literal.isBitInt) {
4004 // The signed version has one more bit for the sign value. There are no
4005 // zero-width bit-precise integers, even if the literal value is 0.
4006 Width = std::max(ResultVal.getActiveBits(), 1u) +
4007 (Literal.isUnsigned ? 0u : 1u);
4008
4009 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4010 // and reset the type to the largest supported width.
4011 unsigned int MaxBitIntWidth =
4012 Context.getTargetInfo().getMaxBitIntWidth();
4013 if (Width > MaxBitIntWidth) {
4014 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4015 << Literal.isUnsigned;
4016 Width = MaxBitIntWidth;
4017 }
4018
4019 // Reset the result value to the smaller APInt and select the correct
4020 // type to be used. Note, we zext even for signed values because the
4021 // literal itself is always an unsigned value (a preceeding - is a
4022 // unary operator, not part of the literal).
4023 ResultVal = ResultVal.zextOrTrunc(Width);
4024 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4025 }
4026
4027 // Check C++23 size_t literals.
4028 if (Literal.isSizeT) {
4029 assert(!Literal.MicrosoftInteger &&
4030 "size_t literals can't be Microsoft literals");
4031 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4032 Context.getTargetInfo().getSizeType());
4033
4034 // Does it fit in size_t?
4035 if (ResultVal.isIntN(SizeTSize)) {
4036 // Does it fit in ssize_t?
4037 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4038 Ty = Context.getSignedSizeType();
4039 else if (AllowUnsigned)
4040 Ty = Context.getSizeType();
4041 Width = SizeTSize;
4042 }
4043 }
4044
4045 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4046 !Literal.isSizeT) {
4047 // Are int/unsigned possibilities?
4048 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4049
4050 // Does it fit in a unsigned int?
4051 if (ResultVal.isIntN(IntSize)) {
4052 // Does it fit in a signed int?
4053 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4054 Ty = Context.IntTy;
4055 else if (AllowUnsigned)
4056 Ty = Context.UnsignedIntTy;
4057 Width = IntSize;
4058 }
4059 }
4060
4061 // Are long/unsigned long possibilities?
4062 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4063 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4064
4065 // Does it fit in a unsigned long?
4066 if (ResultVal.isIntN(LongSize)) {
4067 // Does it fit in a signed long?
4068 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4069 Ty = Context.LongTy;
4070 else if (AllowUnsigned)
4071 Ty = Context.UnsignedLongTy;
4072 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4073 // is compatible.
4074 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4075 const unsigned LongLongSize =
4076 Context.getTargetInfo().getLongLongWidth();
4077 Diag(Tok.getLocation(),
4079 ? Literal.isLong
4080 ? diag::warn_old_implicitly_unsigned_long_cxx
4081 : /*C++98 UB*/ diag::
4082 ext_old_implicitly_unsigned_long_cxx
4083 : diag::warn_old_implicitly_unsigned_long)
4084 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4085 : /*will be ill-formed*/ 1);
4086 Ty = Context.UnsignedLongTy;
4087 }
4088 Width = LongSize;
4089 }
4090 }
4091
4092 // Check long long if needed.
4093 if (Ty.isNull() && !Literal.isSizeT) {
4094 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4095
4096 // Does it fit in a unsigned long long?
4097 if (ResultVal.isIntN(LongLongSize)) {
4098 // Does it fit in a signed long long?
4099 // To be compatible with MSVC, hex integer literals ending with the
4100 // LL or i64 suffix are always signed in Microsoft mode.
4101 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4102 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4103 Ty = Context.LongLongTy;
4104 else if (AllowUnsigned)
4105 Ty = Context.UnsignedLongLongTy;
4106 Width = LongLongSize;
4107
4108 // 'long long' is a C99 or C++11 feature, whether the literal
4109 // explicitly specified 'long long' or we needed the extra width.
4110 if (getLangOpts().CPlusPlus)
4111 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4112 ? diag::warn_cxx98_compat_longlong
4113 : diag::ext_cxx11_longlong);
4114 else if (!getLangOpts().C99)
4115 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4116 }
4117 }
4118
4119 // If we still couldn't decide a type, we either have 'size_t' literal
4120 // that is out of range, or a decimal literal that does not fit in a
4121 // signed long long and has no U suffix.
4122 if (Ty.isNull()) {
4123 if (Literal.isSizeT)
4124 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4125 << Literal.isUnsigned;
4126 else
4127 Diag(Tok.getLocation(),
4128 diag::ext_integer_literal_too_large_for_signed);
4129 Ty = Context.UnsignedLongLongTy;
4130 Width = Context.getTargetInfo().getLongLongWidth();
4131 }
4132
4133 if (ResultVal.getBitWidth() != Width)
4134 ResultVal = ResultVal.trunc(Width);
4135 }
4136 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4137 }
4138
4139 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4140 if (Literal.isImaginary) {
4141 Res = new (Context) ImaginaryLiteral(Res,
4142 Context.getComplexType(Res->getType()));
4143
4144 // In C++, this is a GNU extension. In C, it's a C2y extension.
4145 unsigned DiagId;
4146 if (getLangOpts().CPlusPlus)
4147 DiagId = diag::ext_gnu_imaginary_constant;
4148 else if (getLangOpts().C2y)
4149 DiagId = diag::warn_c23_compat_imaginary_constant;
4150 else
4151 DiagId = diag::ext_c2y_imaginary_constant;
4152 Diag(Tok.getLocation(), DiagId);
4153 }
4154 return Res;
4155}
4156
4158 assert(E && "ActOnParenExpr() missing expr");
4159 QualType ExprTy = E->getType();
4160 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4161 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4162 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4163 return new (Context) ParenExpr(L, R, E);
4164}
4165
4167 SourceLocation Loc,
4168 SourceRange ArgRange) {
4169 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4170 // scalar or vector data type argument..."
4171 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4172 // type (C99 6.2.5p18) or void.
4173 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4174 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4175 << T << ArgRange;
4176 return true;
4177 }
4178
4179 assert((T->isVoidType() || !T->isIncompleteType()) &&
4180 "Scalar types should always be complete");
4181 return false;
4182}
4183
4185 SourceLocation Loc,
4186 SourceRange ArgRange) {
4187 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4188 if (!T->isVectorType() && !T->isSizelessVectorType())
4189 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4190 << ""
4191 << "__builtin_vectorelements" << T << ArgRange;
4192
4193 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4194 if (T->isSVESizelessBuiltinType()) {
4195 llvm::StringMap<bool> CallerFeatureMap;
4196 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4197 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4198 }
4199 }
4200
4201 return false;
4202}
4203
4205 SourceLocation Loc,
4206 SourceRange ArgRange) {
4207 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4208 return true;
4209
4210 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4211 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4212 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4213 return true;
4214 }
4215
4216 return false;
4217}
4218
4220 SourceLocation Loc,
4221 SourceRange ArgRange,
4222 UnaryExprOrTypeTrait TraitKind) {
4223 // Invalid types must be hard errors for SFINAE in C++.
4224 if (S.LangOpts.CPlusPlus)
4225 return true;
4226
4227 // C99 6.5.3.4p1:
4228 if (T->isFunctionType() &&
4229 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4230 TraitKind == UETT_PreferredAlignOf)) {
4231 // sizeof(function)/alignof(function) is allowed as an extension.
4232 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4233 << getTraitSpelling(TraitKind) << ArgRange;
4234 return false;
4235 }
4236
4237 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4238 // this is an error (OpenCL v1.1 s6.3.k)
4239 if (T->isVoidType()) {
4240 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4241 : diag::ext_sizeof_alignof_void_type;
4242 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4243 return false;
4244 }
4245
4246 return true;
4247}
4248
4250 SourceLocation Loc,
4251 SourceRange ArgRange,
4252 UnaryExprOrTypeTrait TraitKind) {
4253 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4254 // runtime doesn't allow it.
4255 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4256 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4257 << T << (TraitKind == UETT_SizeOf)
4258 << ArgRange;
4259 return true;
4260 }
4261
4262 return false;
4263}
4264
4265/// Check whether E is a pointer from a decayed array type (the decayed
4266/// pointer type is equal to T) and emit a warning if it is.
4268 const Expr *E) {
4269 // Don't warn if the operation changed the type.
4270 if (T != E->getType())
4271 return;
4272
4273 // Now look for array decays.
4274 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4275 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4276 return;
4277
4278 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4279 << ICE->getType()
4280 << ICE->getSubExpr()->getType();
4281}
4282
4284 UnaryExprOrTypeTrait ExprKind) {
4285 QualType ExprTy = E->getType();
4286 assert(!ExprTy->isReferenceType());
4287
4288 bool IsUnevaluatedOperand =
4289 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4290 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4291 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4292 if (IsUnevaluatedOperand) {
4294 if (Result.isInvalid())
4295 return true;
4296 E = Result.get();
4297 }
4298
4299 // The operand for sizeof and alignof is in an unevaluated expression context,
4300 // so side effects could result in unintended consequences.
4301 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4302 // used to build SFINAE gadgets.
4303 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4304 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4306 !E->getType()->isVariableArrayType() &&
4307 E->HasSideEffects(Context, false))
4308 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4309
4310 if (ExprKind == UETT_VecStep)
4311 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4312 E->getSourceRange());
4313
4314 if (ExprKind == UETT_VectorElements)
4315 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4316 E->getSourceRange());
4317
4318 // Explicitly list some types as extensions.
4319 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4320 E->getSourceRange(), ExprKind))
4321 return false;
4322
4323 // WebAssembly tables are always illegal operands to unary expressions and
4324 // type traits.
4325 if (Context.getTargetInfo().getTriple().isWasm() &&
4327 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4328 << getTraitSpelling(ExprKind);
4329 return true;
4330 }
4331
4332 // 'alignof' applied to an expression only requires the base element type of
4333 // the expression to be complete. 'sizeof' requires the expression's type to
4334 // be complete (and will attempt to complete it if it's an array of unknown
4335 // bound).
4336 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4338 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4339 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4340 getTraitSpelling(ExprKind), E->getSourceRange()))
4341 return true;
4342 } else {
4344 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4345 getTraitSpelling(ExprKind), E->getSourceRange()))
4346 return true;
4347 }
4348
4349 // Completing the expression's type may have changed it.
4350 ExprTy = E->getType();
4351 assert(!ExprTy->isReferenceType());
4352
4353 if (ExprTy->isFunctionType()) {
4354 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4355 << getTraitSpelling(ExprKind) << E->getSourceRange();
4356 return true;
4357 }
4358
4359 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4360 E->getSourceRange(), ExprKind))
4361 return true;
4362
4363 if (ExprKind == UETT_CountOf) {
4364 // The type has to be an array type. We already checked for incomplete
4365 // types above.
4366 QualType ExprType = E->IgnoreParens()->getType();
4367 if (!ExprType->isArrayType()) {
4368 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4369 return true;
4370 }
4371 // FIXME: warn on _Countof on an array parameter. Not warning on it
4372 // currently because there are papers in WG14 about array types which do
4373 // not decay that could impact this behavior, so we want to see if anything
4374 // changes here before coming up with a warning group for _Countof-related
4375 // diagnostics.
4376 }
4377
4378 if (ExprKind == UETT_SizeOf) {
4379 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4380 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4381 QualType OType = PVD->getOriginalType();
4382 QualType Type = PVD->getType();
4383 if (Type->isPointerType() && OType->isArrayType()) {
4384 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4385 << Type << OType;
4386 Diag(PVD->getLocation(), diag::note_declared_at);
4387 }
4388 }
4389 }
4390
4391 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4392 // decays into a pointer and returns an unintended result. This is most
4393 // likely a typo for "sizeof(array) op x".
4394 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4395 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4396 BO->getLHS());
4397 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4398 BO->getRHS());
4399 }
4400 }
4401
4402 return false;
4403}
4404
4405static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4406 // Cannot know anything else if the expression is dependent.
4407 if (E->isTypeDependent())
4408 return false;
4409
4410 if (E->getObjectKind() == OK_BitField) {
4411 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4412 << 1 << E->getSourceRange();
4413 return true;
4414 }
4415
4416 ValueDecl *D = nullptr;
4417 Expr *Inner = E->IgnoreParens();
4418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4419 D = DRE->getDecl();
4420 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4421 D = ME->getMemberDecl();
4422 }
4423
4424 // If it's a field, require the containing struct to have a
4425 // complete definition so that we can compute the layout.
4426 //
4427 // This can happen in C++11 onwards, either by naming the member
4428 // in a way that is not transformed into a member access expression
4429 // (in an unevaluated operand, for instance), or by naming the member
4430 // in a trailing-return-type.
4431 //
4432 // For the record, since __alignof__ on expressions is a GCC
4433 // extension, GCC seems to permit this but always gives the
4434 // nonsensical answer 0.
4435 //
4436 // We don't really need the layout here --- we could instead just
4437 // directly check for all the appropriate alignment-lowing
4438 // attributes --- but that would require duplicating a lot of
4439 // logic that just isn't worth duplicating for such a marginal
4440 // use-case.
4441 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4442 // Fast path this check, since we at least know the record has a
4443 // definition if we can find a member of it.
4444 if (!FD->getParent()->isCompleteDefinition()) {
4445 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4446 << E->getSourceRange();
4447 return true;
4448 }
4449
4450 // Otherwise, if it's a field, and the field doesn't have
4451 // reference type, then it must have a complete type (or be a
4452 // flexible array member, which we explicitly want to
4453 // white-list anyway), which makes the following checks trivial.
4454 if (!FD->getType()->isReferenceType())
4455 return false;
4456 }
4457
4458 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4459}
4460
4462 E = E->IgnoreParens();
4463
4464 // Cannot know anything else if the expression is dependent.
4465 if (E->isTypeDependent())
4466 return false;
4467
4468 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4469}
4470
4472 CapturingScopeInfo *CSI) {
4473 assert(T->isVariablyModifiedType());
4474 assert(CSI != nullptr);
4475
4476 // We're going to walk down into the type and look for VLA expressions.
4477 do {
4478 const Type *Ty = T.getTypePtr();
4479 switch (Ty->getTypeClass()) {
4480#define TYPE(Class, Base)
4481#define ABSTRACT_TYPE(Class, Base)
4482#define NON_CANONICAL_TYPE(Class, Base)
4483#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4484#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4485#include "clang/AST/TypeNodes.inc"
4486 T = QualType();
4487 break;
4488 // These types are never variably-modified.
4489 case Type::Builtin:
4490 case Type::Complex:
4491 case Type::Vector:
4492 case Type::ExtVector:
4493 case Type::ConstantMatrix:
4494 case Type::Record:
4495 case Type::Enum:
4496 case Type::TemplateSpecialization:
4497 case Type::ObjCObject:
4498 case Type::ObjCInterface:
4499 case Type::ObjCObjectPointer:
4500 case Type::ObjCTypeParam:
4501 case Type::Pipe:
4502 case Type::BitInt:
4503 case Type::HLSLInlineSpirv:
4504 llvm_unreachable("type class is never variably-modified!");
4505 case Type::Adjusted:
4506 T = cast<AdjustedType>(Ty)->getOriginalType();
4507 break;
4508 case Type::Decayed:
4509 T = cast<DecayedType>(Ty)->getPointeeType();
4510 break;
4511 case Type::ArrayParameter:
4512 T = cast<ArrayParameterType>(Ty)->getElementType();
4513 break;
4514 case Type::Pointer:
4515 T = cast<PointerType>(Ty)->getPointeeType();
4516 break;
4517 case Type::BlockPointer:
4518 T = cast<BlockPointerType>(Ty)->getPointeeType();
4519 break;
4520 case Type::LValueReference:
4521 case Type::RValueReference:
4522 T = cast<ReferenceType>(Ty)->getPointeeType();
4523 break;
4524 case Type::MemberPointer:
4525 T = cast<MemberPointerType>(Ty)->getPointeeType();
4526 break;
4527 case Type::ConstantArray:
4528 case Type::IncompleteArray:
4529 // Losing element qualification here is fine.
4530 T = cast<ArrayType>(Ty)->getElementType();
4531 break;
4532 case Type::VariableArray: {
4533 // Losing element qualification here is fine.
4535
4536 // Unknown size indication requires no size computation.
4537 // Otherwise, evaluate and record it.
4538 auto Size = VAT->getSizeExpr();
4539 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4541 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4542
4543 T = VAT->getElementType();
4544 break;
4545 }
4546 case Type::FunctionProto:
4547 case Type::FunctionNoProto:
4548 T = cast<FunctionType>(Ty)->getReturnType();
4549 break;
4550 case Type::Paren:
4551 case Type::TypeOf:
4552 case Type::UnaryTransform:
4553 case Type::Attributed:
4554 case Type::BTFTagAttributed:
4555 case Type::HLSLAttributedResource:
4556 case Type::SubstTemplateTypeParm:
4557 case Type::MacroQualified:
4558 case Type::CountAttributed:
4559 // Keep walking after single level desugaring.
4560 T = T.getSingleStepDesugaredType(Context);
4561 break;
4562 case Type::Typedef:
4563 T = cast<TypedefType>(Ty)->desugar();
4564 break;
4565 case Type::Decltype:
4566 T = cast<DecltypeType>(Ty)->desugar();
4567 break;
4568 case Type::PackIndexing:
4569 T = cast<PackIndexingType>(Ty)->desugar();
4570 break;
4571 case Type::Using:
4572 T = cast<UsingType>(Ty)->desugar();
4573 break;
4574 case Type::Auto:
4575 case Type::DeducedTemplateSpecialization:
4576 T = cast<DeducedType>(Ty)->getDeducedType();
4577 break;
4578 case Type::TypeOfExpr:
4579 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4580 break;
4581 case Type::Atomic:
4582 T = cast<AtomicType>(Ty)->getValueType();
4583 break;
4584 case Type::PredefinedSugar:
4585 T = cast<PredefinedSugarType>(Ty)->desugar();
4586 break;
4587 }
4588 } while (!T.isNull() && T->isVariablyModifiedType());
4589}
4590
4592 SourceLocation OpLoc,
4593 SourceRange ExprRange,
4594 UnaryExprOrTypeTrait ExprKind,
4595 StringRef KWName) {
4596 if (ExprType->isDependentType())
4597 return false;
4598
4599 // C++ [expr.sizeof]p2:
4600 // When applied to a reference or a reference type, the result
4601 // is the size of the referenced type.
4602 // C++11 [expr.alignof]p3:
4603 // When alignof is applied to a reference type, the result
4604 // shall be the alignment of the referenced type.
4605 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4606 ExprType = Ref->getPointeeType();
4607
4608 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4609 // When alignof or _Alignof is applied to an array type, the result
4610 // is the alignment of the element type.
4611 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4612 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4613 // If the trait is 'alignof' in C before C2y, the ability to apply the
4614 // trait to an incomplete array is an extension.
4615 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4616 ExprType->isIncompleteArrayType())
4617 Diag(OpLoc, getLangOpts().C2y
4618 ? diag::warn_c2y_compat_alignof_incomplete_array
4619 : diag::ext_c2y_alignof_incomplete_array);
4620 ExprType = Context.getBaseElementType(ExprType);
4621 }
4622
4623 if (ExprKind == UETT_VecStep)
4624 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4625
4626 if (ExprKind == UETT_VectorElements)
4627 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4628 ExprRange);
4629
4630 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4631 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4632 ExprRange);
4633
4634 // Explicitly list some types as extensions.
4635 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4636 ExprKind))
4637 return false;
4638
4640 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4641 KWName, ExprRange))
4642 return true;
4643
4644 if (ExprType->isFunctionType()) {
4645 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4646 return true;
4647 }
4648
4649 if (ExprKind == UETT_CountOf) {
4650 // The type has to be an array type. We already checked for incomplete
4651 // types above.
4652 if (!ExprType->isArrayType()) {
4653 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4654 return true;
4655 }
4656 }
4657
4658 // WebAssembly tables are always illegal operands to unary expressions and
4659 // type traits.
4660 if (Context.getTargetInfo().getTriple().isWasm() &&
4661 ExprType->isWebAssemblyTableType()) {
4662 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4663 << getTraitSpelling(ExprKind);
4664 return true;
4665 }
4666
4667 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4668 ExprKind))
4669 return true;
4670
4671 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4672 if (auto *TT = ExprType->getAs<TypedefType>()) {
4673 for (auto I = FunctionScopes.rbegin(),
4674 E = std::prev(FunctionScopes.rend());
4675 I != E; ++I) {
4676 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4677 if (CSI == nullptr)
4678 break;
4679 DeclContext *DC = nullptr;
4680 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4681 DC = LSI->CallOperator;
4682 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4683 DC = CRSI->TheCapturedDecl;
4684 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4685 DC = BSI->TheDecl;
4686 if (DC) {
4687 if (DC->containsDecl(TT->getDecl()))
4688 break;
4689 captureVariablyModifiedType(Context, ExprType, CSI);
4690 }
4691 }
4692 }
4693 }
4694
4695 return false;
4696}
4697
4699 SourceLocation OpLoc,
4700 UnaryExprOrTypeTrait ExprKind,
4701 SourceRange R) {
4702 if (!TInfo)
4703 return ExprError();
4704
4705 QualType T = TInfo->getType();
4706
4707 if (!T->isDependentType() &&
4708 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4709 getTraitSpelling(ExprKind)))
4710 return ExprError();
4711
4712 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4713 // properly deal with VLAs in nested calls of sizeof and typeof.
4714 if (currentEvaluationContext().isUnevaluated() &&
4715 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4716 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4717 TInfo->getType()->isVariablyModifiedType())
4718 TInfo = TransformToPotentiallyEvaluated(TInfo);
4719
4720 // It's possible that the transformation above failed.
4721 if (!TInfo)
4722 return ExprError();
4723
4724 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4725 return new (Context) UnaryExprOrTypeTraitExpr(
4726 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4727}
4728
4731 UnaryExprOrTypeTrait ExprKind) {
4733 if (PE.isInvalid())
4734 return ExprError();
4735
4736 E = PE.get();
4737
4738 // Verify that the operand is valid.
4739 bool isInvalid = false;
4740 if (E->isTypeDependent()) {
4741 // Delay type-checking for type-dependent expressions.
4742 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4743 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4744 } else if (ExprKind == UETT_VecStep) {
4746 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4747 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4748 isInvalid = true;
4749 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4750 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4751 isInvalid = true;
4752 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4753 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4755 }
4756
4757 if (isInvalid)
4758 return ExprError();
4759
4760 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4761 E->getType()->isVariableArrayType()) {
4763 if (PE.isInvalid()) return ExprError();
4764 E = PE.get();
4765 }
4766
4767 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4768 return new (Context) UnaryExprOrTypeTraitExpr(
4769 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4770}
4771
4774 UnaryExprOrTypeTrait ExprKind, bool IsType,
4775 void *TyOrEx, SourceRange ArgRange) {
4776 // If error parsing type, ignore.
4777 if (!TyOrEx) return ExprError();
4778
4779 if (IsType) {
4780 TypeSourceInfo *TInfo;
4781 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4782 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4783 }
4784
4785 Expr *ArgEx = (Expr *)TyOrEx;
4786 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4787 return Result;
4788}
4789
4791 SourceLocation OpLoc, SourceRange R) {
4792 if (!TInfo)
4793 return true;
4794 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4795 UETT_AlignOf, KWName);
4796}
4797
4799 SourceLocation OpLoc, SourceRange R) {
4800 TypeSourceInfo *TInfo;
4802 &TInfo);
4803 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4804}
4805
4807 bool IsReal) {
4808 if (V.get()->isTypeDependent())
4809 return S.Context.DependentTy;
4810
4811 // _Real and _Imag are only l-values for normal l-values.
4812 if (V.get()->getObjectKind() != OK_Ordinary) {
4813 V = S.DefaultLvalueConversion(V.get());
4814 if (V.isInvalid())
4815 return QualType();
4816 }
4817
4818 // These operators return the element type of a complex type.
4819 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4820 return CT->getElementType();
4821
4822 // Otherwise they pass through real integer and floating point types here.
4823 if (V.get()->getType()->isArithmeticType())
4824 return V.get()->getType();
4825
4826 // Test for placeholders.
4827 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4828 if (PR.isInvalid()) return QualType();
4829 if (PR.get() != V.get()) {
4830 V = PR;
4831 return CheckRealImagOperand(S, V, Loc, IsReal);
4832 }
4833
4834 // Reject anything else.
4835 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4836 << (IsReal ? "__real" : "__imag");
4837 return QualType();
4838}
4839
4840
4841
4844 tok::TokenKind Kind, Expr *Input) {
4846 switch (Kind) {
4847 default: llvm_unreachable("Unknown unary op!");
4848 case tok::plusplus: Opc = UO_PostInc; break;
4849 case tok::minusminus: Opc = UO_PostDec; break;
4850 }
4851
4852 // Since this might is a postfix expression, get rid of ParenListExprs.
4854 if (Result.isInvalid()) return ExprError();
4855 Input = Result.get();
4856
4857 return BuildUnaryOp(S, OpLoc, Opc, Input);
4858}
4859
4860/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4861///
4862/// \return true on error
4864 SourceLocation opLoc,
4865 Expr *op) {
4866 assert(op->getType()->isObjCObjectPointerType());
4868 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4869 return false;
4870
4871 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4873 << op->getSourceRange();
4874 return true;
4875}
4876
4878 auto *BaseNoParens = Base->IgnoreParens();
4879 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4880 return MSProp->getPropertyDecl()->getType()->isArrayType();
4881 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4882}
4883
4884// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4885// Typically this is DependentTy, but can sometimes be more precise.
4886//
4887// There are cases when we could determine a non-dependent type:
4888// - LHS and RHS may have non-dependent types despite being type-dependent
4889// (e.g. unbounded array static members of the current instantiation)
4890// - one may be a dependent-sized array with known element type
4891// - one may be a dependent-typed valid index (enum in current instantiation)
4892//
4893// We *always* return a dependent type, in such cases it is DependentTy.
4894// This avoids creating type-dependent expressions with non-dependent types.
4895// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4897 const ASTContext &Ctx) {
4898 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4899 QualType LTy = LHS->getType(), RTy = RHS->getType();
4900 QualType Result = Ctx.DependentTy;
4901 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4902 if (const PointerType *PT = LTy->getAs<PointerType>())
4903 Result = PT->getPointeeType();
4904 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4905 Result = AT->getElementType();
4906 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4907 if (const PointerType *PT = RTy->getAs<PointerType>())
4908 Result = PT->getPointeeType();
4909 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4910 Result = AT->getElementType();
4911 }
4912 // Ensure we return a dependent type.
4913 return Result->isDependentType() ? Result : Ctx.DependentTy;
4914}
4915
4917 SourceLocation lbLoc,
4918 MultiExprArg ArgExprs,
4919 SourceLocation rbLoc) {
4920
4921 if (base && !base->getType().isNull() &&
4922 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4923 auto *AS = cast<ArraySectionExpr>(base);
4924 if (AS->isOMPArraySection())
4926 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4927 /*Length*/ nullptr,
4928 /*Stride=*/nullptr, rbLoc);
4929
4930 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4931 SourceLocation(), /*Length*/ nullptr,
4932 rbLoc);
4933 }
4934
4935 // Since this might be a postfix expression, get rid of ParenListExprs.
4936 if (isa<ParenListExpr>(base)) {
4938 if (result.isInvalid())
4939 return ExprError();
4940 base = result.get();
4941 }
4942
4943 // Check if base and idx form a MatrixSubscriptExpr.
4944 //
4945 // Helper to check for comma expressions, which are not allowed as indices for
4946 // matrix subscript expressions.
4947 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4948 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4949 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4950 << SourceRange(base->getBeginLoc(), rbLoc);
4951 return true;
4952 }
4953 return false;
4954 };
4955 // The matrix subscript operator ([][])is considered a single operator.
4956 // Separating the index expressions by parenthesis is not allowed.
4957 if (base && !base->getType().isNull() &&
4958 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4959 !isa<MatrixSubscriptExpr>(base)) {
4960 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4961 << SourceRange(base->getBeginLoc(), rbLoc);
4962 return ExprError();
4963 }
4964 // If the base is a MatrixSubscriptExpr, try to create a new
4965 // MatrixSubscriptExpr.
4966 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4967 if (matSubscriptE) {
4968 assert(ArgExprs.size() == 1);
4969 if (CheckAndReportCommaError(ArgExprs.front()))
4970 return ExprError();
4971
4972 assert(matSubscriptE->isIncomplete() &&
4973 "base has to be an incomplete matrix subscript");
4974 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4975 matSubscriptE->getRowIdx(),
4976 ArgExprs.front(), rbLoc);
4977 }
4978 if (base->getType()->isWebAssemblyTableType()) {
4979 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4980 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4981 return ExprError();
4982 }
4983
4984 CheckInvalidBuiltinCountedByRef(base,
4986
4987 // Handle any non-overload placeholder types in the base and index
4988 // expressions. We can't handle overloads here because the other
4989 // operand might be an overloadable type, in which case the overload
4990 // resolution for the operator overload should get the first crack
4991 // at the overload.
4992 bool IsMSPropertySubscript = false;
4993 if (base->getType()->isNonOverloadPlaceholderType()) {
4994 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4995 if (!IsMSPropertySubscript) {
4996 ExprResult result = CheckPlaceholderExpr(base);
4997 if (result.isInvalid())
4998 return ExprError();
4999 base = result.get();
5000 }
5001 }
5002
5003 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5004 if (base->getType()->isMatrixType()) {
5005 assert(ArgExprs.size() == 1);
5006 if (CheckAndReportCommaError(ArgExprs.front()))
5007 return ExprError();
5008
5009 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5010 rbLoc);
5011 }
5012
5013 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5014 Expr *idx = ArgExprs[0];
5015 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5017 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5018 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5019 << SourceRange(base->getBeginLoc(), rbLoc);
5020 }
5021 }
5022
5023 if (ArgExprs.size() == 1 &&
5024 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5025 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5026 if (result.isInvalid())
5027 return ExprError();
5028 ArgExprs[0] = result.get();
5029 } else {
5030 if (CheckArgsForPlaceholders(ArgExprs))
5031 return ExprError();
5032 }
5033
5034 // Build an unanalyzed expression if either operand is type-dependent.
5035 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5036 (base->isTypeDependent() ||
5038 !isa<PackExpansionExpr>(ArgExprs[0])) {
5039 return new (Context) ArraySubscriptExpr(
5040 base, ArgExprs.front(),
5041 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5042 VK_LValue, OK_Ordinary, rbLoc);
5043 }
5044
5045 // MSDN, property (C++)
5046 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5047 // This attribute can also be used in the declaration of an empty array in a
5048 // class or structure definition. For example:
5049 // __declspec(property(get=GetX, put=PutX)) int x[];
5050 // The above statement indicates that x[] can be used with one or more array
5051 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5052 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5053 if (IsMSPropertySubscript) {
5054 assert(ArgExprs.size() == 1);
5055 // Build MS property subscript expression if base is MS property reference
5056 // or MS property subscript.
5057 return new (Context)
5058 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5059 VK_LValue, OK_Ordinary, rbLoc);
5060 }
5061
5062 // Use C++ overloaded-operator rules if either operand has record
5063 // type. The spec says to do this if either type is *overloadable*,
5064 // but enum types can't declare subscript operators or conversion
5065 // operators, so there's nothing interesting for overload resolution
5066 // to do if there aren't any record types involved.
5067 //
5068 // ObjC pointers have their own subscripting logic that is not tied
5069 // to overload resolution and so should not take this path.
5071 ((base->getType()->isRecordType() ||
5072 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5073 ArgExprs[0]->getType()->isRecordType())))) {
5074 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5075 }
5076
5077 ExprResult Res =
5078 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5079
5080 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5081 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5082
5083 return Res;
5084}
5085
5088 InitializationKind Kind =
5090 InitializationSequence InitSeq(*this, Entity, Kind, E);
5091 return InitSeq.Perform(*this, Entity, Kind, E);
5092}
5093
5095 Expr *RowIdx,
5096 SourceLocation RBLoc) {
5098 if (BaseR.isInvalid())
5099 return BaseR;
5100 Base = BaseR.get();
5101
5102 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5103 if (RowR.isInvalid())
5104 return RowR;
5105 RowIdx = RowR.get();
5106
5107 // Build an unanalyzed expression if any of the operands is type-dependent.
5108 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5109 return new (Context)
5110 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5111
5112 // Check that IndexExpr is an integer expression. If it is a constant
5113 // expression, check that it is less than Dim (= the number of elements in the
5114 // corresponding dimension).
5115 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5116 bool IsColumnIdx) -> Expr * {
5117 if (!IndexExpr->getType()->isIntegerType() &&
5118 !IndexExpr->isTypeDependent()) {
5119 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5120 << IsColumnIdx;
5121 return nullptr;
5122 }
5123
5124 if (std::optional<llvm::APSInt> Idx =
5125 IndexExpr->getIntegerConstantExpr(Context)) {
5126 if ((*Idx < 0 || *Idx >= Dim)) {
5127 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5128 << IsColumnIdx << Dim;
5129 return nullptr;
5130 }
5131 }
5132
5133 ExprResult ConvExpr = IndexExpr;
5134 assert(!ConvExpr.isInvalid() &&
5135 "should be able to convert any integer type to size type");
5136 return ConvExpr.get();
5137 };
5138
5139 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5140 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5141 if (!RowIdx)
5142 return ExprError();
5143
5144 QualType RowVecQT =
5145 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5146
5147 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5148}
5149
5151 Expr *ColumnIdx,
5152 SourceLocation RBLoc) {
5154 if (BaseR.isInvalid())
5155 return BaseR;
5156 Base = BaseR.get();
5157
5158 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5159 if (RowR.isInvalid())
5160 return RowR;
5161 RowIdx = RowR.get();
5162
5163 if (!ColumnIdx)
5164 return new (Context) MatrixSubscriptExpr(
5165 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5166
5167 // Build an unanalyzed expression if any of the operands is type-dependent.
5168 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5169 ColumnIdx->isTypeDependent())
5170 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5171 Context.DependentTy, RBLoc);
5172
5173 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5174 if (ColumnR.isInvalid())
5175 return ColumnR;
5176 ColumnIdx = ColumnR.get();
5177
5178 // Check that IndexExpr is an integer expression. If it is a constant
5179 // expression, check that it is less than Dim (= the number of elements in the
5180 // corresponding dimension).
5181 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5182 bool IsColumnIdx) -> Expr * {
5183 if (!IndexExpr->getType()->isIntegerType() &&
5184 !IndexExpr->isTypeDependent()) {
5185 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5186 << IsColumnIdx;
5187 return nullptr;
5188 }
5189
5190 if (std::optional<llvm::APSInt> Idx =
5191 IndexExpr->getIntegerConstantExpr(Context)) {
5192 if ((*Idx < 0 || *Idx >= Dim)) {
5193 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5194 << IsColumnIdx << Dim;
5195 return nullptr;
5196 }
5197 }
5198
5199 ExprResult ConvExpr = IndexExpr;
5200 assert(!ConvExpr.isInvalid() &&
5201 "should be able to convert any integer type to size type");
5202 return ConvExpr.get();
5203 };
5204
5205 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5206 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5207 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5208 if (!RowIdx || !ColumnIdx)
5209 return ExprError();
5210
5211 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5212 MTy->getElementType(), RBLoc);
5213}
5214
5215void Sema::CheckAddressOfNoDeref(const Expr *E) {
5216 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5217 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5218
5219 // For expressions like `&(*s).b`, the base is recorded and what should be
5220 // checked.
5221 const MemberExpr *Member = nullptr;
5222 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5223 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5224
5225 LastRecord.PossibleDerefs.erase(StrippedExpr);
5226}
5227
5228void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5230 return;
5231
5232 QualType ResultTy = E->getType();
5233 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5234
5235 // Bail if the element is an array since it is not memory access.
5236 if (isa<ArrayType>(ResultTy))
5237 return;
5238
5239 if (ResultTy->hasAttr(attr::NoDeref)) {
5240 LastRecord.PossibleDerefs.insert(E);
5241 return;
5242 }
5243
5244 // Check if the base type is a pointer to a member access of a struct
5245 // marked with noderef.
5246 const Expr *Base = E->getBase();
5247 QualType BaseTy = Base->getType();
5248 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5249 // Not a pointer access
5250 return;
5251
5252 const MemberExpr *Member = nullptr;
5253 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5254 Member->isArrow())
5255 Base = Member->getBase();
5256
5257 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5258 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5259 LastRecord.PossibleDerefs.insert(E);
5260 }
5261}
5262
5265 Expr *Idx, SourceLocation RLoc) {
5266 Expr *LHSExp = Base;
5267 Expr *RHSExp = Idx;
5268
5271
5272 // Per C++ core issue 1213, the result is an xvalue if either operand is
5273 // a non-lvalue array, and an lvalue otherwise.
5274 if (getLangOpts().CPlusPlus11) {
5275 for (auto *Op : {LHSExp, RHSExp}) {
5276 Op = Op->IgnoreImplicit();
5277 if (Op->getType()->isArrayType() && !Op->isLValue())
5278 VK = VK_XValue;
5279 }
5280 }
5281
5282 // Perform default conversions.
5283 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5285 if (Result.isInvalid())
5286 return ExprError();
5287 LHSExp = Result.get();
5288 }
5290 if (Result.isInvalid())
5291 return ExprError();
5292 RHSExp = Result.get();
5293
5294 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5295
5296 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5297 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5298 // in the subscript position. As a result, we need to derive the array base
5299 // and index from the expression types.
5300 Expr *BaseExpr, *IndexExpr;
5301 QualType ResultType;
5302 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5303 BaseExpr = LHSExp;
5304 IndexExpr = RHSExp;
5305 ResultType =
5307 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5308 BaseExpr = LHSExp;
5309 IndexExpr = RHSExp;
5310 ResultType = PTy->getPointeeType();
5311 } else if (const ObjCObjectPointerType *PTy =
5312 LHSTy->getAs<ObjCObjectPointerType>()) {
5313 BaseExpr = LHSExp;
5314 IndexExpr = RHSExp;
5315
5316 // Use custom logic if this should be the pseudo-object subscript
5317 // expression.
5318 if (!LangOpts.isSubscriptPointerArithmetic())
5319 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5320 nullptr, nullptr);
5321
5322 ResultType = PTy->getPointeeType();
5323 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5324 // Handle the uncommon case of "123[Ptr]".
5325 BaseExpr = RHSExp;
5326 IndexExpr = LHSExp;
5327 ResultType = PTy->getPointeeType();
5328 } else if (const ObjCObjectPointerType *PTy =
5329 RHSTy->getAs<ObjCObjectPointerType>()) {
5330 // Handle the uncommon case of "123[Ptr]".
5331 BaseExpr = RHSExp;
5332 IndexExpr = LHSExp;
5333 ResultType = PTy->getPointeeType();
5334 if (!LangOpts.isSubscriptPointerArithmetic()) {
5335 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5336 << ResultType << BaseExpr->getSourceRange();
5337 return ExprError();
5338 }
5339 } else if (LHSTy->isSubscriptableVectorType()) {
5340 if (LHSTy->isBuiltinType() &&
5341 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5342 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5343 if (BTy->isSVEBool())
5344 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5345 << LHSExp->getSourceRange()
5346 << RHSExp->getSourceRange());
5347 ResultType = BTy->getSveEltType(Context);
5348 } else {
5349 const VectorType *VTy = LHSTy->getAs<VectorType>();
5350 ResultType = VTy->getElementType();
5351 }
5352 BaseExpr = LHSExp; // vectors: V[123]
5353 IndexExpr = RHSExp;
5354 // We apply C++ DR1213 to vector subscripting too.
5355 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5356 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5357 if (Materialized.isInvalid())
5358 return ExprError();
5359 LHSExp = Materialized.get();
5360 }
5361 VK = LHSExp->getValueKind();
5362 if (VK != VK_PRValue)
5363 OK = OK_VectorComponent;
5364
5365 QualType BaseType = BaseExpr->getType();
5366 Qualifiers BaseQuals = BaseType.getQualifiers();
5367 Qualifiers MemberQuals = ResultType.getQualifiers();
5368 Qualifiers Combined = BaseQuals + MemberQuals;
5369 if (Combined != MemberQuals)
5370 ResultType = Context.getQualifiedType(ResultType, Combined);
5371 } else if (LHSTy->isArrayType()) {
5372 // If we see an array that wasn't promoted by
5373 // DefaultFunctionArrayLvalueConversion, it must be an array that
5374 // wasn't promoted because of the C90 rule that doesn't
5375 // allow promoting non-lvalue arrays. Warn, then
5376 // force the promotion here.
5377 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5378 << LHSExp->getSourceRange();
5379 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5380 CK_ArrayToPointerDecay).get();
5381 LHSTy = LHSExp->getType();
5382
5383 BaseExpr = LHSExp;
5384 IndexExpr = RHSExp;
5385 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5386 } else if (RHSTy->isArrayType()) {
5387 // Same as previous, except for 123[f().a] case
5388 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5389 << RHSExp->getSourceRange();
5390 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5391 CK_ArrayToPointerDecay).get();
5392 RHSTy = RHSExp->getType();
5393
5394 BaseExpr = RHSExp;
5395 IndexExpr = LHSExp;
5396 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5397 } else {
5398 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5399 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5400 }
5401 // C99 6.5.2.1p1
5402 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5403 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5404 << IndexExpr->getSourceRange());
5405
5406 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5407 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5408 !IndexExpr->isTypeDependent()) {
5409 std::optional<llvm::APSInt> IntegerContantExpr =
5411 if (!IntegerContantExpr.has_value() ||
5412 IntegerContantExpr.value().isNegative())
5413 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5414 }
5415
5416 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5417 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5418 // type. Note that Functions are not objects, and that (in C99 parlance)
5419 // incomplete types are not object types.
5420 if (ResultType->isFunctionType()) {
5421 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5422 << ResultType << BaseExpr->getSourceRange();
5423 return ExprError();
5424 }
5425
5426 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5427 // GNU extension: subscripting on pointer to void
5428 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5429 << BaseExpr->getSourceRange();
5430
5431 // C forbids expressions of unqualified void type from being l-values.
5432 // See IsCForbiddenLValueType.
5433 if (!ResultType.hasQualifiers())
5434 VK = VK_PRValue;
5435 } else if (!ResultType->isDependentType() &&
5436 !ResultType.isWebAssemblyReferenceType() &&
5438 LLoc, ResultType,
5439 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5440 return ExprError();
5441
5442 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5443 !ResultType.isCForbiddenLValueType());
5444
5446 FunctionScopes.size() > 1) {
5447 if (auto *TT =
5448 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5449 for (auto I = FunctionScopes.rbegin(),
5450 E = std::prev(FunctionScopes.rend());
5451 I != E; ++I) {
5452 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5453 if (CSI == nullptr)
5454 break;
5455 DeclContext *DC = nullptr;
5456 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5457 DC = LSI->CallOperator;
5458 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5459 DC = CRSI->TheCapturedDecl;
5460 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5461 DC = BSI->TheDecl;
5462 if (DC) {
5463 if (DC->containsDecl(TT->getDecl()))
5464 break;
5466 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5467 }
5468 }
5469 }
5470 }
5471
5472 return new (Context)
5473 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5474}
5475
5477 ParmVarDecl *Param, Expr *RewrittenInit,
5478 bool SkipImmediateInvocations) {
5479 if (Param->hasUnparsedDefaultArg()) {
5480 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5481 // If we've already cleared out the location for the default argument,
5482 // that means we're parsing it right now.
5483 if (!UnparsedDefaultArgLocs.count(Param)) {
5484 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5485 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5486 Param->setInvalidDecl();
5487 return true;
5488 }
5489
5490 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5491 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5493 diag::note_default_argument_declared_here);
5494 return true;
5495 }
5496
5497 if (Param->hasUninstantiatedDefaultArg()) {
5498 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5499 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5500 return true;
5501 }
5502
5503 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5504 assert(Init && "default argument but no initializer?");
5505
5506 // If the default expression creates temporaries, we need to
5507 // push them to the current stack of expression temporaries so they'll
5508 // be properly destroyed.
5509 // FIXME: We should really be rebuilding the default argument with new
5510 // bound temporaries; see the comment in PR5810.
5511 // We don't need to do that with block decls, though, because
5512 // blocks in default argument expression can never capture anything.
5513 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5514 // Set the "needs cleanups" bit regardless of whether there are
5515 // any explicit objects.
5516 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5517 // Append all the objects to the cleanup list. Right now, this
5518 // should always be a no-op, because blocks in default argument
5519 // expressions should never be able to capture anything.
5520 assert(!InitWithCleanup->getNumObjects() &&
5521 "default argument expression has capturing blocks?");
5522 }
5523 // C++ [expr.const]p15.1:
5524 // An expression or conversion is in an immediate function context if it is
5525 // potentially evaluated and [...] its innermost enclosing non-block scope
5526 // is a function parameter scope of an immediate function.
5528 *this,
5532 Param);
5533 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5534 SkipImmediateInvocations;
5535 runWithSufficientStackSpace(CallLoc, [&] {
5536 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5537 });
5538 return false;
5539}
5540
5545 }
5546
5547 bool HasImmediateCalls = false;
5548
5549 bool VisitCallExpr(CallExpr *E) override {
5550 if (const FunctionDecl *FD = E->getDirectCallee())
5551 HasImmediateCalls |= FD->isImmediateFunction();
5553 }
5554
5556 if (const FunctionDecl *FD = E->getConstructor())
5557 HasImmediateCalls |= FD->isImmediateFunction();
5559 }
5560
5561 // SourceLocExpr are not immediate invocations
5562 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5563 // need to be rebuilt so that they refer to the correct SourceLocation and
5564 // DeclContext.
5566 HasImmediateCalls = true;
5568 }
5569
5570 // A nested lambda might have parameters with immediate invocations
5571 // in their default arguments.
5572 // The compound statement is not visited (as it does not constitute a
5573 // subexpression).
5574 // FIXME: We should consider visiting and transforming captures
5575 // with init expressions.
5576 bool VisitLambdaExpr(LambdaExpr *E) override {
5577 return VisitCXXMethodDecl(E->getCallOperator());
5578 }
5579
5581 return TraverseStmt(E->getExpr());
5582 }
5583
5585 return TraverseStmt(E->getExpr());
5586 }
5587};
5588
5590 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5593
5594 bool AlwaysRebuild() { return true; }
5595
5596 // Lambda can only have immediate invocations in the default
5597 // args of their parameters, which is transformed upon calling the closure.
5598 // The body is not a subexpression, so we have nothing to do.
5599 // FIXME: Immediate calls in capture initializers should be transformed.
5602
5603 // Make sure we don't rebuild the this pointer as it would
5604 // cause it to incorrectly point it to the outermost class
5605 // in the case of nested struct initialization.
5607
5608 // Rewrite to source location to refer to the context in which they are used.
5610 DeclContext *DC = E->getParentContext();
5611 if (DC == SemaRef.CurContext)
5612 return E;
5613
5614 // FIXME: During instantiation, because the rebuild of defaults arguments
5615 // is not always done in the context of the template instantiator,
5616 // we run the risk of producing a dependent source location
5617 // that would never be rebuilt.
5618 // This usually happens during overload resolution, or in contexts
5619 // where the value of the source location does not matter.
5620 // However, we should find a better way to deal with source location
5621 // of function templates.
5622 if (!SemaRef.CurrentInstantiationScope ||
5623 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5624 DC = SemaRef.CurContext;
5625
5626 return getDerived().RebuildSourceLocExpr(
5627 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5628 }
5629};
5630
5632 FunctionDecl *FD, ParmVarDecl *Param,
5633 Expr *Init) {
5634 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5635
5636 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5637 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5638 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5639 InitializationContext =
5641 if (!InitializationContext.has_value())
5642 InitializationContext.emplace(CallLoc, Param, CurContext);
5643
5644 if (!Init && !Param->hasUnparsedDefaultArg()) {
5645 // Mark that we are replacing a default argument first.
5646 // If we are instantiating a template we won't have to
5647 // retransform immediate calls.
5648 // C++ [expr.const]p15.1:
5649 // An expression or conversion is in an immediate function context if it
5650 // is potentially evaluated and [...] its innermost enclosing non-block
5651 // scope is a function parameter scope of an immediate function.
5653 *this,
5657 Param);
5658
5659 if (Param->hasUninstantiatedDefaultArg()) {
5660 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5661 return ExprError();
5662 }
5663 // CWG2631
5664 // An immediate invocation that is not evaluated where it appears is
5665 // evaluated and checked for whether it is a constant expression at the
5666 // point where the enclosing initializer is used in a function call.
5668 if (!NestedDefaultChecking)
5669 V.TraverseDecl(Param);
5670
5671 // Rewrite the call argument that was created from the corresponding
5672 // parameter's default argument.
5673 if (V.HasImmediateCalls ||
5674 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5675 if (V.HasImmediateCalls)
5676 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5677 CallLoc, Param, CurContext};
5678 // Pass down lifetime extending flag, and collect temporaries in
5679 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5683 ExprResult Res;
5684 runWithSufficientStackSpace(CallLoc, [&] {
5685 Res = Immediate.TransformInitializer(Param->getInit(),
5686 /*NotCopy=*/false);
5687 });
5688 if (Res.isInvalid())
5689 return ExprError();
5690 Res = ConvertParamDefaultArgument(Param, Res.get(),
5691 Res.get()->getBeginLoc());
5692 if (Res.isInvalid())
5693 return ExprError();
5694 Init = Res.get();
5695 }
5696 }
5697
5699 CallLoc, FD, Param, Init,
5700 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5701 return ExprError();
5702
5703 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5704 Init, InitializationContext->Context);
5705}
5706
5708 FieldDecl *Field) {
5709 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5710 return Pattern;
5711 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5712 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5714 ClassPattern->lookup(Field->getDeclName());
5715 auto Rng = llvm::make_filter_range(
5716 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5717 if (Rng.empty())
5718 return nullptr;
5719 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5720 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5721 // && "Duplicated instantiation pattern for field decl");
5722 return cast<FieldDecl>(*Rng.begin());
5723}
5724
5726 assert(Field->hasInClassInitializer());
5727
5728 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5729
5730 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5731
5732 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5733 InitializationContext =
5735 if (!InitializationContext.has_value())
5736 InitializationContext.emplace(Loc, Field, CurContext);
5737
5738 Expr *Init = nullptr;
5739
5740 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5741 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5744
5745 if (!Field->getInClassInitializer()) {
5746 // Maybe we haven't instantiated the in-class initializer. Go check the
5747 // pattern FieldDecl to see if it has one.
5748 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5749 FieldDecl *Pattern =
5751 assert(Pattern && "We must have set the Pattern!");
5752 if (!Pattern->hasInClassInitializer() ||
5753 InstantiateInClassInitializer(Loc, Field, Pattern,
5755 Field->setInvalidDecl();
5756 return ExprError();
5757 }
5758 }
5759 }
5760
5761 // CWG2631
5762 // An immediate invocation that is not evaluated where it appears is
5763 // evaluated and checked for whether it is a constant expression at the
5764 // point where the enclosing initializer is used in a [...] a constructor
5765 // definition, or an aggregate initialization.
5767 if (!NestedDefaultChecking)
5768 V.TraverseDecl(Field);
5769
5770 // CWG1815
5771 // Support lifetime extension of temporary created by aggregate
5772 // initialization using a default member initializer. We should rebuild
5773 // the initializer in a lifetime extension context if the initializer
5774 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5775 // extension code recurses into the default initializer and does lifetime
5776 // extension when warranted.
5777 bool ContainsAnyTemporaries =
5778 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5779 if (Field->getInClassInitializer() &&
5780 !Field->getInClassInitializer()->containsErrors() &&
5781 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5782 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5783 CurContext};
5784 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5785 NestedDefaultChecking;
5786 // Pass down lifetime extending flag, and collect temporaries in
5787 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5791 ExprResult Res;
5793 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5794 /*CXXDirectInit=*/false);
5795 });
5796 if (!Res.isInvalid())
5797 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5798 if (Res.isInvalid()) {
5799 Field->setInvalidDecl();
5800 return ExprError();
5801 }
5802 Init = Res.get();
5803 }
5804
5805 if (Field->getInClassInitializer()) {
5806 Expr *E = Init ? Init : Field->getInClassInitializer();
5807 if (!NestedDefaultChecking)
5809 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5810 });
5813 // C++11 [class.base.init]p7:
5814 // The initialization of each base and member constitutes a
5815 // full-expression.
5816 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5817 if (Res.isInvalid()) {
5818 Field->setInvalidDecl();
5819 return ExprError();
5820 }
5821 Init = Res.get();
5822
5823 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5824 Field, InitializationContext->Context,
5825 Init);
5826 }
5827
5828 // DR1351:
5829 // If the brace-or-equal-initializer of a non-static data member
5830 // invokes a defaulted default constructor of its class or of an
5831 // enclosing class in a potentially evaluated subexpression, the
5832 // program is ill-formed.
5833 //
5834 // This resolution is unworkable: the exception specification of the
5835 // default constructor can be needed in an unevaluated context, in
5836 // particular, in the operand of a noexcept-expression, and we can be
5837 // unable to compute an exception specification for an enclosed class.
5838 //
5839 // Any attempt to resolve the exception specification of a defaulted default
5840 // constructor before the initializer is lexically complete will ultimately
5841 // come here at which point we can diagnose it.
5842 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5843 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5844 << OutermostClass << Field;
5845 Diag(Field->getEndLoc(),
5846 diag::note_default_member_initializer_not_yet_parsed);
5847 // Recover by marking the field invalid, unless we're in a SFINAE context.
5848 if (!isSFINAEContext())
5849 Field->setInvalidDecl();
5850 return ExprError();
5851}
5852
5854 const FunctionProtoType *Proto,
5855 Expr *Fn) {
5856 if (Proto && Proto->isVariadic()) {
5857 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5859 else if (Fn && Fn->getType()->isBlockPointerType())
5861 else if (FDecl) {
5862 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5863 if (Method->isInstance())
5865 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5868 }
5870}
5871
5872namespace {
5873class FunctionCallCCC final : public FunctionCallFilterCCC {
5874public:
5875 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5876 unsigned NumArgs, MemberExpr *ME)
5877 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5878 FunctionName(FuncName) {}
5879
5880 bool ValidateCandidate(const TypoCorrection &candidate) override {
5881 if (!candidate.getCorrectionSpecifier() ||
5882 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5883 return false;
5884 }
5885
5887 }
5888
5889 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5890 return std::make_unique<FunctionCallCCC>(*this);
5891 }
5892
5893private:
5894 const IdentifierInfo *const FunctionName;
5895};
5896}
5897
5899 FunctionDecl *FDecl,
5900 ArrayRef<Expr *> Args) {
5901 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5902 DeclarationName FuncName = FDecl->getDeclName();
5903 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5904
5905 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5906 if (TypoCorrection Corrected = S.CorrectTypo(
5908 S.getScopeForContext(S.CurContext), nullptr, CCC,
5910 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5911 if (Corrected.isOverloaded()) {
5914 for (NamedDecl *CD : Corrected) {
5915 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5917 OCS);
5918 }
5919 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5920 case OR_Success:
5921 ND = Best->FoundDecl;
5922 Corrected.setCorrectionDecl(ND);
5923 break;
5924 default:
5925 break;
5926 }
5927 }
5928 ND = ND->getUnderlyingDecl();
5930 return Corrected;
5931 }
5932 }
5933 return TypoCorrection();
5934}
5935
5936// [C++26][[expr.unary.op]/p4
5937// A pointer to member is only formed when an explicit &
5938// is used and its operand is a qualified-id not enclosed in parentheses.
5940 if (!isa<ParenExpr>(Fn))
5941 return false;
5942
5943 Fn = Fn->IgnoreParens();
5944
5945 auto *UO = dyn_cast<UnaryOperator>(Fn);
5946 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5947 return false;
5948 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5949 return DRE->hasQualifier();
5950 }
5951 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5952 return bool(OVL->getQualifier());
5953 return false;
5954}
5955
5956bool
5958 FunctionDecl *FDecl,
5959 const FunctionProtoType *Proto,
5960 ArrayRef<Expr *> Args,
5961 SourceLocation RParenLoc,
5962 bool IsExecConfig) {
5963 // Bail out early if calling a builtin with custom typechecking.
5964 if (FDecl)
5965 if (unsigned ID = FDecl->getBuiltinID())
5966 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5967 return false;
5968
5969 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5970 // assignment, to the types of the corresponding parameter, ...
5971
5972 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5973 bool HasExplicitObjectParameter =
5974 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5975 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5976 unsigned NumParams = Proto->getNumParams();
5977 bool Invalid = false;
5978 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5979 unsigned FnKind = Fn->getType()->isBlockPointerType()
5980 ? 1 /* block */
5981 : (IsExecConfig ? 3 /* kernel function (exec config) */
5982 : 0 /* function */);
5983
5984 // If too few arguments are available (and we don't have default
5985 // arguments for the remaining parameters), don't make the call.
5986 if (Args.size() < NumParams) {
5987 if (Args.size() < MinArgs) {
5988 TypoCorrection TC;
5989 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5990 unsigned diag_id =
5991 MinArgs == NumParams && !Proto->isVariadic()
5992 ? diag::err_typecheck_call_too_few_args_suggest
5993 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5995 TC, PDiag(diag_id)
5996 << FnKind << MinArgs - ExplicitObjectParameterOffset
5997 << static_cast<unsigned>(Args.size()) -
5998 ExplicitObjectParameterOffset
5999 << HasExplicitObjectParameter << TC.getCorrectionRange());
6000 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6001 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6002 ->getDeclName())
6003 Diag(RParenLoc,
6004 MinArgs == NumParams && !Proto->isVariadic()
6005 ? diag::err_typecheck_call_too_few_args_one
6006 : diag::err_typecheck_call_too_few_args_at_least_one)
6007 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6008 << HasExplicitObjectParameter << Fn->getSourceRange();
6009 else
6010 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6011 ? diag::err_typecheck_call_too_few_args
6012 : diag::err_typecheck_call_too_few_args_at_least)
6013 << FnKind << MinArgs - ExplicitObjectParameterOffset
6014 << static_cast<unsigned>(Args.size()) -
6015 ExplicitObjectParameterOffset
6016 << HasExplicitObjectParameter << Fn->getSourceRange();
6017
6018 // Emit the location of the prototype.
6019 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6020 Diag(FDecl->getLocation(), diag::note_callee_decl)
6021 << FDecl << FDecl->getParametersSourceRange();
6022
6023 return true;
6024 }
6025 // We reserve space for the default arguments when we create
6026 // the call expression, before calling ConvertArgumentsForCall.
6027 assert((Call->getNumArgs() == NumParams) &&
6028 "We should have reserved space for the default arguments before!");
6029 }
6030
6031 // If too many are passed and not variadic, error on the extras and drop
6032 // them.
6033 if (Args.size() > NumParams) {
6034 if (!Proto->isVariadic()) {
6035 TypoCorrection TC;
6036 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6037 unsigned diag_id =
6038 MinArgs == NumParams && !Proto->isVariadic()
6039 ? diag::err_typecheck_call_too_many_args_suggest
6040 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6042 TC, PDiag(diag_id)
6043 << FnKind << NumParams - ExplicitObjectParameterOffset
6044 << static_cast<unsigned>(Args.size()) -
6045 ExplicitObjectParameterOffset
6046 << HasExplicitObjectParameter << TC.getCorrectionRange());
6047 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6048 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6049 ->getDeclName())
6050 Diag(Args[NumParams]->getBeginLoc(),
6051 MinArgs == NumParams
6052 ? diag::err_typecheck_call_too_many_args_one
6053 : diag::err_typecheck_call_too_many_args_at_most_one)
6054 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6055 << static_cast<unsigned>(Args.size()) -
6056 ExplicitObjectParameterOffset
6057 << HasExplicitObjectParameter << Fn->getSourceRange()
6058 << SourceRange(Args[NumParams]->getBeginLoc(),
6059 Args.back()->getEndLoc());
6060 else
6061 Diag(Args[NumParams]->getBeginLoc(),
6062 MinArgs == NumParams
6063 ? diag::err_typecheck_call_too_many_args
6064 : diag::err_typecheck_call_too_many_args_at_most)
6065 << FnKind << NumParams - ExplicitObjectParameterOffset
6066 << static_cast<unsigned>(Args.size()) -
6067 ExplicitObjectParameterOffset
6068 << HasExplicitObjectParameter << Fn->getSourceRange()
6069 << SourceRange(Args[NumParams]->getBeginLoc(),
6070 Args.back()->getEndLoc());
6071
6072 // Emit the location of the prototype.
6073 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6074 Diag(FDecl->getLocation(), diag::note_callee_decl)
6075 << FDecl << FDecl->getParametersSourceRange();
6076
6077 // This deletes the extra arguments.
6078 Call->shrinkNumArgs(NumParams);
6079 return true;
6080 }
6081 }
6082 SmallVector<Expr *, 8> AllArgs;
6083 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6084
6085 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6086 AllArgs, CallType);
6087 if (Invalid)
6088 return true;
6089 unsigned TotalNumArgs = AllArgs.size();
6090 for (unsigned i = 0; i < TotalNumArgs; ++i)
6091 Call->setArg(i, AllArgs[i]);
6092
6093 Call->computeDependence();
6094 return false;
6095}
6096
6098 const FunctionProtoType *Proto,
6099 unsigned FirstParam, ArrayRef<Expr *> Args,
6100 SmallVectorImpl<Expr *> &AllArgs,
6101 VariadicCallType CallType, bool AllowExplicit,
6102 bool IsListInitialization) {
6103 unsigned NumParams = Proto->getNumParams();
6104 bool Invalid = false;
6105 size_t ArgIx = 0;
6106 // Continue to check argument types (even if we have too few/many args).
6107 for (unsigned i = FirstParam; i < NumParams; i++) {
6108 QualType ProtoArgType = Proto->getParamType(i);
6109
6110 Expr *Arg;
6111 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6112 if (ArgIx < Args.size()) {
6113 Arg = Args[ArgIx++];
6114
6115 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6116 diag::err_call_incomplete_argument, Arg))
6117 return true;
6118
6119 // Strip the unbridged-cast placeholder expression off, if applicable.
6120 bool CFAudited = false;
6121 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6122 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6123 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6124 Arg = ObjC().stripARCUnbridgedCast(Arg);
6125 else if (getLangOpts().ObjCAutoRefCount &&
6126 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6127 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6128 CFAudited = true;
6129
6130 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6131 ProtoArgType->isBlockPointerType())
6132 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6133 BE->getBlockDecl()->setDoesNotEscape();
6134 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6136 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6137 if (ArgExpr.isInvalid())
6138 return true;
6139 Arg = ArgExpr.getAs<Expr>();
6140 }
6141
6142 InitializedEntity Entity =
6144 ProtoArgType)
6146 Context, ProtoArgType, Proto->isParamConsumed(i));
6147
6148 // Remember that parameter belongs to a CF audited API.
6149 if (CFAudited)
6150 Entity.setParameterCFAudited();
6151
6153 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6154 if (ArgE.isInvalid())
6155 return true;
6156
6157 Arg = ArgE.getAs<Expr>();
6158 } else {
6159 assert(Param && "can't use default arguments without a known callee");
6160
6161 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6162 if (ArgExpr.isInvalid())
6163 return true;
6164
6165 Arg = ArgExpr.getAs<Expr>();
6166 }
6167
6168 // Check for array bounds violations for each argument to the call. This
6169 // check only triggers warnings when the argument isn't a more complex Expr
6170 // with its own checking, such as a BinaryOperator.
6171 CheckArrayAccess(Arg);
6172
6173 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6174 CheckStaticArrayArgument(CallLoc, Param, Arg);
6175
6176 AllArgs.push_back(Arg);
6177 }
6178
6179 // If this is a variadic call, handle args passed through "...".
6180 if (CallType != VariadicCallType::DoesNotApply) {
6181 // Assume that extern "C" functions with variadic arguments that
6182 // return __unknown_anytype aren't *really* variadic.
6183 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6184 FDecl->isExternC()) {
6185 for (Expr *A : Args.slice(ArgIx)) {
6186 QualType paramType; // ignored
6187 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6188 Invalid |= arg.isInvalid();
6189 AllArgs.push_back(arg.get());
6190 }
6191
6192 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6193 } else {
6194 for (Expr *A : Args.slice(ArgIx)) {
6195 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6196 Invalid |= Arg.isInvalid();
6197 AllArgs.push_back(Arg.get());
6198 }
6199 }
6200
6201 // Check for array bounds violations.
6202 for (Expr *A : Args.slice(ArgIx))
6203 CheckArrayAccess(A);
6204 }
6205 return Invalid;
6206}
6207
6209 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6210 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6211 TL = DTL.getOriginalLoc();
6212 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6213 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6214 << ATL.getLocalSourceRange();
6215}
6216
6217void
6219 ParmVarDecl *Param,
6220 const Expr *ArgExpr) {
6221 // Static array parameters are not supported in C++.
6222 if (!Param || getLangOpts().CPlusPlus)
6223 return;
6224
6225 QualType OrigTy = Param->getOriginalType();
6226
6227 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6228 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6229 return;
6230
6231 if (ArgExpr->isNullPointerConstant(Context,
6233 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6234 DiagnoseCalleeStaticArrayParam(*this, Param);
6235 return;
6236 }
6237
6238 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6239 if (!CAT)
6240 return;
6241
6242 const ConstantArrayType *ArgCAT =
6243 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6244 if (!ArgCAT)
6245 return;
6246
6247 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6248 ArgCAT->getElementType())) {
6249 if (ArgCAT->getSize().ult(CAT->getSize())) {
6250 Diag(CallLoc, diag::warn_static_array_too_small)
6251 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6252 << (unsigned)CAT->getZExtSize() << 0;
6253 DiagnoseCalleeStaticArrayParam(*this, Param);
6254 }
6255 return;
6256 }
6257
6258 std::optional<CharUnits> ArgSize =
6260 std::optional<CharUnits> ParmSize =
6262 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6263 Diag(CallLoc, diag::warn_static_array_too_small)
6264 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6265 << (unsigned)ParmSize->getQuantity() << 1;
6266 DiagnoseCalleeStaticArrayParam(*this, Param);
6267 }
6268}
6269
6270/// Given a function expression of unknown-any type, try to rebuild it
6271/// to have a function type.
6273
6274/// Is the given type a placeholder that we need to lower out
6275/// immediately during argument processing?
6277 // Placeholders are never sugared.
6278 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6279 if (!placeholder) return false;
6280
6281 switch (placeholder->getKind()) {
6282 // Ignore all the non-placeholder types.
6283#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6284 case BuiltinType::Id:
6285#include "clang/Basic/OpenCLImageTypes.def"
6286#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6287 case BuiltinType::Id:
6288#include "clang/Basic/OpenCLExtensionTypes.def"
6289 // In practice we'll never use this, since all SVE types are sugared
6290 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6291#define SVE_TYPE(Name, Id, SingletonId) \
6292 case BuiltinType::Id:
6293#include "clang/Basic/AArch64ACLETypes.def"
6294#define PPC_VECTOR_TYPE(Name, Id, Size) \
6295 case BuiltinType::Id:
6296#include "clang/Basic/PPCTypes.def"
6297#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6298#include "clang/Basic/RISCVVTypes.def"
6299#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6300#include "clang/Basic/WebAssemblyReferenceTypes.def"
6301#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6302#include "clang/Basic/AMDGPUTypes.def"
6303#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6304#include "clang/Basic/HLSLIntangibleTypes.def"
6305#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6306#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6307#include "clang/AST/BuiltinTypes.def"
6308 return false;
6309
6310 case BuiltinType::UnresolvedTemplate:
6311 // We cannot lower out overload sets; they might validly be resolved
6312 // by the call machinery.
6313 case BuiltinType::Overload:
6314 return false;
6315
6316 // Unbridged casts in ARC can be handled in some call positions and
6317 // should be left in place.
6318 case BuiltinType::ARCUnbridgedCast:
6319 return false;
6320
6321 // Pseudo-objects should be converted as soon as possible.
6322 case BuiltinType::PseudoObject:
6323 return true;
6324
6325 // The debugger mode could theoretically but currently does not try
6326 // to resolve unknown-typed arguments based on known parameter types.
6327 case BuiltinType::UnknownAny:
6328 return true;
6329
6330 // These are always invalid as call arguments and should be reported.
6331 case BuiltinType::BoundMember:
6332 case BuiltinType::BuiltinFn:
6333 case BuiltinType::IncompleteMatrixIdx:
6334 case BuiltinType::ArraySection:
6335 case BuiltinType::OMPArrayShaping:
6336 case BuiltinType::OMPIterator:
6337 return true;
6338
6339 }
6340 llvm_unreachable("bad builtin type kind");
6341}
6342
6344 // Apply this processing to all the arguments at once instead of
6345 // dying at the first failure.
6346 bool hasInvalid = false;
6347 for (size_t i = 0, e = args.size(); i != e; i++) {
6348 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6349 ExprResult result = CheckPlaceholderExpr(args[i]);
6350 if (result.isInvalid()) hasInvalid = true;
6351 else args[i] = result.get();
6352 }
6353 }
6354 return hasInvalid;
6355}
6356
6357/// If a builtin function has a pointer argument with no explicit address
6358/// space, then it should be able to accept a pointer to any address
6359/// space as input. In order to do this, we need to replace the
6360/// standard builtin declaration with one that uses the same address space
6361/// as the call.
6362///
6363/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6364/// it does not contain any pointer arguments without
6365/// an address space qualifer. Otherwise the rewritten
6366/// FunctionDecl is returned.
6367/// TODO: Handle pointer return types.
6369 FunctionDecl *FDecl,
6370 MultiExprArg ArgExprs) {
6371
6372 QualType DeclType = FDecl->getType();
6373 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6374
6375 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6376 ArgExprs.size() < FT->getNumParams())
6377 return nullptr;
6378
6379 bool NeedsNewDecl = false;
6380 unsigned i = 0;
6381 SmallVector<QualType, 8> OverloadParams;
6382
6383 {
6384 // The lvalue conversions in this loop are only for type resolution and
6385 // don't actually occur.
6388 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6389
6390 for (QualType ParamType : FT->param_types()) {
6391
6392 // Convert array arguments to pointer to simplify type lookup.
6393 ExprResult ArgRes =
6395 if (ArgRes.isInvalid())
6396 return nullptr;
6397 Expr *Arg = ArgRes.get();
6398 QualType ArgType = Arg->getType();
6399 if (!ParamType->isPointerType() ||
6400 ParamType->getPointeeType().hasAddressSpace() ||
6401 !ArgType->isPointerType() ||
6402 !ArgType->getPointeeType().hasAddressSpace() ||
6403 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6404 OverloadParams.push_back(ParamType);
6405 continue;
6406 }
6407
6408 QualType PointeeType = ParamType->getPointeeType();
6409 NeedsNewDecl = true;
6410 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6411
6412 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6413 OverloadParams.push_back(Context.getPointerType(PointeeType));
6414 }
6415 }
6416
6417 if (!NeedsNewDecl)
6418 return nullptr;
6419
6421 EPI.Variadic = FT->isVariadic();
6422 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6423 OverloadParams, EPI);
6424 DeclContext *Parent = FDecl->getParent();
6425 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6426 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6427 FDecl->getIdentifier(), OverloadTy,
6428 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6429 false,
6430 /*hasPrototype=*/true);
6432 FT = cast<FunctionProtoType>(OverloadTy);
6433 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6434 QualType ParamType = FT->getParamType(i);
6435 ParmVarDecl *Parm =
6436 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6437 SourceLocation(), nullptr, ParamType,
6438 /*TInfo=*/nullptr, SC_None, nullptr);
6439 Parm->setScopeInfo(0, i);
6440 Params.push_back(Parm);
6441 }
6442 OverloadDecl->setParams(Params);
6443 // We cannot merge host/device attributes of redeclarations. They have to
6444 // be consistent when created.
6445 if (Sema->LangOpts.CUDA) {
6446 if (FDecl->hasAttr<CUDAHostAttr>())
6447 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6448 if (FDecl->hasAttr<CUDADeviceAttr>())
6449 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6450 }
6451 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6452 return OverloadDecl;
6453}
6454
6455static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6456 FunctionDecl *Callee,
6457 MultiExprArg ArgExprs) {
6458 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6459 // similar attributes) really don't like it when functions are called with an
6460 // invalid number of args.
6461 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6462 /*PartialOverloading=*/false) &&
6463 !Callee->isVariadic())
6464 return;
6465 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6466 return;
6467
6468 if (const EnableIfAttr *Attr =
6469 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6470 S.Diag(Fn->getBeginLoc(),
6471 isa<CXXMethodDecl>(Callee)
6472 ? diag::err_ovl_no_viable_member_function_in_call
6473 : diag::err_ovl_no_viable_function_in_call)
6474 << Callee << Callee->getSourceRange();
6475 S.Diag(Callee->getLocation(),
6476 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6477 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6478 return;
6479 }
6480}
6481
6483 const UnresolvedMemberExpr *const UME, Sema &S) {
6484
6485 const auto GetFunctionLevelDCIfCXXClass =
6486 [](Sema &S) -> const CXXRecordDecl * {
6487 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6488 if (!DC || !DC->getParent())
6489 return nullptr;
6490
6491 // If the call to some member function was made from within a member
6492 // function body 'M' return return 'M's parent.
6493 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6494 return MD->getParent()->getCanonicalDecl();
6495 // else the call was made from within a default member initializer of a
6496 // class, so return the class.
6497 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6498 return RD->getCanonicalDecl();
6499 return nullptr;
6500 };
6501 // If our DeclContext is neither a member function nor a class (in the
6502 // case of a lambda in a default member initializer), we can't have an
6503 // enclosing 'this'.
6504
6505 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6506 if (!CurParentClass)
6507 return false;
6508
6509 // The naming class for implicit member functions call is the class in which
6510 // name lookup starts.
6511 const CXXRecordDecl *const NamingClass =
6513 assert(NamingClass && "Must have naming class even for implicit access");
6514
6515 // If the unresolved member functions were found in a 'naming class' that is
6516 // related (either the same or derived from) to the class that contains the
6517 // member function that itself contained the implicit member access.
6518
6519 return CurParentClass == NamingClass ||
6520 CurParentClass->isDerivedFrom(NamingClass);
6521}
6522
6523static void
6525 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6526
6527 if (!UME)
6528 return;
6529
6530 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6531 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6532 // already been captured, or if this is an implicit member function call (if
6533 // it isn't, an attempt to capture 'this' should already have been made).
6534 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6535 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6536 return;
6537
6538 // Check if the naming class in which the unresolved members were found is
6539 // related (same as or is a base of) to the enclosing class.
6540
6542 return;
6543
6544
6545 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6546 // If the enclosing function is not dependent, then this lambda is
6547 // capture ready, so if we can capture this, do so.
6548 if (!EnclosingFunctionCtx->isDependentContext()) {
6549 // If the current lambda and all enclosing lambdas can capture 'this' -
6550 // then go ahead and capture 'this' (since our unresolved overload set
6551 // contains at least one non-static member function).
6552 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6553 S.CheckCXXThisCapture(CallLoc);
6554 } else if (S.CurContext->isDependentContext()) {
6555 // ... since this is an implicit member reference, that might potentially
6556 // involve a 'this' capture, mark 'this' for potential capture in
6557 // enclosing lambdas.
6558 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6559 CurLSI->addPotentialThisCapture(CallLoc);
6560 }
6561}
6562
6563// Once a call is fully resolved, warn for unqualified calls to specific
6564// C++ standard functions, like move and forward.
6566 const CallExpr *Call) {
6567 // We are only checking unary move and forward so exit early here.
6568 if (Call->getNumArgs() != 1)
6569 return;
6570
6571 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6572 if (!E || isa<UnresolvedLookupExpr>(E))
6573 return;
6574 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6575 if (!DRE || !DRE->getLocation().isValid())
6576 return;
6577
6578 if (DRE->getQualifier())
6579 return;
6580
6581 const FunctionDecl *FD = Call->getDirectCallee();
6582 if (!FD)
6583 return;
6584
6585 // Only warn for some functions deemed more frequent or problematic.
6586 unsigned BuiltinID = FD->getBuiltinID();
6587 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6588 return;
6589
6590 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6592 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6593}
6594
6596 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6597 Expr *ExecConfig) {
6599 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6600 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6601 if (Call.isInvalid())
6602 return Call;
6603
6604 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6605 // language modes.
6606 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6607 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6608 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6609 << ULE->getName();
6610 }
6611
6612 if (LangOpts.OpenMP)
6613 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6614 ExecConfig);
6615 if (LangOpts.CPlusPlus) {
6616 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6618
6619 // If we previously found that the id-expression of this call refers to a
6620 // consteval function but the call is dependent, we should not treat is an
6621 // an invalid immediate call.
6622 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6623 DRE && Call.get()->isValueDependent()) {
6625 }
6626 }
6627 return Call;
6628}
6629
6630// Any type that could be used to form a callable expression
6631static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6632 QualType T = E->getType();
6633 if (T->isDependentType())
6634 return true;
6635
6636 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6637 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6638 T->isFunctionType() || T->isFunctionReferenceType() ||
6639 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6640 T->isBlockPointerType() || T->isRecordType())
6641 return true;
6642
6645}
6646
6648 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6649 Expr *ExecConfig, bool IsExecConfig,
6650 bool AllowRecovery) {
6651 // Since this might be a postfix expression, get rid of ParenListExprs.
6653 if (Result.isInvalid()) return ExprError();
6654 Fn = Result.get();
6655
6656 if (CheckArgsForPlaceholders(ArgExprs))
6657 return ExprError();
6658
6659 // The result of __builtin_counted_by_ref cannot be used as a function
6660 // argument. It allows leaking and modification of bounds safety information.
6661 for (const Expr *Arg : ArgExprs)
6662 if (CheckInvalidBuiltinCountedByRef(Arg,
6664 return ExprError();
6665
6666 if (getLangOpts().CPlusPlus) {
6667 // If this is a pseudo-destructor expression, build the call immediately.
6669 if (!ArgExprs.empty()) {
6670 // Pseudo-destructor calls should not have any arguments.
6671 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6673 SourceRange(ArgExprs.front()->getBeginLoc(),
6674 ArgExprs.back()->getEndLoc()));
6675 }
6676
6677 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6678 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6679 }
6680 if (Fn->getType() == Context.PseudoObjectTy) {
6681 ExprResult result = CheckPlaceholderExpr(Fn);
6682 if (result.isInvalid()) return ExprError();
6683 Fn = result.get();
6684 }
6685
6686 // Determine whether this is a dependent call inside a C++ template,
6687 // in which case we won't do any semantic analysis now.
6688 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6689 if (ExecConfig) {
6691 cast<CallExpr>(ExecConfig), ArgExprs,
6692 Context.DependentTy, VK_PRValue,
6693 RParenLoc, CurFPFeatureOverrides());
6694 } else {
6695
6697 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6698 Fn->getBeginLoc());
6699
6700 // If the type of the function itself is not dependent
6701 // check that it is a reasonable as a function, as type deduction
6702 // later assume the CallExpr has a sensible TYPE.
6703 if (!MayBeFunctionType(Context, Fn))
6704 return ExprError(
6705 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6706 << Fn->getType() << Fn->getSourceRange());
6707
6708 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6709 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6710 }
6711 }
6712
6713 // Determine whether this is a call to an object (C++ [over.call.object]).
6714 if (Fn->getType()->isRecordType())
6715 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6716 RParenLoc);
6717
6718 if (Fn->getType() == Context.UnknownAnyTy) {
6719 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6720 if (result.isInvalid()) return ExprError();
6721 Fn = result.get();
6722 }
6723
6724 if (Fn->getType() == Context.BoundMemberTy) {
6725 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6726 RParenLoc, ExecConfig, IsExecConfig,
6727 AllowRecovery);
6728 }
6729 }
6730
6731 // Check for overloaded calls. This can happen even in C due to extensions.
6732 if (Fn->getType() == Context.OverloadTy) {
6734
6735 // We aren't supposed to apply this logic if there's an '&' involved.
6738 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6739 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6740 OverloadExpr *ovl = find.Expression;
6741 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6743 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6744 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6745 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6746 RParenLoc, ExecConfig, IsExecConfig,
6747 AllowRecovery);
6748 }
6749 }
6750
6751 // If we're directly calling a function, get the appropriate declaration.
6752 if (Fn->getType() == Context.UnknownAnyTy) {
6753 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6754 if (result.isInvalid()) return ExprError();
6755 Fn = result.get();
6756 }
6757
6758 Expr *NakedFn = Fn->IgnoreParens();
6759
6760 bool CallingNDeclIndirectly = false;
6761 NamedDecl *NDecl = nullptr;
6762 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6763 if (UnOp->getOpcode() == UO_AddrOf) {
6764 CallingNDeclIndirectly = true;
6765 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6766 }
6767 }
6768
6769 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6770 NDecl = DRE->getDecl();
6771
6772 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6773 if (FDecl && FDecl->getBuiltinID()) {
6774 // Rewrite the function decl for this builtin by replacing parameters
6775 // with no explicit address space with the address space of the arguments
6776 // in ArgExprs.
6777 if ((FDecl =
6778 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6779 NDecl = FDecl;
6781 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6782 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6783 nullptr, DRE->isNonOdrUse());
6784 }
6785 }
6786 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6787 NDecl = ME->getMemberDecl();
6788
6789 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6790 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6791 FD, /*Complain=*/true, Fn->getBeginLoc()))
6792 return ExprError();
6793
6794 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6795
6796 // If this expression is a call to a builtin function in HIP compilation,
6797 // allow a pointer-type argument to default address space to be passed as a
6798 // pointer-type parameter to a non-default address space. If Arg is declared
6799 // in the default address space and Param is declared in a non-default
6800 // address space, perform an implicit address space cast to the parameter
6801 // type.
6802 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6803 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6804 ++Idx) {
6805 ParmVarDecl *Param = FD->getParamDecl(Idx);
6806 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6807 !ArgExprs[Idx]->getType()->isPointerType())
6808 continue;
6809
6810 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6811 auto ArgTy = ArgExprs[Idx]->getType();
6812 auto ArgPtTy = ArgTy->getPointeeType();
6813 auto ArgAS = ArgPtTy.getAddressSpace();
6814
6815 // Add address space cast if target address spaces are different
6816 bool NeedImplicitASC =
6817 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6818 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6819 // or from specific AS which has target AS matching that of Param.
6821 if (!NeedImplicitASC)
6822 continue;
6823
6824 // First, ensure that the Arg is an RValue.
6825 if (ArgExprs[Idx]->isGLValue()) {
6826 ArgExprs[Idx] = ImplicitCastExpr::Create(
6827 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6828 nullptr, VK_PRValue, FPOptionsOverride());
6829 }
6830
6831 // Construct a new arg type with address space of Param
6832 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6833 ArgPtQuals.setAddressSpace(ParamAS);
6834 auto NewArgPtTy =
6835 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6836 auto NewArgTy =
6837 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6838 ArgTy.getQualifiers());
6839
6840 // Finally perform an implicit address space cast
6841 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6842 CK_AddressSpaceConversion)
6843 .get();
6844 }
6845 }
6846 }
6847
6848 if (Context.isDependenceAllowed() &&
6849 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6850 assert(!getLangOpts().CPlusPlus);
6851 assert((Fn->containsErrors() ||
6852 llvm::any_of(ArgExprs,
6853 [](clang::Expr *E) { return E->containsErrors(); })) &&
6854 "should only occur in error-recovery path.");
6855 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6856 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6857 }
6858 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6859 ExecConfig, IsExecConfig);
6860}
6861
6863 MultiExprArg CallArgs) {
6864 std::string Name = Context.BuiltinInfo.getName(Id);
6865 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6867 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6868
6869 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6870 assert(BuiltInDecl && "failed to find builtin declaration");
6871
6872 ExprResult DeclRef =
6873 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6874 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6875
6877 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6878
6879 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6880 return Call.get();
6881}
6882
6884 SourceLocation BuiltinLoc,
6885 SourceLocation RParenLoc) {
6886 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6887 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6888}
6889
6891 SourceLocation BuiltinLoc,
6892 SourceLocation RParenLoc) {
6895 QualType SrcTy = E->getType();
6896 if (!SrcTy->isDependentType() &&
6897 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6898 return ExprError(
6899 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6900 << DestTy << SrcTy << E->getSourceRange());
6901 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6902}
6903
6905 SourceLocation BuiltinLoc,
6906 SourceLocation RParenLoc) {
6907 TypeSourceInfo *TInfo;
6908 GetTypeFromParser(ParsedDestTy, &TInfo);
6909 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6910}
6911
6913 SourceLocation LParenLoc,
6914 ArrayRef<Expr *> Args,
6915 SourceLocation RParenLoc, Expr *Config,
6916 bool IsExecConfig, ADLCallKind UsesADL) {
6917 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6918 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6919
6920 auto IsSJLJ = [&] {
6921 switch (BuiltinID) {
6922 case Builtin::BI__builtin_longjmp:
6923 case Builtin::BI__builtin_setjmp:
6924 case Builtin::BI__sigsetjmp:
6925 case Builtin::BI_longjmp:
6926 case Builtin::BI_setjmp:
6927 case Builtin::BIlongjmp:
6928 case Builtin::BIsetjmp:
6929 case Builtin::BIsiglongjmp:
6930 case Builtin::BIsigsetjmp:
6931 return true;
6932 default:
6933 return false;
6934 }
6935 };
6936
6937 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
6938 if (!CurrentDefer.empty() && IsSJLJ()) {
6939 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
6940 // for more than just blocks (e.g. lambdas, nested classes...).
6941 Scope *DeferParent = CurrentDefer.back().first;
6942 Scope *Block = CurScope->getBlockParent();
6943 if (DeferParent->Contains(*CurScope) &&
6944 (!Block || !DeferParent->Contains(*Block)))
6945 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
6946 }
6947
6948 // Functions with 'interrupt' attribute cannot be called directly.
6949 if (FDecl) {
6950 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6951 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6952 return ExprError();
6953 }
6954 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6955 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6956 return ExprError();
6957 }
6958 }
6959
6960 // X86 interrupt handlers may only call routines with attribute
6961 // no_caller_saved_registers since there is no efficient way to
6962 // save and restore the non-GPR state.
6963 if (auto *Caller = getCurFunctionDecl()) {
6964 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6965 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6966 const TargetInfo &TI = Context.getTargetInfo();
6967 bool HasNonGPRRegisters =
6968 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6969 if (HasNonGPRRegisters &&
6970 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6971 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6972 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6973 if (FDecl)
6974 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6975 }
6976 }
6977 }
6978
6979 // Promote the function operand.
6980 // We special-case function promotion here because we only allow promoting
6981 // builtin functions to function pointers in the callee of a call.
6983 QualType ResultTy;
6984 if (BuiltinID &&
6985 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6986 // Extract the return type from the (builtin) function pointer type.
6987 // FIXME Several builtins still have setType in
6988 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6989 // Builtins.td to ensure they are correct before removing setType calls.
6990 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6991 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6992 ResultTy = FDecl->getCallResultType();
6993 } else {
6995 ResultTy = Context.BoolTy;
6996 }
6997 if (Result.isInvalid())
6998 return ExprError();
6999 Fn = Result.get();
7000
7001 // Check for a valid function type, but only if it is not a builtin which
7002 // requires custom type checking. These will be handled by
7003 // CheckBuiltinFunctionCall below just after creation of the call expression.
7004 const FunctionType *FuncT = nullptr;
7005 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7006 retry:
7007 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7008 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7009 // have type pointer to function".
7010 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7011 if (!FuncT)
7012 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7013 << Fn->getType() << Fn->getSourceRange());
7014 } else if (const BlockPointerType *BPT =
7015 Fn->getType()->getAs<BlockPointerType>()) {
7016 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7017 } else {
7018 // Handle calls to expressions of unknown-any type.
7019 if (Fn->getType() == Context.UnknownAnyTy) {
7020 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7021 if (rewrite.isInvalid())
7022 return ExprError();
7023 Fn = rewrite.get();
7024 goto retry;
7025 }
7026
7027 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7028 << Fn->getType() << Fn->getSourceRange());
7029 }
7030 }
7031
7032 // Get the number of parameters in the function prototype, if any.
7033 // We will allocate space for max(Args.size(), NumParams) arguments
7034 // in the call expression.
7035 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7036 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7037
7038 CallExpr *TheCall;
7039 if (Config) {
7040 assert(UsesADL == ADLCallKind::NotADL &&
7041 "CUDAKernelCallExpr should not use ADL");
7042 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7043 Args, ResultTy, VK_PRValue, RParenLoc,
7044 CurFPFeatureOverrides(), NumParams);
7045 } else {
7046 TheCall =
7047 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7048 CurFPFeatureOverrides(), NumParams, UsesADL);
7049 }
7050
7051 // Bail out early if calling a builtin with custom type checking.
7052 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7053 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7054 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7055 E = CheckForImmediateInvocation(E, FDecl);
7056 return E;
7057 }
7058
7059 if (getLangOpts().CUDA) {
7060 if (Config) {
7061 // CUDA: Kernel calls must be to global functions
7062 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7063 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7064 << FDecl << Fn->getSourceRange());
7065
7066 // CUDA: Kernel function must have 'void' return type
7067 if (!FuncT->getReturnType()->isVoidType() &&
7068 !FuncT->getReturnType()->getAs<AutoType>() &&
7070 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7071 << Fn->getType() << Fn->getSourceRange());
7072 } else {
7073 // CUDA: Calls to global functions must be configured
7074 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7075 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7076 << FDecl << Fn->getSourceRange());
7077 }
7078 }
7079
7080 // Check for a valid return type
7081 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7082 FDecl))
7083 return ExprError();
7084
7085 // We know the result type of the call, set it.
7086 TheCall->setType(FuncT->getCallResultType(Context));
7088
7089 // WebAssembly tables can't be used as arguments.
7090 if (Context.getTargetInfo().getTriple().isWasm()) {
7091 for (const Expr *Arg : Args) {
7092 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7093 return ExprError(Diag(Arg->getExprLoc(),
7094 diag::err_wasm_table_as_function_parameter));
7095 }
7096 }
7097 }
7098
7099 if (Proto) {
7100 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7101 IsExecConfig))
7102 return ExprError();
7103 } else {
7104 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7105
7106 if (FDecl) {
7107 // Check if we have too few/too many template arguments, based
7108 // on our knowledge of the function definition.
7109 const FunctionDecl *Def = nullptr;
7110 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7111 Proto = Def->getType()->getAs<FunctionProtoType>();
7112 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7113 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7114 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7115 }
7116
7117 // If the function we're calling isn't a function prototype, but we have
7118 // a function prototype from a prior declaratiom, use that prototype.
7119 if (!FDecl->hasPrototype())
7120 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7121 }
7122
7123 // If we still haven't found a prototype to use but there are arguments to
7124 // the call, diagnose this as calling a function without a prototype.
7125 // However, if we found a function declaration, check to see if
7126 // -Wdeprecated-non-prototype was disabled where the function was declared.
7127 // If so, we will silence the diagnostic here on the assumption that this
7128 // interface is intentional and the user knows what they're doing. We will
7129 // also silence the diagnostic if there is a function declaration but it
7130 // was implicitly defined (the user already gets diagnostics about the
7131 // creation of the implicit function declaration, so the additional warning
7132 // is not helpful).
7133 if (!Proto && !Args.empty() &&
7134 (!FDecl || (!FDecl->isImplicit() &&
7135 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7136 FDecl->getLocation()))))
7137 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7138 << (FDecl != nullptr) << FDecl;
7139
7140 // Promote the arguments (C99 6.5.2.2p6).
7141 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7142 Expr *Arg = Args[i];
7143
7144 if (Proto && i < Proto->getNumParams()) {
7146 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7147 ExprResult ArgE =
7149 if (ArgE.isInvalid())
7150 return true;
7151
7152 Arg = ArgE.getAs<Expr>();
7153
7154 } else {
7156
7157 if (ArgE.isInvalid())
7158 return true;
7159
7160 Arg = ArgE.getAs<Expr>();
7161 }
7162
7163 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7164 diag::err_call_incomplete_argument, Arg))
7165 return ExprError();
7166
7167 TheCall->setArg(i, Arg);
7168 }
7169 TheCall->computeDependence();
7170 }
7171
7172 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7173 if (Method->isImplicitObjectMemberFunction())
7174 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7175 << Fn->getSourceRange() << 0);
7176
7177 // Check for sentinels
7178 if (NDecl)
7179 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7180
7181 // Warn for unions passing across security boundary (CMSE).
7182 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7183 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7184 if (const auto *RT =
7185 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7186 if (RT->getDecl()->isOrContainsUnion())
7187 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7188 << 0 << i;
7189 }
7190 }
7191 }
7192
7193 // Do special checking on direct calls to functions.
7194 if (FDecl) {
7195 if (CheckFunctionCall(FDecl, TheCall, Proto))
7196 return ExprError();
7197
7198 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7199
7200 if (BuiltinID)
7201 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7202 } else if (NDecl) {
7203 if (CheckPointerCall(NDecl, TheCall, Proto))
7204 return ExprError();
7205 } else {
7206 if (CheckOtherCall(TheCall, Proto))
7207 return ExprError();
7208 }
7209
7210 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7211}
7212
7215 SourceLocation RParenLoc, Expr *InitExpr) {
7216 assert(Ty && "ActOnCompoundLiteral(): missing type");
7217 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7218
7219 TypeSourceInfo *TInfo;
7220 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7221 if (!TInfo)
7222 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7223
7224 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7225}
7226
7229 SourceLocation RParenLoc, Expr *LiteralExpr) {
7230 QualType literalType = TInfo->getType();
7231
7232 if (literalType->isArrayType()) {
7234 LParenLoc, Context.getBaseElementType(literalType),
7235 diag::err_array_incomplete_or_sizeless_type,
7236 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7237 return ExprError();
7238 if (literalType->isVariableArrayType()) {
7239 // C23 6.7.10p4: An entity of variable length array type shall not be
7240 // initialized except by an empty initializer.
7241 //
7242 // The C extension warnings are issued from ParseBraceInitializer() and
7243 // do not need to be issued here. However, we continue to issue an error
7244 // in the case there are initializers or we are compiling C++. We allow
7245 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7246 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7247 // FIXME: should we allow this construct in C++ when it makes sense to do
7248 // so?
7249 //
7250 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7251 // shall specify an object type or an array of unknown size, but not a
7252 // variable length array type. This seems odd, as it allows 'int a[size] =
7253 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7254 // says, this is what's implemented here for C (except for the extension
7255 // that permits constant foldable size arrays)
7256
7257 auto diagID = LangOpts.CPlusPlus
7258 ? diag::err_variable_object_no_init
7259 : diag::err_compound_literal_with_vla_type;
7260 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7261 diagID))
7262 return ExprError();
7263 }
7264 } else if (!literalType->isDependentType() &&
7265 RequireCompleteType(LParenLoc, literalType,
7266 diag::err_typecheck_decl_incomplete_type,
7267 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7268 return ExprError();
7269
7270 InitializedEntity Entity
7274 SourceRange(LParenLoc, RParenLoc),
7275 /*InitList=*/true);
7276 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7277 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7278 &literalType);
7279 if (Result.isInvalid())
7280 return ExprError();
7281 LiteralExpr = Result.get();
7282
7283 // We treat the compound literal as being at file scope if it's not in a
7284 // function or method body, or within the function's prototype scope. This
7285 // means the following compound literal is not at file scope:
7286 // void func(char *para[(int [1]){ 0 }[0]);
7287 const Scope *S = getCurScope();
7288 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7289 !S->isInCFunctionScope() &&
7290 (!S || !S->isFunctionPrototypeScope());
7291
7292 // In C, compound literals are l-values for some reason.
7293 // For GCC compatibility, in C++, file-scope array compound literals with
7294 // constant initializers are also l-values, and compound literals are
7295 // otherwise prvalues.
7296 //
7297 // (GCC also treats C++ list-initialized file-scope array prvalues with
7298 // constant initializers as l-values, but that's non-conforming, so we don't
7299 // follow it there.)
7300 //
7301 // FIXME: It would be better to handle the lvalue cases as materializing and
7302 // lifetime-extending a temporary object, but our materialized temporaries
7303 // representation only supports lifetime extension from a variable, not "out
7304 // of thin air".
7305 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7306 // is bound to the result of applying array-to-pointer decay to the compound
7307 // literal.
7308 // FIXME: GCC supports compound literals of reference type, which should
7309 // obviously have a value kind derived from the kind of reference involved.
7311 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7312 ? VK_PRValue
7313 : VK_LValue;
7314
7315 // C99 6.5.2.5
7316 // "If the compound literal occurs outside the body of a function, the
7317 // initializer list shall consist of constant expressions."
7318 if (IsFileScope)
7319 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7320 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7321 Expr *Init = ILE->getInit(i);
7322 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7323 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7324 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7325 << Init->getSourceBitField();
7326 return ExprError();
7327 }
7328
7329 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7330 }
7331
7332 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7333 LiteralExpr, IsFileScope);
7334 if (IsFileScope) {
7335 if (!LiteralExpr->isTypeDependent() &&
7336 !LiteralExpr->isValueDependent() &&
7337 !literalType->isDependentType()) // C99 6.5.2.5p3
7338 if (CheckForConstantInitializer(LiteralExpr))
7339 return ExprError();
7340 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7341 literalType.getAddressSpace() != LangAS::Default) {
7342 // Embedded-C extensions to C99 6.5.2.5:
7343 // "If the compound literal occurs inside the body of a function, the
7344 // type name shall not be qualified by an address-space qualifier."
7345 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7346 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7347 return ExprError();
7348 }
7349
7350 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7351 // Compound literals that have automatic storage duration are destroyed at
7352 // the end of the scope in C; in C++, they're just temporaries.
7353
7354 // Emit diagnostics if it is or contains a C union type that is non-trivial
7355 // to destruct.
7360
7361 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7362 if (literalType.isDestructedType()) {
7363 Cleanup.setExprNeedsCleanups(true);
7364 ExprCleanupObjects.push_back(E);
7366 }
7367 }
7368
7371 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7372 E->getInitializer()->getExprLoc());
7373
7374 return MaybeBindToTemporary(E);
7375}
7376
7379 SourceLocation RBraceLoc) {
7380 // Only produce each kind of designated initialization diagnostic once.
7381 SourceLocation FirstDesignator;
7382 bool DiagnosedArrayDesignator = false;
7383 bool DiagnosedNestedDesignator = false;
7384 bool DiagnosedMixedDesignator = false;
7385
7386 // Check that any designated initializers are syntactically valid in the
7387 // current language mode.
7388 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7389 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7390 if (FirstDesignator.isInvalid())
7391 FirstDesignator = DIE->getBeginLoc();
7392
7393 if (!getLangOpts().CPlusPlus)
7394 break;
7395
7396 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7397 DiagnosedNestedDesignator = true;
7398 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7399 << DIE->getDesignatorsSourceRange();
7400 }
7401
7402 for (auto &Desig : DIE->designators()) {
7403 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7404 DiagnosedArrayDesignator = true;
7405 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7406 << Desig.getSourceRange();
7407 }
7408 }
7409
7410 if (!DiagnosedMixedDesignator &&
7411 !isa<DesignatedInitExpr>(InitArgList[0])) {
7412 DiagnosedMixedDesignator = true;
7413 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7414 << DIE->getSourceRange();
7415 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7416 << InitArgList[0]->getSourceRange();
7417 }
7418 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7419 isa<DesignatedInitExpr>(InitArgList[0])) {
7420 DiagnosedMixedDesignator = true;
7421 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7422 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7423 << DIE->getSourceRange();
7424 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7425 << InitArgList[I]->getSourceRange();
7426 }
7427 }
7428
7429 if (FirstDesignator.isValid()) {
7430 // Only diagnose designated initiaization as a C++20 extension if we didn't
7431 // already diagnose use of (non-C++20) C99 designator syntax.
7432 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7433 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7434 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7435 ? diag::warn_cxx17_compat_designated_init
7436 : diag::ext_cxx_designated_init);
7437 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7438 Diag(FirstDesignator, diag::ext_designated_init);
7439 }
7440 }
7441
7442 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7443}
7444
7447 SourceLocation RBraceLoc) {
7448 // Semantic analysis for initializers is done by ActOnDeclarator() and
7449 // CheckInitializer() - it requires knowledge of the object being initialized.
7450
7451 // Immediately handle non-overload placeholders. Overloads can be
7452 // resolved contextually, but everything else here can't.
7453 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7454 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7455 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7456
7457 // Ignore failures; dropping the entire initializer list because
7458 // of one failure would be terrible for indexing/etc.
7459 if (result.isInvalid()) continue;
7460
7461 InitArgList[I] = result.get();
7462 }
7463 }
7464
7465 InitListExpr *E =
7466 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7467 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7468 return E;
7469}
7470
7472 assert(E.get()->getType()->isBlockPointerType());
7473 assert(E.get()->isPRValue());
7474
7475 // Only do this in an r-value context.
7476 if (!getLangOpts().ObjCAutoRefCount) return;
7477
7479 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7480 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7481 Cleanup.setExprNeedsCleanups(true);
7482}
7483
7485 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7486 // Also, callers should have filtered out the invalid cases with
7487 // pointers. Everything else should be possible.
7488
7489 QualType SrcTy = Src.get()->getType();
7490 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7491 return CK_NoOp;
7492
7493 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7495 llvm_unreachable("member pointer type in C");
7496
7497 case Type::STK_CPointer:
7500 switch (DestTy->getScalarTypeKind()) {
7501 case Type::STK_CPointer: {
7502 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7503 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7504 if (SrcAS != DestAS)
7505 return CK_AddressSpaceConversion;
7506 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7507 return CK_NoOp;
7508 return CK_BitCast;
7509 }
7511 return (SrcKind == Type::STK_BlockPointer
7512 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7514 if (SrcKind == Type::STK_ObjCObjectPointer)
7515 return CK_BitCast;
7516 if (SrcKind == Type::STK_CPointer)
7517 return CK_CPointerToObjCPointerCast;
7519 return CK_BlockPointerToObjCPointerCast;
7520 case Type::STK_Bool:
7521 return CK_PointerToBoolean;
7522 case Type::STK_Integral:
7523 return CK_PointerToIntegral;
7524 case Type::STK_Floating:
7529 llvm_unreachable("illegal cast from pointer");
7530 }
7531 llvm_unreachable("Should have returned before this");
7532
7534 switch (DestTy->getScalarTypeKind()) {
7536 return CK_FixedPointCast;
7537 case Type::STK_Bool:
7538 return CK_FixedPointToBoolean;
7539 case Type::STK_Integral:
7540 return CK_FixedPointToIntegral;
7541 case Type::STK_Floating:
7542 return CK_FixedPointToFloating;
7545 Diag(Src.get()->getExprLoc(),
7546 diag::err_unimplemented_conversion_with_fixed_point_type)
7547 << DestTy;
7548 return CK_IntegralCast;
7549 case Type::STK_CPointer:
7553 llvm_unreachable("illegal cast to pointer type");
7554 }
7555 llvm_unreachable("Should have returned before this");
7556
7557 case Type::STK_Bool: // casting from bool is like casting from an integer
7558 case Type::STK_Integral:
7559 switch (DestTy->getScalarTypeKind()) {
7560 case Type::STK_CPointer:
7565 return CK_NullToPointer;
7566 return CK_IntegralToPointer;
7567 case Type::STK_Bool:
7568 return CK_IntegralToBoolean;
7569 case Type::STK_Integral:
7570 return CK_IntegralCast;
7571 case Type::STK_Floating:
7572 return CK_IntegralToFloating;
7574 Src = ImpCastExprToType(Src.get(),
7575 DestTy->castAs<ComplexType>()->getElementType(),
7576 CK_IntegralCast);
7577 return CK_IntegralRealToComplex;
7579 Src = ImpCastExprToType(Src.get(),
7580 DestTy->castAs<ComplexType>()->getElementType(),
7581 CK_IntegralToFloating);
7582 return CK_FloatingRealToComplex;
7584 llvm_unreachable("member pointer type in C");
7586 return CK_IntegralToFixedPoint;
7587 }
7588 llvm_unreachable("Should have returned before this");
7589
7590 case Type::STK_Floating:
7591 switch (DestTy->getScalarTypeKind()) {
7592 case Type::STK_Floating:
7593 return CK_FloatingCast;
7594 case Type::STK_Bool:
7595 return CK_FloatingToBoolean;
7596 case Type::STK_Integral:
7597 return CK_FloatingToIntegral;
7599 Src = ImpCastExprToType(Src.get(),
7600 DestTy->castAs<ComplexType>()->getElementType(),
7601 CK_FloatingCast);
7602 return CK_FloatingRealToComplex;
7604 Src = ImpCastExprToType(Src.get(),
7605 DestTy->castAs<ComplexType>()->getElementType(),
7606 CK_FloatingToIntegral);
7607 return CK_IntegralRealToComplex;
7608 case Type::STK_CPointer:
7611 llvm_unreachable("valid float->pointer cast?");
7613 llvm_unreachable("member pointer type in C");
7615 return CK_FloatingToFixedPoint;
7616 }
7617 llvm_unreachable("Should have returned before this");
7618
7620 switch (DestTy->getScalarTypeKind()) {
7622 return CK_FloatingComplexCast;
7624 return CK_FloatingComplexToIntegralComplex;
7625 case Type::STK_Floating: {
7626 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7627 if (Context.hasSameType(ET, DestTy))
7628 return CK_FloatingComplexToReal;
7629 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7630 return CK_FloatingCast;
7631 }
7632 case Type::STK_Bool:
7633 return CK_FloatingComplexToBoolean;
7634 case Type::STK_Integral:
7635 Src = ImpCastExprToType(Src.get(),
7636 SrcTy->castAs<ComplexType>()->getElementType(),
7637 CK_FloatingComplexToReal);
7638 return CK_FloatingToIntegral;
7639 case Type::STK_CPointer:
7642 llvm_unreachable("valid complex float->pointer cast?");
7644 llvm_unreachable("member pointer type in C");
7646 Diag(Src.get()->getExprLoc(),
7647 diag::err_unimplemented_conversion_with_fixed_point_type)
7648 << SrcTy;
7649 return CK_IntegralCast;
7650 }
7651 llvm_unreachable("Should have returned before this");
7652
7654 switch (DestTy->getScalarTypeKind()) {
7656 return CK_IntegralComplexToFloatingComplex;
7658 return CK_IntegralComplexCast;
7659 case Type::STK_Integral: {
7660 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7661 if (Context.hasSameType(ET, DestTy))
7662 return CK_IntegralComplexToReal;
7663 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7664 return CK_IntegralCast;
7665 }
7666 case Type::STK_Bool:
7667 return CK_IntegralComplexToBoolean;
7668 case Type::STK_Floating:
7669 Src = ImpCastExprToType(Src.get(),
7670 SrcTy->castAs<ComplexType>()->getElementType(),
7671 CK_IntegralComplexToReal);
7672 return CK_IntegralToFloating;
7673 case Type::STK_CPointer:
7676 llvm_unreachable("valid complex int->pointer cast?");
7678 llvm_unreachable("member pointer type in C");
7680 Diag(Src.get()->getExprLoc(),
7681 diag::err_unimplemented_conversion_with_fixed_point_type)
7682 << SrcTy;
7683 return CK_IntegralCast;
7684 }
7685 llvm_unreachable("Should have returned before this");
7686 }
7687
7688 llvm_unreachable("Unhandled scalar cast");
7689}
7690
7691static bool breakDownVectorType(QualType type, uint64_t &len,
7692 QualType &eltType) {
7693 // Vectors are simple.
7694 if (const VectorType *vecType = type->getAs<VectorType>()) {
7695 len = vecType->getNumElements();
7696 eltType = vecType->getElementType();
7697 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7698 return true;
7699 }
7700
7701 // We allow lax conversion to and from non-vector types, but only if
7702 // they're real types (i.e. non-complex, non-pointer scalar types).
7703 if (!type->isRealType()) return false;
7704
7705 len = 1;
7706 eltType = type;
7707 return true;
7708}
7709
7711 assert(srcTy->isVectorType() || destTy->isVectorType());
7712
7713 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7714 if (!FirstType->isSVESizelessBuiltinType())
7715 return false;
7716
7717 const auto *VecTy = SecondType->getAs<VectorType>();
7718 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7719 };
7720
7721 return ValidScalableConversion(srcTy, destTy) ||
7722 ValidScalableConversion(destTy, srcTy);
7723}
7724
7726 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7727 return false;
7728
7729 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7730 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7731
7732 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7733 matSrcType->getNumColumns() == matDestType->getNumColumns();
7734}
7735
7737 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7738
7739 uint64_t SrcLen, DestLen;
7740 QualType SrcEltTy, DestEltTy;
7741 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7742 return false;
7743 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7744 return false;
7745
7746 // ASTContext::getTypeSize will return the size rounded up to a
7747 // power of 2, so instead of using that, we need to use the raw
7748 // element size multiplied by the element count.
7749 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7750 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7751
7752 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7753}
7754
7756 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7757 "expected at least one type to be a vector here");
7758
7759 bool IsSrcTyAltivec =
7760 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7762 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7764 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7766
7767 bool IsDestTyAltivec = DestTy->isVectorType() &&
7768 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7770 (DestTy->castAs<VectorType>()->getVectorKind() ==
7772 (DestTy->castAs<VectorType>()->getVectorKind() ==
7774
7775 return (IsSrcTyAltivec || IsDestTyAltivec);
7776}
7777
7779 assert(destTy->isVectorType() || srcTy->isVectorType());
7780
7781 // Disallow lax conversions between scalars and ExtVectors (these
7782 // conversions are allowed for other vector types because common headers
7783 // depend on them). Most scalar OP ExtVector cases are handled by the
7784 // splat path anyway, which does what we want (convert, not bitcast).
7785 // What this rules out for ExtVectors is crazy things like char4*float.
7786 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7787 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7788
7789 return areVectorTypesSameSize(srcTy, destTy);
7790}
7791
7793 assert(destTy->isVectorType() || srcTy->isVectorType());
7794
7795 switch (Context.getLangOpts().getLaxVectorConversions()) {
7797 return false;
7798
7800 if (!srcTy->isIntegralOrEnumerationType()) {
7801 auto *Vec = srcTy->getAs<VectorType>();
7802 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7803 return false;
7804 }
7805 if (!destTy->isIntegralOrEnumerationType()) {
7806 auto *Vec = destTy->getAs<VectorType>();
7807 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7808 return false;
7809 }
7810 // OK, integer (vector) -> integer (vector) bitcast.
7811 break;
7812
7814 break;
7815 }
7816
7817 return areLaxCompatibleVectorTypes(srcTy, destTy);
7818}
7819
7821 CastKind &Kind) {
7822 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7823 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7824 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7825 << DestTy << SrcTy << R;
7826 }
7827 } else if (SrcTy->isMatrixType()) {
7828 return Diag(R.getBegin(),
7829 diag::err_invalid_conversion_between_matrix_and_type)
7830 << SrcTy << DestTy << R;
7831 } else if (DestTy->isMatrixType()) {
7832 return Diag(R.getBegin(),
7833 diag::err_invalid_conversion_between_matrix_and_type)
7834 << DestTy << SrcTy << R;
7835 }
7836
7837 Kind = CK_MatrixCast;
7838 return false;
7839}
7840
7842 CastKind &Kind) {
7843 assert(VectorTy->isVectorType() && "Not a vector type!");
7844
7845 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7846 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7847 return Diag(R.getBegin(),
7848 Ty->isVectorType() ?
7849 diag::err_invalid_conversion_between_vectors :
7850 diag::err_invalid_conversion_between_vector_and_integer)
7851 << VectorTy << Ty << R;
7852 } else
7853 return Diag(R.getBegin(),
7854 diag::err_invalid_conversion_between_vector_and_scalar)
7855 << VectorTy << Ty << R;
7856
7857 Kind = CK_BitCast;
7858 return false;
7859}
7860
7862 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7863
7864 if (DestElemTy == SplattedExpr->getType())
7865 return SplattedExpr;
7866
7867 assert(DestElemTy->isFloatingType() ||
7868 DestElemTy->isIntegralOrEnumerationType());
7869
7870 CastKind CK;
7871 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7872 // OpenCL requires that we convert `true` boolean expressions to -1, but
7873 // only when splatting vectors.
7874 if (DestElemTy->isFloatingType()) {
7875 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7876 // in two steps: boolean to signed integral, then to floating.
7877 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7878 CK_BooleanToSignedIntegral);
7879 SplattedExpr = CastExprRes.get();
7880 CK = CK_IntegralToFloating;
7881 } else {
7882 CK = CK_BooleanToSignedIntegral;
7883 }
7884 } else {
7885 ExprResult CastExprRes = SplattedExpr;
7886 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7887 if (CastExprRes.isInvalid())
7888 return ExprError();
7889 SplattedExpr = CastExprRes.get();
7890 }
7891 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7892}
7893
7895 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
7896
7897 if (DestElemTy == SplattedExpr->getType())
7898 return SplattedExpr;
7899
7900 assert(DestElemTy->isFloatingType() ||
7901 DestElemTy->isIntegralOrEnumerationType());
7902
7903 ExprResult CastExprRes = SplattedExpr;
7904 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
7905 if (CastExprRes.isInvalid())
7906 return ExprError();
7907 SplattedExpr = CastExprRes.get();
7908
7909 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7910}
7911
7913 Expr *CastExpr, CastKind &Kind) {
7914 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7915
7916 QualType SrcTy = CastExpr->getType();
7917
7918 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7919 // an ExtVectorType.
7920 // In OpenCL, casts between vectors of different types are not allowed.
7921 // (See OpenCL 6.2).
7922 if (SrcTy->isVectorType()) {
7923 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7924 (getLangOpts().OpenCL &&
7925 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
7926 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
7927 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7928 << DestTy << SrcTy << R;
7929 return ExprError();
7930 }
7931 Kind = CK_BitCast;
7932 return CastExpr;
7933 }
7934
7935 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7936 // conversion will take place first from scalar to elt type, and then
7937 // splat from elt type to vector.
7938 if (SrcTy->isPointerType())
7939 return Diag(R.getBegin(),
7940 diag::err_invalid_conversion_between_vector_and_scalar)
7941 << DestTy << SrcTy << R;
7942
7943 Kind = CK_VectorSplat;
7944 return prepareVectorSplat(DestTy, CastExpr);
7945}
7946
7947/// Check that a call to alloc_size function specifies sufficient space for the
7948/// destination type.
7949static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7950 const Expr *E) {
7951 QualType SourceType = E->getType();
7952 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7953 DestType == SourceType)
7954 return;
7955
7956 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
7957 if (!CE)
7958 return;
7959
7960 // Find the total size allocated by the function call.
7961 if (!CE->getCalleeAllocSizeAttr())
7962 return;
7963 std::optional<llvm::APInt> AllocSize =
7964 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
7965 // Allocations of size zero are permitted as a special case. They are usually
7966 // done intentionally.
7967 if (!AllocSize || AllocSize->isZero())
7968 return;
7969 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
7970
7971 QualType TargetType = DestType->getPointeeType();
7972 // Find the destination size. As a special case function types have size of
7973 // one byte to match the sizeof operator behavior.
7974 auto LhsSize = TargetType->isFunctionType()
7975 ? CharUnits::One()
7976 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
7977 if (LhsSize && Size < LhsSize)
7978 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
7979 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7980}
7981
7984 Declarator &D, ParsedType &Ty,
7985 SourceLocation RParenLoc, Expr *CastExpr) {
7986 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7987 "ActOnCastExpr(): missing type or expr");
7988
7990 if (D.isInvalidType())
7991 return ExprError();
7992
7993 if (getLangOpts().CPlusPlus) {
7994 // Check that there are no default arguments (C++ only).
7996 }
7997
7999
8000 QualType castType = castTInfo->getType();
8001 Ty = CreateParsedType(castType, castTInfo);
8002
8003 bool isVectorLiteral = false;
8004
8005 // Check for an altivec or OpenCL literal,
8006 // i.e. all the elements are integer constants.
8007 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8008 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8009 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8010 && castType->isVectorType() && (PE || PLE)) {
8011 if (PLE && PLE->getNumExprs() == 0) {
8012 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8013 return ExprError();
8014 }
8015 if (PE || PLE->getNumExprs() == 1) {
8016 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8017 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8018 isVectorLiteral = true;
8019 }
8020 else
8021 isVectorLiteral = true;
8022 }
8023
8024 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8025 // then handle it as such.
8026 if (isVectorLiteral)
8027 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8028
8029 // If the Expr being casted is a ParenListExpr, handle it specially.
8030 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8031 // sequence of BinOp comma operators.
8034 if (Result.isInvalid()) return ExprError();
8035 CastExpr = Result.get();
8036 }
8037
8038 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8039 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8040
8042
8044
8046
8047 CheckSufficientAllocSize(*this, castType, CastExpr);
8048
8049 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8050}
8051
8053 SourceLocation RParenLoc, Expr *E,
8054 TypeSourceInfo *TInfo) {
8055 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8056 "Expected paren or paren list expression");
8057
8058 Expr **exprs;
8059 unsigned numExprs;
8060 Expr *subExpr;
8061 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8062 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8063 LiteralLParenLoc = PE->getLParenLoc();
8064 LiteralRParenLoc = PE->getRParenLoc();
8065 exprs = PE->getExprs();
8066 numExprs = PE->getNumExprs();
8067 } else { // isa<ParenExpr> by assertion at function entrance
8068 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8069 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8070 subExpr = cast<ParenExpr>(E)->getSubExpr();
8071 exprs = &subExpr;
8072 numExprs = 1;
8073 }
8074
8075 QualType Ty = TInfo->getType();
8076 assert(Ty->isVectorType() && "Expected vector type");
8077
8078 SmallVector<Expr *, 8> initExprs;
8079 const VectorType *VTy = Ty->castAs<VectorType>();
8080 unsigned numElems = VTy->getNumElements();
8081
8082 // '(...)' form of vector initialization in AltiVec: the number of
8083 // initializers must be one or must match the size of the vector.
8084 // If a single value is specified in the initializer then it will be
8085 // replicated to all the components of the vector
8087 VTy->getElementType()))
8088 return ExprError();
8090 // The number of initializers must be one or must match the size of the
8091 // vector. If a single value is specified in the initializer then it will
8092 // be replicated to all the components of the vector
8093 if (numExprs == 1) {
8094 QualType ElemTy = VTy->getElementType();
8095 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8096 if (Literal.isInvalid())
8097 return ExprError();
8098 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8099 PrepareScalarCast(Literal, ElemTy));
8100 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8101 }
8102 else if (numExprs < numElems) {
8103 Diag(E->getExprLoc(),
8104 diag::err_incorrect_number_of_vector_initializers);
8105 return ExprError();
8106 }
8107 else
8108 initExprs.append(exprs, exprs + numExprs);
8109 }
8110 else {
8111 // For OpenCL, when the number of initializers is a single value,
8112 // it will be replicated to all components of the vector.
8114 numExprs == 1) {
8115 QualType ElemTy = VTy->getElementType();
8116 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8117 if (Literal.isInvalid())
8118 return ExprError();
8119 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8120 PrepareScalarCast(Literal, ElemTy));
8121 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8122 }
8123
8124 initExprs.append(exprs, exprs + numExprs);
8125 }
8126 // FIXME: This means that pretty-printing the final AST will produce curly
8127 // braces instead of the original commas.
8128 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8129 initExprs, LiteralRParenLoc);
8130 initE->setType(Ty);
8131 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8132}
8133
8136 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8137 if (!E)
8138 return OrigExpr;
8139
8140 ExprResult Result(E->getExpr(0));
8141
8142 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8143 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8144 E->getExpr(i));
8145
8146 if (Result.isInvalid()) return ExprError();
8147
8148 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8149}
8150
8156
8158 unsigned NumUserSpecifiedExprs,
8159 SourceLocation InitLoc,
8160 SourceLocation LParenLoc,
8161 SourceLocation RParenLoc) {
8162 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8163 InitLoc, LParenLoc, RParenLoc);
8164}
8165
8166bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8167 SourceLocation QuestionLoc) {
8168 const Expr *NullExpr = LHSExpr;
8169 const Expr *NonPointerExpr = RHSExpr;
8173
8174 if (NullKind == Expr::NPCK_NotNull) {
8175 NullExpr = RHSExpr;
8176 NonPointerExpr = LHSExpr;
8177 NullKind =
8180 }
8181
8182 if (NullKind == Expr::NPCK_NotNull)
8183 return false;
8184
8185 if (NullKind == Expr::NPCK_ZeroExpression)
8186 return false;
8187
8188 if (NullKind == Expr::NPCK_ZeroLiteral) {
8189 // In this case, check to make sure that we got here from a "NULL"
8190 // string in the source code.
8191 NullExpr = NullExpr->IgnoreParenImpCasts();
8192 SourceLocation loc = NullExpr->getExprLoc();
8193 if (!findMacroSpelling(loc, "NULL"))
8194 return false;
8195 }
8196
8197 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8198 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8199 << NonPointerExpr->getType() << DiagType
8200 << NonPointerExpr->getSourceRange();
8201 return true;
8202}
8203
8204/// Return false if the condition expression is valid, true otherwise.
8205static bool checkCondition(Sema &S, const Expr *Cond,
8206 SourceLocation QuestionLoc) {
8207 QualType CondTy = Cond->getType();
8208
8209 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8210 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8211 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8212 << CondTy << Cond->getSourceRange();
8213 return true;
8214 }
8215
8216 // C99 6.5.15p2
8217 if (CondTy->isScalarType()) return false;
8218
8219 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8220 << CondTy << Cond->getSourceRange();
8221 return true;
8222}
8223
8224/// Return false if the NullExpr can be promoted to PointerTy,
8225/// true otherwise.
8227 QualType PointerTy) {
8228 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8229 !NullExpr.get()->isNullPointerConstant(S.Context,
8231 return true;
8232
8233 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8234 return false;
8235}
8236
8237/// Checks compatibility between two pointers and return the resulting
8238/// type.
8240 ExprResult &RHS,
8241 SourceLocation Loc) {
8242 QualType LHSTy = LHS.get()->getType();
8243 QualType RHSTy = RHS.get()->getType();
8244
8245 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8246 // Two identical pointers types are always compatible.
8247 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8248 }
8249
8250 QualType lhptee, rhptee;
8251
8252 // Get the pointee types.
8253 bool IsBlockPointer = false;
8254 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8255 lhptee = LHSBTy->getPointeeType();
8256 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8257 IsBlockPointer = true;
8258 } else {
8259 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8260 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8261 }
8262
8263 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8264 // differently qualified versions of compatible types, the result type is
8265 // a pointer to an appropriately qualified version of the composite
8266 // type.
8267
8268 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8269 // clause doesn't make sense for our extensions. E.g. address space 2 should
8270 // be incompatible with address space 3: they may live on different devices or
8271 // anything.
8272 Qualifiers lhQual = lhptee.getQualifiers();
8273 Qualifiers rhQual = rhptee.getQualifiers();
8274
8275 LangAS ResultAddrSpace = LangAS::Default;
8276 LangAS LAddrSpace = lhQual.getAddressSpace();
8277 LangAS RAddrSpace = rhQual.getAddressSpace();
8278
8279 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8280 // spaces is disallowed.
8281 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8282 ResultAddrSpace = LAddrSpace;
8283 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8284 ResultAddrSpace = RAddrSpace;
8285 else {
8286 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8287 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8288 << RHS.get()->getSourceRange();
8289 return QualType();
8290 }
8291
8292 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8293 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8294 lhQual.removeCVRQualifiers();
8295 rhQual.removeCVRQualifiers();
8296
8297 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8298 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8299 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8300 << RHS.get()->getSourceRange();
8301 return QualType();
8302 }
8303
8304 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8305 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8306 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8307 // qual types are compatible iff
8308 // * corresponded types are compatible
8309 // * CVR qualifiers are equal
8310 // * address spaces are equal
8311 // Thus for conditional operator we merge CVR and address space unqualified
8312 // pointees and if there is a composite type we return a pointer to it with
8313 // merged qualifiers.
8314 LHSCastKind =
8315 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8316 RHSCastKind =
8317 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8318 lhQual.removeAddressSpace();
8319 rhQual.removeAddressSpace();
8320
8321 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8322 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8323
8324 QualType CompositeTy = S.Context.mergeTypes(
8325 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8326 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8327
8328 if (CompositeTy.isNull()) {
8329 // In this situation, we assume void* type. No especially good
8330 // reason, but this is what gcc does, and we do have to pick
8331 // to get a consistent AST.
8332 QualType incompatTy;
8333 incompatTy = S.Context.getPointerType(
8334 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8335 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8336 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8337
8338 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8339 // for casts between types with incompatible address space qualifiers.
8340 // For the following code the compiler produces casts between global and
8341 // local address spaces of the corresponded innermost pointees:
8342 // local int *global *a;
8343 // global int *global *b;
8344 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8345 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8346 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8347 << RHS.get()->getSourceRange();
8348
8349 return incompatTy;
8350 }
8351
8352 // The pointer types are compatible.
8353 // In case of OpenCL ResultTy should have the address space qualifier
8354 // which is a superset of address spaces of both the 2nd and the 3rd
8355 // operands of the conditional operator.
8356 QualType ResultTy = [&, ResultAddrSpace]() {
8357 if (S.getLangOpts().OpenCL) {
8358 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8359 CompositeQuals.setAddressSpace(ResultAddrSpace);
8360 return S.Context
8361 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8362 .withCVRQualifiers(MergedCVRQual);
8363 }
8364 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8365 }();
8366 if (IsBlockPointer)
8367 ResultTy = S.Context.getBlockPointerType(ResultTy);
8368 else
8369 ResultTy = S.Context.getPointerType(ResultTy);
8370
8371 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8372 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8373 return ResultTy;
8374}
8375
8376/// Return the resulting type when the operands are both block pointers.
8378 ExprResult &LHS,
8379 ExprResult &RHS,
8380 SourceLocation Loc) {
8381 QualType LHSTy = LHS.get()->getType();
8382 QualType RHSTy = RHS.get()->getType();
8383
8384 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8385 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8387 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8388 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8389 return destType;
8390 }
8391 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8392 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8393 << RHS.get()->getSourceRange();
8394 return QualType();
8395 }
8396
8397 // We have 2 block pointer types.
8398 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8399}
8400
8401/// Return the resulting type when the operands are both pointers.
8402static QualType
8404 ExprResult &RHS,
8405 SourceLocation Loc) {
8406 // get the pointer types
8407 QualType LHSTy = LHS.get()->getType();
8408 QualType RHSTy = RHS.get()->getType();
8409
8410 // get the "pointed to" types
8411 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8412 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8413
8414 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8415 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8416 // Figure out necessary qualifiers (C99 6.5.15p6)
8417 QualType destPointee
8418 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8419 QualType destType = S.Context.getPointerType(destPointee);
8420 // Add qualifiers if necessary.
8421 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8422 // Promote to void*.
8423 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8424 return destType;
8425 }
8426 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8427 QualType destPointee
8428 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8429 QualType destType = S.Context.getPointerType(destPointee);
8430 // Add qualifiers if necessary.
8431 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8432 // Promote to void*.
8433 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8434 return destType;
8435 }
8436
8437 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8438}
8439
8440/// Return false if the first expression is not an integer and the second
8441/// expression is not a pointer, true otherwise.
8443 Expr* PointerExpr, SourceLocation Loc,
8444 bool IsIntFirstExpr) {
8445 if (!PointerExpr->getType()->isPointerType() ||
8446 !Int.get()->getType()->isIntegerType())
8447 return false;
8448
8449 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8450 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8451
8452 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8453 << Expr1->getType() << Expr2->getType()
8454 << Expr1->getSourceRange() << Expr2->getSourceRange();
8455 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8456 CK_IntegralToPointer);
8457 return true;
8458}
8459
8460/// Simple conversion between integer and floating point types.
8461///
8462/// Used when handling the OpenCL conditional operator where the
8463/// condition is a vector while the other operands are scalar.
8464///
8465/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8466/// types are either integer or floating type. Between the two
8467/// operands, the type with the higher rank is defined as the "result
8468/// type". The other operand needs to be promoted to the same type. No
8469/// other type promotion is allowed. We cannot use
8470/// UsualArithmeticConversions() for this purpose, since it always
8471/// promotes promotable types.
8473 ExprResult &RHS,
8474 SourceLocation QuestionLoc) {
8476 if (LHS.isInvalid())
8477 return QualType();
8479 if (RHS.isInvalid())
8480 return QualType();
8481
8482 // For conversion purposes, we ignore any qualifiers.
8483 // For example, "const float" and "float" are equivalent.
8484 QualType LHSType =
8486 QualType RHSType =
8488
8489 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8490 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8491 << LHSType << LHS.get()->getSourceRange();
8492 return QualType();
8493 }
8494
8495 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8496 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8497 << RHSType << RHS.get()->getSourceRange();
8498 return QualType();
8499 }
8500
8501 // If both types are identical, no conversion is needed.
8502 if (LHSType == RHSType)
8503 return LHSType;
8504
8505 // Now handle "real" floating types (i.e. float, double, long double).
8506 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8507 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8508 /*IsCompAssign = */ false);
8509
8510 // Finally, we have two differing integer types.
8512 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8513}
8514
8515/// Convert scalar operands to a vector that matches the
8516/// condition in length.
8517///
8518/// Used when handling the OpenCL conditional operator where the
8519/// condition is a vector while the other operands are scalar.
8520///
8521/// We first compute the "result type" for the scalar operands
8522/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8523/// into a vector of that type where the length matches the condition
8524/// vector type. s6.11.6 requires that the element types of the result
8525/// and the condition must have the same number of bits.
8526static QualType
8528 QualType CondTy, SourceLocation QuestionLoc) {
8529 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8530 if (ResTy.isNull()) return QualType();
8531
8532 const VectorType *CV = CondTy->getAs<VectorType>();
8533 assert(CV);
8534
8535 // Determine the vector result type
8536 unsigned NumElements = CV->getNumElements();
8537 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8538
8539 // Ensure that all types have the same number of bits
8541 != S.Context.getTypeSize(ResTy)) {
8542 // Since VectorTy is created internally, it does not pretty print
8543 // with an OpenCL name. Instead, we just print a description.
8544 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8545 SmallString<64> Str;
8546 llvm::raw_svector_ostream OS(Str);
8547 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8548 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8549 << CondTy << OS.str();
8550 return QualType();
8551 }
8552
8553 // Convert operands to the vector result type
8554 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8555 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8556
8557 return VectorTy;
8558}
8559
8560/// Return false if this is a valid OpenCL condition vector
8562 SourceLocation QuestionLoc) {
8563 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8564 // integral type.
8565 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8566 assert(CondTy);
8567 QualType EleTy = CondTy->getElementType();
8568 if (EleTy->isIntegerType()) return false;
8569
8570 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8571 << Cond->getType() << Cond->getSourceRange();
8572 return true;
8573}
8574
8575/// Return false if the vector condition type and the vector
8576/// result type are compatible.
8577///
8578/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8579/// number of elements, and their element types have the same number
8580/// of bits.
8581static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8582 SourceLocation QuestionLoc) {
8583 const VectorType *CV = CondTy->getAs<VectorType>();
8584 const VectorType *RV = VecResTy->getAs<VectorType>();
8585 assert(CV && RV);
8586
8587 if (CV->getNumElements() != RV->getNumElements()) {
8588 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8589 << CondTy << VecResTy;
8590 return true;
8591 }
8592
8593 QualType CVE = CV->getElementType();
8594 QualType RVE = RV->getElementType();
8595
8596 // Boolean vectors are permitted outside of OpenCL mode.
8597 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8598 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8599 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8600 << CondTy << VecResTy;
8601 return true;
8602 }
8603
8604 return false;
8605}
8606
8607/// Return the resulting type for the conditional operator in
8608/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8609/// s6.3.i) when the condition is a vector type.
8610static QualType
8612 ExprResult &LHS, ExprResult &RHS,
8613 SourceLocation QuestionLoc) {
8615 if (Cond.isInvalid())
8616 return QualType();
8617 QualType CondTy = Cond.get()->getType();
8618
8619 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8620 return QualType();
8621
8622 // If either operand is a vector then find the vector type of the
8623 // result as specified in OpenCL v1.1 s6.3.i.
8624 if (LHS.get()->getType()->isVectorType() ||
8625 RHS.get()->getType()->isVectorType()) {
8626 bool IsBoolVecLang =
8627 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8628 QualType VecResTy =
8629 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8630 /*isCompAssign*/ false,
8631 /*AllowBothBool*/ true,
8632 /*AllowBoolConversions*/ false,
8633 /*AllowBooleanOperation*/ IsBoolVecLang,
8634 /*ReportInvalid*/ true);
8635 if (VecResTy.isNull())
8636 return QualType();
8637 // The result type must match the condition type as specified in
8638 // OpenCL v1.1 s6.11.6.
8639 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8640 return QualType();
8641 return VecResTy;
8642 }
8643
8644 // Both operands are scalar.
8645 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8646}
8647
8648/// Return true if the Expr is block type
8649static bool checkBlockType(Sema &S, const Expr *E) {
8650 if (E->getType()->isBlockPointerType()) {
8651 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8652 return true;
8653 }
8654
8655 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8656 QualType Ty = CE->getCallee()->getType();
8657 if (Ty->isBlockPointerType()) {
8658 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8659 return true;
8660 }
8661 }
8662 return false;
8663}
8664
8665/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8666/// In that case, LHS = cond.
8667/// C99 6.5.15
8670 ExprObjectKind &OK,
8671 SourceLocation QuestionLoc) {
8672
8673 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8674 if (!LHSResult.isUsable()) return QualType();
8675 LHS = LHSResult;
8676
8677 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8678 if (!RHSResult.isUsable()) return QualType();
8679 RHS = RHSResult;
8680
8681 // C++ is sufficiently different to merit its own checker.
8682 if (getLangOpts().CPlusPlus)
8683 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8684
8685 VK = VK_PRValue;
8686 OK = OK_Ordinary;
8687
8688 if (Context.isDependenceAllowed() &&
8689 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8690 RHS.get()->isTypeDependent())) {
8691 assert(!getLangOpts().CPlusPlus);
8692 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8693 RHS.get()->containsErrors()) &&
8694 "should only occur in error-recovery path.");
8695 return Context.DependentTy;
8696 }
8697
8698 // The OpenCL operator with a vector condition is sufficiently
8699 // different to merit its own checker.
8700 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8701 Cond.get()->getType()->isExtVectorType())
8702 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8703
8704 // First, check the condition.
8706 if (Cond.isInvalid())
8707 return QualType();
8708 if (checkCondition(*this, Cond.get(), QuestionLoc))
8709 return QualType();
8710
8711 // Handle vectors.
8712 if (LHS.get()->getType()->isVectorType() ||
8713 RHS.get()->getType()->isVectorType())
8714 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8715 /*AllowBothBool*/ true,
8716 /*AllowBoolConversions*/ false,
8717 /*AllowBooleanOperation*/ false,
8718 /*ReportInvalid*/ true);
8719
8720 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8722 if (LHS.isInvalid() || RHS.isInvalid())
8723 return QualType();
8724
8725 // WebAssembly tables are not allowed as conditional LHS or RHS.
8726 QualType LHSTy = LHS.get()->getType();
8727 QualType RHSTy = RHS.get()->getType();
8728 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8729 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8730 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8731 return QualType();
8732 }
8733
8734 // Diagnose attempts to convert between __ibm128, __float128 and long double
8735 // where such conversions currently can't be handled.
8736 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8737 Diag(QuestionLoc,
8738 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8740 return QualType();
8741 }
8742
8743 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8744 // selection operator (?:).
8745 if (getLangOpts().OpenCL &&
8746 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8747 return QualType();
8748 }
8749
8750 // If both operands have arithmetic type, do the usual arithmetic conversions
8751 // to find a common type: C99 6.5.15p3,5.
8752 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8753 // Disallow invalid arithmetic conversions, such as those between bit-
8754 // precise integers types of different sizes, or between a bit-precise
8755 // integer and another type.
8756 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8757 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8758 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8759 << RHS.get()->getSourceRange();
8760 return QualType();
8761 }
8762
8763 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8764 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8765
8766 return ResTy;
8767 }
8768
8769 // If both operands are the same structure or union type, the result is that
8770 // type.
8771 // FIXME: Type of conditional expression must be complete in C mode.
8772 if (LHSTy->isRecordType() &&
8773 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8774 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8775 RHSTy.getUnqualifiedType());
8776
8777 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8778 // The following || allows only one side to be void (a GCC-ism).
8779 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8780 QualType ResTy;
8781 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8782 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8783 } else if (RHSTy->isVoidType()) {
8784 ResTy = RHSTy;
8785 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8786 << RHS.get()->getSourceRange();
8787 } else {
8788 ResTy = LHSTy;
8789 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8790 << LHS.get()->getSourceRange();
8791 }
8792 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8793 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8794 return ResTy;
8795 }
8796
8797 // C23 6.5.15p7:
8798 // ... if both the second and third operands have nullptr_t type, the
8799 // result also has that type.
8800 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8801 return ResTy;
8802
8803 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8804 // the type of the other operand."
8805 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8806 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8807
8808 // All objective-c pointer type analysis is done here.
8809 QualType compositeType =
8810 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8811 if (LHS.isInvalid() || RHS.isInvalid())
8812 return QualType();
8813 if (!compositeType.isNull())
8814 return compositeType;
8815
8816
8817 // Handle block pointer types.
8818 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8819 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8820 QuestionLoc);
8821
8822 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8823 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8824 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8825 QuestionLoc);
8826
8827 // GCC compatibility: soften pointer/integer mismatch. Note that
8828 // null pointers have been filtered out by this point.
8829 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8830 /*IsIntFirstExpr=*/true))
8831 return RHSTy;
8832 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8833 /*IsIntFirstExpr=*/false))
8834 return LHSTy;
8835
8836 // Emit a better diagnostic if one of the expressions is a null pointer
8837 // constant and the other is not a pointer type. In this case, the user most
8838 // likely forgot to take the address of the other expression.
8839 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8840 return QualType();
8841
8842 // Finally, if the LHS and RHS types are canonically the same type, we can
8843 // use the common sugared type.
8844 if (Context.hasSameType(LHSTy, RHSTy))
8845 return Context.getCommonSugaredType(LHSTy, RHSTy);
8846
8847 // Otherwise, the operands are not compatible.
8848 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8849 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8850 << RHS.get()->getSourceRange();
8851 return QualType();
8852}
8853
8854/// SuggestParentheses - Emit a note with a fixit hint that wraps
8855/// ParenRange in parentheses.
8857 const PartialDiagnostic &Note,
8858 SourceRange ParenRange) {
8859 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8860 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8861 EndLoc.isValid()) {
8862 Self.Diag(Loc, Note)
8863 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8864 << FixItHint::CreateInsertion(EndLoc, ")");
8865 } else {
8866 // We can't display the parentheses, so just show the bare note.
8867 Self.Diag(Loc, Note) << ParenRange;
8868 }
8869}
8870
8872 return BinaryOperator::isAdditiveOp(Opc) ||
8874 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8875 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8876 // not any of the logical operators. Bitwise-xor is commonly used as a
8877 // logical-xor because there is no logical-xor operator. The logical
8878 // operators, including uses of xor, have a high false positive rate for
8879 // precedence warnings.
8880}
8881
8882/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8883/// expression, either using a built-in or overloaded operator,
8884/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8885/// expression.
8886static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8887 const Expr **RHSExprs) {
8888 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8889 E = E->IgnoreImpCasts();
8891 E = E->IgnoreImpCasts();
8892 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8893 E = MTE->getSubExpr();
8894 E = E->IgnoreImpCasts();
8895 }
8896
8897 // Built-in binary operator.
8898 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8899 OP && IsArithmeticOp(OP->getOpcode())) {
8900 *Opcode = OP->getOpcode();
8901 *RHSExprs = OP->getRHS();
8902 return true;
8903 }
8904
8905 // Overloaded operator.
8906 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8907 if (Call->getNumArgs() != 2)
8908 return false;
8909
8910 // Make sure this is really a binary operator that is safe to pass into
8911 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8912 OverloadedOperatorKind OO = Call->getOperator();
8913 if (OO < OO_Plus || OO > OO_Arrow ||
8914 OO == OO_PlusPlus || OO == OO_MinusMinus)
8915 return false;
8916
8918 if (IsArithmeticOp(OpKind)) {
8919 *Opcode = OpKind;
8920 *RHSExprs = Call->getArg(1);
8921 return true;
8922 }
8923 }
8924
8925 return false;
8926}
8927
8928/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8929/// or is a logical expression such as (x==y) which has int type, but is
8930/// commonly interpreted as boolean.
8931static bool ExprLooksBoolean(const Expr *E) {
8932 E = E->IgnoreParenImpCasts();
8933
8934 if (E->getType()->isBooleanType())
8935 return true;
8936 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8937 return OP->isComparisonOp() || OP->isLogicalOp();
8938 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8939 return OP->getOpcode() == UO_LNot;
8940 if (E->getType()->isPointerType())
8941 return true;
8942 // FIXME: What about overloaded operator calls returning "unspecified boolean
8943 // type"s (commonly pointer-to-members)?
8944
8945 return false;
8946}
8947
8948/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8949/// and binary operator are mixed in a way that suggests the programmer assumed
8950/// the conditional operator has higher precedence, for example:
8951/// "int x = a + someBinaryCondition ? 1 : 2".
8953 Expr *Condition, const Expr *LHSExpr,
8954 const Expr *RHSExpr) {
8955 BinaryOperatorKind CondOpcode;
8956 const Expr *CondRHS;
8957
8958 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8959 return;
8960 if (!ExprLooksBoolean(CondRHS))
8961 return;
8962
8963 // The condition is an arithmetic binary expression, with a right-
8964 // hand side that looks boolean, so warn.
8965
8966 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8967 ? diag::warn_precedence_bitwise_conditional
8968 : diag::warn_precedence_conditional;
8969
8970 Self.Diag(OpLoc, DiagID)
8971 << Condition->getSourceRange()
8972 << BinaryOperator::getOpcodeStr(CondOpcode);
8973
8975 Self, OpLoc,
8976 Self.PDiag(diag::note_precedence_silence)
8977 << BinaryOperator::getOpcodeStr(CondOpcode),
8978 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8979
8980 SuggestParentheses(Self, OpLoc,
8981 Self.PDiag(diag::note_precedence_conditional_first),
8982 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8983}
8984
8985/// Compute the nullability of a conditional expression.
8987 QualType LHSTy, QualType RHSTy,
8988 ASTContext &Ctx) {
8989 if (!ResTy->isAnyPointerType())
8990 return ResTy;
8991
8992 auto GetNullability = [](QualType Ty) {
8993 std::optional<NullabilityKind> Kind = Ty->getNullability();
8994 if (Kind) {
8995 // For our purposes, treat _Nullable_result as _Nullable.
8998 return *Kind;
8999 }
9001 };
9002
9003 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9004 NullabilityKind MergedKind;
9005
9006 // Compute nullability of a binary conditional expression.
9007 if (IsBin) {
9008 if (LHSKind == NullabilityKind::NonNull)
9009 MergedKind = NullabilityKind::NonNull;
9010 else
9011 MergedKind = RHSKind;
9012 // Compute nullability of a normal conditional expression.
9013 } else {
9014 if (LHSKind == NullabilityKind::Nullable ||
9015 RHSKind == NullabilityKind::Nullable)
9016 MergedKind = NullabilityKind::Nullable;
9017 else if (LHSKind == NullabilityKind::NonNull)
9018 MergedKind = RHSKind;
9019 else if (RHSKind == NullabilityKind::NonNull)
9020 MergedKind = LHSKind;
9021 else
9022 MergedKind = NullabilityKind::Unspecified;
9023 }
9024
9025 // Return if ResTy already has the correct nullability.
9026 if (GetNullability(ResTy) == MergedKind)
9027 return ResTy;
9028
9029 // Strip all nullability from ResTy.
9030 while (ResTy->getNullability())
9031 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9032
9033 // Create a new AttributedType with the new nullability kind.
9034 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9035}
9036
9038 SourceLocation ColonLoc,
9039 Expr *CondExpr, Expr *LHSExpr,
9040 Expr *RHSExpr) {
9041 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9042 // was the condition.
9043 OpaqueValueExpr *opaqueValue = nullptr;
9044 Expr *commonExpr = nullptr;
9045 if (!LHSExpr) {
9046 commonExpr = CondExpr;
9047 // Lower out placeholder types first. This is important so that we don't
9048 // try to capture a placeholder. This happens in few cases in C++; such
9049 // as Objective-C++'s dictionary subscripting syntax.
9050 if (commonExpr->hasPlaceholderType()) {
9051 ExprResult result = CheckPlaceholderExpr(commonExpr);
9052 if (!result.isUsable()) return ExprError();
9053 commonExpr = result.get();
9054 }
9055 // We usually want to apply unary conversions *before* saving, except
9056 // in the special case of a C++ l-value conditional.
9057 if (!(getLangOpts().CPlusPlus
9058 && !commonExpr->isTypeDependent()
9059 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9060 && commonExpr->isGLValue()
9061 && commonExpr->isOrdinaryOrBitFieldObject()
9062 && RHSExpr->isOrdinaryOrBitFieldObject()
9063 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9064 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9065 if (commonRes.isInvalid())
9066 return ExprError();
9067 commonExpr = commonRes.get();
9068 }
9069
9070 // If the common expression is a class or array prvalue, materialize it
9071 // so that we can safely refer to it multiple times.
9072 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9073 commonExpr->getType()->isArrayType())) {
9074 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9075 if (MatExpr.isInvalid())
9076 return ExprError();
9077 commonExpr = MatExpr.get();
9078 }
9079
9080 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9081 commonExpr->getType(),
9082 commonExpr->getValueKind(),
9083 commonExpr->getObjectKind(),
9084 commonExpr);
9085 LHSExpr = CondExpr = opaqueValue;
9086 }
9087
9088 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9091 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9092 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9093 VK, OK, QuestionLoc);
9094 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9095 RHS.isInvalid())
9096 return ExprError();
9097
9098 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9099 RHS.get());
9100
9101 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9102
9103 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9104 Context);
9105
9106 if (!commonExpr)
9107 return new (Context)
9108 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9109 RHS.get(), result, VK, OK);
9110
9112 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9113 ColonLoc, result, VK, OK);
9114}
9115
9117 unsigned FromAttributes = 0, ToAttributes = 0;
9118 if (const auto *FromFn =
9119 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9120 FromAttributes =
9121 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9122 if (const auto *ToFn =
9123 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9124 ToAttributes =
9125 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9126
9127 return FromAttributes != ToAttributes;
9128}
9129
9130// checkPointerTypesForAssignment - This is a very tricky routine (despite
9131// being closely modeled after the C99 spec:-). The odd characteristic of this
9132// routine is it effectively iqnores the qualifiers on the top level pointee.
9133// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9134// FIXME: add a couple examples in this comment.
9136 QualType LHSType,
9137 QualType RHSType,
9138 SourceLocation Loc) {
9139 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9140 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9141
9142 // get the "pointed to" type (ignoring qualifiers at the top level)
9143 const Type *lhptee, *rhptee;
9144 Qualifiers lhq, rhq;
9145 std::tie(lhptee, lhq) =
9146 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9147 std::tie(rhptee, rhq) =
9148 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9149
9151
9152 // C99 6.5.16.1p1: This following citation is common to constraints
9153 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9154 // qualifiers of the type *pointed to* by the right;
9155
9156 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9157 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9159 // Ignore lifetime for further calculation.
9160 lhq.removeObjCLifetime();
9161 rhq.removeObjCLifetime();
9162 }
9163
9164 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9165 // Treat address-space mismatches as fatal.
9166 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9168
9169 // It's okay to add or remove GC or lifetime qualifiers when converting to
9170 // and from void*.
9173 S.getASTContext()) &&
9174 (lhptee->isVoidType() || rhptee->isVoidType()))
9175 ; // keep old
9176
9177 // Treat lifetime mismatches as fatal.
9178 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9180
9181 // Treat pointer-auth mismatches as fatal.
9182 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9184
9185 // For GCC/MS compatibility, other qualifier mismatches are treated
9186 // as still compatible in C.
9187 else
9189 }
9190
9191 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9192 // incomplete type and the other is a pointer to a qualified or unqualified
9193 // version of void...
9194 if (lhptee->isVoidType()) {
9195 if (rhptee->isIncompleteOrObjectType())
9196 return ConvTy;
9197
9198 // As an extension, we allow cast to/from void* to function pointer.
9199 assert(rhptee->isFunctionType());
9201 }
9202
9203 if (rhptee->isVoidType()) {
9204 // In C, void * to another pointer type is compatible, but we want to note
9205 // that there will be an implicit conversion happening here.
9206 if (lhptee->isIncompleteOrObjectType())
9207 return ConvTy == AssignConvertType::Compatible &&
9208 !S.getLangOpts().CPlusPlus
9210 : ConvTy;
9211
9212 // As an extension, we allow cast to/from void* to function pointer.
9213 assert(lhptee->isFunctionType());
9215 }
9216
9217 if (!S.Diags.isIgnored(
9218 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9219 Loc) &&
9220 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9221 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9223
9224 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9225 // unqualified versions of compatible types, ...
9226 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9227 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9228 // Check if the pointee types are compatible ignoring the sign.
9229 // We explicitly check for char so that we catch "char" vs
9230 // "unsigned char" on systems where "char" is unsigned.
9231 if (lhptee->isCharType())
9232 ltrans = S.Context.UnsignedCharTy;
9233 else if (lhptee->hasSignedIntegerRepresentation())
9234 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9235
9236 if (rhptee->isCharType())
9237 rtrans = S.Context.UnsignedCharTy;
9238 else if (rhptee->hasSignedIntegerRepresentation())
9239 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9240
9241 if (ltrans == rtrans) {
9242 // Types are compatible ignoring the sign. Qualifier incompatibility
9243 // takes priority over sign incompatibility because the sign
9244 // warning can be disabled.
9245 if (!S.IsAssignConvertCompatible(ConvTy))
9246 return ConvTy;
9247
9249 }
9250
9251 // If we are a multi-level pointer, it's possible that our issue is simply
9252 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9253 // the eventual target type is the same and the pointers have the same
9254 // level of indirection, this must be the issue.
9255 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9256 do {
9257 std::tie(lhptee, lhq) =
9258 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9259 std::tie(rhptee, rhq) =
9260 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9261
9262 // Inconsistent address spaces at this point is invalid, even if the
9263 // address spaces would be compatible.
9264 // FIXME: This doesn't catch address space mismatches for pointers of
9265 // different nesting levels, like:
9266 // __local int *** a;
9267 // int ** b = a;
9268 // It's not clear how to actually determine when such pointers are
9269 // invalidly incompatible.
9270 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9271 return AssignConvertType::
9272 IncompatibleNestedPointerAddressSpaceMismatch;
9273
9274 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9275
9276 if (lhptee == rhptee)
9278 }
9279
9280 // General pointer incompatibility takes priority over qualifiers.
9281 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9284 }
9285 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9286 // hasSameType, so we can skip further checks.
9287 const auto *LFT = ltrans->getAs<FunctionType>();
9288 const auto *RFT = rtrans->getAs<FunctionType>();
9289 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9290 // The invocation of IsFunctionConversion below will try to transform rtrans
9291 // to obtain an exact match for ltrans. This should not fail because of
9292 // mismatches in result type and parameter types, they were already checked
9293 // by typesAreCompatible above. So we will recreate rtrans (or where
9294 // appropriate ltrans) using the result type and parameter types from ltrans
9295 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9296 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9297 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9298 if (LFPT && RFPT) {
9299 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9300 LFPT->getParamTypes(),
9301 RFPT->getExtProtoInfo());
9302 } else if (LFPT) {
9304 EPI.ExtInfo = RFT->getExtInfo();
9305 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9306 LFPT->getParamTypes(), EPI);
9307 } else if (RFPT) {
9308 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9309 // all of its ExtProtoInfo. Transform ltrans instead.
9311 EPI.ExtInfo = LFT->getExtInfo();
9312 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9313 RFPT->getParamTypes(), EPI);
9314 } else {
9315 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9316 RFT->getExtInfo());
9317 }
9318 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9319 !S.IsFunctionConversion(rtrans, ltrans))
9321 }
9322 return ConvTy;
9323}
9324
9325/// checkBlockPointerTypesForAssignment - This routine determines whether two
9326/// block pointer types are compatible or whether a block and normal pointer
9327/// are compatible. It is more restrict than comparing two function pointer
9328// types.
9330 QualType LHSType,
9331 QualType RHSType) {
9332 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9333 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9334
9335 QualType lhptee, rhptee;
9336
9337 // get the "pointed to" type (ignoring qualifiers at the top level)
9338 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9339 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9340
9341 // In C++, the types have to match exactly.
9342 if (S.getLangOpts().CPlusPlus)
9344
9346
9347 // For blocks we enforce that qualifiers are identical.
9348 Qualifiers LQuals = lhptee.getLocalQualifiers();
9349 Qualifiers RQuals = rhptee.getLocalQualifiers();
9350 if (S.getLangOpts().OpenCL) {
9351 LQuals.removeAddressSpace();
9352 RQuals.removeAddressSpace();
9353 }
9354 if (LQuals != RQuals)
9356
9357 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9358 // assignment.
9359 // The current behavior is similar to C++ lambdas. A block might be
9360 // assigned to a variable iff its return type and parameters are compatible
9361 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9362 // an assignment. Presumably it should behave in way that a function pointer
9363 // assignment does in C, so for each parameter and return type:
9364 // * CVR and address space of LHS should be a superset of CVR and address
9365 // space of RHS.
9366 // * unqualified types should be compatible.
9367 if (S.getLangOpts().OpenCL) {
9369 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9370 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9372 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9374
9375 return ConvTy;
9376}
9377
9378/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9379/// for assignment compatibility.
9381 QualType LHSType,
9382 QualType RHSType) {
9383 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9384 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9385
9386 if (LHSType->isObjCBuiltinType()) {
9387 // Class is not compatible with ObjC object pointers.
9388 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9389 !RHSType->isObjCQualifiedClassType())
9392 }
9393 if (RHSType->isObjCBuiltinType()) {
9394 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9395 !LHSType->isObjCQualifiedClassType())
9398 }
9399 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9400 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9401
9402 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9403 // make an exception for id<P>
9404 !LHSType->isObjCQualifiedIdType())
9406
9407 if (S.Context.typesAreCompatible(LHSType, RHSType))
9409 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9412}
9413
9415 QualType LHSType,
9416 QualType RHSType) {
9417 // Fake up an opaque expression. We don't actually care about what
9418 // cast operations are required, so if CheckAssignmentConstraints
9419 // adds casts to this they'll be wasted, but fortunately that doesn't
9420 // usually happen on valid code.
9421 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9422 ExprResult RHSPtr = &RHSExpr;
9423 CastKind K;
9424
9425 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9426}
9427
9428/// This helper function returns true if QT is a vector type that has element
9429/// type ElementType.
9430static bool isVector(QualType QT, QualType ElementType) {
9431 if (const VectorType *VT = QT->getAs<VectorType>())
9432 return VT->getElementType().getCanonicalType() == ElementType;
9433 return false;
9434}
9435
9436/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9437/// has code to accommodate several GCC extensions when type checking
9438/// pointers. Here are some objectionable examples that GCC considers warnings:
9439///
9440/// int a, *pint;
9441/// short *pshort;
9442/// struct foo *pfoo;
9443///
9444/// pint = pshort; // warning: assignment from incompatible pointer type
9445/// a = pint; // warning: assignment makes integer from pointer without a cast
9446/// pint = a; // warning: assignment makes pointer from integer without a cast
9447/// pint = pfoo; // warning: assignment from incompatible pointer type
9448///
9449/// As a result, the code for dealing with pointers is more complex than the
9450/// C99 spec dictates.
9451///
9452/// Sets 'Kind' for any result kind except Incompatible.
9454 ExprResult &RHS,
9455 CastKind &Kind,
9456 bool ConvertRHS) {
9457 QualType RHSType = RHS.get()->getType();
9458 QualType OrigLHSType = LHSType;
9459
9460 // Get canonical types. We're not formatting these types, just comparing
9461 // them.
9462 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9463 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9464
9465 // Common case: no conversion required.
9466 if (LHSType == RHSType) {
9467 Kind = CK_NoOp;
9469 }
9470
9471 // If the LHS has an __auto_type, there are no additional type constraints
9472 // to be worried about.
9473 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9474 if (AT->isGNUAutoType()) {
9475 Kind = CK_NoOp;
9477 }
9478 }
9479
9480 // If we have an atomic type, try a non-atomic assignment, then just add an
9481 // atomic qualification step.
9482 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9484 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9486 return Result;
9487 if (Kind != CK_NoOp && ConvertRHS)
9488 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9489 Kind = CK_NonAtomicToAtomic;
9490 return Result;
9491 }
9492
9493 // If the left-hand side is a reference type, then we are in a
9494 // (rare!) case where we've allowed the use of references in C,
9495 // e.g., as a parameter type in a built-in function. In this case,
9496 // just make sure that the type referenced is compatible with the
9497 // right-hand side type. The caller is responsible for adjusting
9498 // LHSType so that the resulting expression does not have reference
9499 // type.
9500 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9501 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9502 Kind = CK_LValueBitCast;
9504 }
9506 }
9507
9508 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9509 // of an ExtVector type to the same ExtVector type.
9510 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9511 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9512 // Implicit conversions require the same number of elements.
9513 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9515
9516 if (LHSType->isExtVectorBoolType() &&
9517 RHSExtType->getElementType()->isIntegerType()) {
9518 Kind = CK_IntegralToBoolean;
9520 }
9521 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9522 if (Context.getLangOpts().OpenCL &&
9523 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9524 Kind = CK_BitCast;
9526 }
9528 }
9529 if (RHSType->isArithmeticType()) {
9530 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9531 if (ConvertRHS)
9532 RHS = prepareVectorSplat(LHSType, RHS.get());
9533 Kind = CK_VectorSplat;
9535 }
9536 }
9537
9538 // Conversions to or from vector type.
9539 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9540 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9541 // Allow assignments of an AltiVec vector type to an equivalent GCC
9542 // vector type and vice versa
9543 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9544 Kind = CK_BitCast;
9546 }
9547
9548 // If we are allowing lax vector conversions, and LHS and RHS are both
9549 // vectors, the total size only needs to be the same. This is a bitcast;
9550 // no bits are changed but the result type is different.
9551 if (isLaxVectorConversion(RHSType, LHSType)) {
9552 // The default for lax vector conversions with Altivec vectors will
9553 // change, so if we are converting between vector types where
9554 // at least one is an Altivec vector, emit a warning.
9555 if (Context.getTargetInfo().getTriple().isPPC() &&
9556 anyAltivecTypes(RHSType, LHSType) &&
9557 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9558 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9559 << RHSType << LHSType;
9560 Kind = CK_BitCast;
9562 }
9563 }
9564
9565 // When the RHS comes from another lax conversion (e.g. binops between
9566 // scalars and vectors) the result is canonicalized as a vector. When the
9567 // LHS is also a vector, the lax is allowed by the condition above. Handle
9568 // the case where LHS is a scalar.
9569 if (LHSType->isScalarType()) {
9570 const VectorType *VecType = RHSType->getAs<VectorType>();
9571 if (VecType && VecType->getNumElements() == 1 &&
9572 isLaxVectorConversion(RHSType, LHSType)) {
9573 if (Context.getTargetInfo().getTriple().isPPC() &&
9575 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9577 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9578 << RHSType << LHSType;
9579 ExprResult *VecExpr = &RHS;
9580 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9581 Kind = CK_BitCast;
9583 }
9584 }
9585
9586 // Allow assignments between fixed-length and sizeless SVE vectors.
9587 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9588 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9589 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9590 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9591 Kind = CK_BitCast;
9593 }
9594
9595 // Allow assignments between fixed-length and sizeless RVV vectors.
9596 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9597 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9598 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9599 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9600 Kind = CK_BitCast;
9602 }
9603 }
9604
9606 }
9607
9608 // Diagnose attempts to convert between __ibm128, __float128 and long double
9609 // where such conversions currently can't be handled.
9610 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9612
9613 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9614 // discards the imaginary part.
9615 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9616 !LHSType->getAs<ComplexType>())
9618
9619 // Arithmetic conversions.
9620 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9621 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9622 if (ConvertRHS)
9623 Kind = PrepareScalarCast(RHS, LHSType);
9625 }
9626
9627 // Conversions to normal pointers.
9628 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9629 // U* -> T*
9630 if (isa<PointerType>(RHSType)) {
9631 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9632 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9633 if (AddrSpaceL != AddrSpaceR)
9634 Kind = CK_AddressSpaceConversion;
9635 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9636 Kind = CK_NoOp;
9637 else
9638 Kind = CK_BitCast;
9639 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9640 RHS.get()->getBeginLoc());
9641 }
9642
9643 // int -> T*
9644 if (RHSType->isIntegerType()) {
9645 Kind = CK_IntegralToPointer; // FIXME: null?
9647 }
9648
9649 // C pointers are not compatible with ObjC object pointers,
9650 // with two exceptions:
9651 if (isa<ObjCObjectPointerType>(RHSType)) {
9652 // - conversions to void*
9653 if (LHSPointer->getPointeeType()->isVoidType()) {
9654 Kind = CK_BitCast;
9656 }
9657
9658 // - conversions from 'Class' to the redefinition type
9659 if (RHSType->isObjCClassType() &&
9660 Context.hasSameType(LHSType,
9661 Context.getObjCClassRedefinitionType())) {
9662 Kind = CK_BitCast;
9664 }
9665
9666 Kind = CK_BitCast;
9668 }
9669
9670 // U^ -> void*
9671 if (RHSType->getAs<BlockPointerType>()) {
9672 if (LHSPointer->getPointeeType()->isVoidType()) {
9673 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9674 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9675 ->getPointeeType()
9676 .getAddressSpace();
9677 Kind =
9678 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9680 }
9681 }
9682
9684 }
9685
9686 // Conversions to block pointers.
9687 if (isa<BlockPointerType>(LHSType)) {
9688 // U^ -> T^
9689 if (RHSType->isBlockPointerType()) {
9690 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9691 ->getPointeeType()
9692 .getAddressSpace();
9693 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9694 ->getPointeeType()
9695 .getAddressSpace();
9696 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9697 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9698 }
9699
9700 // int or null -> T^
9701 if (RHSType->isIntegerType()) {
9702 Kind = CK_IntegralToPointer; // FIXME: null
9704 }
9705
9706 // id -> T^
9707 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9708 Kind = CK_AnyPointerToBlockPointerCast;
9710 }
9711
9712 // void* -> T^
9713 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9714 if (RHSPT->getPointeeType()->isVoidType()) {
9715 Kind = CK_AnyPointerToBlockPointerCast;
9717 }
9718
9720 }
9721
9722 // Conversions to Objective-C pointers.
9723 if (isa<ObjCObjectPointerType>(LHSType)) {
9724 // A* -> B*
9725 if (RHSType->isObjCObjectPointerType()) {
9726 Kind = CK_BitCast;
9727 AssignConvertType result =
9728 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9729 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9731 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9733 return result;
9734 }
9735
9736 // int or null -> A*
9737 if (RHSType->isIntegerType()) {
9738 Kind = CK_IntegralToPointer; // FIXME: null
9740 }
9741
9742 // In general, C pointers are not compatible with ObjC object pointers,
9743 // with two exceptions:
9744 if (isa<PointerType>(RHSType)) {
9745 Kind = CK_CPointerToObjCPointerCast;
9746
9747 // - conversions from 'void*'
9748 if (RHSType->isVoidPointerType()) {
9750 }
9751
9752 // - conversions to 'Class' from its redefinition type
9753 if (LHSType->isObjCClassType() &&
9754 Context.hasSameType(RHSType,
9755 Context.getObjCClassRedefinitionType())) {
9757 }
9758
9760 }
9761
9762 // Only under strict condition T^ is compatible with an Objective-C pointer.
9763 if (RHSType->isBlockPointerType() &&
9765 if (ConvertRHS)
9767 Kind = CK_BlockPointerToObjCPointerCast;
9769 }
9770
9772 }
9773
9774 // Conversion to nullptr_t (C23 only)
9775 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9778 // null -> nullptr_t
9779 Kind = CK_NullToPointer;
9781 }
9782
9783 // Conversions from pointers that are not covered by the above.
9784 if (isa<PointerType>(RHSType)) {
9785 // T* -> _Bool
9786 if (LHSType == Context.BoolTy) {
9787 Kind = CK_PointerToBoolean;
9789 }
9790
9791 // T* -> int
9792 if (LHSType->isIntegerType()) {
9793 Kind = CK_PointerToIntegral;
9795 }
9796
9798 }
9799
9800 // Conversions from Objective-C pointers that are not covered by the above.
9801 if (isa<ObjCObjectPointerType>(RHSType)) {
9802 // T* -> _Bool
9803 if (LHSType == Context.BoolTy) {
9804 Kind = CK_PointerToBoolean;
9806 }
9807
9808 // T* -> int
9809 if (LHSType->isIntegerType()) {
9810 Kind = CK_PointerToIntegral;
9812 }
9813
9815 }
9816
9817 // struct A -> struct B
9818 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9819 if (Context.typesAreCompatible(LHSType, RHSType)) {
9820 Kind = CK_NoOp;
9822 }
9823 }
9824
9825 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9826 Kind = CK_IntToOCLSampler;
9828 }
9829
9831}
9832
9833/// Constructs a transparent union from an expression that is
9834/// used to initialize the transparent union.
9836 ExprResult &EResult, QualType UnionType,
9837 FieldDecl *Field) {
9838 // Build an initializer list that designates the appropriate member
9839 // of the transparent union.
9840 Expr *E = EResult.get();
9842 E, SourceLocation());
9843 Initializer->setType(UnionType);
9844 Initializer->setInitializedFieldInUnion(Field);
9845
9846 // Build a compound literal constructing a value of the transparent
9847 // union type from this initializer list.
9848 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9849 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9850 VK_PRValue, Initializer, false);
9851}
9852
9855 ExprResult &RHS) {
9856 QualType RHSType = RHS.get()->getType();
9857
9858 // If the ArgType is a Union type, we want to handle a potential
9859 // transparent_union GCC extension.
9860 const RecordType *UT = ArgType->getAsUnionType();
9861 if (!UT)
9863
9864 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
9865 if (!UD->hasAttr<TransparentUnionAttr>())
9867
9868 // The field to initialize within the transparent union.
9869 FieldDecl *InitField = nullptr;
9870 // It's compatible if the expression matches any of the fields.
9871 for (auto *it : UD->fields()) {
9872 if (it->getType()->isPointerType()) {
9873 // If the transparent union contains a pointer type, we allow:
9874 // 1) void pointer
9875 // 2) null pointer constant
9876 if (RHSType->isPointerType())
9877 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9878 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9879 InitField = it;
9880 break;
9881 }
9882
9885 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9886 CK_NullToPointer);
9887 InitField = it;
9888 break;
9889 }
9890 }
9891
9892 CastKind Kind;
9893 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
9895 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9896 InitField = it;
9897 break;
9898 }
9899 }
9900
9901 if (!InitField)
9903
9904 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9906}
9907
9909 ExprResult &CallerRHS,
9910 bool Diagnose,
9911 bool DiagnoseCFAudited,
9912 bool ConvertRHS) {
9913 // We need to be able to tell the caller whether we diagnosed a problem, if
9914 // they ask us to issue diagnostics.
9915 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9916
9917 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9918 // we can't avoid *all* modifications at the moment, so we need some somewhere
9919 // to put the updated value.
9920 ExprResult LocalRHS = CallerRHS;
9921 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9922
9923 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9924 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9925 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9926 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9927 Diag(RHS.get()->getExprLoc(),
9928 diag::warn_noderef_to_dereferenceable_pointer)
9929 << RHS.get()->getSourceRange();
9930 }
9931 }
9932 }
9933
9934 if (getLangOpts().CPlusPlus) {
9935 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9936 // C++ 5.17p3: If the left operand is not of class type, the
9937 // expression is implicitly converted (C++ 4) to the
9938 // cv-unqualified type of the left operand.
9939 QualType RHSType = RHS.get()->getType();
9940 if (Diagnose) {
9941 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9943 } else {
9946 /*SuppressUserConversions=*/false,
9947 AllowedExplicit::None,
9948 /*InOverloadResolution=*/false,
9949 /*CStyle=*/false,
9950 /*AllowObjCWritebackConversion=*/false);
9951 if (ICS.isFailure())
9953 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9955 }
9956 if (RHS.isInvalid())
9959 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9960 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9962 return result;
9963 }
9964
9965 // FIXME: Currently, we fall through and treat C++ classes like C
9966 // structures.
9967 // FIXME: We also fall through for atomics; not sure what should
9968 // happen there, though.
9969 } else if (RHS.get()->getType() == Context.OverloadTy) {
9970 // As a set of extensions to C, we support overloading on functions. These
9971 // functions need to be resolved here.
9972 DeclAccessPair DAP;
9974 RHS.get(), LHSType, /*Complain=*/false, DAP))
9975 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9976 else
9978 }
9979
9980 // This check seems unnatural, however it is necessary to ensure the proper
9981 // conversion of functions/arrays. If the conversion were done for all
9982 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9983 // expressions that suppress this implicit conversion (&, sizeof). This needs
9984 // to happen before we check for null pointer conversions because C does not
9985 // undergo the same implicit conversions as C++ does above (by the calls to
9986 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9987 // lvalue to rvalue cast before checking for null pointer constraints. This
9988 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9989 //
9990 // Suppress this for references: C++ 8.5.3p5.
9991 if (!LHSType->isReferenceType()) {
9992 // FIXME: We potentially allocate here even if ConvertRHS is false.
9994 if (RHS.isInvalid())
9996 }
9997
9998 // The constraints are expressed in terms of the atomic, qualified, or
9999 // unqualified type of the LHS.
10000 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10001
10002 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10003 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10004 if ((LHSTypeAfterConversion->isPointerType() ||
10005 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10006 LHSTypeAfterConversion->isBlockPointerType()) &&
10007 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10011 if (Diagnose || ConvertRHS) {
10012 CastKind Kind;
10013 CXXCastPath Path;
10014 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10015 /*IgnoreBaseAccess=*/false, Diagnose);
10016
10017 // If there is a conversion of some kind, check to see what kind of
10018 // pointer conversion happened so we can diagnose a C++ compatibility
10019 // diagnostic if the conversion is invalid. This only matters if the RHS
10020 // is some kind of void pointer. We have a carve-out when the RHS is from
10021 // a macro expansion because the use of a macro may indicate different
10022 // code between C and C++. Consider: char *s = NULL; where NULL is
10023 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10024 // C++, which is valid in C++.
10025 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10026 !RHS.get()->getBeginLoc().isMacroID()) {
10027 QualType CanRHS =
10029 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10030 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10031 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10032 RHS.get()->getExprLoc());
10033 // Anything that's not considered perfectly compatible would be
10034 // incompatible in C++.
10037 }
10038 }
10039
10040 if (ConvertRHS)
10041 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10042 }
10043 return Ret;
10044 }
10045 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10046 // unqualified bool, and the right operand is a pointer or its type is
10047 // nullptr_t.
10048 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10049 RHS.get()->getType()->isNullPtrType()) {
10050 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10051 // only handles nullptr -> _Bool due to needing an extra conversion
10052 // step.
10053 // We model this by converting from nullptr -> void * and then let the
10054 // conversion from void * -> _Bool happen naturally.
10055 if (Diagnose || ConvertRHS) {
10056 CastKind Kind;
10057 CXXCastPath Path;
10058 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10059 /*IgnoreBaseAccess=*/false, Diagnose);
10060 if (ConvertRHS)
10061 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10062 &Path);
10063 }
10064 }
10065
10066 // OpenCL queue_t type assignment.
10067 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10069 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10071 }
10072
10073 CastKind Kind;
10074 AssignConvertType result =
10075 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10076
10077 // If assigning a void * created by an allocation function call to some other
10078 // type, check that the allocated size is sufficient for that type.
10079 if (result != AssignConvertType::Incompatible &&
10080 RHS.get()->getType()->isVoidPointerType())
10081 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10082
10083 // C99 6.5.16.1p2: The value of the right operand is converted to the
10084 // type of the assignment expression.
10085 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10086 // so that we can use references in built-in functions even in C.
10087 // The getNonReferenceType() call makes sure that the resulting expression
10088 // does not have reference type.
10089 if (result != AssignConvertType::Incompatible &&
10090 RHS.get()->getType() != LHSType) {
10092 Expr *E = RHS.get();
10093
10094 // Check for various Objective-C errors. If we are not reporting
10095 // diagnostics and just checking for errors, e.g., during overload
10096 // resolution, return Incompatible to indicate the failure.
10097 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10098 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10100 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10101 if (!Diagnose)
10103 }
10104 if (getLangOpts().ObjC &&
10105 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10106 E->getType(), E, Diagnose) ||
10107 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10108 if (!Diagnose)
10110 // Replace the expression with a corrected version and continue so we
10111 // can find further errors.
10112 RHS = E;
10114 }
10115
10116 if (ConvertRHS)
10117 RHS = ImpCastExprToType(E, Ty, Kind);
10118 }
10119
10120 return result;
10121}
10122
10123namespace {
10124/// The original operand to an operator, prior to the application of the usual
10125/// arithmetic conversions and converting the arguments of a builtin operator
10126/// candidate.
10127struct OriginalOperand {
10128 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10129 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10130 Op = MTE->getSubExpr();
10131 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10132 Op = BTE->getSubExpr();
10133 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10134 Orig = ICE->getSubExprAsWritten();
10135 Conversion = ICE->getConversionFunction();
10136 }
10137 }
10138
10139 QualType getType() const { return Orig->getType(); }
10140
10141 Expr *Orig;
10142 NamedDecl *Conversion;
10143};
10144}
10145
10147 ExprResult &RHS) {
10148 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10149
10150 Diag(Loc, diag::err_typecheck_invalid_operands)
10151 << OrigLHS.getType() << OrigRHS.getType()
10152 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10153
10154 // If a user-defined conversion was applied to either of the operands prior
10155 // to applying the built-in operator rules, tell the user about it.
10156 if (OrigLHS.Conversion) {
10157 Diag(OrigLHS.Conversion->getLocation(),
10158 diag::note_typecheck_invalid_operands_converted)
10159 << 0 << LHS.get()->getType();
10160 }
10161 if (OrigRHS.Conversion) {
10162 Diag(OrigRHS.Conversion->getLocation(),
10163 diag::note_typecheck_invalid_operands_converted)
10164 << 1 << RHS.get()->getType();
10165 }
10166
10167 return QualType();
10168}
10169
10171 ExprResult &RHS) {
10172 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10173 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10174
10175 bool LHSNatVec = LHSType->isVectorType();
10176 bool RHSNatVec = RHSType->isVectorType();
10177
10178 if (!(LHSNatVec && RHSNatVec)) {
10179 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10180 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10181 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10182 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10183 << Vector->getSourceRange();
10184 return QualType();
10185 }
10186
10187 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10188 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10189 << RHS.get()->getSourceRange();
10190
10191 return QualType();
10192}
10193
10194/// Try to convert a value of non-vector type to a vector type by converting
10195/// the type to the element type of the vector and then performing a splat.
10196/// If the language is OpenCL, we only use conversions that promote scalar
10197/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10198/// for float->int.
10199///
10200/// OpenCL V2.0 6.2.6.p2:
10201/// An error shall occur if any scalar operand type has greater rank
10202/// than the type of the vector element.
10203///
10204/// \param scalar - if non-null, actually perform the conversions
10205/// \return true if the operation fails (but without diagnosing the failure)
10207 QualType scalarTy,
10208 QualType vectorEltTy,
10209 QualType vectorTy,
10210 unsigned &DiagID) {
10211 // The conversion to apply to the scalar before splatting it,
10212 // if necessary.
10213 CastKind scalarCast = CK_NoOp;
10214
10215 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10216 scalarCast = CK_IntegralToBoolean;
10217 } else if (vectorEltTy->isIntegralType(S.Context)) {
10218 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10219 (scalarTy->isIntegerType() &&
10220 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10221 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10222 return true;
10223 }
10224 if (!scalarTy->isIntegralType(S.Context))
10225 return true;
10226 scalarCast = CK_IntegralCast;
10227 } else if (vectorEltTy->isRealFloatingType()) {
10228 if (scalarTy->isRealFloatingType()) {
10229 if (S.getLangOpts().OpenCL &&
10230 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10231 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10232 return true;
10233 }
10234 scalarCast = CK_FloatingCast;
10235 }
10236 else if (scalarTy->isIntegralType(S.Context))
10237 scalarCast = CK_IntegralToFloating;
10238 else
10239 return true;
10240 } else {
10241 return true;
10242 }
10243
10244 // Adjust scalar if desired.
10245 if (scalar) {
10246 if (scalarCast != CK_NoOp)
10247 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10248 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10249 }
10250 return false;
10251}
10252
10253/// Convert vector E to a vector with the same number of elements but different
10254/// element type.
10255static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10256 const auto *VecTy = E->getType()->getAs<VectorType>();
10257 assert(VecTy && "Expression E must be a vector");
10258 QualType NewVecTy =
10259 VecTy->isExtVectorType()
10260 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10261 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10262 VecTy->getVectorKind());
10263
10264 // Look through the implicit cast. Return the subexpression if its type is
10265 // NewVecTy.
10266 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10267 if (ICE->getSubExpr()->getType() == NewVecTy)
10268 return ICE->getSubExpr();
10269
10270 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10271 return S.ImpCastExprToType(E, NewVecTy, Cast);
10272}
10273
10274/// Test if a (constant) integer Int can be casted to another integer type
10275/// IntTy without losing precision.
10277 QualType OtherIntTy) {
10278 Expr *E = Int->get();
10280 return false;
10281
10282 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10283
10284 // Reject cases where the value of the Int is unknown as that would
10285 // possibly cause truncation, but accept cases where the scalar can be
10286 // demoted without loss of precision.
10287 Expr::EvalResult EVResult;
10288 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10289 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10290 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10291 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10292
10293 if (CstInt) {
10294 // If the scalar is constant and is of a higher order and has more active
10295 // bits that the vector element type, reject it.
10296 llvm::APSInt Result = EVResult.Val.getInt();
10297 unsigned NumBits = IntSigned
10298 ? (Result.isNegative() ? Result.getSignificantBits()
10299 : Result.getActiveBits())
10300 : Result.getActiveBits();
10301 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10302 return true;
10303
10304 // If the signedness of the scalar type and the vector element type
10305 // differs and the number of bits is greater than that of the vector
10306 // element reject it.
10307 return (IntSigned != OtherIntSigned &&
10308 NumBits > S.Context.getIntWidth(OtherIntTy));
10309 }
10310
10311 // Reject cases where the value of the scalar is not constant and it's
10312 // order is greater than that of the vector element type.
10313 return (Order < 0);
10314}
10315
10316/// Test if a (constant) integer Int can be casted to floating point type
10317/// FloatTy without losing precision.
10319 QualType FloatTy) {
10320 if (Int->get()->containsErrors())
10321 return false;
10322
10323 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10324
10325 // Determine if the integer constant can be expressed as a floating point
10326 // number of the appropriate type.
10327 Expr::EvalResult EVResult;
10328 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10329
10330 uint64_t Bits = 0;
10331 if (CstInt) {
10332 // Reject constants that would be truncated if they were converted to
10333 // the floating point type. Test by simple to/from conversion.
10334 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10335 // could be avoided if there was a convertFromAPInt method
10336 // which could signal back if implicit truncation occurred.
10337 llvm::APSInt Result = EVResult.Val.getInt();
10338 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10339 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10340 llvm::APFloat::rmTowardZero);
10341 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10343 bool Ignored = false;
10344 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10345 &Ignored);
10346 if (Result != ConvertBack)
10347 return true;
10348 } else {
10349 // Reject types that cannot be fully encoded into the mantissa of
10350 // the float.
10351 Bits = S.Context.getTypeSize(IntTy);
10352 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10353 S.Context.getFloatTypeSemantics(FloatTy));
10354 if (Bits > FloatPrec)
10355 return true;
10356 }
10357
10358 return false;
10359}
10360
10361/// Attempt to convert and splat Scalar into a vector whose types matches
10362/// Vector following GCC conversion rules. The rule is that implicit
10363/// conversion can occur when Scalar can be casted to match Vector's element
10364/// type without causing truncation of Scalar.
10366 ExprResult *Vector) {
10367 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10368 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10369 QualType VectorEltTy;
10370
10371 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10372 assert(!isa<ExtVectorType>(VT) &&
10373 "ExtVectorTypes should not be handled here!");
10374 VectorEltTy = VT->getElementType();
10375 } else if (VectorTy->isSveVLSBuiltinType()) {
10376 VectorEltTy =
10377 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10378 } else {
10379 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10380 }
10381
10382 // Reject cases where the vector element type or the scalar element type are
10383 // not integral or floating point types.
10384 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10385 return true;
10386
10387 // The conversion to apply to the scalar before splatting it,
10388 // if necessary.
10389 CastKind ScalarCast = CK_NoOp;
10390
10391 // Accept cases where the vector elements are integers and the scalar is
10392 // an integer.
10393 // FIXME: Notionally if the scalar was a floating point value with a precise
10394 // integral representation, we could cast it to an appropriate integer
10395 // type and then perform the rest of the checks here. GCC will perform
10396 // this conversion in some cases as determined by the input language.
10397 // We should accept it on a language independent basis.
10398 if (VectorEltTy->isIntegralType(S.Context) &&
10399 ScalarTy->isIntegralType(S.Context) &&
10400 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10401
10402 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10403 return true;
10404
10405 ScalarCast = CK_IntegralCast;
10406 } else if (VectorEltTy->isIntegralType(S.Context) &&
10407 ScalarTy->isRealFloatingType()) {
10408 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10409 ScalarCast = CK_FloatingToIntegral;
10410 else
10411 return true;
10412 } else if (VectorEltTy->isRealFloatingType()) {
10413 if (ScalarTy->isRealFloatingType()) {
10414
10415 // Reject cases where the scalar type is not a constant and has a higher
10416 // Order than the vector element type.
10417 llvm::APFloat Result(0.0);
10418
10419 // Determine whether this is a constant scalar. In the event that the
10420 // value is dependent (and thus cannot be evaluated by the constant
10421 // evaluator), skip the evaluation. This will then diagnose once the
10422 // expression is instantiated.
10423 bool CstScalar = Scalar->get()->isValueDependent() ||
10424 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10425 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10426 if (!CstScalar && Order < 0)
10427 return true;
10428
10429 // If the scalar cannot be safely casted to the vector element type,
10430 // reject it.
10431 if (CstScalar) {
10432 bool Truncated = false;
10433 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10434 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10435 if (Truncated)
10436 return true;
10437 }
10438
10439 ScalarCast = CK_FloatingCast;
10440 } else if (ScalarTy->isIntegralType(S.Context)) {
10441 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10442 return true;
10443
10444 ScalarCast = CK_IntegralToFloating;
10445 } else
10446 return true;
10447 } else if (ScalarTy->isEnumeralType())
10448 return true;
10449
10450 // Adjust scalar if desired.
10451 if (ScalarCast != CK_NoOp)
10452 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10453 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10454 return false;
10455}
10456
10458 SourceLocation Loc, bool IsCompAssign,
10459 bool AllowBothBool,
10460 bool AllowBoolConversions,
10461 bool AllowBoolOperation,
10462 bool ReportInvalid) {
10463 if (!IsCompAssign) {
10465 if (LHS.isInvalid())
10466 return QualType();
10467 }
10469 if (RHS.isInvalid())
10470 return QualType();
10471
10472 // For conversion purposes, we ignore any qualifiers.
10473 // For example, "const float" and "float" are equivalent.
10474 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10475 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10476
10477 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10478 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10479 assert(LHSVecType || RHSVecType);
10480
10481 if (getLangOpts().HLSL)
10482 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10483 IsCompAssign);
10484
10485 // Any operation with MFloat8 type is only possible with C intrinsics
10486 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10487 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10488 return InvalidOperands(Loc, LHS, RHS);
10489
10490 // AltiVec-style "vector bool op vector bool" combinations are allowed
10491 // for some operators but not others.
10492 if (!AllowBothBool && LHSVecType &&
10493 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10494 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10495 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10496
10497 // This operation may not be performed on boolean vectors.
10498 if (!AllowBoolOperation &&
10499 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10500 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10501
10502 // If the vector types are identical, return.
10503 if (Context.hasSameType(LHSType, RHSType))
10504 return Context.getCommonSugaredType(LHSType, RHSType);
10505
10506 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10507 if (LHSVecType && RHSVecType &&
10508 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10509 if (isa<ExtVectorType>(LHSVecType)) {
10510 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10511 return LHSType;
10512 }
10513
10514 if (!IsCompAssign)
10515 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10516 return RHSType;
10517 }
10518
10519 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10520 // can be mixed, with the result being the non-bool type. The non-bool
10521 // operand must have integer element type.
10522 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10523 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10524 (Context.getTypeSize(LHSVecType->getElementType()) ==
10525 Context.getTypeSize(RHSVecType->getElementType()))) {
10526 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10527 LHSVecType->getElementType()->isIntegerType() &&
10528 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10529 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10530 return LHSType;
10531 }
10532 if (!IsCompAssign &&
10533 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10534 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10535 RHSVecType->getElementType()->isIntegerType()) {
10536 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10537 return RHSType;
10538 }
10539 }
10540
10541 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10542 // invalid since the ambiguity can affect the ABI.
10543 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10544 unsigned &SVEorRVV) {
10545 const VectorType *VecType = SecondType->getAs<VectorType>();
10546 SVEorRVV = 0;
10547 if (FirstType->isSizelessBuiltinType() && VecType) {
10550 return true;
10556 SVEorRVV = 1;
10557 return true;
10558 }
10559 }
10560
10561 return false;
10562 };
10563
10564 unsigned SVEorRVV;
10565 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10566 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10567 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10568 << SVEorRVV << LHSType << RHSType;
10569 return QualType();
10570 }
10571
10572 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10573 // invalid since the ambiguity can affect the ABI.
10574 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10575 unsigned &SVEorRVV) {
10576 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10577 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10578
10579 SVEorRVV = 0;
10580 if (FirstVecType && SecondVecType) {
10581 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10582 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10583 SecondVecType->getVectorKind() ==
10585 return true;
10586 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10587 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10588 SecondVecType->getVectorKind() ==
10590 SecondVecType->getVectorKind() ==
10592 SecondVecType->getVectorKind() ==
10594 SVEorRVV = 1;
10595 return true;
10596 }
10597 }
10598 return false;
10599 }
10600
10601 if (SecondVecType &&
10602 SecondVecType->getVectorKind() == VectorKind::Generic) {
10603 if (FirstType->isSVESizelessBuiltinType())
10604 return true;
10605 if (FirstType->isRVVSizelessBuiltinType()) {
10606 SVEorRVV = 1;
10607 return true;
10608 }
10609 }
10610
10611 return false;
10612 };
10613
10614 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10615 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10616 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10617 << SVEorRVV << LHSType << RHSType;
10618 return QualType();
10619 }
10620
10621 // If there's a vector type and a scalar, try to convert the scalar to
10622 // the vector element type and splat.
10623 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10624 if (!RHSVecType) {
10625 if (isa<ExtVectorType>(LHSVecType)) {
10626 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10627 LHSVecType->getElementType(), LHSType,
10628 DiagID))
10629 return LHSType;
10630 } else {
10631 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10632 return LHSType;
10633 }
10634 }
10635 if (!LHSVecType) {
10636 if (isa<ExtVectorType>(RHSVecType)) {
10637 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10638 LHSType, RHSVecType->getElementType(),
10639 RHSType, DiagID))
10640 return RHSType;
10641 } else {
10642 if (LHS.get()->isLValue() ||
10643 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10644 return RHSType;
10645 }
10646 }
10647
10648 // FIXME: The code below also handles conversion between vectors and
10649 // non-scalars, we should break this down into fine grained specific checks
10650 // and emit proper diagnostics.
10651 QualType VecType = LHSVecType ? LHSType : RHSType;
10652 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10653 QualType OtherType = LHSVecType ? RHSType : LHSType;
10654 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10655 if (isLaxVectorConversion(OtherType, VecType)) {
10656 if (Context.getTargetInfo().getTriple().isPPC() &&
10657 anyAltivecTypes(RHSType, LHSType) &&
10658 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10659 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10660 // If we're allowing lax vector conversions, only the total (data) size
10661 // needs to be the same. For non compound assignment, if one of the types is
10662 // scalar, the result is always the vector type.
10663 if (!IsCompAssign) {
10664 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10665 return VecType;
10666 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10667 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10668 // type. Note that this is already done by non-compound assignments in
10669 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10670 // <1 x T> -> T. The result is also a vector type.
10671 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10672 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10673 ExprResult *RHSExpr = &RHS;
10674 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10675 return VecType;
10676 }
10677 }
10678
10679 // Okay, the expression is invalid.
10680
10681 // If there's a non-vector, non-real operand, diagnose that.
10682 if ((!RHSVecType && !RHSType->isRealType()) ||
10683 (!LHSVecType && !LHSType->isRealType())) {
10684 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10685 << LHSType << RHSType
10686 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10687 return QualType();
10688 }
10689
10690 // OpenCL V1.1 6.2.6.p1:
10691 // If the operands are of more than one vector type, then an error shall
10692 // occur. Implicit conversions between vector types are not permitted, per
10693 // section 6.2.1.
10694 if (getLangOpts().OpenCL &&
10695 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10696 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10697 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10698 << RHSType;
10699 return QualType();
10700 }
10701
10702
10703 // If there is a vector type that is not a ExtVector and a scalar, we reach
10704 // this point if scalar could not be converted to the vector's element type
10705 // without truncation.
10706 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10707 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10708 QualType Scalar = LHSVecType ? RHSType : LHSType;
10709 QualType Vector = LHSVecType ? LHSType : RHSType;
10710 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10711 Diag(Loc,
10712 diag::err_typecheck_vector_not_convertable_implict_truncation)
10713 << ScalarOrVector << Scalar << Vector;
10714
10715 return QualType();
10716 }
10717
10718 // Otherwise, use the generic diagnostic.
10719 Diag(Loc, DiagID)
10720 << LHSType << RHSType
10721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10722 return QualType();
10723}
10724
10726 SourceLocation Loc,
10727 bool IsCompAssign,
10728 ArithConvKind OperationKind) {
10729 if (!IsCompAssign) {
10731 if (LHS.isInvalid())
10732 return QualType();
10733 }
10735 if (RHS.isInvalid())
10736 return QualType();
10737
10738 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10739 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10740
10741 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10742 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10743
10744 unsigned DiagID = diag::err_typecheck_invalid_operands;
10745 if ((OperationKind == ArithConvKind::Arithmetic) &&
10746 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10747 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10748 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10749 << RHS.get()->getSourceRange();
10750 return QualType();
10751 }
10752
10753 if (Context.hasSameType(LHSType, RHSType))
10754 return LHSType;
10755
10756 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10757 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10758 return LHSType;
10759 }
10760 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10761 if (LHS.get()->isLValue() ||
10762 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10763 return RHSType;
10764 }
10765
10766 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10767 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10768 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10769 << LHSType << RHSType << LHS.get()->getSourceRange()
10770 << RHS.get()->getSourceRange();
10771 return QualType();
10772 }
10773
10774 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10775 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10776 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10777 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10778 << LHSType << RHSType << LHS.get()->getSourceRange()
10779 << RHS.get()->getSourceRange();
10780 return QualType();
10781 }
10782
10783 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10784 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10785 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10786 bool ScalarOrVector =
10787 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10788
10789 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10790 << ScalarOrVector << Scalar << Vector;
10791
10792 return QualType();
10793 }
10794
10795 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10796 << RHS.get()->getSourceRange();
10797 return QualType();
10798}
10799
10800// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10801// expression. These are mainly cases where the null pointer is used as an
10802// integer instead of a pointer.
10804 SourceLocation Loc, bool IsCompare) {
10805 // The canonical way to check for a GNU null is with isNullPointerConstant,
10806 // but we use a bit of a hack here for speed; this is a relatively
10807 // hot path, and isNullPointerConstant is slow.
10808 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10809 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10810
10811 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10812
10813 // Avoid analyzing cases where the result will either be invalid (and
10814 // diagnosed as such) or entirely valid and not something to warn about.
10815 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10816 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10817 return;
10818
10819 // Comparison operations would not make sense with a null pointer no matter
10820 // what the other expression is.
10821 if (!IsCompare) {
10822 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10823 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10824 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10825 return;
10826 }
10827
10828 // The rest of the operations only make sense with a null pointer
10829 // if the other expression is a pointer.
10830 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10831 NonNullType->canDecayToPointerType())
10832 return;
10833
10834 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10835 << LHSNull /* LHS is NULL */ << NonNullType
10836 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10837}
10838
10840 SourceLocation OpLoc) {
10841 // If the divisor is real, then this is real/real or complex/real division.
10842 // Either way there can be no precision loss.
10843 auto *CT = DivisorTy->getAs<ComplexType>();
10844 if (!CT)
10845 return;
10846
10847 QualType ElementType = CT->getElementType().getCanonicalType();
10848 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10850 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10851 return;
10852
10853 ASTContext &Ctx = S.getASTContext();
10854 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10855 const llvm::fltSemantics &ElementTypeSemantics =
10856 Ctx.getFloatTypeSemantics(ElementType);
10857 const llvm::fltSemantics &HigherElementTypeSemantics =
10858 Ctx.getFloatTypeSemantics(HigherElementType);
10859
10860 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10861 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10862 (HigherElementType == Ctx.LongDoubleTy &&
10863 !Ctx.getTargetInfo().hasLongDoubleType())) {
10864 // Retain the location of the first use of higher precision type.
10867 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10868 if (Type == HigherElementType) {
10869 Num++;
10870 return;
10871 }
10872 }
10873 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
10874 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
10875 }
10876}
10877
10879 SourceLocation Loc) {
10880 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10881 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10882 if (!LUE || !RUE)
10883 return;
10884 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10885 RUE->getKind() != UETT_SizeOf)
10886 return;
10887
10888 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10889 QualType LHSTy = LHSArg->getType();
10890 QualType RHSTy;
10891
10892 if (RUE->isArgumentType())
10893 RHSTy = RUE->getArgumentType().getNonReferenceType();
10894 else
10895 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10896
10897 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10898 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10899 return;
10900
10901 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10902 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10903 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10904 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10905 << LHSArgDecl;
10906 }
10907 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10908 QualType ArrayElemTy = ArrayTy->getElementType();
10909 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10910 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10911 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10912 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10913 return;
10914 S.Diag(Loc, diag::warn_division_sizeof_array)
10915 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10916 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10917 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10918 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10919 << LHSArgDecl;
10920 }
10921
10922 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10923 }
10924}
10925
10927 ExprResult &RHS,
10928 SourceLocation Loc, bool IsDiv) {
10929 // Check for division/remainder by zero.
10930 Expr::EvalResult RHSValue;
10931 if (!RHS.get()->isValueDependent() &&
10932 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10933 RHSValue.Val.getInt() == 0)
10934 S.DiagRuntimeBehavior(Loc, RHS.get(),
10935 S.PDiag(diag::warn_remainder_division_by_zero)
10936 << IsDiv << RHS.get()->getSourceRange());
10937}
10938
10939static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
10940 const ExprResult &LHS, const ExprResult &RHS,
10941 BinaryOperatorKind Opc) {
10942 if (!LHS.isUsable() || !RHS.isUsable())
10943 return;
10944 const Expr *LHSExpr = LHS.get();
10945 const Expr *RHSExpr = RHS.get();
10946 const QualType LHSType = LHSExpr->getType();
10947 const QualType RHSType = RHSExpr->getType();
10948 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10949 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10950 if (!LHSIsScoped && !RHSIsScoped)
10951 return;
10952 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10953 return;
10954 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10955 return;
10956 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10957 return;
10958 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10959 SourceLocation BeginLoc = expr->getBeginLoc();
10960 QualType IntType = type->castAs<EnumType>()
10961 ->getDecl()
10962 ->getDefinitionOrSelf()
10963 ->getIntegerType();
10964 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10965 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
10966 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
10967 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
10968 };
10969 if (LHSIsScoped) {
10970 DiagnosticHelper(LHSExpr, LHSType);
10971 }
10972 if (RHSIsScoped) {
10973 DiagnosticHelper(RHSExpr, RHSType);
10974 }
10975}
10976
10978 SourceLocation Loc,
10979 BinaryOperatorKind Opc) {
10980 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10981 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10982
10983 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10984
10985 QualType LHSTy = LHS.get()->getType();
10986 QualType RHSTy = RHS.get()->getType();
10987 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10988 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10989 /*AllowBothBool*/ getLangOpts().AltiVec,
10990 /*AllowBoolConversions*/ false,
10991 /*AllowBooleanOperation*/ false,
10992 /*ReportInvalid*/ true);
10993 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10994 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10996 if (!IsDiv &&
10997 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10998 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10999 // For division, only matrix-by-scalar is supported. Other combinations with
11000 // matrix types are invalid.
11001 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11002 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11003
11005 LHS, RHS, Loc,
11007 if (LHS.isInvalid() || RHS.isInvalid())
11008 return QualType();
11009
11010 if (compType.isNull() || !compType->isArithmeticType()) {
11011 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11012 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11013 return ResultTy;
11014 }
11015 if (IsDiv) {
11016 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11017 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11018 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11019 }
11020 return compType;
11021}
11022
11024 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11025 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11026
11027 // Note: This check is here to simplify the double exclusions of
11028 // scalar and vector HLSL checks. No getLangOpts().HLSL
11029 // is needed since all languages exlcude doubles.
11030 if (LHS.get()->getType()->isDoubleType() ||
11031 RHS.get()->getType()->isDoubleType() ||
11032 (LHS.get()->getType()->isVectorType() && LHS.get()
11033 ->getType()
11034 ->getAs<VectorType>()
11035 ->getElementType()
11036 ->isDoubleType()) ||
11037 (RHS.get()->getType()->isVectorType() && RHS.get()
11038 ->getType()
11039 ->getAs<VectorType>()
11040 ->getElementType()
11041 ->isDoubleType()))
11042 return InvalidOperands(Loc, LHS, RHS);
11043
11044 if (LHS.get()->getType()->isVectorType() ||
11045 RHS.get()->getType()->isVectorType()) {
11046 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11047 RHS.get()->getType()->hasIntegerRepresentation()) ||
11048 (getLangOpts().HLSL &&
11049 (LHS.get()->getType()->hasFloatingRepresentation() ||
11051 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11052 /*AllowBothBool*/ getLangOpts().AltiVec,
11053 /*AllowBoolConversions*/ false,
11054 /*AllowBooleanOperation*/ false,
11055 /*ReportInvalid*/ true);
11056 return InvalidOperands(Loc, LHS, RHS);
11057 }
11058
11059 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11060 RHS.get()->getType()->isSveVLSBuiltinType()) {
11061 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11063 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11065
11066 return InvalidOperands(Loc, LHS, RHS);
11067 }
11068
11070 LHS, RHS, Loc,
11072 if (LHS.isInvalid() || RHS.isInvalid())
11073 return QualType();
11074
11075 if (compType.isNull() ||
11076 (!compType->isIntegerType() &&
11077 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11078 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11079 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11080 IsCompAssign ? BO_RemAssign : BO_Rem);
11081 return ResultTy;
11082 }
11083 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11084 return compType;
11085}
11086
11087/// Diagnose invalid arithmetic on two void pointers.
11089 Expr *LHSExpr, Expr *RHSExpr) {
11090 S.Diag(Loc, S.getLangOpts().CPlusPlus
11091 ? diag::err_typecheck_pointer_arith_void_type
11092 : diag::ext_gnu_void_ptr)
11093 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11094 << RHSExpr->getSourceRange();
11095}
11096
11097/// Diagnose invalid arithmetic on a void pointer.
11099 Expr *Pointer) {
11100 S.Diag(Loc, S.getLangOpts().CPlusPlus
11101 ? diag::err_typecheck_pointer_arith_void_type
11102 : diag::ext_gnu_void_ptr)
11103 << 0 /* one pointer */ << Pointer->getSourceRange();
11104}
11105
11106/// Diagnose invalid arithmetic on a null pointer.
11107///
11108/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11109/// idiom, which we recognize as a GNU extension.
11110///
11112 Expr *Pointer, bool IsGNUIdiom) {
11113 if (IsGNUIdiom)
11114 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11115 << Pointer->getSourceRange();
11116 else
11117 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11118 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11119}
11120
11121/// Diagnose invalid subraction on a null pointer.
11122///
11124 Expr *Pointer, bool BothNull) {
11125 // Null - null is valid in C++ [expr.add]p7
11126 if (BothNull && S.getLangOpts().CPlusPlus)
11127 return;
11128
11129 // Is this s a macro from a system header?
11131 return;
11132
11134 S.PDiag(diag::warn_pointer_sub_null_ptr)
11135 << S.getLangOpts().CPlusPlus
11136 << Pointer->getSourceRange());
11137}
11138
11139/// Diagnose invalid arithmetic on two function pointers.
11141 Expr *LHS, Expr *RHS) {
11142 assert(LHS->getType()->isAnyPointerType());
11143 assert(RHS->getType()->isAnyPointerType());
11144 S.Diag(Loc, S.getLangOpts().CPlusPlus
11145 ? diag::err_typecheck_pointer_arith_function_type
11146 : diag::ext_gnu_ptr_func_arith)
11147 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11148 // We only show the second type if it differs from the first.
11150 RHS->getType())
11151 << RHS->getType()->getPointeeType()
11152 << LHS->getSourceRange() << RHS->getSourceRange();
11153}
11154
11155/// Diagnose invalid arithmetic on a function pointer.
11157 Expr *Pointer) {
11158 assert(Pointer->getType()->isAnyPointerType());
11159 S.Diag(Loc, S.getLangOpts().CPlusPlus
11160 ? diag::err_typecheck_pointer_arith_function_type
11161 : diag::ext_gnu_ptr_func_arith)
11162 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11163 << 0 /* one pointer, so only one type */
11164 << Pointer->getSourceRange();
11165}
11166
11167/// Emit error if Operand is incomplete pointer type
11168///
11169/// \returns True if pointer has incomplete type
11171 Expr *Operand) {
11172 QualType ResType = Operand->getType();
11173 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11174 ResType = ResAtomicType->getValueType();
11175
11176 assert(ResType->isAnyPointerType());
11177 QualType PointeeTy = ResType->getPointeeType();
11178 return S.RequireCompleteSizedType(
11179 Loc, PointeeTy,
11180 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11181 Operand->getSourceRange());
11182}
11183
11184/// Check the validity of an arithmetic pointer operand.
11185///
11186/// If the operand has pointer type, this code will check for pointer types
11187/// which are invalid in arithmetic operations. These will be diagnosed
11188/// appropriately, including whether or not the use is supported as an
11189/// extension.
11190///
11191/// \returns True when the operand is valid to use (even if as an extension).
11193 Expr *Operand) {
11194 QualType ResType = Operand->getType();
11195 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11196 ResType = ResAtomicType->getValueType();
11197
11198 if (!ResType->isAnyPointerType()) return true;
11199
11200 QualType PointeeTy = ResType->getPointeeType();
11201 if (PointeeTy->isVoidType()) {
11202 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11203 return !S.getLangOpts().CPlusPlus;
11204 }
11205 if (PointeeTy->isFunctionType()) {
11206 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11207 return !S.getLangOpts().CPlusPlus;
11208 }
11209
11210 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11211
11212 return true;
11213}
11214
11215/// Check the validity of a binary arithmetic operation w.r.t. pointer
11216/// operands.
11217///
11218/// This routine will diagnose any invalid arithmetic on pointer operands much
11219/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11220/// for emitting a single diagnostic even for operations where both LHS and RHS
11221/// are (potentially problematic) pointers.
11222///
11223/// \returns True when the operand is valid to use (even if as an extension).
11225 Expr *LHSExpr, Expr *RHSExpr) {
11226 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11227 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11228 if (!isLHSPointer && !isRHSPointer) return true;
11229
11230 QualType LHSPointeeTy, RHSPointeeTy;
11231 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11232 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11233
11234 // if both are pointers check if operation is valid wrt address spaces
11235 if (isLHSPointer && isRHSPointer) {
11236 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11237 S.getASTContext())) {
11238 S.Diag(Loc,
11239 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11240 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11241 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11242 return false;
11243 }
11244 }
11245
11246 // Check for arithmetic on pointers to incomplete types.
11247 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11248 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11249 if (isLHSVoidPtr || isRHSVoidPtr) {
11250 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11251 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11252 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11253
11254 return !S.getLangOpts().CPlusPlus;
11255 }
11256
11257 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11258 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11259 if (isLHSFuncPtr || isRHSFuncPtr) {
11260 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11261 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11262 RHSExpr);
11263 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11264
11265 return !S.getLangOpts().CPlusPlus;
11266 }
11267
11268 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11269 return false;
11270 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11271 return false;
11272
11273 return true;
11274}
11275
11276/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11277/// literal.
11279 Expr *LHSExpr, Expr *RHSExpr) {
11280 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11281 Expr* IndexExpr = RHSExpr;
11282 if (!StrExpr) {
11283 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11284 IndexExpr = LHSExpr;
11285 }
11286
11287 bool IsStringPlusInt = StrExpr &&
11289 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11290 return;
11291
11292 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11293 Self.Diag(OpLoc, diag::warn_string_plus_int)
11294 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11295
11296 // Only print a fixit for "str" + int, not for int + "str".
11297 if (IndexExpr == RHSExpr) {
11298 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11299 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11300 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11302 << FixItHint::CreateInsertion(EndLoc, "]");
11303 } else
11304 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11305}
11306
11307/// Emit a warning when adding a char literal to a string.
11309 Expr *LHSExpr, Expr *RHSExpr) {
11310 const Expr *StringRefExpr = LHSExpr;
11311 const CharacterLiteral *CharExpr =
11312 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11313
11314 if (!CharExpr) {
11315 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11316 StringRefExpr = RHSExpr;
11317 }
11318
11319 if (!CharExpr || !StringRefExpr)
11320 return;
11321
11322 const QualType StringType = StringRefExpr->getType();
11323
11324 // Return if not a PointerType.
11325 if (!StringType->isAnyPointerType())
11326 return;
11327
11328 // Return if not a CharacterType.
11329 if (!StringType->getPointeeType()->isAnyCharacterType())
11330 return;
11331
11332 ASTContext &Ctx = Self.getASTContext();
11333 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11334
11335 const QualType CharType = CharExpr->getType();
11336 if (!CharType->isAnyCharacterType() &&
11337 CharType->isIntegerType() &&
11338 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11339 Self.Diag(OpLoc, diag::warn_string_plus_char)
11340 << DiagRange << Ctx.CharTy;
11341 } else {
11342 Self.Diag(OpLoc, diag::warn_string_plus_char)
11343 << DiagRange << CharExpr->getType();
11344 }
11345
11346 // Only print a fixit for str + char, not for char + str.
11347 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11348 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11349 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11350 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11352 << FixItHint::CreateInsertion(EndLoc, "]");
11353 } else {
11354 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11355 }
11356}
11357
11358/// Emit error when two pointers are incompatible.
11360 Expr *LHSExpr, Expr *RHSExpr) {
11361 assert(LHSExpr->getType()->isAnyPointerType());
11362 assert(RHSExpr->getType()->isAnyPointerType());
11363 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11364 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11365 << RHSExpr->getSourceRange();
11366}
11367
11368// C99 6.5.6
11371 QualType* CompLHSTy) {
11372 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11373
11374 if (LHS.get()->getType()->isVectorType() ||
11375 RHS.get()->getType()->isVectorType()) {
11376 QualType compType =
11377 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11378 /*AllowBothBool*/ getLangOpts().AltiVec,
11379 /*AllowBoolConversions*/ getLangOpts().ZVector,
11380 /*AllowBooleanOperation*/ false,
11381 /*ReportInvalid*/ true);
11382 if (CompLHSTy) *CompLHSTy = compType;
11383 return compType;
11384 }
11385
11386 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11387 RHS.get()->getType()->isSveVLSBuiltinType()) {
11388 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11390 if (CompLHSTy)
11391 *CompLHSTy = compType;
11392 return compType;
11393 }
11394
11395 if (LHS.get()->getType()->isConstantMatrixType() ||
11396 RHS.get()->getType()->isConstantMatrixType()) {
11397 QualType compType =
11398 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11399 if (CompLHSTy)
11400 *CompLHSTy = compType;
11401 return compType;
11402 }
11403
11405 LHS, RHS, Loc,
11407 if (LHS.isInvalid() || RHS.isInvalid())
11408 return QualType();
11409
11410 // Diagnose "string literal" '+' int and string '+' "char literal".
11411 if (Opc == BO_Add) {
11412 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11413 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11414 }
11415
11416 // handle the common case first (both operands are arithmetic).
11417 if (!compType.isNull() && compType->isArithmeticType()) {
11418 if (CompLHSTy) *CompLHSTy = compType;
11419 return compType;
11420 }
11421
11422 // Type-checking. Ultimately the pointer's going to be in PExp;
11423 // note that we bias towards the LHS being the pointer.
11424 Expr *PExp = LHS.get(), *IExp = RHS.get();
11425
11426 bool isObjCPointer;
11427 if (PExp->getType()->isPointerType()) {
11428 isObjCPointer = false;
11429 } else if (PExp->getType()->isObjCObjectPointerType()) {
11430 isObjCPointer = true;
11431 } else {
11432 std::swap(PExp, IExp);
11433 if (PExp->getType()->isPointerType()) {
11434 isObjCPointer = false;
11435 } else if (PExp->getType()->isObjCObjectPointerType()) {
11436 isObjCPointer = true;
11437 } else {
11438 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11439 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11440 return ResultTy;
11441 }
11442 }
11443 assert(PExp->getType()->isAnyPointerType());
11444
11445 if (!IExp->getType()->isIntegerType())
11446 return InvalidOperands(Loc, LHS, RHS);
11447
11448 // Adding to a null pointer results in undefined behavior.
11451 // In C++ adding zero to a null pointer is defined.
11452 Expr::EvalResult KnownVal;
11453 if (!getLangOpts().CPlusPlus ||
11454 (!IExp->isValueDependent() &&
11455 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11456 KnownVal.Val.getInt() != 0))) {
11457 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11459 Context, BO_Add, PExp, IExp);
11460 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11461 }
11462 }
11463
11464 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11465 return QualType();
11466
11467 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11468 return QualType();
11469
11470 // Arithmetic on label addresses is normally allowed, except when we add
11471 // a ptrauth signature to the addresses.
11472 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11473 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11474 << /*addition*/ 1;
11475 return QualType();
11476 }
11477
11478 // Check array bounds for pointer arithemtic
11479 CheckArrayAccess(PExp, IExp);
11480
11481 if (CompLHSTy) {
11482 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11483 if (LHSTy.isNull()) {
11484 LHSTy = LHS.get()->getType();
11485 if (Context.isPromotableIntegerType(LHSTy))
11486 LHSTy = Context.getPromotedIntegerType(LHSTy);
11487 }
11488 *CompLHSTy = LHSTy;
11489 }
11490
11491 return PExp->getType();
11492}
11493
11494// C99 6.5.6
11496 SourceLocation Loc,
11498 QualType *CompLHSTy) {
11499 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11500
11501 if (LHS.get()->getType()->isVectorType() ||
11502 RHS.get()->getType()->isVectorType()) {
11503 QualType compType =
11504 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11505 /*AllowBothBool*/ getLangOpts().AltiVec,
11506 /*AllowBoolConversions*/ getLangOpts().ZVector,
11507 /*AllowBooleanOperation*/ false,
11508 /*ReportInvalid*/ true);
11509 if (CompLHSTy) *CompLHSTy = compType;
11510 return compType;
11511 }
11512
11513 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11514 RHS.get()->getType()->isSveVLSBuiltinType()) {
11515 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11517 if (CompLHSTy)
11518 *CompLHSTy = compType;
11519 return compType;
11520 }
11521
11522 if (LHS.get()->getType()->isConstantMatrixType() ||
11523 RHS.get()->getType()->isConstantMatrixType()) {
11524 QualType compType =
11525 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11526 if (CompLHSTy)
11527 *CompLHSTy = compType;
11528 return compType;
11529 }
11530
11532 LHS, RHS, Loc,
11534 if (LHS.isInvalid() || RHS.isInvalid())
11535 return QualType();
11536
11537 // Enforce type constraints: C99 6.5.6p3.
11538
11539 // Handle the common case first (both operands are arithmetic).
11540 if (!compType.isNull() && compType->isArithmeticType()) {
11541 if (CompLHSTy) *CompLHSTy = compType;
11542 return compType;
11543 }
11544
11545 // Either ptr - int or ptr - ptr.
11546 if (LHS.get()->getType()->isAnyPointerType()) {
11547 QualType lpointee = LHS.get()->getType()->getPointeeType();
11548
11549 // Diagnose bad cases where we step over interface counts.
11550 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11551 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11552 return QualType();
11553
11554 // Arithmetic on label addresses is normally allowed, except when we add
11555 // a ptrauth signature to the addresses.
11556 if (isa<AddrLabelExpr>(LHS.get()) &&
11557 getLangOpts().PointerAuthIndirectGotos) {
11558 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11559 << /*subtraction*/ 0;
11560 return QualType();
11561 }
11562
11563 // The result type of a pointer-int computation is the pointer type.
11564 if (RHS.get()->getType()->isIntegerType()) {
11565 // Subtracting from a null pointer should produce a warning.
11566 // The last argument to the diagnose call says this doesn't match the
11567 // GNU int-to-pointer idiom.
11570 // In C++ adding zero to a null pointer is defined.
11571 Expr::EvalResult KnownVal;
11572 if (!getLangOpts().CPlusPlus ||
11573 (!RHS.get()->isValueDependent() &&
11574 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11575 KnownVal.Val.getInt() != 0))) {
11576 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11577 }
11578 }
11579
11580 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11581 return QualType();
11582
11583 // Check array bounds for pointer arithemtic
11584 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11585 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11586
11587 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11588 return LHS.get()->getType();
11589 }
11590
11591 // Handle pointer-pointer subtractions.
11592 if (const PointerType *RHSPTy
11593 = RHS.get()->getType()->getAs<PointerType>()) {
11594 QualType rpointee = RHSPTy->getPointeeType();
11595
11596 if (getLangOpts().CPlusPlus) {
11597 // Pointee types must be the same: C++ [expr.add]
11598 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11599 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11600 }
11601 } else {
11602 // Pointee types must be compatible C99 6.5.6p3
11603 if (!Context.typesAreCompatible(
11604 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11605 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11606 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11607 return QualType();
11608 }
11609 }
11610
11612 LHS.get(), RHS.get()))
11613 return QualType();
11614
11615 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11617 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11619
11620 // Subtracting nullptr or from nullptr is suspect
11621 if (LHSIsNullPtr)
11622 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11623 if (RHSIsNullPtr)
11624 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11625
11626 // The pointee type may have zero size. As an extension, a structure or
11627 // union may have zero size or an array may have zero length. In this
11628 // case subtraction does not make sense.
11629 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11630 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11631 if (ElementSize.isZero()) {
11632 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11633 << rpointee.getUnqualifiedType()
11634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11635 }
11636 }
11637
11638 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11639 return Context.getPointerDiffType();
11640 }
11641 }
11642
11643 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11644 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11645 return ResultTy;
11646}
11647
11649 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11650 return ET->getDecl()->isScoped();
11651 return false;
11652}
11653
11656 QualType LHSType) {
11657 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11658 // so skip remaining warnings as we don't want to modify values within Sema.
11659 if (S.getLangOpts().OpenCL)
11660 return;
11661
11662 if (Opc == BO_Shr &&
11664 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11665
11666 // Check right/shifter operand
11667 Expr::EvalResult RHSResult;
11668 if (RHS.get()->isValueDependent() ||
11669 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11670 return;
11671 llvm::APSInt Right = RHSResult.Val.getInt();
11672
11673 if (Right.isNegative()) {
11674 S.DiagRuntimeBehavior(Loc, RHS.get(),
11675 S.PDiag(diag::warn_shift_negative)
11676 << RHS.get()->getSourceRange());
11677 return;
11678 }
11679
11680 QualType LHSExprType = LHS.get()->getType();
11681 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11682 if (LHSExprType->isBitIntType())
11683 LeftSize = S.Context.getIntWidth(LHSExprType);
11684 else if (LHSExprType->isFixedPointType()) {
11685 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11686 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11687 }
11688 if (Right.uge(LeftSize)) {
11689 S.DiagRuntimeBehavior(Loc, RHS.get(),
11690 S.PDiag(diag::warn_shift_gt_typewidth)
11691 << RHS.get()->getSourceRange());
11692 return;
11693 }
11694
11695 // FIXME: We probably need to handle fixed point types specially here.
11696 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11697 return;
11698
11699 // When left shifting an ICE which is signed, we can check for overflow which
11700 // according to C++ standards prior to C++2a has undefined behavior
11701 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11702 // more than the maximum value representable in the result type, so never
11703 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11704 // expression is still probably a bug.)
11705 Expr::EvalResult LHSResult;
11706 if (LHS.get()->isValueDependent() ||
11708 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11709 return;
11710 llvm::APSInt Left = LHSResult.Val.getInt();
11711
11712 // Don't warn if signed overflow is defined, then all the rest of the
11713 // diagnostics will not be triggered because the behavior is defined.
11714 // Also don't warn in C++20 mode (and newer), as signed left shifts
11715 // always wrap and never overflow.
11716 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11717 return;
11718
11719 // If LHS does not have a non-negative value then, the
11720 // behavior is undefined before C++2a. Warn about it.
11721 if (Left.isNegative()) {
11722 S.DiagRuntimeBehavior(Loc, LHS.get(),
11723 S.PDiag(diag::warn_shift_lhs_negative)
11724 << LHS.get()->getSourceRange());
11725 return;
11726 }
11727
11728 llvm::APInt ResultBits =
11729 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11730 if (ResultBits.ule(LeftSize))
11731 return;
11732 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11733 Result = Result.shl(Right);
11734
11735 // Print the bit representation of the signed integer as an unsigned
11736 // hexadecimal number.
11737 SmallString<40> HexResult;
11738 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11739
11740 // If we are only missing a sign bit, this is less likely to result in actual
11741 // bugs -- if the result is cast back to an unsigned type, it will have the
11742 // expected value. Thus we place this behind a different warning that can be
11743 // turned off separately if needed.
11744 if (ResultBits - 1 == LeftSize) {
11745 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11746 << HexResult << LHSType
11747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11748 return;
11749 }
11750
11751 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11752 << HexResult.str() << Result.getSignificantBits() << LHSType
11753 << Left.getBitWidth() << LHS.get()->getSourceRange()
11754 << RHS.get()->getSourceRange();
11755}
11756
11757/// Return the resulting type when a vector is shifted
11758/// by a scalar or vector shift amount.
11760 SourceLocation Loc, bool IsCompAssign) {
11761 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11762 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11763 !LHS.get()->getType()->isVectorType()) {
11764 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11765 << RHS.get()->getType() << LHS.get()->getType()
11766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11767 return QualType();
11768 }
11769
11770 if (!IsCompAssign) {
11771 LHS = S.UsualUnaryConversions(LHS.get());
11772 if (LHS.isInvalid()) return QualType();
11773 }
11774
11775 RHS = S.UsualUnaryConversions(RHS.get());
11776 if (RHS.isInvalid()) return QualType();
11777
11778 QualType LHSType = LHS.get()->getType();
11779 // Note that LHS might be a scalar because the routine calls not only in
11780 // OpenCL case.
11781 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11782 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11783
11784 // Note that RHS might not be a vector.
11785 QualType RHSType = RHS.get()->getType();
11786 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11787 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11788
11789 // Do not allow shifts for boolean vectors.
11790 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11791 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11792 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11793 << LHS.get()->getType() << RHS.get()->getType()
11794 << LHS.get()->getSourceRange();
11795 return QualType();
11796 }
11797
11798 // The operands need to be integers.
11799 if (!LHSEleType->isIntegerType()) {
11800 S.Diag(Loc, diag::err_typecheck_expect_int)
11801 << LHS.get()->getType() << LHS.get()->getSourceRange();
11802 return QualType();
11803 }
11804
11805 if (!RHSEleType->isIntegerType()) {
11806 S.Diag(Loc, diag::err_typecheck_expect_int)
11807 << RHS.get()->getType() << RHS.get()->getSourceRange();
11808 return QualType();
11809 }
11810
11811 if (!LHSVecTy) {
11812 assert(RHSVecTy);
11813 if (IsCompAssign)
11814 return RHSType;
11815 if (LHSEleType != RHSEleType) {
11816 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11817 LHSEleType = RHSEleType;
11818 }
11819 QualType VecTy =
11820 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11821 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11822 LHSType = VecTy;
11823 } else if (RHSVecTy) {
11824 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11825 // are applied component-wise. So if RHS is a vector, then ensure
11826 // that the number of elements is the same as LHS...
11827 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11828 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11829 << LHS.get()->getType() << RHS.get()->getType()
11830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11831 return QualType();
11832 }
11833 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11834 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11835 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11836 if (LHSBT != RHSBT &&
11837 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11838 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11839 << LHS.get()->getType() << RHS.get()->getType()
11840 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11841 }
11842 }
11843 } else {
11844 // ...else expand RHS to match the number of elements in LHS.
11845 QualType VecTy =
11846 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11847 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11848 }
11849
11850 return LHSType;
11851}
11852
11854 ExprResult &RHS, SourceLocation Loc,
11855 bool IsCompAssign) {
11856 if (!IsCompAssign) {
11857 LHS = S.UsualUnaryConversions(LHS.get());
11858 if (LHS.isInvalid())
11859 return QualType();
11860 }
11861
11862 RHS = S.UsualUnaryConversions(RHS.get());
11863 if (RHS.isInvalid())
11864 return QualType();
11865
11866 QualType LHSType = LHS.get()->getType();
11867 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11868 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11869 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11870 : LHSType;
11871
11872 // Note that RHS might not be a vector
11873 QualType RHSType = RHS.get()->getType();
11874 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11875 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11876 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11877 : RHSType;
11878
11879 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11880 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11881 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11882 << LHSType << RHSType << LHS.get()->getSourceRange();
11883 return QualType();
11884 }
11885
11886 if (!LHSEleType->isIntegerType()) {
11887 S.Diag(Loc, diag::err_typecheck_expect_int)
11888 << LHS.get()->getType() << LHS.get()->getSourceRange();
11889 return QualType();
11890 }
11891
11892 if (!RHSEleType->isIntegerType()) {
11893 S.Diag(Loc, diag::err_typecheck_expect_int)
11894 << RHS.get()->getType() << RHS.get()->getSourceRange();
11895 return QualType();
11896 }
11897
11898 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11899 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11900 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11901 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11902 << LHSType << RHSType << LHS.get()->getSourceRange()
11903 << RHS.get()->getSourceRange();
11904 return QualType();
11905 }
11906
11907 if (!LHSType->isSveVLSBuiltinType()) {
11908 assert(RHSType->isSveVLSBuiltinType());
11909 if (IsCompAssign)
11910 return RHSType;
11911 if (LHSEleType != RHSEleType) {
11912 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11913 LHSEleType = RHSEleType;
11914 }
11915 const llvm::ElementCount VecSize =
11916 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11917 QualType VecTy =
11918 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11919 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11920 LHSType = VecTy;
11921 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11922 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11923 S.Context.getTypeSize(LHSBuiltinTy)) {
11924 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11925 << LHSType << RHSType << LHS.get()->getSourceRange()
11926 << RHS.get()->getSourceRange();
11927 return QualType();
11928 }
11929 } else {
11930 const llvm::ElementCount VecSize =
11931 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11932 if (LHSEleType != RHSEleType) {
11933 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11934 RHSEleType = LHSEleType;
11935 }
11936 QualType VecTy =
11937 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11938 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11939 }
11940
11941 return LHSType;
11942}
11943
11944// C99 6.5.7
11947 bool IsCompAssign) {
11948 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11949
11950 // Vector shifts promote their scalar inputs to vector type.
11951 if (LHS.get()->getType()->isVectorType() ||
11952 RHS.get()->getType()->isVectorType()) {
11953 if (LangOpts.ZVector) {
11954 // The shift operators for the z vector extensions work basically
11955 // like general shifts, except that neither the LHS nor the RHS is
11956 // allowed to be a "vector bool".
11957 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11958 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11959 return InvalidOperands(Loc, LHS, RHS);
11960 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11961 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11962 return InvalidOperands(Loc, LHS, RHS);
11963 }
11964 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11965 }
11966
11967 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11968 RHS.get()->getType()->isSveVLSBuiltinType())
11969 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11970
11971 // Shifts don't perform usual arithmetic conversions, they just do integer
11972 // promotions on each operand. C99 6.5.7p3
11973
11974 // For the LHS, do usual unary conversions, but then reset them away
11975 // if this is a compound assignment.
11976 ExprResult OldLHS = LHS;
11977 LHS = UsualUnaryConversions(LHS.get());
11978 if (LHS.isInvalid())
11979 return QualType();
11980 QualType LHSType = LHS.get()->getType();
11981 if (IsCompAssign) LHS = OldLHS;
11982
11983 // The RHS is simpler.
11984 RHS = UsualUnaryConversions(RHS.get());
11985 if (RHS.isInvalid())
11986 return QualType();
11987 QualType RHSType = RHS.get()->getType();
11988
11989 // C99 6.5.7p2: Each of the operands shall have integer type.
11990 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11991 if ((!LHSType->isFixedPointOrIntegerType() &&
11992 !LHSType->hasIntegerRepresentation()) ||
11993 !RHSType->hasIntegerRepresentation()) {
11994 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11995 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11996 return ResultTy;
11997 }
11998
11999 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12000
12001 // "The type of the result is that of the promoted left operand."
12002 return LHSType;
12003}
12004
12005/// Diagnose bad pointer comparisons.
12007 ExprResult &LHS, ExprResult &RHS,
12008 bool IsError) {
12009 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12010 : diag::ext_typecheck_comparison_of_distinct_pointers)
12011 << LHS.get()->getType() << RHS.get()->getType()
12012 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12013}
12014
12015/// Returns false if the pointers are converted to a composite type,
12016/// true otherwise.
12018 ExprResult &LHS, ExprResult &RHS) {
12019 // C++ [expr.rel]p2:
12020 // [...] Pointer conversions (4.10) and qualification
12021 // conversions (4.4) are performed on pointer operands (or on
12022 // a pointer operand and a null pointer constant) to bring
12023 // them to their composite pointer type. [...]
12024 //
12025 // C++ [expr.eq]p1 uses the same notion for (in)equality
12026 // comparisons of pointers.
12027
12028 QualType LHSType = LHS.get()->getType();
12029 QualType RHSType = RHS.get()->getType();
12030 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12031 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12032
12033 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12034 if (T.isNull()) {
12035 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12036 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12037 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12038 else
12039 S.InvalidOperands(Loc, LHS, RHS);
12040 return true;
12041 }
12042
12043 return false;
12044}
12045
12047 ExprResult &LHS,
12048 ExprResult &RHS,
12049 bool IsError) {
12050 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12051 : diag::ext_typecheck_comparison_of_fptr_to_void)
12052 << LHS.get()->getType() << RHS.get()->getType()
12053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12054}
12055
12057 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12058 case Stmt::ObjCArrayLiteralClass:
12059 case Stmt::ObjCDictionaryLiteralClass:
12060 case Stmt::ObjCStringLiteralClass:
12061 case Stmt::ObjCBoxedExprClass:
12062 return true;
12063 default:
12064 // Note that ObjCBoolLiteral is NOT an object literal!
12065 return false;
12066 }
12067}
12068
12069static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12072
12073 // If this is not actually an Objective-C object, bail out.
12074 if (!Type)
12075 return false;
12076
12077 // Get the LHS object's interface type.
12078 QualType InterfaceType = Type->getPointeeType();
12079
12080 // If the RHS isn't an Objective-C object, bail out.
12081 if (!RHS->getType()->isObjCObjectPointerType())
12082 return false;
12083
12084 // Try to find the -isEqual: method.
12085 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12086 ObjCMethodDecl *Method =
12087 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12088 /*IsInstance=*/true);
12089 if (!Method) {
12090 if (Type->isObjCIdType()) {
12091 // For 'id', just check the global pool.
12092 Method =
12094 /*receiverId=*/true);
12095 } else {
12096 // Check protocols.
12097 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12098 /*IsInstance=*/true);
12099 }
12100 }
12101
12102 if (!Method)
12103 return false;
12104
12105 QualType T = Method->parameters()[0]->getType();
12106 if (!T->isObjCObjectPointerType())
12107 return false;
12108
12109 QualType R = Method->getReturnType();
12110 if (!R->isScalarType())
12111 return false;
12112
12113 return true;
12114}
12115
12117 ExprResult &LHS, ExprResult &RHS,
12119 Expr *Literal;
12120 Expr *Other;
12121 if (isObjCObjectLiteral(LHS)) {
12122 Literal = LHS.get();
12123 Other = RHS.get();
12124 } else {
12125 Literal = RHS.get();
12126 Other = LHS.get();
12127 }
12128
12129 // Don't warn on comparisons against nil.
12130 Other = Other->IgnoreParenCasts();
12131 if (Other->isNullPointerConstant(S.getASTContext(),
12133 return;
12134
12135 // This should be kept in sync with warn_objc_literal_comparison.
12136 // LK_String should always be after the other literals, since it has its own
12137 // warning flag.
12138 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12139 assert(LiteralKind != SemaObjC::LK_Block);
12140 if (LiteralKind == SemaObjC::LK_None) {
12141 llvm_unreachable("Unknown Objective-C object literal kind");
12142 }
12143
12144 if (LiteralKind == SemaObjC::LK_String)
12145 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12146 << Literal->getSourceRange();
12147 else
12148 S.Diag(Loc, diag::warn_objc_literal_comparison)
12149 << LiteralKind << Literal->getSourceRange();
12150
12152 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12153 SourceLocation Start = LHS.get()->getBeginLoc();
12155 CharSourceRange OpRange =
12157
12158 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12159 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12160 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12161 << FixItHint::CreateInsertion(End, "]");
12162 }
12163}
12164
12165/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12167 ExprResult &RHS, SourceLocation Loc,
12168 BinaryOperatorKind Opc) {
12169 // Check that left hand side is !something.
12170 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12171 if (!UO || UO->getOpcode() != UO_LNot) return;
12172
12173 // Only check if the right hand side is non-bool arithmetic type.
12174 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12175
12176 // Make sure that the something in !something is not bool.
12177 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12178 if (SubExpr->isKnownToHaveBooleanValue()) return;
12179
12180 // Emit warning.
12181 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12182 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12183 << Loc << IsBitwiseOp;
12184
12185 // First note suggest !(x < y)
12186 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12187 SourceLocation FirstClose = RHS.get()->getEndLoc();
12188 FirstClose = S.getLocForEndOfToken(FirstClose);
12189 if (FirstClose.isInvalid())
12190 FirstOpen = SourceLocation();
12191 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12192 << IsBitwiseOp
12193 << FixItHint::CreateInsertion(FirstOpen, "(")
12194 << FixItHint::CreateInsertion(FirstClose, ")");
12195
12196 // Second note suggests (!x) < y
12197 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12198 SourceLocation SecondClose = LHS.get()->getEndLoc();
12199 SecondClose = S.getLocForEndOfToken(SecondClose);
12200 if (SecondClose.isInvalid())
12201 SecondOpen = SourceLocation();
12202 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12203 << FixItHint::CreateInsertion(SecondOpen, "(")
12204 << FixItHint::CreateInsertion(SecondClose, ")");
12205}
12206
12207// Returns true if E refers to a non-weak array.
12208static bool checkForArray(const Expr *E) {
12209 const ValueDecl *D = nullptr;
12210 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12211 D = DR->getDecl();
12212 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12213 if (Mem->isImplicitAccess())
12214 D = Mem->getMemberDecl();
12215 }
12216 if (!D)
12217 return false;
12218 return D->getType()->isArrayType() && !D->isWeak();
12219}
12220
12221/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12222/// pointer and size is an unsigned integer. Return whether the result is
12223/// always true/false.
12224static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12225 const Expr *RHS,
12226 BinaryOperatorKind Opc) {
12227 if (!LHS->getType()->isPointerType() ||
12228 S.getLangOpts().PointerOverflowDefined)
12229 return std::nullopt;
12230
12231 // Canonicalize to >= or < predicate.
12232 switch (Opc) {
12233 case BO_GE:
12234 case BO_LT:
12235 break;
12236 case BO_GT:
12237 std::swap(LHS, RHS);
12238 Opc = BO_LT;
12239 break;
12240 case BO_LE:
12241 std::swap(LHS, RHS);
12242 Opc = BO_GE;
12243 break;
12244 default:
12245 return std::nullopt;
12246 }
12247
12248 auto *BO = dyn_cast<BinaryOperator>(LHS);
12249 if (!BO || BO->getOpcode() != BO_Add)
12250 return std::nullopt;
12251
12252 Expr *Other;
12253 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12254 Other = BO->getRHS();
12255 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12256 Other = BO->getLHS();
12257 else
12258 return std::nullopt;
12259
12260 if (!Other->getType()->isUnsignedIntegerType())
12261 return std::nullopt;
12262
12263 return Opc == BO_GE;
12264}
12265
12266/// Diagnose some forms of syntactically-obvious tautological comparison.
12268 Expr *LHS, Expr *RHS,
12269 BinaryOperatorKind Opc) {
12270 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12271 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12272
12273 QualType LHSType = LHS->getType();
12274 QualType RHSType = RHS->getType();
12275 if (LHSType->hasFloatingRepresentation() ||
12276 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12278 return;
12279
12280 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12281 // Tautological diagnostics.
12282 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12283 return;
12284
12285 // Comparisons between two array types are ill-formed for operator<=>, so
12286 // we shouldn't emit any additional warnings about it.
12287 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12288 return;
12289
12290 // For non-floating point types, check for self-comparisons of the form
12291 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12292 // often indicate logic errors in the program.
12293 //
12294 // NOTE: Don't warn about comparison expressions resulting from macro
12295 // expansion. Also don't warn about comparisons which are only self
12296 // comparisons within a template instantiation. The warnings should catch
12297 // obvious cases in the definition of the template anyways. The idea is to
12298 // warn when the typed comparison operator will always evaluate to the same
12299 // result.
12300
12301 // Used for indexing into %select in warn_comparison_always
12302 enum {
12303 AlwaysConstant,
12304 AlwaysTrue,
12305 AlwaysFalse,
12306 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12307 };
12308
12309 // C++1a [array.comp]:
12310 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12311 // operands of array type.
12312 // C++2a [depr.array.comp]:
12313 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12314 // operands of array type are deprecated.
12315 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12316 RHSStripped->getType()->isArrayType()) {
12317 auto IsDeprArrayComparionIgnored =
12318 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12319 auto DiagID = S.getLangOpts().CPlusPlus26
12320 ? diag::warn_array_comparison_cxx26
12321 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12322 ? diag::warn_array_comparison
12323 : diag::warn_depr_array_comparison;
12324 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12325 << LHSStripped->getType() << RHSStripped->getType();
12326 // Carry on to produce the tautological comparison warning, if this
12327 // expression is potentially-evaluated, we can resolve the array to a
12328 // non-weak declaration, and so on.
12329 }
12330
12331 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12332 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12333 unsigned Result;
12334 switch (Opc) {
12335 case BO_EQ:
12336 case BO_LE:
12337 case BO_GE:
12338 Result = AlwaysTrue;
12339 break;
12340 case BO_NE:
12341 case BO_LT:
12342 case BO_GT:
12343 Result = AlwaysFalse;
12344 break;
12345 case BO_Cmp:
12346 Result = AlwaysEqual;
12347 break;
12348 default:
12349 Result = AlwaysConstant;
12350 break;
12351 }
12352 S.DiagRuntimeBehavior(Loc, nullptr,
12353 S.PDiag(diag::warn_comparison_always)
12354 << 0 /*self-comparison*/
12355 << Result);
12356 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12357 // What is it always going to evaluate to?
12358 unsigned Result;
12359 switch (Opc) {
12360 case BO_EQ: // e.g. array1 == array2
12361 Result = AlwaysFalse;
12362 break;
12363 case BO_NE: // e.g. array1 != array2
12364 Result = AlwaysTrue;
12365 break;
12366 default: // e.g. array1 <= array2
12367 // The best we can say is 'a constant'
12368 Result = AlwaysConstant;
12369 break;
12370 }
12371 S.DiagRuntimeBehavior(Loc, nullptr,
12372 S.PDiag(diag::warn_comparison_always)
12373 << 1 /*array comparison*/
12374 << Result);
12375 } else if (std::optional<bool> Res =
12376 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12377 S.DiagRuntimeBehavior(Loc, nullptr,
12378 S.PDiag(diag::warn_comparison_always)
12379 << 2 /*pointer comparison*/
12380 << (*Res ? AlwaysTrue : AlwaysFalse));
12381 }
12382 }
12383
12384 if (isa<CastExpr>(LHSStripped))
12385 LHSStripped = LHSStripped->IgnoreParenCasts();
12386 if (isa<CastExpr>(RHSStripped))
12387 RHSStripped = RHSStripped->IgnoreParenCasts();
12388
12389 // Warn about comparisons against a string constant (unless the other
12390 // operand is null); the user probably wants string comparison function.
12391 Expr *LiteralString = nullptr;
12392 Expr *LiteralStringStripped = nullptr;
12393 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12394 !RHSStripped->isNullPointerConstant(S.Context,
12396 LiteralString = LHS;
12397 LiteralStringStripped = LHSStripped;
12398 } else if ((isa<StringLiteral>(RHSStripped) ||
12399 isa<ObjCEncodeExpr>(RHSStripped)) &&
12400 !LHSStripped->isNullPointerConstant(S.Context,
12402 LiteralString = RHS;
12403 LiteralStringStripped = RHSStripped;
12404 }
12405
12406 if (LiteralString) {
12407 S.DiagRuntimeBehavior(Loc, nullptr,
12408 S.PDiag(diag::warn_stringcompare)
12409 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12410 << LiteralString->getSourceRange());
12411 }
12412}
12413
12415 switch (CK) {
12416 default: {
12417#ifndef NDEBUG
12418 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12419 << "\n";
12420#endif
12421 llvm_unreachable("unhandled cast kind");
12422 }
12423 case CK_UserDefinedConversion:
12424 return ICK_Identity;
12425 case CK_LValueToRValue:
12426 return ICK_Lvalue_To_Rvalue;
12427 case CK_ArrayToPointerDecay:
12428 return ICK_Array_To_Pointer;
12429 case CK_FunctionToPointerDecay:
12431 case CK_IntegralCast:
12433 case CK_FloatingCast:
12435 case CK_IntegralToFloating:
12436 case CK_FloatingToIntegral:
12437 return ICK_Floating_Integral;
12438 case CK_IntegralComplexCast:
12439 case CK_FloatingComplexCast:
12440 case CK_FloatingComplexToIntegralComplex:
12441 case CK_IntegralComplexToFloatingComplex:
12443 case CK_FloatingComplexToReal:
12444 case CK_FloatingRealToComplex:
12445 case CK_IntegralComplexToReal:
12446 case CK_IntegralRealToComplex:
12447 return ICK_Complex_Real;
12448 case CK_HLSLArrayRValue:
12449 return ICK_HLSL_Array_RValue;
12450 }
12451}
12452
12454 QualType FromType,
12455 SourceLocation Loc) {
12456 // Check for a narrowing implicit conversion.
12459 SCS.setToType(0, FromType);
12460 SCS.setToType(1, ToType);
12461 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12462 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12463
12464 APValue PreNarrowingValue;
12465 QualType PreNarrowingType;
12466 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12467 PreNarrowingType,
12468 /*IgnoreFloatToIntegralConversion*/ true)) {
12470 // Implicit conversion to a narrower type, but the expression is
12471 // value-dependent so we can't tell whether it's actually narrowing.
12472 case NK_Not_Narrowing:
12473 return false;
12474
12476 // Implicit conversion to a narrower type, and the value is not a constant
12477 // expression.
12478 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12479 << /*Constant*/ 1
12480 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12481 return true;
12482
12484 // Implicit conversion to a narrower type, and the value is not a constant
12485 // expression.
12486 case NK_Type_Narrowing:
12487 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12488 << /*Constant*/ 0 << FromType << ToType;
12489 // TODO: It's not a constant expression, but what if the user intended it
12490 // to be? Can we produce notes to help them figure out why it isn't?
12491 return true;
12492 }
12493 llvm_unreachable("unhandled case in switch");
12494}
12495
12497 ExprResult &LHS,
12498 ExprResult &RHS,
12499 SourceLocation Loc) {
12500 QualType LHSType = LHS.get()->getType();
12501 QualType RHSType = RHS.get()->getType();
12502 // Dig out the original argument type and expression before implicit casts
12503 // were applied. These are the types/expressions we need to check the
12504 // [expr.spaceship] requirements against.
12505 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12506 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12507 QualType LHSStrippedType = LHSStripped.get()->getType();
12508 QualType RHSStrippedType = RHSStripped.get()->getType();
12509
12510 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12511 // other is not, the program is ill-formed.
12512 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12513 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12514 return QualType();
12515 }
12516
12517 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12518 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12519 RHSStrippedType->isEnumeralType();
12520 if (NumEnumArgs == 1) {
12521 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12522 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12523 if (OtherTy->hasFloatingRepresentation()) {
12524 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12525 return QualType();
12526 }
12527 }
12528 if (NumEnumArgs == 2) {
12529 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12530 // type E, the operator yields the result of converting the operands
12531 // to the underlying type of E and applying <=> to the converted operands.
12532 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12533 S.InvalidOperands(Loc, LHS, RHS);
12534 return QualType();
12535 }
12536 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12537 assert(IntType->isArithmeticType());
12538
12539 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12540 // promote the boolean type, and all other promotable integer types, to
12541 // avoid this.
12542 if (S.Context.isPromotableIntegerType(IntType))
12543 IntType = S.Context.getPromotedIntegerType(IntType);
12544
12545 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12546 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12547 LHSType = RHSType = IntType;
12548 }
12549
12550 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12551 // usual arithmetic conversions are applied to the operands.
12552 QualType Type =
12554 if (LHS.isInvalid() || RHS.isInvalid())
12555 return QualType();
12556 if (Type.isNull()) {
12557 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12558 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12559 return ResultTy;
12560 }
12561
12562 std::optional<ComparisonCategoryType> CCT =
12564 if (!CCT)
12565 return S.InvalidOperands(Loc, LHS, RHS);
12566
12567 bool HasNarrowing = checkThreeWayNarrowingConversion(
12568 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12569 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12570 RHS.get()->getBeginLoc());
12571 if (HasNarrowing)
12572 return QualType();
12573
12574 assert(!Type.isNull() && "composite type for <=> has not been set");
12575
12578}
12579
12581 ExprResult &RHS,
12582 SourceLocation Loc,
12583 BinaryOperatorKind Opc) {
12584 if (Opc == BO_Cmp)
12585 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12586
12587 // C99 6.5.8p3 / C99 6.5.9p4
12588 QualType Type =
12590 if (LHS.isInvalid() || RHS.isInvalid())
12591 return QualType();
12592 if (Type.isNull()) {
12593 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12594 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12595 return ResultTy;
12596 }
12597 assert(Type->isArithmeticType() || Type->isEnumeralType());
12598
12600 return S.InvalidOperands(Loc, LHS, RHS);
12601
12602 // Check for comparisons of floating point operands using != and ==.
12604 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12605
12606 // The result of comparisons is 'bool' in C++, 'int' in C.
12608}
12609
12611 if (!NullE.get()->getType()->isAnyPointerType())
12612 return;
12613 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12614 if (!E.get()->getType()->isAnyPointerType() &&
12618 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12619 if (CL->getValue() == 0)
12620 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12621 << NullValue
12623 NullValue ? "NULL" : "(void *)0");
12624 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12625 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12626 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12627 if (T == Context.CharTy)
12628 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12629 << NullValue
12631 NullValue ? "NULL" : "(void *)0");
12632 }
12633 }
12634}
12635
12636// C99 6.5.8, C++ [expr.rel]
12638 SourceLocation Loc,
12639 BinaryOperatorKind Opc) {
12640 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12641 bool IsThreeWay = Opc == BO_Cmp;
12642 bool IsOrdered = IsRelational || IsThreeWay;
12643 auto IsAnyPointerType = [](ExprResult E) {
12644 QualType Ty = E.get()->getType();
12645 return Ty->isPointerType() || Ty->isMemberPointerType();
12646 };
12647
12648 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12649 // type, array-to-pointer, ..., conversions are performed on both operands to
12650 // bring them to their composite type.
12651 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12652 // any type-related checks.
12653 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12655 if (LHS.isInvalid())
12656 return QualType();
12658 if (RHS.isInvalid())
12659 return QualType();
12660 } else {
12661 LHS = DefaultLvalueConversion(LHS.get());
12662 if (LHS.isInvalid())
12663 return QualType();
12664 RHS = DefaultLvalueConversion(RHS.get());
12665 if (RHS.isInvalid())
12666 return QualType();
12667 }
12668
12669 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12673 }
12674
12675 // Handle vector comparisons separately.
12676 if (LHS.get()->getType()->isVectorType() ||
12677 RHS.get()->getType()->isVectorType())
12678 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12679
12680 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12681 RHS.get()->getType()->isSveVLSBuiltinType())
12682 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12683
12684 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12685 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12686
12687 QualType LHSType = LHS.get()->getType();
12688 QualType RHSType = RHS.get()->getType();
12689 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12690 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12691 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12692
12693 if ((LHSType->isPointerType() &&
12695 (RHSType->isPointerType() &&
12697 return InvalidOperands(Loc, LHS, RHS);
12698
12699 const Expr::NullPointerConstantKind LHSNullKind =
12701 const Expr::NullPointerConstantKind RHSNullKind =
12703 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12704 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12705
12706 auto computeResultTy = [&]() {
12707 if (Opc != BO_Cmp)
12708 return QualType(Context.getLogicalOperationType());
12709 assert(getLangOpts().CPlusPlus);
12710 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12711
12712 QualType CompositeTy = LHS.get()->getType();
12713 assert(!CompositeTy->isReferenceType());
12714
12715 std::optional<ComparisonCategoryType> CCT =
12717 if (!CCT)
12718 return InvalidOperands(Loc, LHS, RHS);
12719
12720 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12721 // P0946R0: Comparisons between a null pointer constant and an object
12722 // pointer result in std::strong_equality, which is ill-formed under
12723 // P1959R0.
12724 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12725 << (LHSIsNull ? LHS.get()->getSourceRange()
12726 : RHS.get()->getSourceRange());
12727 return QualType();
12728 }
12729
12732 };
12733
12734 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12735 bool IsEquality = Opc == BO_EQ;
12736 if (RHSIsNull)
12737 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12738 RHS.get()->getSourceRange());
12739 else
12740 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12741 LHS.get()->getSourceRange());
12742 }
12743
12744 if (IsOrdered && LHSType->isFunctionPointerType() &&
12745 RHSType->isFunctionPointerType()) {
12746 // Valid unless a relational comparison of function pointers
12747 bool IsError = Opc == BO_Cmp;
12748 auto DiagID =
12749 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12750 : getLangOpts().CPlusPlus
12751 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12752 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12753 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12754 << RHS.get()->getSourceRange();
12755 if (IsError)
12756 return QualType();
12757 }
12758
12759 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12760 (RHSType->isIntegerType() && !RHSIsNull)) {
12761 // Skip normal pointer conversion checks in this case; we have better
12762 // diagnostics for this below.
12763 } else if (getLangOpts().CPlusPlus) {
12764 // Equality comparison of a function pointer to a void pointer is invalid,
12765 // but we allow it as an extension.
12766 // FIXME: If we really want to allow this, should it be part of composite
12767 // pointer type computation so it works in conditionals too?
12768 if (!IsOrdered &&
12769 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12770 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12771 // This is a gcc extension compatibility comparison.
12772 // In a SFINAE context, we treat this as a hard error to maintain
12773 // conformance with the C++ standard.
12774 bool IsError = isSFINAEContext();
12775 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
12776
12777 if (IsError)
12778 return QualType();
12779
12780 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12781 return computeResultTy();
12782 }
12783
12784 // C++ [expr.eq]p2:
12785 // If at least one operand is a pointer [...] bring them to their
12786 // composite pointer type.
12787 // C++ [expr.spaceship]p6
12788 // If at least one of the operands is of pointer type, [...] bring them
12789 // to their composite pointer type.
12790 // C++ [expr.rel]p2:
12791 // If both operands are pointers, [...] bring them to their composite
12792 // pointer type.
12793 // For <=>, the only valid non-pointer types are arrays and functions, and
12794 // we already decayed those, so this is really the same as the relational
12795 // comparison rule.
12796 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12797 (IsOrdered ? 2 : 1) &&
12798 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12799 RHSType->isObjCObjectPointerType()))) {
12800 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12801 return QualType();
12802 return computeResultTy();
12803 }
12804 } else if (LHSType->isPointerType() &&
12805 RHSType->isPointerType()) { // C99 6.5.8p2
12806 // All of the following pointer-related warnings are GCC extensions, except
12807 // when handling null pointer constants.
12808 QualType LCanPointeeTy =
12810 QualType RCanPointeeTy =
12812
12813 // C99 6.5.9p2 and C99 6.5.8p2
12814 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12815 RCanPointeeTy.getUnqualifiedType())) {
12816 if (IsRelational) {
12817 // Pointers both need to point to complete or incomplete types
12818 if ((LCanPointeeTy->isIncompleteType() !=
12819 RCanPointeeTy->isIncompleteType()) &&
12820 !getLangOpts().C11) {
12821 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12822 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12823 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12824 << RCanPointeeTy->isIncompleteType();
12825 }
12826 }
12827 } else if (!IsRelational &&
12828 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12829 // Valid unless comparison between non-null pointer and function pointer
12830 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12831 && !LHSIsNull && !RHSIsNull)
12832 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12833 /*isError*/false);
12834 } else {
12835 // Invalid
12836 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12837 }
12838 if (LCanPointeeTy != RCanPointeeTy) {
12839 // Treat NULL constant as a special case in OpenCL.
12840 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12841 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12842 getASTContext())) {
12843 Diag(Loc,
12844 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12845 << LHSType << RHSType << 0 /* comparison */
12846 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12847 }
12848 }
12849 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12850 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12851 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12852 : CK_BitCast;
12853
12854 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12855 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12856 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12857 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12858 bool ChangingCFIUncheckedCallee =
12859 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12860
12861 if (LHSIsNull && !RHSIsNull)
12862 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12863 else if (!ChangingCFIUncheckedCallee)
12864 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12865 }
12866 return computeResultTy();
12867 }
12868
12869
12870 // C++ [expr.eq]p4:
12871 // Two operands of type std::nullptr_t or one operand of type
12872 // std::nullptr_t and the other a null pointer constant compare
12873 // equal.
12874 // C23 6.5.9p5:
12875 // If both operands have type nullptr_t or one operand has type nullptr_t
12876 // and the other is a null pointer constant, they compare equal if the
12877 // former is a null pointer.
12878 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12879 if (LHSType->isNullPtrType()) {
12880 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12881 return computeResultTy();
12882 }
12883 if (RHSType->isNullPtrType()) {
12884 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12885 return computeResultTy();
12886 }
12887 }
12888
12889 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12890 // C23 6.5.9p6:
12891 // Otherwise, at least one operand is a pointer. If one is a pointer and
12892 // the other is a null pointer constant or has type nullptr_t, they
12893 // compare equal
12894 if (LHSIsNull && RHSType->isPointerType()) {
12895 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12896 return computeResultTy();
12897 }
12898 if (RHSIsNull && LHSType->isPointerType()) {
12899 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12900 return computeResultTy();
12901 }
12902 }
12903
12904 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12905 // These aren't covered by the composite pointer type rules.
12906 if (!IsOrdered && RHSType->isNullPtrType() &&
12907 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12908 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12909 return computeResultTy();
12910 }
12911 if (!IsOrdered && LHSType->isNullPtrType() &&
12912 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12913 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12914 return computeResultTy();
12915 }
12916
12917 if (getLangOpts().CPlusPlus) {
12918 if (IsRelational &&
12919 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12920 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12921 // HACK: Relational comparison of nullptr_t against a pointer type is
12922 // invalid per DR583, but we allow it within std::less<> and friends,
12923 // since otherwise common uses of it break.
12924 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12925 // friends to have std::nullptr_t overload candidates.
12926 DeclContext *DC = CurContext;
12927 if (isa<FunctionDecl>(DC))
12928 DC = DC->getParent();
12929 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12930 if (CTSD->isInStdNamespace() &&
12931 llvm::StringSwitch<bool>(CTSD->getName())
12932 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
12933 .Default(false)) {
12934 if (RHSType->isNullPtrType())
12935 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12936 else
12937 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12938 return computeResultTy();
12939 }
12940 }
12941 }
12942
12943 // C++ [expr.eq]p2:
12944 // If at least one operand is a pointer to member, [...] bring them to
12945 // their composite pointer type.
12946 if (!IsOrdered &&
12947 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12948 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12949 return QualType();
12950 else
12951 return computeResultTy();
12952 }
12953 }
12954
12955 // Handle block pointer types.
12956 if (!IsOrdered && LHSType->isBlockPointerType() &&
12957 RHSType->isBlockPointerType()) {
12958 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12959 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12960
12961 if (!LHSIsNull && !RHSIsNull &&
12962 !Context.typesAreCompatible(lpointee, rpointee)) {
12963 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12964 << LHSType << RHSType << LHS.get()->getSourceRange()
12965 << RHS.get()->getSourceRange();
12966 }
12967 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12968 return computeResultTy();
12969 }
12970
12971 // Allow block pointers to be compared with null pointer constants.
12972 if (!IsOrdered
12973 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12974 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12975 if (!LHSIsNull && !RHSIsNull) {
12976 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12978 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12979 ->getPointeeType()->isVoidType())))
12980 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12981 << LHSType << RHSType << LHS.get()->getSourceRange()
12982 << RHS.get()->getSourceRange();
12983 }
12984 if (LHSIsNull && !RHSIsNull)
12985 LHS = ImpCastExprToType(LHS.get(), RHSType,
12986 RHSType->isPointerType() ? CK_BitCast
12987 : CK_AnyPointerToBlockPointerCast);
12988 else
12989 RHS = ImpCastExprToType(RHS.get(), LHSType,
12990 LHSType->isPointerType() ? CK_BitCast
12991 : CK_AnyPointerToBlockPointerCast);
12992 return computeResultTy();
12993 }
12994
12995 if (LHSType->isObjCObjectPointerType() ||
12996 RHSType->isObjCObjectPointerType()) {
12997 const PointerType *LPT = LHSType->getAs<PointerType>();
12998 const PointerType *RPT = RHSType->getAs<PointerType>();
12999 if (LPT || RPT) {
13000 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13001 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13002
13003 if (!LPtrToVoid && !RPtrToVoid &&
13004 !Context.typesAreCompatible(LHSType, RHSType)) {
13005 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13006 /*isError*/false);
13007 }
13008 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13009 // the RHS, but we have test coverage for this behavior.
13010 // FIXME: Consider using convertPointersToCompositeType in C++.
13011 if (LHSIsNull && !RHSIsNull) {
13012 Expr *E = LHS.get();
13013 if (getLangOpts().ObjCAutoRefCount)
13014 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13016 LHS = ImpCastExprToType(E, RHSType,
13017 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13018 }
13019 else {
13020 Expr *E = RHS.get();
13021 if (getLangOpts().ObjCAutoRefCount)
13022 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13024 /*Diagnose=*/true,
13025 /*DiagnoseCFAudited=*/false, Opc);
13026 RHS = ImpCastExprToType(E, LHSType,
13027 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13028 }
13029 return computeResultTy();
13030 }
13031 if (LHSType->isObjCObjectPointerType() &&
13032 RHSType->isObjCObjectPointerType()) {
13033 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13034 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13035 /*isError*/false);
13037 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13038
13039 if (LHSIsNull && !RHSIsNull)
13040 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13041 else
13042 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13043 return computeResultTy();
13044 }
13045
13046 if (!IsOrdered && LHSType->isBlockPointerType() &&
13048 LHS = ImpCastExprToType(LHS.get(), RHSType,
13049 CK_BlockPointerToObjCPointerCast);
13050 return computeResultTy();
13051 } else if (!IsOrdered &&
13053 RHSType->isBlockPointerType()) {
13054 RHS = ImpCastExprToType(RHS.get(), LHSType,
13055 CK_BlockPointerToObjCPointerCast);
13056 return computeResultTy();
13057 }
13058 }
13059 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13060 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13061 unsigned DiagID = 0;
13062 bool isError = false;
13063 if (LangOpts.DebuggerSupport) {
13064 // Under a debugger, allow the comparison of pointers to integers,
13065 // since users tend to want to compare addresses.
13066 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13067 (RHSIsNull && RHSType->isIntegerType())) {
13068 if (IsOrdered) {
13069 isError = getLangOpts().CPlusPlus;
13070 DiagID =
13071 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13072 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13073 }
13074 } else if (getLangOpts().CPlusPlus) {
13075 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13076 isError = true;
13077 } else if (IsOrdered)
13078 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13079 else
13080 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13081
13082 if (DiagID) {
13083 Diag(Loc, DiagID)
13084 << LHSType << RHSType << LHS.get()->getSourceRange()
13085 << RHS.get()->getSourceRange();
13086 if (isError)
13087 return QualType();
13088 }
13089
13090 if (LHSType->isIntegerType())
13091 LHS = ImpCastExprToType(LHS.get(), RHSType,
13092 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13093 else
13094 RHS = ImpCastExprToType(RHS.get(), LHSType,
13095 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13096 return computeResultTy();
13097 }
13098
13099 // Handle block pointers.
13100 if (!IsOrdered && RHSIsNull
13101 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13102 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13103 return computeResultTy();
13104 }
13105 if (!IsOrdered && LHSIsNull
13106 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13107 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13108 return computeResultTy();
13109 }
13110
13111 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13112 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13113 return computeResultTy();
13114 }
13115
13116 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13117 return computeResultTy();
13118 }
13119
13120 if (LHSIsNull && RHSType->isQueueT()) {
13121 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13122 return computeResultTy();
13123 }
13124
13125 if (LHSType->isQueueT() && RHSIsNull) {
13126 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13127 return computeResultTy();
13128 }
13129 }
13130
13131 return InvalidOperands(Loc, LHS, RHS);
13132}
13133
13135 const VectorType *VTy = V->castAs<VectorType>();
13136 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13137
13138 if (isa<ExtVectorType>(VTy)) {
13139 if (VTy->isExtVectorBoolType())
13140 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13141 if (TypeSize == Context.getTypeSize(Context.CharTy))
13142 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13143 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13144 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13145 if (TypeSize == Context.getTypeSize(Context.IntTy))
13146 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13147 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13148 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13149 if (TypeSize == Context.getTypeSize(Context.LongTy))
13150 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13151 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13152 "Unhandled vector element size in vector compare");
13153 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13154 }
13155
13156 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13157 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13159 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13160 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13162 if (TypeSize == Context.getTypeSize(Context.LongTy))
13163 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13165 if (TypeSize == Context.getTypeSize(Context.IntTy))
13166 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13168 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13169 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13171 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13172 "Unhandled vector element size in vector compare");
13173 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13175}
13176
13178 const BuiltinType *VTy = V->castAs<BuiltinType>();
13179 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13180
13181 const QualType ETy = V->getSveEltType(Context);
13182 const auto TypeSize = Context.getTypeSize(ETy);
13183
13184 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13185 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13186 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13187}
13188
13190 SourceLocation Loc,
13191 BinaryOperatorKind Opc) {
13192 if (Opc == BO_Cmp) {
13193 Diag(Loc, diag::err_three_way_vector_comparison);
13194 return QualType();
13195 }
13196
13197 // Check to make sure we're operating on vectors of the same type and width,
13198 // Allowing one side to be a scalar of element type.
13199 QualType vType =
13200 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13201 /*AllowBothBool*/ true,
13202 /*AllowBoolConversions*/ getLangOpts().ZVector,
13203 /*AllowBooleanOperation*/ true,
13204 /*ReportInvalid*/ true);
13205 if (vType.isNull())
13206 return vType;
13207
13208 QualType LHSType = LHS.get()->getType();
13209
13210 // Determine the return type of a vector compare. By default clang will return
13211 // a scalar for all vector compares except vector bool and vector pixel.
13212 // With the gcc compiler we will always return a vector type and with the xl
13213 // compiler we will always return a scalar type. This switch allows choosing
13214 // which behavior is prefered.
13215 if (getLangOpts().AltiVec) {
13216 switch (getLangOpts().getAltivecSrcCompat()) {
13218 // If AltiVec, the comparison results in a numeric type, i.e.
13219 // bool for C++, int for C
13220 if (vType->castAs<VectorType>()->getVectorKind() ==
13222 return Context.getLogicalOperationType();
13223 else
13224 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13225 break;
13227 // For GCC we always return the vector type.
13228 break;
13230 return Context.getLogicalOperationType();
13231 break;
13232 }
13233 }
13234
13235 // For non-floating point types, check for self-comparisons of the form
13236 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13237 // often indicate logic errors in the program.
13238 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13239
13240 // Check for comparisons of floating point operands using != and ==.
13241 if (LHSType->hasFloatingRepresentation()) {
13242 assert(RHS.get()->getType()->hasFloatingRepresentation());
13243 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13244 }
13245
13246 // Return a signed type for the vector.
13247 return GetSignedVectorType(vType);
13248}
13249
13251 ExprResult &RHS,
13252 SourceLocation Loc,
13253 BinaryOperatorKind Opc) {
13254 if (Opc == BO_Cmp) {
13255 Diag(Loc, diag::err_three_way_vector_comparison);
13256 return QualType();
13257 }
13258
13259 // Check to make sure we're operating on vectors of the same type and width,
13260 // Allowing one side to be a scalar of element type.
13262 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13263
13264 if (vType.isNull())
13265 return vType;
13266
13267 QualType LHSType = LHS.get()->getType();
13268
13269 // For non-floating point types, check for self-comparisons of the form
13270 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13271 // often indicate logic errors in the program.
13272 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13273
13274 // Check for comparisons of floating point operands using != and ==.
13275 if (LHSType->hasFloatingRepresentation()) {
13276 assert(RHS.get()->getType()->hasFloatingRepresentation());
13277 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13278 }
13279
13280 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13281 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13282
13283 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13284 RHSBuiltinTy->isSVEBool())
13285 return LHSType;
13286
13287 // Return a signed type for the vector.
13288 return GetSignedSizelessVectorType(vType);
13289}
13290
13291static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13292 const ExprResult &XorRHS,
13293 const SourceLocation Loc) {
13294 // Do not diagnose macros.
13295 if (Loc.isMacroID())
13296 return;
13297
13298 // Do not diagnose if both LHS and RHS are macros.
13299 if (XorLHS.get()->getExprLoc().isMacroID() &&
13300 XorRHS.get()->getExprLoc().isMacroID())
13301 return;
13302
13303 bool Negative = false;
13304 bool ExplicitPlus = false;
13305 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13306 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13307
13308 if (!LHSInt)
13309 return;
13310 if (!RHSInt) {
13311 // Check negative literals.
13312 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13313 UnaryOperatorKind Opc = UO->getOpcode();
13314 if (Opc != UO_Minus && Opc != UO_Plus)
13315 return;
13316 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13317 if (!RHSInt)
13318 return;
13319 Negative = (Opc == UO_Minus);
13320 ExplicitPlus = !Negative;
13321 } else {
13322 return;
13323 }
13324 }
13325
13326 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13327 llvm::APInt RightSideValue = RHSInt->getValue();
13328 if (LeftSideValue != 2 && LeftSideValue != 10)
13329 return;
13330
13331 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13332 return;
13333
13335 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13336 llvm::StringRef ExprStr =
13338
13339 CharSourceRange XorRange =
13341 llvm::StringRef XorStr =
13343 // Do not diagnose if xor keyword/macro is used.
13344 if (XorStr == "xor")
13345 return;
13346
13347 std::string LHSStr = std::string(Lexer::getSourceText(
13348 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13349 S.getSourceManager(), S.getLangOpts()));
13350 std::string RHSStr = std::string(Lexer::getSourceText(
13351 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13352 S.getSourceManager(), S.getLangOpts()));
13353
13354 if (Negative) {
13355 RightSideValue = -RightSideValue;
13356 RHSStr = "-" + RHSStr;
13357 } else if (ExplicitPlus) {
13358 RHSStr = "+" + RHSStr;
13359 }
13360
13361 StringRef LHSStrRef = LHSStr;
13362 StringRef RHSStrRef = RHSStr;
13363 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13364 // literals.
13365 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13366 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13367 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13368 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13369 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13370 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13371 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13372 return;
13373
13374 bool SuggestXor =
13375 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13376 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13377 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13378 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13379 std::string SuggestedExpr = "1 << " + RHSStr;
13380 bool Overflow = false;
13381 llvm::APInt One = (LeftSideValue - 1);
13382 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13383 if (Overflow) {
13384 if (RightSideIntValue < 64)
13385 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13386 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13387 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13388 else if (RightSideIntValue == 64)
13389 S.Diag(Loc, diag::warn_xor_used_as_pow)
13390 << ExprStr << toString(XorValue, 10, true);
13391 else
13392 return;
13393 } else {
13394 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13395 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13396 << toString(PowValue, 10, true)
13398 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13399 }
13400
13401 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13402 << ("0x2 ^ " + RHSStr) << SuggestXor;
13403 } else if (LeftSideValue == 10) {
13404 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13405 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13406 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13407 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13408 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13409 << ("0xA ^ " + RHSStr) << SuggestXor;
13410 }
13411}
13412
13414 SourceLocation Loc,
13415 BinaryOperatorKind Opc) {
13416 // Ensure that either both operands are of the same vector type, or
13417 // one operand is of a vector type and the other is of its element type.
13418 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13419 /*AllowBothBool*/ true,
13420 /*AllowBoolConversions*/ false,
13421 /*AllowBooleanOperation*/ false,
13422 /*ReportInvalid*/ false);
13423 if (vType.isNull())
13424 return InvalidOperands(Loc, LHS, RHS);
13425 if (getLangOpts().OpenCL &&
13426 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13428 return InvalidOperands(Loc, LHS, RHS);
13429 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13430 // usage of the logical operators && and || with vectors in C. This
13431 // check could be notionally dropped.
13432 if (!getLangOpts().CPlusPlus &&
13433 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13434 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13435 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13436 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13437 // `select` functions.
13438 if (getLangOpts().HLSL &&
13439 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13440 (void)InvalidOperands(Loc, LHS, RHS);
13441 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13442 return QualType();
13443 }
13444
13445 return GetSignedVectorType(LHS.get()->getType());
13446}
13447
13449 SourceLocation Loc,
13450 BinaryOperatorKind Opc) {
13451
13452 if (!getLangOpts().HLSL) {
13453 assert(false && "Logical operands are not supported in C\\C++");
13454 return QualType();
13455 }
13456
13457 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13458 (void)InvalidOperands(Loc, LHS, RHS);
13459 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13460 return QualType();
13461 }
13462 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13463 << getLangOpts().getHLSLVersion();
13464 return QualType();
13465}
13466
13468 SourceLocation Loc,
13469 bool IsCompAssign) {
13470 if (!IsCompAssign) {
13472 if (LHS.isInvalid())
13473 return QualType();
13474 }
13476 if (RHS.isInvalid())
13477 return QualType();
13478
13479 // For conversion purposes, we ignore any qualifiers.
13480 // For example, "const float" and "float" are equivalent.
13481 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13482 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13483
13484 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13485 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13486 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13487
13488 if (Context.hasSameType(LHSType, RHSType))
13489 return Context.getCommonSugaredType(LHSType, RHSType);
13490
13491 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13492 // case we have to return InvalidOperands.
13493 ExprResult OriginalLHS = LHS;
13494 ExprResult OriginalRHS = RHS;
13495 if (LHSMatType && !RHSMatType) {
13496 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13497 if (!RHS.isInvalid())
13498 return LHSType;
13499
13500 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13501 }
13502
13503 if (!LHSMatType && RHSMatType) {
13504 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13505 if (!LHS.isInvalid())
13506 return RHSType;
13507 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13508 }
13509
13510 return InvalidOperands(Loc, LHS, RHS);
13511}
13512
13514 SourceLocation Loc,
13515 bool IsCompAssign) {
13516 if (!IsCompAssign) {
13518 if (LHS.isInvalid())
13519 return QualType();
13520 }
13522 if (RHS.isInvalid())
13523 return QualType();
13524
13525 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13526 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13527 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13528
13529 if (LHSMatType && RHSMatType) {
13530 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13531 return InvalidOperands(Loc, LHS, RHS);
13532
13533 if (Context.hasSameType(LHSMatType, RHSMatType))
13534 return Context.getCommonSugaredType(
13535 LHS.get()->getType().getUnqualifiedType(),
13536 RHS.get()->getType().getUnqualifiedType());
13537
13538 QualType LHSELTy = LHSMatType->getElementType(),
13539 RHSELTy = RHSMatType->getElementType();
13540 if (!Context.hasSameType(LHSELTy, RHSELTy))
13541 return InvalidOperands(Loc, LHS, RHS);
13542
13543 return Context.getConstantMatrixType(
13544 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13545 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13546 }
13547 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13548}
13549
13551 switch (Opc) {
13552 default:
13553 return false;
13554 case BO_And:
13555 case BO_AndAssign:
13556 case BO_Or:
13557 case BO_OrAssign:
13558 case BO_Xor:
13559 case BO_XorAssign:
13560 return true;
13561 }
13562}
13563
13565 SourceLocation Loc,
13566 BinaryOperatorKind Opc) {
13567 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13568
13569 bool IsCompAssign =
13570 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13571
13572 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13573
13574 if (LHS.get()->getType()->isVectorType() ||
13575 RHS.get()->getType()->isVectorType()) {
13576 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13578 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13579 /*AllowBothBool*/ true,
13580 /*AllowBoolConversions*/ getLangOpts().ZVector,
13581 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13582 /*ReportInvalid*/ true);
13583 return InvalidOperands(Loc, LHS, RHS);
13584 }
13585
13586 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13587 RHS.get()->getType()->isSveVLSBuiltinType()) {
13588 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13590 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13592 return InvalidOperands(Loc, LHS, RHS);
13593 }
13594
13595 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13596 RHS.get()->getType()->isSveVLSBuiltinType()) {
13597 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13599 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13601 return InvalidOperands(Loc, LHS, RHS);
13602 }
13603
13604 if (Opc == BO_And)
13605 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13606
13607 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13609 return InvalidOperands(Loc, LHS, RHS);
13610
13611 ExprResult LHSResult = LHS, RHSResult = RHS;
13613 LHSResult, RHSResult, Loc,
13615 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13616 return QualType();
13617 LHS = LHSResult.get();
13618 RHS = RHSResult.get();
13619
13620 if (Opc == BO_Xor)
13621 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13622
13623 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13624 return compType;
13625 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13626 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13627 return ResultTy;
13628}
13629
13630// C99 6.5.[13,14]
13632 SourceLocation Loc,
13633 BinaryOperatorKind Opc) {
13634 // Check vector operands differently.
13635 if (LHS.get()->getType()->isVectorType() ||
13636 RHS.get()->getType()->isVectorType())
13637 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13638
13639 if (LHS.get()->getType()->isConstantMatrixType() ||
13640 RHS.get()->getType()->isConstantMatrixType())
13641 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13642
13643 bool EnumConstantInBoolContext = false;
13644 for (const ExprResult &HS : {LHS, RHS}) {
13645 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13646 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13647 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13648 EnumConstantInBoolContext = true;
13649 }
13650 }
13651
13652 if (EnumConstantInBoolContext)
13653 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13654
13655 // WebAssembly tables can't be used with logical operators.
13656 QualType LHSTy = LHS.get()->getType();
13657 QualType RHSTy = RHS.get()->getType();
13658 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13659 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13660 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13661 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13662 return InvalidOperands(Loc, LHS, RHS);
13663 }
13664
13665 // Diagnose cases where the user write a logical and/or but probably meant a
13666 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13667 // is a constant.
13668 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13669 !LHS.get()->getType()->isBooleanType() &&
13670 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13671 // Don't warn in macros or template instantiations.
13672 !Loc.isMacroID() && !inTemplateInstantiation()) {
13673 // If the RHS can be constant folded, and if it constant folds to something
13674 // that isn't 0 or 1 (which indicate a potential logical operation that
13675 // happened to fold to true/false) then warn.
13676 // Parens on the RHS are ignored.
13677 Expr::EvalResult EVResult;
13678 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13679 llvm::APSInt Result = EVResult.Val.getInt();
13680 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13681 !RHS.get()->getExprLoc().isMacroID()) ||
13682 (Result != 0 && Result != 1)) {
13683 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13684 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13685 // Suggest replacing the logical operator with the bitwise version
13686 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13687 << (Opc == BO_LAnd ? "&" : "|")
13690 Opc == BO_LAnd ? "&" : "|");
13691 if (Opc == BO_LAnd)
13692 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13693 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13696 RHS.get()->getEndLoc()));
13697 }
13698 }
13699 }
13700
13701 if (!Context.getLangOpts().CPlusPlus) {
13702 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13703 // not operate on the built-in scalar and vector float types.
13704 if (Context.getLangOpts().OpenCL &&
13705 Context.getLangOpts().OpenCLVersion < 120) {
13706 if (LHS.get()->getType()->isFloatingType() ||
13707 RHS.get()->getType()->isFloatingType())
13708 return InvalidOperands(Loc, LHS, RHS);
13709 }
13710
13711 LHS = UsualUnaryConversions(LHS.get());
13712 if (LHS.isInvalid())
13713 return QualType();
13714
13715 RHS = UsualUnaryConversions(RHS.get());
13716 if (RHS.isInvalid())
13717 return QualType();
13718
13719 if (!LHS.get()->getType()->isScalarType() ||
13720 !RHS.get()->getType()->isScalarType())
13721 return InvalidOperands(Loc, LHS, RHS);
13722
13723 return Context.IntTy;
13724 }
13725
13726 // The following is safe because we only use this method for
13727 // non-overloadable operands.
13728
13729 // C++ [expr.log.and]p1
13730 // C++ [expr.log.or]p1
13731 // The operands are both contextually converted to type bool.
13733 if (LHSRes.isInvalid()) {
13734 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13735 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13736 return ResultTy;
13737 }
13738 LHS = LHSRes;
13739
13741 if (RHSRes.isInvalid()) {
13742 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13743 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13744 return ResultTy;
13745 }
13746 RHS = RHSRes;
13747
13748 // C++ [expr.log.and]p2
13749 // C++ [expr.log.or]p2
13750 // The result is a bool.
13751 return Context.BoolTy;
13752}
13753
13754static bool IsReadonlyMessage(Expr *E, Sema &S) {
13755 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13756 if (!ME) return false;
13757 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13758 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13760 if (!Base) return false;
13761 return Base->getMethodDecl() != nullptr;
13762}
13763
13764/// Is the given expression (which must be 'const') a reference to a
13765/// variable which was originally non-const, but which has become
13766/// 'const' due to being captured within a block?
13769 assert(E->isLValue() && E->getType().isConstQualified());
13770 E = E->IgnoreParens();
13771
13772 // Must be a reference to a declaration from an enclosing scope.
13773 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13774 if (!DRE) return NCCK_None;
13776
13777 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13778
13779 // The declaration must be a value which is not declared 'const'.
13780 if (!Value || Value->getType().isConstQualified())
13781 return NCCK_None;
13782
13783 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13784 if (Binding) {
13785 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13786 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13787 return NCCK_Lambda;
13788 }
13789
13790 VarDecl *Var = dyn_cast<VarDecl>(Value);
13791 if (!Var)
13792 return NCCK_None;
13793 if (Var->getType()->isReferenceType())
13794 return NCCK_None;
13795
13796 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13797
13798 // Decide whether the first capture was for a block or a lambda.
13799 DeclContext *DC = S.CurContext, *Prev = nullptr;
13800 // Decide whether the first capture was for a block or a lambda.
13801 while (DC) {
13802 // For init-capture, it is possible that the variable belongs to the
13803 // template pattern of the current context.
13804 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13805 if (Var->isInitCapture() &&
13806 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13807 break;
13808 if (DC == Var->getDeclContext())
13809 break;
13810 Prev = DC;
13811 DC = DC->getParent();
13812 }
13813 // Unless we have an init-capture, we've gone one step too far.
13814 if (!Var->isInitCapture())
13815 DC = Prev;
13816 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13817}
13818
13819static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13820 Ty = Ty.getNonReferenceType();
13821 if (IsDereference && Ty->isPointerType())
13822 Ty = Ty->getPointeeType();
13823 return !Ty.isConstQualified();
13824}
13825
13826// Update err_typecheck_assign_const and note_typecheck_assign_const
13827// when this enum is changed.
13828enum {
13834 ConstUnknown, // Keep as last element
13835};
13836
13837/// Emit the "read-only variable not assignable" error and print notes to give
13838/// more information about why the variable is not assignable, such as pointing
13839/// to the declaration of a const variable, showing that a method is const, or
13840/// that the function is returning a const reference.
13841static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13842 SourceLocation Loc) {
13843 SourceRange ExprRange = E->getSourceRange();
13844
13845 // Only emit one error on the first const found. All other consts will emit
13846 // a note to the error.
13847 bool DiagnosticEmitted = false;
13848
13849 // Track if the current expression is the result of a dereference, and if the
13850 // next checked expression is the result of a dereference.
13851 bool IsDereference = false;
13852 bool NextIsDereference = false;
13853
13854 // Loop to process MemberExpr chains.
13855 while (true) {
13856 IsDereference = NextIsDereference;
13857
13859 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13860 NextIsDereference = ME->isArrow();
13861 const ValueDecl *VD = ME->getMemberDecl();
13862 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13863 // Mutable fields can be modified even if the class is const.
13864 if (Field->isMutable()) {
13865 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13866 break;
13867 }
13868
13869 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13870 if (!DiagnosticEmitted) {
13871 S.Diag(Loc, diag::err_typecheck_assign_const)
13872 << ExprRange << ConstMember << false /*static*/ << Field
13873 << Field->getType();
13874 DiagnosticEmitted = true;
13875 }
13876 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13877 << ConstMember << false /*static*/ << Field << Field->getType()
13878 << Field->getSourceRange();
13879 }
13880 E = ME->getBase();
13881 continue;
13882 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13883 if (VDecl->getType().isConstQualified()) {
13884 if (!DiagnosticEmitted) {
13885 S.Diag(Loc, diag::err_typecheck_assign_const)
13886 << ExprRange << ConstMember << true /*static*/ << VDecl
13887 << VDecl->getType();
13888 DiagnosticEmitted = true;
13889 }
13890 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13891 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13892 << VDecl->getSourceRange();
13893 }
13894 // Static fields do not inherit constness from parents.
13895 break;
13896 }
13897 break; // End MemberExpr
13898 } else if (const ArraySubscriptExpr *ASE =
13899 dyn_cast<ArraySubscriptExpr>(E)) {
13900 E = ASE->getBase()->IgnoreParenImpCasts();
13901 continue;
13902 } else if (const ExtVectorElementExpr *EVE =
13903 dyn_cast<ExtVectorElementExpr>(E)) {
13904 E = EVE->getBase()->IgnoreParenImpCasts();
13905 continue;
13906 }
13907 break;
13908 }
13909
13910 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13911 // Function calls
13912 const FunctionDecl *FD = CE->getDirectCallee();
13913 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13914 if (!DiagnosticEmitted) {
13915 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13916 << ConstFunction << FD;
13917 DiagnosticEmitted = true;
13918 }
13920 diag::note_typecheck_assign_const)
13921 << ConstFunction << FD << FD->getReturnType()
13922 << FD->getReturnTypeSourceRange();
13923 }
13924 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13925 // Point to variable declaration.
13926 if (const ValueDecl *VD = DRE->getDecl()) {
13927 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13928 if (!DiagnosticEmitted) {
13929 S.Diag(Loc, diag::err_typecheck_assign_const)
13930 << ExprRange << ConstVariable << VD << VD->getType();
13931 DiagnosticEmitted = true;
13932 }
13933 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13934 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13935 }
13936 }
13937 } else if (isa<CXXThisExpr>(E)) {
13938 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13939 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13940 if (MD->isConst()) {
13941 if (!DiagnosticEmitted) {
13942 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13943 << ConstMethod << MD;
13944 DiagnosticEmitted = true;
13945 }
13946 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13947 << ConstMethod << MD << MD->getSourceRange();
13948 }
13949 }
13950 }
13951 }
13952
13953 if (DiagnosticEmitted)
13954 return;
13955
13956 // Can't determine a more specific message, so display the generic error.
13957 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13958}
13959
13965
13967 const RecordType *Ty,
13968 SourceLocation Loc, SourceRange Range,
13969 OriginalExprKind OEK,
13970 bool &DiagnosticEmitted) {
13971 std::vector<const RecordType *> RecordTypeList;
13972 RecordTypeList.push_back(Ty);
13973 unsigned NextToCheckIndex = 0;
13974 // We walk the record hierarchy breadth-first to ensure that we print
13975 // diagnostics in field nesting order.
13976 while (RecordTypeList.size() > NextToCheckIndex) {
13977 bool IsNested = NextToCheckIndex > 0;
13978 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13979 ->getDecl()
13981 ->fields()) {
13982 // First, check every field for constness.
13983 QualType FieldTy = Field->getType();
13984 if (FieldTy.isConstQualified()) {
13985 if (!DiagnosticEmitted) {
13986 S.Diag(Loc, diag::err_typecheck_assign_const)
13987 << Range << NestedConstMember << OEK << VD
13988 << IsNested << Field;
13989 DiagnosticEmitted = true;
13990 }
13991 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13992 << NestedConstMember << IsNested << Field
13993 << FieldTy << Field->getSourceRange();
13994 }
13995
13996 // Then we append it to the list to check next in order.
13997 FieldTy = FieldTy.getCanonicalType();
13998 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
13999 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14000 RecordTypeList.push_back(FieldRecTy);
14001 }
14002 }
14003 ++NextToCheckIndex;
14004 }
14005}
14006
14007/// Emit an error for the case where a record we are trying to assign to has a
14008/// const-qualified field somewhere in its hierarchy.
14009static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14010 SourceLocation Loc) {
14011 QualType Ty = E->getType();
14012 assert(Ty->isRecordType() && "lvalue was not record?");
14013 SourceRange Range = E->getSourceRange();
14014 const auto *RTy = Ty->getAsCanonical<RecordType>();
14015 bool DiagEmitted = false;
14016
14017 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14018 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14019 Range, OEK_Member, DiagEmitted);
14020 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14021 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14022 Range, OEK_Variable, DiagEmitted);
14023 else
14024 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14025 Range, OEK_LValue, DiagEmitted);
14026 if (!DiagEmitted)
14027 DiagnoseConstAssignment(S, E, Loc);
14028}
14029
14030/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14031/// emit an error and return true. If so, return false.
14033 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14034
14036
14037 SourceLocation OrigLoc = Loc;
14039 &Loc);
14040 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14042 if (IsLV == Expr::MLV_Valid)
14043 return false;
14044
14045 unsigned DiagID = 0;
14046 bool NeedType = false;
14047 switch (IsLV) { // C99 6.5.16p2
14049 // Use a specialized diagnostic when we're assigning to an object
14050 // from an enclosing function or block.
14052 if (NCCK == NCCK_Block)
14053 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14054 else
14055 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14056 break;
14057 }
14058
14059 // In ARC, use some specialized diagnostics for occasions where we
14060 // infer 'const'. These are always pseudo-strong variables.
14061 if (S.getLangOpts().ObjCAutoRefCount) {
14062 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14063 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14064 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14065
14066 // Use the normal diagnostic if it's pseudo-__strong but the
14067 // user actually wrote 'const'.
14068 if (var->isARCPseudoStrong() &&
14069 (!var->getTypeSourceInfo() ||
14070 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14071 // There are three pseudo-strong cases:
14072 // - self
14073 ObjCMethodDecl *method = S.getCurMethodDecl();
14074 if (method && var == method->getSelfDecl()) {
14075 DiagID = method->isClassMethod()
14076 ? diag::err_typecheck_arc_assign_self_class_method
14077 : diag::err_typecheck_arc_assign_self;
14078
14079 // - Objective-C externally_retained attribute.
14080 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14081 isa<ParmVarDecl>(var)) {
14082 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14083
14084 // - fast enumeration variables
14085 } else {
14086 DiagID = diag::err_typecheck_arr_assign_enumeration;
14087 }
14088
14089 SourceRange Assign;
14090 if (Loc != OrigLoc)
14091 Assign = SourceRange(OrigLoc, OrigLoc);
14092 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14093 // We need to preserve the AST regardless, so migration tool
14094 // can do its job.
14095 return false;
14096 }
14097 }
14098 }
14099
14100 // If none of the special cases above are triggered, then this is a
14101 // simple const assignment.
14102 if (DiagID == 0) {
14103 DiagnoseConstAssignment(S, E, Loc);
14104 return true;
14105 }
14106
14107 break;
14109 DiagnoseConstAssignment(S, E, Loc);
14110 return true;
14113 return true;
14116 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14117 NeedType = true;
14118 break;
14120 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14121 NeedType = true;
14122 break;
14124 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14125 break;
14126 case Expr::MLV_Valid:
14127 llvm_unreachable("did not take early return for MLV_Valid");
14131 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14132 break;
14135 return S.RequireCompleteType(Loc, E->getType(),
14136 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14138 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14139 break;
14141 llvm_unreachable("readonly properties should be processed differently");
14143 DiagID = diag::err_readonly_message_assignment;
14144 break;
14146 DiagID = diag::err_no_subobject_property_setting;
14147 break;
14148 }
14149
14150 SourceRange Assign;
14151 if (Loc != OrigLoc)
14152 Assign = SourceRange(OrigLoc, OrigLoc);
14153 if (NeedType)
14154 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14155 else
14156 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14157 return true;
14158}
14159
14160static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14161 SourceLocation Loc,
14162 Sema &Sema) {
14164 return;
14166 return;
14167 if (Loc.isInvalid() || Loc.isMacroID())
14168 return;
14169 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14170 return;
14171
14172 // C / C++ fields
14173 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14174 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14175 if (ML && MR) {
14176 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14177 return;
14178 const ValueDecl *LHSDecl =
14180 const ValueDecl *RHSDecl =
14182 if (LHSDecl != RHSDecl)
14183 return;
14184 if (LHSDecl->getType().isVolatileQualified())
14185 return;
14186 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14187 if (RefTy->getPointeeType().isVolatileQualified())
14188 return;
14189
14190 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14191 }
14192
14193 // Objective-C instance variables
14194 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14195 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14196 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14197 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14198 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14199 if (RL && RR && RL->getDecl() == RR->getDecl())
14200 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14201 }
14202}
14203
14204// C99 6.5.16.1
14206 SourceLocation Loc,
14207 QualType CompoundType,
14208 BinaryOperatorKind Opc) {
14209 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14210
14211 // Verify that LHS is a modifiable lvalue, and emit error if not.
14212 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14213 return QualType();
14214
14215 QualType LHSType = LHSExpr->getType();
14216 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14217 CompoundType;
14218
14219 if (RHS.isUsable()) {
14220 // Even if this check fails don't return early to allow the best
14221 // possible error recovery and to allow any subsequent diagnostics to
14222 // work.
14223 const ValueDecl *Assignee = nullptr;
14224 bool ShowFullyQualifiedAssigneeName = false;
14225 // In simple cases describe what is being assigned to
14226 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14227 Assignee = DR->getDecl();
14228 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14229 Assignee = ME->getMemberDecl();
14230 ShowFullyQualifiedAssigneeName = true;
14231 }
14232
14234 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14235 ShowFullyQualifiedAssigneeName);
14236 }
14237
14238 // OpenCL v1.2 s6.1.1.1 p2:
14239 // The half data type can only be used to declare a pointer to a buffer that
14240 // contains half values
14241 if (getLangOpts().OpenCL &&
14242 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14243 LHSType->isHalfType()) {
14244 Diag(Loc, diag::err_opencl_half_load_store) << 1
14245 << LHSType.getUnqualifiedType();
14246 return QualType();
14247 }
14248
14249 // WebAssembly tables can't be used on RHS of an assignment expression.
14250 if (RHSType->isWebAssemblyTableType()) {
14251 Diag(Loc, diag::err_wasm_table_art) << 0;
14252 return QualType();
14253 }
14254
14255 AssignConvertType ConvTy;
14256 if (CompoundType.isNull()) {
14257 Expr *RHSCheck = RHS.get();
14258
14259 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14260
14261 QualType LHSTy(LHSType);
14262 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14263 if (RHS.isInvalid())
14264 return QualType();
14265 // Special case of NSObject attributes on c-style pointer types.
14267 ((Context.isObjCNSObjectType(LHSType) &&
14268 RHSType->isObjCObjectPointerType()) ||
14269 (Context.isObjCNSObjectType(RHSType) &&
14270 LHSType->isObjCObjectPointerType())))
14272
14273 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14274 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14275
14276 // If the RHS is a unary plus or minus, check to see if they = and + are
14277 // right next to each other. If so, the user may have typo'd "x =+ 4"
14278 // instead of "x += 4".
14279 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14280 RHSCheck = ICE->getSubExpr();
14281 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14282 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14283 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14284 // Only if the two operators are exactly adjacent.
14285 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14286 // And there is a space or other character before the subexpr of the
14287 // unary +/-. We don't want to warn on "x=-1".
14288 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14289 UO->getSubExpr()->getBeginLoc().isFileID()) {
14290 Diag(Loc, diag::warn_not_compound_assign)
14291 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14292 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14293 }
14294 }
14295
14296 if (IsAssignConvertCompatible(ConvTy)) {
14297 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14298 // Warn about retain cycles where a block captures the LHS, but
14299 // not if the LHS is a simple variable into which the block is
14300 // being stored...unless that variable can be captured by reference!
14301 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14302 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14303 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14304 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14305 }
14306
14307 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14309 // It is safe to assign a weak reference into a strong variable.
14310 // Although this code can still have problems:
14311 // id x = self.weakProp;
14312 // id y = self.weakProp;
14313 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14314 // paths through the function. This should be revisited if
14315 // -Wrepeated-use-of-weak is made flow-sensitive.
14316 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14317 // variable, which will be valid for the current autorelease scope.
14318 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14319 RHS.get()->getBeginLoc()))
14321
14322 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14323 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14324 }
14325 }
14326 } else {
14327 // Compound assignment "x += y"
14328 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14329 }
14330
14331 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14333 return QualType();
14334
14335 CheckForNullPointerDereference(*this, LHSExpr);
14336
14337 AssignedEntity AE{LHSExpr};
14338 checkAssignmentLifetime(*this, AE, RHS.get());
14339
14340 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14341 if (CompoundType.isNull()) {
14342 // C++2a [expr.ass]p5:
14343 // A simple-assignment whose left operand is of a volatile-qualified
14344 // type is deprecated unless the assignment is either a discarded-value
14345 // expression or an unevaluated operand
14346 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14347 }
14348 }
14349
14350 // C11 6.5.16p3: The type of an assignment expression is the type of the
14351 // left operand would have after lvalue conversion.
14352 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14353 // qualified type, the value has the unqualified version of the type of the
14354 // lvalue; additionally, if the lvalue has atomic type, the value has the
14355 // non-atomic version of the type of the lvalue.
14356 // C++ 5.17p1: the type of the assignment expression is that of its left
14357 // operand.
14358 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14359}
14360
14361// Scenarios to ignore if expression E is:
14362// 1. an explicit cast expression into void
14363// 2. a function call expression that returns void
14364static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14365 E = E->IgnoreParens();
14366
14367 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14368 if (CE->getCastKind() == CK_ToVoid) {
14369 return true;
14370 }
14371
14372 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14373 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14374 CE->getSubExpr()->getType()->isDependentType()) {
14375 return true;
14376 }
14377 }
14378
14379 if (const auto *CE = dyn_cast<CallExpr>(E))
14380 return CE->getCallReturnType(Context)->isVoidType();
14381 return false;
14382}
14383
14385 // No warnings in macros
14386 if (Loc.isMacroID())
14387 return;
14388
14389 // Don't warn in template instantiations.
14391 return;
14392
14393 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14394 // instead, skip more than needed, then call back into here with the
14395 // CommaVisitor in SemaStmt.cpp.
14396 // The listed locations are the initialization and increment portions
14397 // of a for loop. The additional checks are on the condition of
14398 // if statements, do/while loops, and for loops.
14399 // Differences in scope flags for C89 mode requires the extra logic.
14400 const unsigned ForIncrementFlags =
14401 getLangOpts().C99 || getLangOpts().CPlusPlus
14404 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14405 const unsigned ScopeFlags = getCurScope()->getFlags();
14406 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14407 (ScopeFlags & ForInitFlags) == ForInitFlags)
14408 return;
14409
14410 // If there are multiple comma operators used together, get the RHS of the
14411 // of the comma operator as the LHS.
14412 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14413 if (BO->getOpcode() != BO_Comma)
14414 break;
14415 LHS = BO->getRHS();
14416 }
14417
14418 // Only allow some expressions on LHS to not warn.
14419 if (IgnoreCommaOperand(LHS, Context))
14420 return;
14421
14422 Diag(Loc, diag::warn_comma_operator);
14423 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14424 << LHS->getSourceRange()
14426 LangOpts.CPlusPlus ? "static_cast<void>("
14427 : "(void)(")
14428 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14429 ")");
14430}
14431
14432// C99 6.5.17
14434 SourceLocation Loc) {
14435 LHS = S.CheckPlaceholderExpr(LHS.get());
14436 RHS = S.CheckPlaceholderExpr(RHS.get());
14437 if (LHS.isInvalid() || RHS.isInvalid())
14438 return QualType();
14439
14440 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14441 // operands, but not unary promotions.
14442 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14443
14444 // So we treat the LHS as a ignored value, and in C++ we allow the
14445 // containing site to determine what should be done with the RHS.
14446 LHS = S.IgnoredValueConversions(LHS.get());
14447 if (LHS.isInvalid())
14448 return QualType();
14449
14450 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14451
14452 if (!S.getLangOpts().CPlusPlus) {
14454 if (RHS.isInvalid())
14455 return QualType();
14456 if (!RHS.get()->getType()->isVoidType())
14457 S.RequireCompleteType(Loc, RHS.get()->getType(),
14458 diag::err_incomplete_type);
14459 }
14460
14461 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14462 S.DiagnoseCommaOperator(LHS.get(), Loc);
14463
14464 return RHS.get()->getType();
14465}
14466
14467/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14468/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14471 ExprObjectKind &OK,
14472 SourceLocation OpLoc, bool IsInc,
14473 bool IsPrefix) {
14474 QualType ResType = Op->getType();
14475 // Atomic types can be used for increment / decrement where the non-atomic
14476 // versions can, so ignore the _Atomic() specifier for the purpose of
14477 // checking.
14478 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14479 ResType = ResAtomicType->getValueType();
14480
14481 assert(!ResType.isNull() && "no type for increment/decrement expression");
14482
14483 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14484 // Decrement of bool is not allowed.
14485 if (!IsInc) {
14486 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14487 return QualType();
14488 }
14489 // Increment of bool sets it to true, but is deprecated.
14490 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14491 : diag::warn_increment_bool)
14492 << Op->getSourceRange();
14493 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14494 // Error on enum increments and decrements in C++ mode
14495 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14496 return QualType();
14497 } else if (ResType->isRealType()) {
14498 // OK!
14499 } else if (ResType->isPointerType()) {
14500 // C99 6.5.2.4p2, 6.5.6p2
14501 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14502 return QualType();
14503 } else if (ResType->isObjCObjectPointerType()) {
14504 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14505 // Otherwise, we just need a complete type.
14506 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14507 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14508 return QualType();
14509 } else if (ResType->isAnyComplexType()) {
14510 // C99 does not support ++/-- on complex types, we allow as an extension.
14511 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14512 : diag::ext_c2y_increment_complex)
14513 << IsInc << Op->getSourceRange();
14514 } else if (ResType->isPlaceholderType()) {
14516 if (PR.isInvalid()) return QualType();
14517 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14518 IsInc, IsPrefix);
14519 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14520 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14521 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14522 (ResType->castAs<VectorType>()->getVectorKind() !=
14524 // The z vector extensions allow ++ and -- for non-bool vectors.
14525 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14526 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14527 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14528 } else {
14529 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14530 << ResType << int(IsInc) << Op->getSourceRange();
14531 return QualType();
14532 }
14533 // At this point, we know we have a real, complex or pointer type.
14534 // Now make sure the operand is a modifiable lvalue.
14535 if (CheckForModifiableLvalue(Op, OpLoc, S))
14536 return QualType();
14537 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14538 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14539 // An operand with volatile-qualified type is deprecated
14540 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14541 << IsInc << ResType;
14542 }
14543 // In C++, a prefix increment is the same type as the operand. Otherwise
14544 // (in C or with postfix), the increment is the unqualified type of the
14545 // operand.
14546 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14547 VK = VK_LValue;
14548 OK = Op->getObjectKind();
14549 return ResType;
14550 } else {
14551 VK = VK_PRValue;
14552 return ResType.getUnqualifiedType();
14553 }
14554}
14555
14556/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14557/// This routine allows us to typecheck complex/recursive expressions
14558/// where the declaration is needed for type checking. We only need to
14559/// handle cases when the expression references a function designator
14560/// or is an lvalue. Here are some examples:
14561/// - &(x) => x
14562/// - &*****f => f for f a function designator.
14563/// - &s.xx => s
14564/// - &s.zz[1].yy -> s, if zz is an array
14565/// - *(x + 1) -> x, if x is an array
14566/// - &"123"[2] -> 0
14567/// - & __real__ x -> x
14568///
14569/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14570/// members.
14572 switch (E->getStmtClass()) {
14573 case Stmt::DeclRefExprClass:
14574 return cast<DeclRefExpr>(E)->getDecl();
14575 case Stmt::MemberExprClass:
14576 // If this is an arrow operator, the address is an offset from
14577 // the base's value, so the object the base refers to is
14578 // irrelevant.
14579 if (cast<MemberExpr>(E)->isArrow())
14580 return nullptr;
14581 // Otherwise, the expression refers to a part of the base
14582 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14583 case Stmt::ArraySubscriptExprClass: {
14584 // FIXME: This code shouldn't be necessary! We should catch the implicit
14585 // promotion of register arrays earlier.
14586 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14587 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14588 if (ICE->getSubExpr()->getType()->isArrayType())
14589 return getPrimaryDecl(ICE->getSubExpr());
14590 }
14591 return nullptr;
14592 }
14593 case Stmt::UnaryOperatorClass: {
14595
14596 switch(UO->getOpcode()) {
14597 case UO_Real:
14598 case UO_Imag:
14599 case UO_Extension:
14600 return getPrimaryDecl(UO->getSubExpr());
14601 default:
14602 return nullptr;
14603 }
14604 }
14605 case Stmt::ParenExprClass:
14606 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14607 case Stmt::ImplicitCastExprClass:
14608 // If the result of an implicit cast is an l-value, we care about
14609 // the sub-expression; otherwise, the result here doesn't matter.
14610 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14611 case Stmt::CXXUuidofExprClass:
14612 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14613 default:
14614 return nullptr;
14615 }
14616}
14617
14618namespace {
14619enum {
14620 AO_Bit_Field = 0,
14621 AO_Vector_Element = 1,
14622 AO_Property_Expansion = 2,
14623 AO_Register_Variable = 3,
14624 AO_Matrix_Element = 4,
14625 AO_No_Error = 5
14626};
14627}
14628/// Diagnose invalid operand for address of operations.
14629///
14630/// \param Type The type of operand which cannot have its address taken.
14632 Expr *E, unsigned Type) {
14633 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14634}
14635
14637 const Expr *Op,
14638 const CXXMethodDecl *MD) {
14639 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14640
14641 if (Op != DRE)
14642 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14643 << Op->getSourceRange();
14644
14645 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14646 if (isa<CXXDestructorDecl>(MD))
14647 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14648 << DRE->getSourceRange();
14649
14650 if (DRE->getQualifier())
14651 return false;
14652
14653 if (MD->getParent()->getName().empty())
14654 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14655 << DRE->getSourceRange();
14656
14657 SmallString<32> Str;
14658 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14659 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14660 << DRE->getSourceRange()
14661 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14662}
14663
14665 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14666 if (PTy->getKind() == BuiltinType::Overload) {
14667 Expr *E = OrigOp.get()->IgnoreParens();
14668 if (!isa<OverloadExpr>(E)) {
14669 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14670 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14671 << OrigOp.get()->getSourceRange();
14672 return QualType();
14673 }
14674
14678 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14679 << OrigOp.get()->getSourceRange();
14680 return QualType();
14681 }
14682
14683 return Context.OverloadTy;
14684 }
14685
14686 if (PTy->getKind() == BuiltinType::UnknownAny)
14687 return Context.UnknownAnyTy;
14688
14689 if (PTy->getKind() == BuiltinType::BoundMember) {
14690 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14691 << OrigOp.get()->getSourceRange();
14692 return QualType();
14693 }
14694
14695 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14696 if (OrigOp.isInvalid()) return QualType();
14697 }
14698
14699 if (OrigOp.get()->isTypeDependent())
14700 return Context.DependentTy;
14701
14702 assert(!OrigOp.get()->hasPlaceholderType());
14703
14704 // Make sure to ignore parentheses in subsequent checks
14705 Expr *op = OrigOp.get()->IgnoreParens();
14706
14707 // In OpenCL captures for blocks called as lambda functions
14708 // are located in the private address space. Blocks used in
14709 // enqueue_kernel can be located in a different address space
14710 // depending on a vendor implementation. Thus preventing
14711 // taking an address of the capture to avoid invalid AS casts.
14712 if (LangOpts.OpenCL) {
14713 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14714 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14715 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14716 return QualType();
14717 }
14718 }
14719
14720 if (getLangOpts().C99) {
14721 // Implement C99-only parts of addressof rules.
14722 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14723 if (uOp->getOpcode() == UO_Deref)
14724 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14725 // (assuming the deref expression is valid).
14726 return uOp->getSubExpr()->getType();
14727 }
14728 // Technically, there should be a check for array subscript
14729 // expressions here, but the result of one is always an lvalue anyway.
14730 }
14731 ValueDecl *dcl = getPrimaryDecl(op);
14732
14733 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14734 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14735 op->getBeginLoc()))
14736 return QualType();
14737
14739 unsigned AddressOfError = AO_No_Error;
14740
14741 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14742 bool IsError = isSFINAEContext();
14743 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14744 : diag::ext_typecheck_addrof_temporary)
14745 << op->getType() << op->getSourceRange();
14746 if (IsError)
14747 return QualType();
14748 // Materialize the temporary as an lvalue so that we can take its address.
14749 OrigOp = op =
14750 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14751 } else if (isa<ObjCSelectorExpr>(op)) {
14752 return Context.getPointerType(op->getType());
14753 } else if (lval == Expr::LV_MemberFunction) {
14754 // If it's an instance method, make a member pointer.
14755 // The expression must have exactly the form &A::foo.
14756
14757 // If the underlying expression isn't a decl ref, give up.
14758 if (!isa<DeclRefExpr>(op)) {
14759 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14760 << OrigOp.get()->getSourceRange();
14761 return QualType();
14762 }
14763 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14765
14766 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14767 QualType MPTy = Context.getMemberPointerType(
14768 op->getType(), DRE->getQualifier(), MD->getParent());
14769
14770 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14771 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14772 // When pointer authentication is enabled, argument and return types of
14773 // vitual member functions must be complete. This is because vitrual
14774 // member function pointers are implemented using virtual dispatch
14775 // thunks and the thunks cannot be emitted if the argument or return
14776 // types are incomplete.
14777 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14778 SourceLocation DeclRefLoc,
14779 SourceLocation RetArgTypeLoc) {
14780 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14781 Diag(DeclRefLoc,
14782 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14783 Diag(RetArgTypeLoc,
14784 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14785 << T;
14786 return true;
14787 }
14788 return false;
14789 };
14790 QualType RetTy = MD->getReturnType();
14791 bool IsIncomplete =
14792 !RetTy->isVoidType() &&
14793 ReturnOrParamTypeIsIncomplete(
14794 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14795 for (auto *PVD : MD->parameters())
14796 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14797 PVD->getBeginLoc());
14798 if (IsIncomplete)
14799 return QualType();
14800 }
14801
14802 // Under the MS ABI, lock down the inheritance model now.
14803 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14804 (void)isCompleteType(OpLoc, MPTy);
14805 return MPTy;
14806 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14807 // C99 6.5.3.2p1
14808 // The operand must be either an l-value or a function designator
14809 if (!op->getType()->isFunctionType()) {
14810 // Use a special diagnostic for loads from property references.
14811 if (isa<PseudoObjectExpr>(op)) {
14812 AddressOfError = AO_Property_Expansion;
14813 } else {
14814 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14815 << op->getType() << op->getSourceRange();
14816 return QualType();
14817 }
14818 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14819 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14820 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14821 }
14822
14823 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14824 // The operand cannot be a bit-field
14825 AddressOfError = AO_Bit_Field;
14826 } else if (op->getObjectKind() == OK_VectorComponent) {
14827 // The operand cannot be an element of a vector
14828 AddressOfError = AO_Vector_Element;
14829 } else if (op->getObjectKind() == OK_MatrixComponent) {
14830 // The operand cannot be an element of a matrix.
14831 AddressOfError = AO_Matrix_Element;
14832 } else if (dcl) { // C99 6.5.3.2p1
14833 // We have an lvalue with a decl. Make sure the decl is not declared
14834 // with the register storage-class specifier.
14835 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14836 // in C++ it is not error to take address of a register
14837 // variable (c++03 7.1.1P3)
14838 if (vd->getStorageClass() == SC_Register &&
14840 AddressOfError = AO_Register_Variable;
14841 }
14842 } else if (isa<MSPropertyDecl>(dcl)) {
14843 AddressOfError = AO_Property_Expansion;
14844 } else if (isa<FunctionTemplateDecl>(dcl)) {
14845 return Context.OverloadTy;
14846 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14847 // Okay: we can take the address of a field.
14848 // Could be a pointer to member, though, if there is an explicit
14849 // scope qualifier for the class.
14850
14851 // [C++26] [expr.prim.id.general]
14852 // If an id-expression E denotes a non-static non-type member
14853 // of some class C [...] and if E is a qualified-id, E is
14854 // not the un-parenthesized operand of the unary & operator [...]
14855 // the id-expression is transformed into a class member access expression.
14856 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
14857 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
14858 DeclContext *Ctx = dcl->getDeclContext();
14859 if (Ctx && Ctx->isRecord()) {
14860 if (dcl->getType()->isReferenceType()) {
14861 Diag(OpLoc,
14862 diag::err_cannot_form_pointer_to_member_of_reference_type)
14863 << dcl->getDeclName() << dcl->getType();
14864 return QualType();
14865 }
14866
14867 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14868 Ctx = Ctx->getParent();
14869
14870 QualType MPTy = Context.getMemberPointerType(
14871 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
14872 // Under the MS ABI, lock down the inheritance model now.
14873 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14874 (void)isCompleteType(OpLoc, MPTy);
14875 return MPTy;
14876 }
14877 }
14881 llvm_unreachable("Unknown/unexpected decl type");
14882 }
14883
14884 if (AddressOfError != AO_No_Error) {
14885 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14886 return QualType();
14887 }
14888
14889 if (lval == Expr::LV_IncompleteVoidType) {
14890 // Taking the address of a void variable is technically illegal, but we
14891 // allow it in cases which are otherwise valid.
14892 // Example: "extern void x; void* y = &x;".
14893 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14894 }
14895
14896 // If the operand has type "type", the result has type "pointer to type".
14897 if (op->getType()->isObjCObjectType())
14898 return Context.getObjCObjectPointerType(op->getType());
14899
14900 // Cannot take the address of WebAssembly references or tables.
14901 if (Context.getTargetInfo().getTriple().isWasm()) {
14902 QualType OpTy = op->getType();
14903 if (OpTy.isWebAssemblyReferenceType()) {
14904 Diag(OpLoc, diag::err_wasm_ca_reference)
14905 << 1 << OrigOp.get()->getSourceRange();
14906 return QualType();
14907 }
14908 if (OpTy->isWebAssemblyTableType()) {
14909 Diag(OpLoc, diag::err_wasm_table_pr)
14910 << 1 << OrigOp.get()->getSourceRange();
14911 return QualType();
14912 }
14913 }
14914
14915 CheckAddressOfPackedMember(op);
14916
14917 return Context.getPointerType(op->getType());
14918}
14919
14920static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14921 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14922 if (!DRE)
14923 return;
14924 const Decl *D = DRE->getDecl();
14925 if (!D)
14926 return;
14927 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14928 if (!Param)
14929 return;
14930 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14931 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14932 return;
14933 if (FunctionScopeInfo *FD = S.getCurFunction())
14934 FD->ModifiedNonNullParams.insert(Param);
14935}
14936
14937/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14939 SourceLocation OpLoc,
14940 bool IsAfterAmp = false) {
14941 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14942 if (ConvResult.isInvalid())
14943 return QualType();
14944 Op = ConvResult.get();
14945 QualType OpTy = Op->getType();
14946 QualType Result;
14947
14949 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14950 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14951 Op->getSourceRange());
14952 }
14953
14954 if (const PointerType *PT = OpTy->getAs<PointerType>())
14955 {
14956 Result = PT->getPointeeType();
14957 }
14958 else if (const ObjCObjectPointerType *OPT =
14960 Result = OPT->getPointeeType();
14961 else {
14963 if (PR.isInvalid()) return QualType();
14964 if (PR.get() != Op)
14965 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14966 }
14967
14968 if (Result.isNull()) {
14969 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14970 << OpTy << Op->getSourceRange();
14971 return QualType();
14972 }
14973
14974 if (Result->isVoidType()) {
14975 // C++ [expr.unary.op]p1:
14976 // [...] the expression to which [the unary * operator] is applied shall
14977 // be a pointer to an object type, or a pointer to a function type
14978 LangOptions LO = S.getLangOpts();
14979 if (LO.CPlusPlus)
14980 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14981 << OpTy << Op->getSourceRange();
14982 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14983 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14984 << OpTy << Op->getSourceRange();
14985 }
14986
14987 // Dereferences are usually l-values...
14988 VK = VK_LValue;
14989
14990 // ...except that certain expressions are never l-values in C.
14991 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14992 VK = VK_PRValue;
14993
14994 return Result;
14995}
14996
14997BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14999 switch (Kind) {
15000 default: llvm_unreachable("Unknown binop!");
15001 case tok::periodstar: Opc = BO_PtrMemD; break;
15002 case tok::arrowstar: Opc = BO_PtrMemI; break;
15003 case tok::star: Opc = BO_Mul; break;
15004 case tok::slash: Opc = BO_Div; break;
15005 case tok::percent: Opc = BO_Rem; break;
15006 case tok::plus: Opc = BO_Add; break;
15007 case tok::minus: Opc = BO_Sub; break;
15008 case tok::lessless: Opc = BO_Shl; break;
15009 case tok::greatergreater: Opc = BO_Shr; break;
15010 case tok::lessequal: Opc = BO_LE; break;
15011 case tok::less: Opc = BO_LT; break;
15012 case tok::greaterequal: Opc = BO_GE; break;
15013 case tok::greater: Opc = BO_GT; break;
15014 case tok::exclaimequal: Opc = BO_NE; break;
15015 case tok::equalequal: Opc = BO_EQ; break;
15016 case tok::spaceship: Opc = BO_Cmp; break;
15017 case tok::amp: Opc = BO_And; break;
15018 case tok::caret: Opc = BO_Xor; break;
15019 case tok::pipe: Opc = BO_Or; break;
15020 case tok::ampamp: Opc = BO_LAnd; break;
15021 case tok::pipepipe: Opc = BO_LOr; break;
15022 case tok::equal: Opc = BO_Assign; break;
15023 case tok::starequal: Opc = BO_MulAssign; break;
15024 case tok::slashequal: Opc = BO_DivAssign; break;
15025 case tok::percentequal: Opc = BO_RemAssign; break;
15026 case tok::plusequal: Opc = BO_AddAssign; break;
15027 case tok::minusequal: Opc = BO_SubAssign; break;
15028 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15029 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15030 case tok::ampequal: Opc = BO_AndAssign; break;
15031 case tok::caretequal: Opc = BO_XorAssign; break;
15032 case tok::pipeequal: Opc = BO_OrAssign; break;
15033 case tok::comma: Opc = BO_Comma; break;
15034 }
15035 return Opc;
15036}
15037
15039 tok::TokenKind Kind) {
15041 switch (Kind) {
15042 default: llvm_unreachable("Unknown unary op!");
15043 case tok::plusplus: Opc = UO_PreInc; break;
15044 case tok::minusminus: Opc = UO_PreDec; break;
15045 case tok::amp: Opc = UO_AddrOf; break;
15046 case tok::star: Opc = UO_Deref; break;
15047 case tok::plus: Opc = UO_Plus; break;
15048 case tok::minus: Opc = UO_Minus; break;
15049 case tok::tilde: Opc = UO_Not; break;
15050 case tok::exclaim: Opc = UO_LNot; break;
15051 case tok::kw___real: Opc = UO_Real; break;
15052 case tok::kw___imag: Opc = UO_Imag; break;
15053 case tok::kw___extension__: Opc = UO_Extension; break;
15054 }
15055 return Opc;
15056}
15057
15058const FieldDecl *
15060 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15061 // common for setters.
15062 // struct A {
15063 // int X;
15064 // -void setX(int X) { X = X; }
15065 // +void setX(int X) { this->X = X; }
15066 // };
15067
15068 // Only consider parameters for self assignment fixes.
15069 if (!isa<ParmVarDecl>(SelfAssigned))
15070 return nullptr;
15071 const auto *Method =
15072 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15073 if (!Method)
15074 return nullptr;
15075
15076 const CXXRecordDecl *Parent = Method->getParent();
15077 // In theory this is fixable if the lambda explicitly captures this, but
15078 // that's added complexity that's rarely going to be used.
15079 if (Parent->isLambda())
15080 return nullptr;
15081
15082 // FIXME: Use an actual Lookup operation instead of just traversing fields
15083 // in order to get base class fields.
15084 auto Field =
15085 llvm::find_if(Parent->fields(),
15086 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15087 return F->getDeclName() == Name;
15088 });
15089 return (Field != Parent->field_end()) ? *Field : nullptr;
15090}
15091
15092/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15093/// This warning suppressed in the event of macro expansions.
15094static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15095 SourceLocation OpLoc, bool IsBuiltin) {
15097 return;
15098 if (S.isUnevaluatedContext())
15099 return;
15100 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15101 return;
15102 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15103 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15104 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15105 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15106 if (!LHSDeclRef || !RHSDeclRef ||
15107 LHSDeclRef->getLocation().isMacroID() ||
15108 RHSDeclRef->getLocation().isMacroID())
15109 return;
15110 const ValueDecl *LHSDecl =
15111 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15112 const ValueDecl *RHSDecl =
15113 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15114 if (LHSDecl != RHSDecl)
15115 return;
15116 if (LHSDecl->getType().isVolatileQualified())
15117 return;
15118 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15119 if (RefTy->getPointeeType().isVolatileQualified())
15120 return;
15121
15122 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15123 : diag::warn_self_assignment_overloaded)
15124 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15125 << RHSExpr->getSourceRange();
15126 if (const FieldDecl *SelfAssignField =
15128 Diag << 1 << SelfAssignField
15129 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15130 else
15131 Diag << 0;
15132}
15133
15134/// Check if a bitwise-& is performed on an Objective-C pointer. This
15135/// is usually indicative of introspection within the Objective-C pointer.
15137 SourceLocation OpLoc) {
15138 if (!S.getLangOpts().ObjC)
15139 return;
15140
15141 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15142 const Expr *LHS = L.get();
15143 const Expr *RHS = R.get();
15144
15146 ObjCPointerExpr = LHS;
15147 OtherExpr = RHS;
15148 }
15149 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15150 ObjCPointerExpr = RHS;
15151 OtherExpr = LHS;
15152 }
15153
15154 // This warning is deliberately made very specific to reduce false
15155 // positives with logic that uses '&' for hashing. This logic mainly
15156 // looks for code trying to introspect into tagged pointers, which
15157 // code should generally never do.
15158 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15159 unsigned Diag = diag::warn_objc_pointer_masking;
15160 // Determine if we are introspecting the result of performSelectorXXX.
15161 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15162 // Special case messages to -performSelector and friends, which
15163 // can return non-pointer values boxed in a pointer value.
15164 // Some clients may wish to silence warnings in this subcase.
15165 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15166 Selector S = ME->getSelector();
15167 StringRef SelArg0 = S.getNameForSlot(0);
15168 if (SelArg0.starts_with("performSelector"))
15169 Diag = diag::warn_objc_pointer_masking_performSelector;
15170 }
15171
15172 S.Diag(OpLoc, Diag)
15173 << ObjCPointerExpr->getSourceRange();
15174 }
15175}
15176
15177// This helper function promotes a binary operator's operands (which are of a
15178// half vector type) to a vector of floats and then truncates the result to
15179// a vector of either half or short.
15181 BinaryOperatorKind Opc, QualType ResultTy,
15183 bool IsCompAssign, SourceLocation OpLoc,
15184 FPOptionsOverride FPFeatures) {
15185 auto &Context = S.getASTContext();
15186 assert((isVector(ResultTy, Context.HalfTy) ||
15187 isVector(ResultTy, Context.ShortTy)) &&
15188 "Result must be a vector of half or short");
15189 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15190 isVector(RHS.get()->getType(), Context.HalfTy) &&
15191 "both operands expected to be a half vector");
15192
15193 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15194 QualType BinOpResTy = RHS.get()->getType();
15195
15196 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15197 // change BinOpResTy to a vector of ints.
15198 if (isVector(ResultTy, Context.ShortTy))
15199 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15200
15201 if (IsCompAssign)
15202 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15203 ResultTy, VK, OK, OpLoc, FPFeatures,
15204 BinOpResTy, BinOpResTy);
15205
15206 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15207 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15208 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15209 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15210}
15211
15212/// Returns true if conversion between vectors of halfs and vectors of floats
15213/// is needed.
15214static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15215 Expr *E0, Expr *E1 = nullptr) {
15216 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15218 return false;
15219
15220 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15221 QualType Ty = E->IgnoreImplicit()->getType();
15222
15223 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15224 // to vectors of floats. Although the element type of the vectors is __fp16,
15225 // the vectors shouldn't be treated as storage-only types. See the
15226 // discussion here: https://reviews.llvm.org/rG825235c140e7
15227 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15228 if (VT->getVectorKind() == VectorKind::Neon)
15229 return false;
15230 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15231 }
15232 return false;
15233 };
15234
15235 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15236}
15237
15239 BinaryOperatorKind Opc, Expr *LHSExpr,
15240 Expr *RHSExpr, bool ForFoldExpression) {
15241 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15242 // The syntax only allows initializer lists on the RHS of assignment,
15243 // so we don't need to worry about accepting invalid code for
15244 // non-assignment operators.
15245 // C++11 5.17p9:
15246 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15247 // of x = {} is x = T().
15249 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15250 InitializedEntity Entity =
15252 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15253 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15254 if (Init.isInvalid())
15255 return Init;
15256 RHSExpr = Init.get();
15257 }
15258
15259 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15260 QualType ResultTy; // Result type of the binary operator.
15261 // The following two variables are used for compound assignment operators
15262 QualType CompLHSTy; // Type of LHS after promotions for computation
15263 QualType CompResultTy; // Type of computation result
15266 bool ConvertHalfVec = false;
15267
15268 if (!LHS.isUsable() || !RHS.isUsable())
15269 return ExprError();
15270
15271 if (getLangOpts().OpenCL) {
15272 QualType LHSTy = LHSExpr->getType();
15273 QualType RHSTy = RHSExpr->getType();
15274 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15275 // the ATOMIC_VAR_INIT macro.
15276 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15277 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15278 if (BO_Assign == Opc)
15279 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15280 else
15281 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15282 return ExprError();
15283 }
15284
15285 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15286 // only with a builtin functions and therefore should be disallowed here.
15287 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15288 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15289 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15290 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15291 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15292 return ExprError();
15293 }
15294 }
15295
15296 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15297 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15298
15299 switch (Opc) {
15300 case BO_Assign:
15301 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15302 if (getLangOpts().CPlusPlus &&
15303 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15304 VK = LHS.get()->getValueKind();
15305 OK = LHS.get()->getObjectKind();
15306 }
15307 if (!ResultTy.isNull()) {
15308 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15309 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15310
15311 // Avoid copying a block to the heap if the block is assigned to a local
15312 // auto variable that is declared in the same scope as the block. This
15313 // optimization is unsafe if the local variable is declared in an outer
15314 // scope. For example:
15315 //
15316 // BlockTy b;
15317 // {
15318 // b = ^{...};
15319 // }
15320 // // It is unsafe to invoke the block here if it wasn't copied to the
15321 // // heap.
15322 // b();
15323
15324 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15325 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15326 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15327 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15328 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15329
15331 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15333 }
15334 RecordModifiableNonNullParam(*this, LHS.get());
15335 break;
15336 case BO_PtrMemD:
15337 case BO_PtrMemI:
15338 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15339 Opc == BO_PtrMemI);
15340 break;
15341 case BO_Mul:
15342 case BO_Div:
15343 ConvertHalfVec = true;
15344 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15345 break;
15346 case BO_Rem:
15347 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15348 break;
15349 case BO_Add:
15350 ConvertHalfVec = true;
15351 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15352 break;
15353 case BO_Sub:
15354 ConvertHalfVec = true;
15355 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15356 break;
15357 case BO_Shl:
15358 case BO_Shr:
15359 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15360 break;
15361 case BO_LE:
15362 case BO_LT:
15363 case BO_GE:
15364 case BO_GT:
15365 ConvertHalfVec = true;
15366 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15367
15368 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15369 !ForFoldExpression && BI && BI->isComparisonOp())
15370 Diag(OpLoc, diag::warn_consecutive_comparison)
15371 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15372
15373 break;
15374 case BO_EQ:
15375 case BO_NE:
15376 ConvertHalfVec = true;
15377 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15378 break;
15379 case BO_Cmp:
15380 ConvertHalfVec = true;
15381 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15382 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15383 break;
15384 case BO_And:
15385 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15386 [[fallthrough]];
15387 case BO_Xor:
15388 case BO_Or:
15389 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15390 break;
15391 case BO_LAnd:
15392 case BO_LOr:
15393 ConvertHalfVec = true;
15394 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15395 break;
15396 case BO_MulAssign:
15397 case BO_DivAssign:
15398 ConvertHalfVec = true;
15399 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15400 CompLHSTy = CompResultTy;
15401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15402 ResultTy =
15403 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15404 break;
15405 case BO_RemAssign:
15406 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15407 CompLHSTy = CompResultTy;
15408 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15409 ResultTy =
15410 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15411 break;
15412 case BO_AddAssign:
15413 ConvertHalfVec = true;
15414 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15416 ResultTy =
15417 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15418 break;
15419 case BO_SubAssign:
15420 ConvertHalfVec = true;
15421 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15422 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15423 ResultTy =
15424 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15425 break;
15426 case BO_ShlAssign:
15427 case BO_ShrAssign:
15428 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15429 CompLHSTy = CompResultTy;
15430 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15431 ResultTy =
15432 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15433 break;
15434 case BO_AndAssign:
15435 case BO_OrAssign: // fallthrough
15436 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15437 [[fallthrough]];
15438 case BO_XorAssign:
15439 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15440 CompLHSTy = CompResultTy;
15441 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15442 ResultTy =
15443 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15444 break;
15445 case BO_Comma:
15446 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15447 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15448 VK = RHS.get()->getValueKind();
15449 OK = RHS.get()->getObjectKind();
15450 }
15451 break;
15452 }
15453 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15454 return ExprError();
15455
15456 // Some of the binary operations require promoting operands of half vector to
15457 // float vectors and truncating the result back to half vector. For now, we do
15458 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15459 // arm64).
15460 assert(
15461 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15462 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15463 "both sides are half vectors or neither sides are");
15464 ConvertHalfVec =
15465 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15466
15467 // Check for array bounds violations for both sides of the BinaryOperator
15468 CheckArrayAccess(LHS.get());
15469 CheckArrayAccess(RHS.get());
15470
15471 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15472 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15473 &Context.Idents.get("object_setClass"),
15475 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15476 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15477 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15479 "object_setClass(")
15480 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15481 ",")
15482 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15483 }
15484 else
15485 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15486 }
15487 else if (const ObjCIvarRefExpr *OIRE =
15488 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15489 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15490
15491 // Opc is not a compound assignment if CompResultTy is null.
15492 if (CompResultTy.isNull()) {
15493 if (ConvertHalfVec)
15494 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15495 OpLoc, CurFPFeatureOverrides());
15496 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15497 VK, OK, OpLoc, CurFPFeatureOverrides());
15498 }
15499
15500 // Handle compound assignments.
15501 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15503 VK = VK_LValue;
15504 OK = LHS.get()->getObjectKind();
15505 }
15506
15507 // The LHS is not converted to the result type for fixed-point compound
15508 // assignment as the common type is computed on demand. Reset the CompLHSTy
15509 // to the LHS type we would have gotten after unary conversions.
15510 if (CompResultTy->isFixedPointType())
15511 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15512
15513 if (ConvertHalfVec)
15514 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15515 OpLoc, CurFPFeatureOverrides());
15516
15518 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15519 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15520}
15521
15522/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15523/// operators are mixed in a way that suggests that the programmer forgot that
15524/// comparison operators have higher precedence. The most typical example of
15525/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15527 SourceLocation OpLoc, Expr *LHSExpr,
15528 Expr *RHSExpr) {
15529 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15530 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15531
15532 // Check that one of the sides is a comparison operator and the other isn't.
15533 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15534 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15535 if (isLeftComp == isRightComp)
15536 return;
15537
15538 // Bitwise operations are sometimes used as eager logical ops.
15539 // Don't diagnose this.
15540 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15541 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15542 if (isLeftBitwise || isRightBitwise)
15543 return;
15544
15545 SourceRange DiagRange = isLeftComp
15546 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15547 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15548 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15549 SourceRange ParensRange =
15550 isLeftComp
15551 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15552 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15553
15554 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15555 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15556 SuggestParentheses(Self, OpLoc,
15557 Self.PDiag(diag::note_precedence_silence) << OpStr,
15558 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15559 SuggestParentheses(Self, OpLoc,
15560 Self.PDiag(diag::note_precedence_bitwise_first)
15562 ParensRange);
15563}
15564
15565/// It accepts a '&&' expr that is inside a '||' one.
15566/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15567/// in parentheses.
15568static void
15570 BinaryOperator *Bop) {
15571 assert(Bop->getOpcode() == BO_LAnd);
15572 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15573 << Bop->getSourceRange() << OpLoc;
15575 Self.PDiag(diag::note_precedence_silence)
15576 << Bop->getOpcodeStr(),
15577 Bop->getSourceRange());
15578}
15579
15580/// Look for '&&' in the left hand of a '||' expr.
15582 Expr *LHSExpr, Expr *RHSExpr) {
15583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15584 if (Bop->getOpcode() == BO_LAnd) {
15585 // If it's "string_literal && a || b" don't warn since the precedence
15586 // doesn't matter.
15587 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15588 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15589 } else if (Bop->getOpcode() == BO_LOr) {
15590 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15591 // If it's "a || b && string_literal || c" we didn't warn earlier for
15592 // "a || b && string_literal", but warn now.
15593 if (RBop->getOpcode() == BO_LAnd &&
15594 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15595 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15596 }
15597 }
15598 }
15599}
15600
15601/// Look for '&&' in the right hand of a '||' expr.
15603 Expr *LHSExpr, Expr *RHSExpr) {
15604 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15605 if (Bop->getOpcode() == BO_LAnd) {
15606 // If it's "a || b && string_literal" don't warn since the precedence
15607 // doesn't matter.
15608 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15609 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15610 }
15611 }
15612}
15613
15614/// Look for bitwise op in the left or right hand of a bitwise op with
15615/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15616/// the '&' expression in parentheses.
15618 SourceLocation OpLoc, Expr *SubExpr) {
15619 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15620 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15621 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15622 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15623 << Bop->getSourceRange() << OpLoc;
15624 SuggestParentheses(S, Bop->getOperatorLoc(),
15625 S.PDiag(diag::note_precedence_silence)
15626 << Bop->getOpcodeStr(),
15627 Bop->getSourceRange());
15628 }
15629 }
15630}
15631
15633 Expr *SubExpr, StringRef Shift) {
15634 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15635 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15636 StringRef Op = Bop->getOpcodeStr();
15637 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15638 << Bop->getSourceRange() << OpLoc << Shift << Op;
15639 SuggestParentheses(S, Bop->getOperatorLoc(),
15640 S.PDiag(diag::note_precedence_silence) << Op,
15641 Bop->getSourceRange());
15642 }
15643 }
15644}
15645
15647 Expr *LHSExpr, Expr *RHSExpr) {
15648 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15649 if (!OCE)
15650 return;
15651
15652 FunctionDecl *FD = OCE->getDirectCallee();
15653 if (!FD || !FD->isOverloadedOperator())
15654 return;
15655
15657 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15658 return;
15659
15660 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15661 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15662 << (Kind == OO_LessLess);
15664 S.PDiag(diag::note_precedence_silence)
15665 << (Kind == OO_LessLess ? "<<" : ">>"),
15666 OCE->getSourceRange());
15668 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15669 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15670}
15671
15672/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15673/// precedence.
15675 SourceLocation OpLoc, Expr *LHSExpr,
15676 Expr *RHSExpr){
15677 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15679 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15680
15681 // Diagnose "arg1 & arg2 | arg3"
15682 if ((Opc == BO_Or || Opc == BO_Xor) &&
15683 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15684 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15685 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15686 }
15687
15688 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15689 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15690 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15691 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15692 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15693 }
15694
15695 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15696 || Opc == BO_Shr) {
15697 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15698 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15699 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15700 }
15701
15702 // Warn on overloaded shift operators and comparisons, such as:
15703 // cout << 5 == 4;
15705 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15706}
15707
15709 tok::TokenKind Kind,
15710 Expr *LHSExpr, Expr *RHSExpr) {
15711 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15712 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15713 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15714
15715 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15716 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15717
15721
15722 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15723 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15724
15725 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15726}
15727
15729 UnresolvedSetImpl &Functions) {
15731 if (OverOp != OO_None && OverOp != OO_Equal)
15732 LookupOverloadedOperatorName(OverOp, S, Functions);
15733
15734 // In C++20 onwards, we may have a second operator to look up.
15735 if (getLangOpts().CPlusPlus20) {
15737 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15738 }
15739}
15740
15741/// Build an overloaded binary operator expression in the given scope.
15744 Expr *LHS, Expr *RHS) {
15745 switch (Opc) {
15746 case BO_Assign:
15747 // In the non-overloaded case, we warn about self-assignment (x = x) for
15748 // both simple assignment and certain compound assignments where algebra
15749 // tells us the operation yields a constant result. When the operator is
15750 // overloaded, we can't do the latter because we don't want to assume that
15751 // those algebraic identities still apply; for example, a path-building
15752 // library might use operator/= to append paths. But it's still reasonable
15753 // to assume that simple assignment is just moving/copying values around
15754 // and so self-assignment is likely a bug.
15755 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15756 [[fallthrough]];
15757 case BO_DivAssign:
15758 case BO_RemAssign:
15759 case BO_SubAssign:
15760 case BO_AndAssign:
15761 case BO_OrAssign:
15762 case BO_XorAssign:
15763 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15764 break;
15765 default:
15766 break;
15767 }
15768
15769 // Find all of the overloaded operators visible from this point.
15770 UnresolvedSet<16> Functions;
15771 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15772
15773 // Build the (potentially-overloaded, potentially-dependent)
15774 // binary operation.
15775 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15776}
15777
15779 BinaryOperatorKind Opc, Expr *LHSExpr,
15780 Expr *RHSExpr, bool ForFoldExpression) {
15781 if (!LHSExpr || !RHSExpr)
15782 return ExprError();
15783
15784 // We want to end up calling one of SemaPseudoObject::checkAssignment
15785 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15786 // both expressions are overloadable or either is type-dependent),
15787 // or CreateBuiltinBinOp (in any other case). We also want to get
15788 // any placeholder types out of the way.
15789
15790 // Handle pseudo-objects in the LHS.
15791 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15792 // Assignments with a pseudo-object l-value need special analysis.
15793 if (pty->getKind() == BuiltinType::PseudoObject &&
15795 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15796
15797 // Don't resolve overloads if the other type is overloadable.
15798 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15799 // We can't actually test that if we still have a placeholder,
15800 // though. Fortunately, none of the exceptions we see in that
15801 // code below are valid when the LHS is an overload set. Note
15802 // that an overload set can be dependently-typed, but it never
15803 // instantiates to having an overloadable type.
15804 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15805 if (resolvedRHS.isInvalid()) return ExprError();
15806 RHSExpr = resolvedRHS.get();
15807
15808 if (RHSExpr->isTypeDependent() ||
15809 RHSExpr->getType()->isOverloadableType())
15810 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15811 }
15812
15813 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15814 // template, diagnose the missing 'template' keyword instead of diagnosing
15815 // an invalid use of a bound member function.
15816 //
15817 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15818 // to C++1z [over.over]/1.4, but we already checked for that case above.
15819 if (Opc == BO_LT && inTemplateInstantiation() &&
15820 (pty->getKind() == BuiltinType::BoundMember ||
15821 pty->getKind() == BuiltinType::Overload)) {
15822 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15823 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15824 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15825 return isa<FunctionTemplateDecl>(ND);
15826 })) {
15827 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15828 : OE->getNameLoc(),
15829 diag::err_template_kw_missing)
15830 << OE->getName().getAsIdentifierInfo();
15831 return ExprError();
15832 }
15833 }
15834
15835 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15836 if (LHS.isInvalid()) return ExprError();
15837 LHSExpr = LHS.get();
15838 }
15839
15840 // Handle pseudo-objects in the RHS.
15841 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15842 // An overload in the RHS can potentially be resolved by the type
15843 // being assigned to.
15844 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15845 if (getLangOpts().CPlusPlus &&
15846 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15847 LHSExpr->getType()->isOverloadableType()))
15848 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15849
15850 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15851 ForFoldExpression);
15852 }
15853
15854 // Don't resolve overloads if the other type is overloadable.
15855 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15856 LHSExpr->getType()->isOverloadableType())
15857 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15858
15859 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15860 if (!resolvedRHS.isUsable()) return ExprError();
15861 RHSExpr = resolvedRHS.get();
15862 }
15863
15864 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
15865 LHSExpr->getType()->isHLSLResourceRecordArray())) {
15866 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
15867 return ExprError();
15868 }
15869
15870 if (getLangOpts().CPlusPlus) {
15871 // Otherwise, build an overloaded op if either expression is type-dependent
15872 // or has an overloadable type.
15873 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15874 LHSExpr->getType()->isOverloadableType() ||
15875 RHSExpr->getType()->isOverloadableType())
15876 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15877 }
15878
15879 if (getLangOpts().RecoveryAST &&
15880 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15881 assert(!getLangOpts().CPlusPlus);
15882 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15883 "Should only occur in error-recovery path.");
15885 // C [6.15.16] p3:
15886 // An assignment expression has the value of the left operand after the
15887 // assignment, but is not an lvalue.
15889 Context, LHSExpr, RHSExpr, Opc,
15891 OpLoc, CurFPFeatureOverrides());
15892 QualType ResultType;
15893 switch (Opc) {
15894 case BO_Assign:
15895 ResultType = LHSExpr->getType().getUnqualifiedType();
15896 break;
15897 case BO_LT:
15898 case BO_GT:
15899 case BO_LE:
15900 case BO_GE:
15901 case BO_EQ:
15902 case BO_NE:
15903 case BO_LAnd:
15904 case BO_LOr:
15905 // These operators have a fixed result type regardless of operands.
15906 ResultType = Context.IntTy;
15907 break;
15908 case BO_Comma:
15909 ResultType = RHSExpr->getType();
15910 break;
15911 default:
15912 ResultType = Context.DependentTy;
15913 break;
15914 }
15915 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15916 VK_PRValue, OK_Ordinary, OpLoc,
15918 }
15919
15920 // Build a built-in binary operation.
15921 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15922}
15923
15925 if (T.isNull() || T->isDependentType())
15926 return false;
15927
15928 if (!Ctx.isPromotableIntegerType(T))
15929 return true;
15930
15931 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15932}
15933
15935 UnaryOperatorKind Opc, Expr *InputExpr,
15936 bool IsAfterAmp) {
15937 ExprResult Input = InputExpr;
15940 QualType resultType;
15941 bool CanOverflow = false;
15942
15943 bool ConvertHalfVec = false;
15944 if (getLangOpts().OpenCL) {
15945 QualType Ty = InputExpr->getType();
15946 // The only legal unary operation for atomics is '&'.
15947 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15948 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15949 // only with a builtin functions and therefore should be disallowed here.
15950 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15951 || Ty->isBlockPointerType())) {
15952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15953 << InputExpr->getType()
15954 << Input.get()->getSourceRange());
15955 }
15956 }
15957
15958 if (getLangOpts().HLSL && OpLoc.isValid()) {
15959 if (Opc == UO_AddrOf)
15960 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15961 if (Opc == UO_Deref)
15962 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15963 }
15964
15965 if (InputExpr->isTypeDependent() &&
15966 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15967 resultType = Context.DependentTy;
15968 } else {
15969 switch (Opc) {
15970 case UO_PreInc:
15971 case UO_PreDec:
15972 case UO_PostInc:
15973 case UO_PostDec:
15974 resultType =
15975 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15976 Opc == UO_PreInc || Opc == UO_PostInc,
15977 Opc == UO_PreInc || Opc == UO_PreDec);
15978 CanOverflow = isOverflowingIntegerType(Context, resultType);
15979 break;
15980 case UO_AddrOf:
15981 resultType = CheckAddressOfOperand(Input, OpLoc);
15982 CheckAddressOfNoDeref(InputExpr);
15983 RecordModifiableNonNullParam(*this, InputExpr);
15984 break;
15985 case UO_Deref: {
15987 if (Input.isInvalid())
15988 return ExprError();
15989 resultType =
15990 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15991 break;
15992 }
15993 case UO_Plus:
15994 case UO_Minus:
15995 CanOverflow = Opc == UO_Minus &&
15997 Input = UsualUnaryConversions(Input.get());
15998 if (Input.isInvalid())
15999 return ExprError();
16000 // Unary plus and minus require promoting an operand of half vector to a
16001 // float vector and truncating the result back to a half vector. For now,
16002 // we do this only when HalfArgsAndReturns is set (that is, when the
16003 // target is arm or arm64).
16004 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16005
16006 // If the operand is a half vector, promote it to a float vector.
16007 if (ConvertHalfVec)
16008 Input = convertVector(Input.get(), Context.FloatTy, *this);
16009 resultType = Input.get()->getType();
16010 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16011 break;
16012 else if (resultType->isVectorType() &&
16013 // The z vector extensions don't allow + or - with bool vectors.
16014 (!Context.getLangOpts().ZVector ||
16015 resultType->castAs<VectorType>()->getVectorKind() !=
16017 break;
16018 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16019 break;
16020 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16021 Opc == UO_Plus && resultType->isPointerType())
16022 break;
16023
16024 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16025 << resultType << Input.get()->getSourceRange());
16026
16027 case UO_Not: // bitwise complement
16028 Input = UsualUnaryConversions(Input.get());
16029 if (Input.isInvalid())
16030 return ExprError();
16031 resultType = Input.get()->getType();
16032 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16033 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16034 // C99 does not support '~' for complex conjugation.
16035 Diag(OpLoc, diag::ext_integer_complement_complex)
16036 << resultType << Input.get()->getSourceRange();
16037 else if (resultType->hasIntegerRepresentation())
16038 break;
16039 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16040 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16041 // on vector float types.
16042 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16043 if (!T->isIntegerType())
16044 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16045 << resultType << Input.get()->getSourceRange());
16046 } else {
16047 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16048 << resultType << Input.get()->getSourceRange());
16049 }
16050 break;
16051
16052 case UO_LNot: // logical negation
16053 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16055 if (Input.isInvalid())
16056 return ExprError();
16057 resultType = Input.get()->getType();
16058
16059 // Though we still have to promote half FP to float...
16060 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16061 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16062 .get();
16063 resultType = Context.FloatTy;
16064 }
16065
16066 // WebAsembly tables can't be used in unary expressions.
16067 if (resultType->isPointerType() &&
16069 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16070 << resultType << Input.get()->getSourceRange());
16071 }
16072
16073 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16074 // C99 6.5.3.3p1: ok, fallthrough;
16075 if (Context.getLangOpts().CPlusPlus) {
16076 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16077 // operand contextually converted to bool.
16078 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16079 ScalarTypeToBooleanCastKind(resultType));
16080 } else if (Context.getLangOpts().OpenCL &&
16081 Context.getLangOpts().OpenCLVersion < 120) {
16082 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16083 // operate on scalar float types.
16084 if (!resultType->isIntegerType() && !resultType->isPointerType())
16085 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16086 << resultType << Input.get()->getSourceRange());
16087 }
16088 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16089 !resultType->hasBooleanRepresentation()) {
16090 // HLSL unary logical 'not' behaves like C++, which states that the
16091 // operand is converted to bool and the result is bool, however HLSL
16092 // extends this property to vectors.
16093 const VectorType *VTy = resultType->castAs<VectorType>();
16094 resultType =
16095 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16096
16097 Input = ImpCastExprToType(
16098 Input.get(), resultType,
16100 .get();
16101 break;
16102 } else if (resultType->isExtVectorType()) {
16103 if (Context.getLangOpts().OpenCL &&
16104 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16105 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16106 // operate on vector float types.
16107 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16108 if (!T->isIntegerType())
16109 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16110 << resultType << Input.get()->getSourceRange());
16111 }
16112 // Vector logical not returns the signed variant of the operand type.
16113 resultType = GetSignedVectorType(resultType);
16114 break;
16115 } else if (Context.getLangOpts().CPlusPlus &&
16116 resultType->isVectorType()) {
16117 const VectorType *VTy = resultType->castAs<VectorType>();
16118 if (VTy->getVectorKind() != VectorKind::Generic)
16119 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16120 << resultType << Input.get()->getSourceRange());
16121
16122 // Vector logical not returns the signed variant of the operand type.
16123 resultType = GetSignedVectorType(resultType);
16124 break;
16125 } else {
16126 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16127 << resultType << Input.get()->getSourceRange());
16128 }
16129
16130 // LNot always has type int. C99 6.5.3.3p5.
16131 // In C++, it's bool. C++ 5.3.1p8
16132 resultType = Context.getLogicalOperationType();
16133 break;
16134 case UO_Real:
16135 case UO_Imag:
16136 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16137 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16138 // ordinary complex l-values to ordinary l-values and all other values to
16139 // r-values.
16140 if (Input.isInvalid())
16141 return ExprError();
16142 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16143 if (Input.get()->isGLValue() &&
16144 Input.get()->getObjectKind() == OK_Ordinary)
16145 VK = Input.get()->getValueKind();
16146 } else if (!getLangOpts().CPlusPlus) {
16147 // In C, a volatile scalar is read by __imag. In C++, it is not.
16148 Input = DefaultLvalueConversion(Input.get());
16149 }
16150 break;
16151 case UO_Extension:
16152 resultType = Input.get()->getType();
16153 VK = Input.get()->getValueKind();
16154 OK = Input.get()->getObjectKind();
16155 break;
16156 case UO_Coawait:
16157 // It's unnecessary to represent the pass-through operator co_await in the
16158 // AST; just return the input expression instead.
16159 assert(!Input.get()->getType()->isDependentType() &&
16160 "the co_await expression must be non-dependant before "
16161 "building operator co_await");
16162 return Input;
16163 }
16164 }
16165 if (resultType.isNull() || Input.isInvalid())
16166 return ExprError();
16167
16168 // Check for array bounds violations in the operand of the UnaryOperator,
16169 // except for the '*' and '&' operators that have to be handled specially
16170 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16171 // that are explicitly defined as valid by the standard).
16172 if (Opc != UO_AddrOf && Opc != UO_Deref)
16173 CheckArrayAccess(Input.get());
16174
16175 auto *UO =
16176 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16177 OpLoc, CanOverflow, CurFPFeatureOverrides());
16178
16179 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16180 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16182 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16183
16184 // Convert the result back to a half vector.
16185 if (ConvertHalfVec)
16186 return convertVector(UO, Context.HalfTy, *this);
16187 return UO;
16188}
16189
16191 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16192 if (!DRE->getQualifier())
16193 return false;
16194
16195 ValueDecl *VD = DRE->getDecl();
16196 if (!VD->isCXXClassMember())
16197 return false;
16198
16200 return true;
16201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16202 return Method->isImplicitObjectMemberFunction();
16203
16204 return false;
16205 }
16206
16207 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16208 if (!ULE->getQualifier())
16209 return false;
16210
16211 for (NamedDecl *D : ULE->decls()) {
16212 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16213 if (Method->isImplicitObjectMemberFunction())
16214 return true;
16215 } else {
16216 // Overload set does not contain methods.
16217 break;
16218 }
16219 }
16220
16221 return false;
16222 }
16223
16224 return false;
16225}
16226
16228 UnaryOperatorKind Opc, Expr *Input,
16229 bool IsAfterAmp) {
16230 // First things first: handle placeholders so that the
16231 // overloaded-operator check considers the right type.
16232 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16233 // Increment and decrement of pseudo-object references.
16234 if (pty->getKind() == BuiltinType::PseudoObject &&
16236 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16237
16238 // extension is always a builtin operator.
16239 if (Opc == UO_Extension)
16240 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16241
16242 // & gets special logic for several kinds of placeholder.
16243 // The builtin code knows what to do.
16244 if (Opc == UO_AddrOf &&
16245 (pty->getKind() == BuiltinType::Overload ||
16246 pty->getKind() == BuiltinType::UnknownAny ||
16247 pty->getKind() == BuiltinType::BoundMember))
16248 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16249
16250 // Anything else needs to be handled now.
16252 if (Result.isInvalid()) return ExprError();
16253 Input = Result.get();
16254 }
16255
16256 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16258 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16259 // Find all of the overloaded operators visible from this point.
16260 UnresolvedSet<16> Functions;
16262 if (S && OverOp != OO_None)
16263 LookupOverloadedOperatorName(OverOp, S, Functions);
16264
16265 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16266 }
16267
16268 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16269}
16270
16272 Expr *Input, bool IsAfterAmp) {
16273 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16274 IsAfterAmp);
16275}
16276
16278 LabelDecl *TheDecl) {
16279 TheDecl->markUsed(Context);
16280 // Create the AST node. The address of a label always has type 'void*'.
16281 auto *Res = new (Context) AddrLabelExpr(
16282 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16283
16284 if (getCurFunction())
16285 getCurFunction()->AddrLabels.push_back(Res);
16286
16287 return Res;
16288}
16289
16292 // Make sure we diagnose jumping into a statement expression.
16294}
16295
16297 // Note that function is also called by TreeTransform when leaving a
16298 // StmtExpr scope without rebuilding anything.
16299
16302}
16303
16305 SourceLocation RPLoc) {
16306 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16307}
16308
16310 SourceLocation RPLoc, unsigned TemplateDepth) {
16311 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16312 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16313
16316 assert(!Cleanup.exprNeedsCleanups() &&
16317 "cleanups within StmtExpr not correctly bound!");
16319
16320 // FIXME: there are a variety of strange constraints to enforce here, for
16321 // example, it is not possible to goto into a stmt expression apparently.
16322 // More semantic analysis is needed.
16323
16324 // If there are sub-stmts in the compound stmt, take the type of the last one
16325 // as the type of the stmtexpr.
16326 QualType Ty = Context.VoidTy;
16327 bool StmtExprMayBindToTemp = false;
16328 if (!Compound->body_empty()) {
16329 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16330 if (const Expr *Value = LastStmt->getExprStmt()) {
16331 StmtExprMayBindToTemp = true;
16332 Ty = Value->getType();
16333 }
16334 }
16335 }
16336
16337 // FIXME: Check that expression type is complete/non-abstract; statement
16338 // expressions are not lvalues.
16339 Expr *ResStmtExpr =
16340 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16341 if (StmtExprMayBindToTemp)
16342 return MaybeBindToTemporary(ResStmtExpr);
16343 return ResStmtExpr;
16344}
16345
16347 if (ER.isInvalid())
16348 return ExprError();
16349
16350 // Do function/array conversion on the last expression, but not
16351 // lvalue-to-rvalue. However, initialize an unqualified type.
16353 if (ER.isInvalid())
16354 return ExprError();
16355 Expr *E = ER.get();
16356
16357 if (E->isTypeDependent())
16358 return E;
16359
16360 // In ARC, if the final expression ends in a consume, splice
16361 // the consume out and bind it later. In the alternate case
16362 // (when dealing with a retainable type), the result
16363 // initialization will create a produce. In both cases the
16364 // result will be +1, and we'll need to balance that out with
16365 // a bind.
16366 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16367 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16368 return Cast->getSubExpr();
16369
16370 // FIXME: Provide a better location for the initialization.
16374 SourceLocation(), E);
16375}
16376
16378 TypeSourceInfo *TInfo,
16379 ArrayRef<OffsetOfComponent> Components,
16380 SourceLocation RParenLoc) {
16381 QualType ArgTy = TInfo->getType();
16382 bool Dependent = ArgTy->isDependentType();
16383 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16384
16385 // We must have at least one component that refers to the type, and the first
16386 // one is known to be a field designator. Verify that the ArgTy represents
16387 // a struct/union/class.
16388 if (!Dependent && !ArgTy->isRecordType())
16389 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16390 << ArgTy << TypeRange);
16391
16392 // Type must be complete per C99 7.17p3 because a declaring a variable
16393 // with an incomplete type would be ill-formed.
16394 if (!Dependent
16395 && RequireCompleteType(BuiltinLoc, ArgTy,
16396 diag::err_offsetof_incomplete_type, TypeRange))
16397 return ExprError();
16398
16399 bool DidWarnAboutNonPOD = false;
16400 QualType CurrentType = ArgTy;
16403 for (const OffsetOfComponent &OC : Components) {
16404 if (OC.isBrackets) {
16405 // Offset of an array sub-field. TODO: Should we allow vector elements?
16406 if (!CurrentType->isDependentType()) {
16407 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16408 if(!AT)
16409 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16410 << CurrentType);
16411 CurrentType = AT->getElementType();
16412 } else
16413 CurrentType = Context.DependentTy;
16414
16415 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16416 if (IdxRval.isInvalid())
16417 return ExprError();
16418 Expr *Idx = IdxRval.get();
16419
16420 // The expression must be an integral expression.
16421 // FIXME: An integral constant expression?
16422 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16423 !Idx->getType()->isIntegerType())
16424 return ExprError(
16425 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16426 << Idx->getSourceRange());
16427
16428 // Record this array index.
16429 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16430 Exprs.push_back(Idx);
16431 continue;
16432 }
16433
16434 // Offset of a field.
16435 if (CurrentType->isDependentType()) {
16436 // We have the offset of a field, but we can't look into the dependent
16437 // type. Just record the identifier of the field.
16438 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16439 CurrentType = Context.DependentTy;
16440 continue;
16441 }
16442
16443 // We need to have a complete type to look into.
16444 if (RequireCompleteType(OC.LocStart, CurrentType,
16445 diag::err_offsetof_incomplete_type))
16446 return ExprError();
16447
16448 // Look for the designated field.
16449 auto *RD = CurrentType->getAsRecordDecl();
16450 if (!RD)
16451 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16452 << CurrentType);
16453
16454 // C++ [lib.support.types]p5:
16455 // The macro offsetof accepts a restricted set of type arguments in this
16456 // International Standard. type shall be a POD structure or a POD union
16457 // (clause 9).
16458 // C++11 [support.types]p4:
16459 // If type is not a standard-layout class (Clause 9), the results are
16460 // undefined.
16461 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16462 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16463 unsigned DiagID =
16464 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16465 : diag::ext_offsetof_non_pod_type;
16466
16467 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16468 Diag(BuiltinLoc, DiagID)
16469 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16470 DidWarnAboutNonPOD = true;
16471 }
16472 }
16473
16474 // Look for the field.
16475 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16476 LookupQualifiedName(R, RD);
16477 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16478 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16479 if (!MemberDecl) {
16480 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16481 MemberDecl = IndirectMemberDecl->getAnonField();
16482 }
16483
16484 if (!MemberDecl) {
16485 // Lookup could be ambiguous when looking up a placeholder variable
16486 // __builtin_offsetof(S, _).
16487 // In that case we would already have emitted a diagnostic
16488 if (!R.isAmbiguous())
16489 Diag(BuiltinLoc, diag::err_no_member)
16490 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16491 return ExprError();
16492 }
16493
16494 // C99 7.17p3:
16495 // (If the specified member is a bit-field, the behavior is undefined.)
16496 //
16497 // We diagnose this as an error.
16498 if (MemberDecl->isBitField()) {
16499 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16500 << MemberDecl->getDeclName()
16501 << SourceRange(BuiltinLoc, RParenLoc);
16502 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16503 return ExprError();
16504 }
16505
16506 RecordDecl *Parent = MemberDecl->getParent();
16507 if (IndirectMemberDecl)
16508 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16509
16510 // If the member was found in a base class, introduce OffsetOfNodes for
16511 // the base class indirections.
16512 CXXBasePaths Paths;
16513 if (IsDerivedFrom(OC.LocStart, CurrentType,
16514 Context.getCanonicalTagType(Parent), Paths)) {
16515 if (Paths.getDetectedVirtual()) {
16516 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16517 << MemberDecl->getDeclName()
16518 << SourceRange(BuiltinLoc, RParenLoc);
16519 return ExprError();
16520 }
16521
16522 CXXBasePath &Path = Paths.front();
16523 for (const CXXBasePathElement &B : Path)
16524 Comps.push_back(OffsetOfNode(B.Base));
16525 }
16526
16527 if (IndirectMemberDecl) {
16528 for (auto *FI : IndirectMemberDecl->chain()) {
16529 assert(isa<FieldDecl>(FI));
16530 Comps.push_back(OffsetOfNode(OC.LocStart,
16531 cast<FieldDecl>(FI), OC.LocEnd));
16532 }
16533 } else
16534 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16535
16536 CurrentType = MemberDecl->getType().getNonReferenceType();
16537 }
16538
16539 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16540 Comps, Exprs, RParenLoc);
16541}
16542
16544 SourceLocation BuiltinLoc,
16546 ParsedType ParsedArgTy,
16547 ArrayRef<OffsetOfComponent> Components,
16548 SourceLocation RParenLoc) {
16549
16550 TypeSourceInfo *ArgTInfo;
16551 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16552 if (ArgTy.isNull())
16553 return ExprError();
16554
16555 if (!ArgTInfo)
16556 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16557
16558 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16559}
16560
16561
16563 Expr *CondExpr,
16564 Expr *LHSExpr, Expr *RHSExpr,
16565 SourceLocation RPLoc) {
16566 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16567
16570 QualType resType;
16571 bool CondIsTrue = false;
16572 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16573 resType = Context.DependentTy;
16574 } else {
16575 // The conditional expression is required to be a constant expression.
16576 llvm::APSInt condEval(32);
16578 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16579 if (CondICE.isInvalid())
16580 return ExprError();
16581 CondExpr = CondICE.get();
16582 CondIsTrue = condEval.getZExtValue();
16583
16584 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16585 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16586
16587 resType = ActiveExpr->getType();
16588 VK = ActiveExpr->getValueKind();
16589 OK = ActiveExpr->getObjectKind();
16590 }
16591
16592 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16593 resType, VK, OK, RPLoc, CondIsTrue);
16594}
16595
16596//===----------------------------------------------------------------------===//
16597// Clang Extensions.
16598//===----------------------------------------------------------------------===//
16599
16600void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16602
16603 if (LangOpts.CPlusPlus) {
16605 Decl *ManglingContextDecl;
16606 std::tie(MCtx, ManglingContextDecl) =
16607 getCurrentMangleNumberContext(Block->getDeclContext());
16608 if (MCtx) {
16609 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16610 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16611 }
16612 }
16613
16614 PushBlockScope(CurScope, Block);
16615 CurContext->addDecl(Block);
16616 if (CurScope)
16617 PushDeclContext(CurScope, Block);
16618 else
16619 CurContext = Block;
16620
16622
16623 // Enter a new evaluation context to insulate the block from any
16624 // cleanups from the enclosing full-expression.
16627}
16628
16630 Scope *CurScope) {
16631 assert(ParamInfo.getIdentifier() == nullptr &&
16632 "block-id should have no identifier!");
16633 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16634 BlockScopeInfo *CurBlock = getCurBlock();
16635
16636 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16637 QualType T = Sig->getType();
16639
16640 // GetTypeForDeclarator always produces a function type for a block
16641 // literal signature. Furthermore, it is always a FunctionProtoType
16642 // unless the function was written with a typedef.
16643 assert(T->isFunctionType() &&
16644 "GetTypeForDeclarator made a non-function block signature");
16645
16646 // Look for an explicit signature in that function type.
16647 FunctionProtoTypeLoc ExplicitSignature;
16648
16649 if ((ExplicitSignature = Sig->getTypeLoc()
16651
16652 // Check whether that explicit signature was synthesized by
16653 // GetTypeForDeclarator. If so, don't save that as part of the
16654 // written signature.
16655 if (ExplicitSignature.getLocalRangeBegin() ==
16656 ExplicitSignature.getLocalRangeEnd()) {
16657 // This would be much cheaper if we stored TypeLocs instead of
16658 // TypeSourceInfos.
16659 TypeLoc Result = ExplicitSignature.getReturnLoc();
16660 unsigned Size = Result.getFullDataSize();
16661 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16662 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16663
16664 ExplicitSignature = FunctionProtoTypeLoc();
16665 }
16666 }
16667
16668 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16669 CurBlock->FunctionType = T;
16670
16671 const auto *Fn = T->castAs<FunctionType>();
16672 QualType RetTy = Fn->getReturnType();
16673 bool isVariadic =
16674 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16675
16676 CurBlock->TheDecl->setIsVariadic(isVariadic);
16677
16678 // Context.DependentTy is used as a placeholder for a missing block
16679 // return type. TODO: what should we do with declarators like:
16680 // ^ * { ... }
16681 // If the answer is "apply template argument deduction"....
16682 if (RetTy != Context.DependentTy) {
16683 CurBlock->ReturnType = RetTy;
16684 CurBlock->TheDecl->setBlockMissingReturnType(false);
16685 CurBlock->HasImplicitReturnType = false;
16686 }
16687
16688 // Push block parameters from the declarator if we had them.
16690 if (ExplicitSignature) {
16691 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16692 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16693 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16694 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16695 // Diagnose this as an extension in C17 and earlier.
16696 if (!getLangOpts().C23)
16697 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16698 }
16699 Params.push_back(Param);
16700 }
16701
16702 // Fake up parameter variables if we have a typedef, like
16703 // ^ fntype { ... }
16704 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16705 for (const auto &I : Fn->param_types()) {
16707 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16708 Params.push_back(Param);
16709 }
16710 }
16711
16712 // Set the parameters on the block decl.
16713 if (!Params.empty()) {
16714 CurBlock->TheDecl->setParams(Params);
16716 /*CheckParameterNames=*/false);
16717 }
16718
16719 // Finally we can process decl attributes.
16720 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16721
16722 // Put the parameter variables in scope.
16723 for (auto *AI : CurBlock->TheDecl->parameters()) {
16724 AI->setOwningFunction(CurBlock->TheDecl);
16725
16726 // If this has an identifier, add it to the scope stack.
16727 if (AI->getIdentifier()) {
16728 CheckShadow(CurBlock->TheScope, AI);
16729
16730 PushOnScopeChains(AI, CurBlock->TheScope);
16731 }
16732
16733 if (AI->isInvalidDecl())
16734 CurBlock->TheDecl->setInvalidDecl();
16735 }
16736}
16737
16738void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16739 // Leave the expression-evaluation context.
16742
16743 // Pop off CurBlock, handle nested blocks.
16746}
16747
16749 Stmt *Body, Scope *CurScope) {
16750 // If blocks are disabled, emit an error.
16751 if (!LangOpts.Blocks)
16752 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16753
16754 // Leave the expression-evaluation context.
16757 assert(!Cleanup.exprNeedsCleanups() &&
16758 "cleanups within block not correctly bound!");
16760
16762 BlockDecl *BD = BSI->TheDecl;
16763
16765
16766 if (BSI->HasImplicitReturnType)
16768
16769 QualType RetTy = Context.VoidTy;
16770 if (!BSI->ReturnType.isNull())
16771 RetTy = BSI->ReturnType;
16772
16773 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16774 QualType BlockTy;
16775
16776 // If the user wrote a function type in some form, try to use that.
16777 if (!BSI->FunctionType.isNull()) {
16778 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16779
16780 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16781 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16782
16783 // Turn protoless block types into nullary block types.
16784 if (isa<FunctionNoProtoType>(FTy)) {
16786 EPI.ExtInfo = Ext;
16787 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16788
16789 // Otherwise, if we don't need to change anything about the function type,
16790 // preserve its sugar structure.
16791 } else if (FTy->getReturnType() == RetTy &&
16792 (!NoReturn || FTy->getNoReturnAttr())) {
16793 BlockTy = BSI->FunctionType;
16794
16795 // Otherwise, make the minimal modifications to the function type.
16796 } else {
16799 EPI.TypeQuals = Qualifiers();
16800 EPI.ExtInfo = Ext;
16801 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16802 }
16803
16804 // If we don't have a function type, just build one from nothing.
16805 } else {
16807 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16808 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16809 }
16810
16812 BlockTy = Context.getBlockPointerType(BlockTy);
16813
16814 // If needed, diagnose invalid gotos and switches in the block.
16815 if (getCurFunction()->NeedsScopeChecking() &&
16816 !PP.isCodeCompletionEnabled())
16818
16819 BD->setBody(cast<CompoundStmt>(Body));
16820
16821 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16823
16824 // Try to apply the named return value optimization. We have to check again
16825 // if we can do this, though, because blocks keep return statements around
16826 // to deduce an implicit return type.
16827 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16828 !BD->isDependentContext())
16829 computeNRVO(Body, BSI);
16830
16836
16838
16839 // Set the captured variables on the block.
16841 for (Capture &Cap : BSI->Captures) {
16842 if (Cap.isInvalid() || Cap.isThisCapture())
16843 continue;
16844 // Cap.getVariable() is always a VarDecl because
16845 // blocks cannot capture structured bindings or other ValueDecl kinds.
16846 auto *Var = cast<VarDecl>(Cap.getVariable());
16847 Expr *CopyExpr = nullptr;
16848 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16849 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16850 // The capture logic needs the destructor, so make sure we mark it.
16851 // Usually this is unnecessary because most local variables have
16852 // their destructors marked at declaration time, but parameters are
16853 // an exception because it's technically only the call site that
16854 // actually requires the destructor.
16855 if (isa<ParmVarDecl>(Var))
16857
16858 // Enter a separate potentially-evaluated context while building block
16859 // initializers to isolate their cleanups from those of the block
16860 // itself.
16861 // FIXME: Is this appropriate even when the block itself occurs in an
16862 // unevaluated operand?
16865
16866 SourceLocation Loc = Cap.getLocation();
16867
16869 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16870
16871 // According to the blocks spec, the capture of a variable from
16872 // the stack requires a const copy constructor. This is not true
16873 // of the copy/move done to move a __block variable to the heap.
16874 if (!Result.isInvalid() &&
16875 !Result.get()->getType().isConstQualified()) {
16877 Result.get()->getType().withConst(),
16878 CK_NoOp, VK_LValue);
16879 }
16880
16881 if (!Result.isInvalid()) {
16883 InitializedEntity::InitializeBlock(Var->getLocation(),
16884 Cap.getCaptureType()),
16885 Loc, Result.get());
16886 }
16887
16888 // Build a full-expression copy expression if initialization
16889 // succeeded and used a non-trivial constructor. Recover from
16890 // errors by pretending that the copy isn't necessary.
16891 if (!Result.isInvalid() &&
16892 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16893 ->isTrivial()) {
16895 CopyExpr = Result.get();
16896 }
16897 }
16898 }
16899
16900 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16901 CopyExpr);
16902 Captures.push_back(NewCap);
16903 }
16904 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16905
16906 // Pop the block scope now but keep it alive to the end of this function.
16908 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
16909 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16910
16911 BlockExpr *Result = new (Context)
16912 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16913
16914 // If the block isn't obviously global, i.e. it captures anything at
16915 // all, then we need to do a few things in the surrounding context:
16916 if (Result->getBlockDecl()->hasCaptures()) {
16917 // First, this expression has a new cleanup object.
16918 ExprCleanupObjects.push_back(Result->getBlockDecl());
16919 Cleanup.setExprNeedsCleanups(true);
16920
16921 // It also gets a branch-protected scope if any of the captured
16922 // variables needs destruction.
16923 for (const auto &CI : Result->getBlockDecl()->captures()) {
16924 const VarDecl *var = CI.getVariable();
16925 if (var->getType().isDestructedType() != QualType::DK_none) {
16927 break;
16928 }
16929 }
16930 }
16931
16932 if (getCurFunction())
16933 getCurFunction()->addBlock(BD);
16934
16935 // This can happen if the block's return type is deduced, but
16936 // the return expression is invalid.
16937 if (BD->isInvalidDecl())
16938 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16939 {Result}, Result->getType());
16940 return Result;
16941}
16942
16944 SourceLocation RPLoc) {
16945 TypeSourceInfo *TInfo;
16946 GetTypeFromParser(Ty, &TInfo);
16947 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16948}
16949
16951 Expr *E, TypeSourceInfo *TInfo,
16952 SourceLocation RPLoc) {
16953 Expr *OrigExpr = E;
16954 bool IsMS = false;
16955
16956 // CUDA device global function does not support varargs.
16957 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16958 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16961 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16962 }
16963 }
16964
16965 // NVPTX does not support va_arg expression.
16966 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16967 Context.getTargetInfo().getTriple().isNVPTX())
16968 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16969
16970 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16971 // as Microsoft ABI on an actual Microsoft platform, where
16972 // __builtin_ms_va_list and __builtin_va_list are the same.)
16973 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16974 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16975 QualType MSVaListType = Context.getBuiltinMSVaListType();
16976 if (Context.hasSameType(MSVaListType, E->getType())) {
16977 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16978 return ExprError();
16979 IsMS = true;
16980 }
16981 }
16982
16983 // Get the va_list type
16984 QualType VaListType = Context.getBuiltinVaListType();
16985 if (!IsMS) {
16986 if (VaListType->isArrayType()) {
16987 // Deal with implicit array decay; for example, on x86-64,
16988 // va_list is an array, but it's supposed to decay to
16989 // a pointer for va_arg.
16990 VaListType = Context.getArrayDecayedType(VaListType);
16991 // Make sure the input expression also decays appropriately.
16993 if (Result.isInvalid())
16994 return ExprError();
16995 E = Result.get();
16996 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16997 // If va_list is a record type and we are compiling in C++ mode,
16998 // check the argument using reference binding.
17000 Context, Context.getLValueReferenceType(VaListType), false);
17002 if (Init.isInvalid())
17003 return ExprError();
17004 E = Init.getAs<Expr>();
17005 } else {
17006 // Otherwise, the va_list argument must be an l-value because
17007 // it is modified by va_arg.
17008 if (!E->isTypeDependent() &&
17009 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17010 return ExprError();
17011 }
17012 }
17013
17014 if (!IsMS && !E->isTypeDependent() &&
17015 !Context.hasSameType(VaListType, E->getType()))
17016 return ExprError(
17017 Diag(E->getBeginLoc(),
17018 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17019 << OrigExpr->getType() << E->getSourceRange());
17020
17021 if (!TInfo->getType()->isDependentType()) {
17022 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17023 diag::err_second_parameter_to_va_arg_incomplete,
17024 TInfo->getTypeLoc()))
17025 return ExprError();
17026
17028 TInfo->getType(),
17029 diag::err_second_parameter_to_va_arg_abstract,
17030 TInfo->getTypeLoc()))
17031 return ExprError();
17032
17033 if (!TInfo->getType().isPODType(Context)) {
17034 Diag(TInfo->getTypeLoc().getBeginLoc(),
17035 TInfo->getType()->isObjCLifetimeType()
17036 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17037 : diag::warn_second_parameter_to_va_arg_not_pod)
17038 << TInfo->getType()
17039 << TInfo->getTypeLoc().getSourceRange();
17040 }
17041
17042 if (TInfo->getType()->isArrayType()) {
17044 PDiag(diag::warn_second_parameter_to_va_arg_array)
17045 << TInfo->getType()
17046 << TInfo->getTypeLoc().getSourceRange());
17047 }
17048
17049 // Check for va_arg where arguments of the given type will be promoted
17050 // (i.e. this va_arg is guaranteed to have undefined behavior).
17051 QualType PromoteType;
17052 if (Context.isPromotableIntegerType(TInfo->getType())) {
17053 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17054 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17055 // and C23 7.16.1.1p2 says, in part:
17056 // If type is not compatible with the type of the actual next argument
17057 // (as promoted according to the default argument promotions), the
17058 // behavior is undefined, except for the following cases:
17059 // - both types are pointers to qualified or unqualified versions of
17060 // compatible types;
17061 // - one type is compatible with a signed integer type, the other
17062 // type is compatible with the corresponding unsigned integer type,
17063 // and the value is representable in both types;
17064 // - one type is pointer to qualified or unqualified void and the
17065 // other is a pointer to a qualified or unqualified character type;
17066 // - or, the type of the next argument is nullptr_t and type is a
17067 // pointer type that has the same representation and alignment
17068 // requirements as a pointer to a character type.
17069 // Given that type compatibility is the primary requirement (ignoring
17070 // qualifications), you would think we could call typesAreCompatible()
17071 // directly to test this. However, in C++, that checks for *same type*,
17072 // which causes false positives when passing an enumeration type to
17073 // va_arg. Instead, get the underlying type of the enumeration and pass
17074 // that.
17075 QualType UnderlyingType = TInfo->getType();
17076 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17077 UnderlyingType = ED->getIntegerType();
17078 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17079 /*CompareUnqualified*/ true))
17080 PromoteType = QualType();
17081
17082 // If the types are still not compatible, we need to test whether the
17083 // promoted type and the underlying type are the same except for
17084 // signedness. Ask the AST for the correctly corresponding type and see
17085 // if that's compatible.
17086 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17087 PromoteType->isUnsignedIntegerType() !=
17088 UnderlyingType->isUnsignedIntegerType()) {
17089 UnderlyingType =
17090 UnderlyingType->isUnsignedIntegerType()
17091 ? Context.getCorrespondingSignedType(UnderlyingType)
17092 : Context.getCorrespondingUnsignedType(UnderlyingType);
17093 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17094 /*CompareUnqualified*/ true))
17095 PromoteType = QualType();
17096 }
17097 }
17098 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17099 PromoteType = Context.DoubleTy;
17100 if (!PromoteType.isNull())
17102 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17103 << TInfo->getType()
17104 << PromoteType
17105 << TInfo->getTypeLoc().getSourceRange());
17106 }
17107
17109 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17110}
17111
17113 // The type of __null will be int or long, depending on the size of
17114 // pointers on the target.
17115 QualType Ty;
17116 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17117 if (pw == Context.getTargetInfo().getIntWidth())
17118 Ty = Context.IntTy;
17119 else if (pw == Context.getTargetInfo().getLongWidth())
17120 Ty = Context.LongTy;
17121 else if (pw == Context.getTargetInfo().getLongLongWidth())
17122 Ty = Context.LongLongTy;
17123 else {
17124 llvm_unreachable("I don't know size of pointer!");
17125 }
17126
17127 return new (Context) GNUNullExpr(Ty, TokenLoc);
17128}
17129
17131 CXXRecordDecl *ImplDecl = nullptr;
17132
17133 // Fetch the std::source_location::__impl decl.
17134 if (NamespaceDecl *Std = S.getStdNamespace()) {
17135 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17137 if (S.LookupQualifiedName(ResultSL, Std)) {
17138 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17139 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17141 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17142 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17143 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17144 }
17145 }
17146 }
17147 }
17148
17149 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17150 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17151 return nullptr;
17152 }
17153
17154 // Verify that __impl is a trivial struct type, with no base classes, and with
17155 // only the four expected fields.
17156 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17157 ImplDecl->getNumBases() != 0) {
17158 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17159 return nullptr;
17160 }
17161
17162 unsigned Count = 0;
17163 for (FieldDecl *F : ImplDecl->fields()) {
17164 StringRef Name = F->getName();
17165
17166 if (Name == "_M_file_name") {
17167 if (F->getType() !=
17169 break;
17170 Count++;
17171 } else if (Name == "_M_function_name") {
17172 if (F->getType() !=
17174 break;
17175 Count++;
17176 } else if (Name == "_M_line") {
17177 if (!F->getType()->isIntegerType())
17178 break;
17179 Count++;
17180 } else if (Name == "_M_column") {
17181 if (!F->getType()->isIntegerType())
17182 break;
17183 Count++;
17184 } else {
17185 Count = 100; // invalid
17186 break;
17187 }
17188 }
17189 if (Count != 4) {
17190 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17191 return nullptr;
17192 }
17193
17194 return ImplDecl;
17195}
17196
17198 SourceLocation BuiltinLoc,
17199 SourceLocation RPLoc) {
17200 QualType ResultTy;
17201 switch (Kind) {
17206 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17207 ResultTy =
17208 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17209 break;
17210 }
17213 ResultTy = Context.UnsignedIntTy;
17214 break;
17218 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17220 return ExprError();
17221 }
17222 ResultTy = Context.getPointerType(
17223 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17224 break;
17225 }
17226
17227 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17228}
17229
17231 SourceLocation BuiltinLoc,
17232 SourceLocation RPLoc,
17233 DeclContext *ParentContext) {
17234 return new (Context)
17235 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17236}
17237
17239 StringLiteral *BinaryData, StringRef FileName) {
17241 Data->BinaryData = BinaryData;
17242 Data->FileName = FileName;
17243 return new (Context)
17244 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17245 Data->getDataElementCount());
17246}
17247
17249 const Expr *SrcExpr) {
17250 if (!DstType->isFunctionPointerType() ||
17251 !SrcExpr->getType()->isFunctionType())
17252 return false;
17253
17254 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17255 if (!DRE)
17256 return false;
17257
17258 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17259 if (!FD)
17260 return false;
17261
17263 /*Complain=*/true,
17264 SrcExpr->getBeginLoc());
17265}
17266
17268 SourceLocation Loc,
17269 QualType DstType, QualType SrcType,
17270 Expr *SrcExpr, AssignmentAction Action,
17271 bool *Complained) {
17272 if (Complained)
17273 *Complained = false;
17274
17275 // Decode the result (notice that AST's are still created for extensions).
17276 bool CheckInferredResultType = false;
17277 bool isInvalid = false;
17278 unsigned DiagKind = 0;
17279 ConversionFixItGenerator ConvHints;
17280 bool MayHaveConvFixit = false;
17281 bool MayHaveFunctionDiff = false;
17282 const ObjCInterfaceDecl *IFace = nullptr;
17283 const ObjCProtocolDecl *PDecl = nullptr;
17284
17285 switch (ConvTy) {
17287 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17288 return false;
17290 // Still a valid conversion, but we may want to diagnose for C++
17291 // compatibility reasons.
17292 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17293 break;
17295 if (getLangOpts().CPlusPlus) {
17296 DiagKind = diag::err_typecheck_convert_pointer_int;
17297 isInvalid = true;
17298 } else {
17299 DiagKind = diag::ext_typecheck_convert_pointer_int;
17300 }
17301 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17302 MayHaveConvFixit = true;
17303 break;
17305 if (getLangOpts().CPlusPlus) {
17306 DiagKind = diag::err_typecheck_convert_int_pointer;
17307 isInvalid = true;
17308 } else {
17309 DiagKind = diag::ext_typecheck_convert_int_pointer;
17310 }
17311 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17312 MayHaveConvFixit = true;
17313 break;
17315 DiagKind =
17316 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17317 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17318 MayHaveConvFixit = true;
17319 break;
17321 if (getLangOpts().CPlusPlus) {
17322 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17323 isInvalid = true;
17324 } else {
17325 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17326 }
17327 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17328 MayHaveConvFixit = true;
17329 break;
17332 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17333 } else if (getLangOpts().CPlusPlus) {
17334 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17335 isInvalid = true;
17336 } else {
17337 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17338 }
17339 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17340 SrcType->isObjCObjectPointerType();
17341 if (CheckInferredResultType) {
17342 SrcType = SrcType.getUnqualifiedType();
17343 DstType = DstType.getUnqualifiedType();
17344 } else {
17345 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17346 }
17347 MayHaveConvFixit = true;
17348 break;
17350 if (getLangOpts().CPlusPlus) {
17351 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17352 isInvalid = true;
17353 } else {
17354 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17355 }
17356 break;
17358 if (getLangOpts().CPlusPlus) {
17359 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17360 isInvalid = true;
17361 } else {
17362 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17363 }
17364 break;
17366 // Perform array-to-pointer decay if necessary.
17367 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17368
17369 isInvalid = true;
17370
17371 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17372 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17373 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17374 DiagKind = diag::err_typecheck_incompatible_address_space;
17375 break;
17376 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17377 DiagKind = diag::err_typecheck_incompatible_ownership;
17378 break;
17379 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17380 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17381 break;
17382 }
17383
17384 llvm_unreachable("unknown error case for discarding qualifiers!");
17385 // fallthrough
17386 }
17388 // If the qualifiers lost were because we were applying the
17389 // (deprecated) C++ conversion from a string literal to a char*
17390 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17391 // Ideally, this check would be performed in
17392 // checkPointerTypesForAssignment. However, that would require a
17393 // bit of refactoring (so that the second argument is an
17394 // expression, rather than a type), which should be done as part
17395 // of a larger effort to fix checkPointerTypesForAssignment for
17396 // C++ semantics.
17397 if (getLangOpts().CPlusPlus &&
17399 return false;
17400 if (getLangOpts().CPlusPlus) {
17401 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17402 isInvalid = true;
17403 } else {
17404 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17405 }
17406
17407 break;
17409 if (getLangOpts().CPlusPlus) {
17410 isInvalid = true;
17411 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17412 } else {
17413 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17414 }
17415 break;
17417 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17418 isInvalid = true;
17419 break;
17421 DiagKind = diag::err_int_to_block_pointer;
17422 isInvalid = true;
17423 break;
17425 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17426 isInvalid = true;
17427 break;
17429 if (SrcType->isObjCQualifiedIdType()) {
17430 const ObjCObjectPointerType *srcOPT =
17431 SrcType->castAs<ObjCObjectPointerType>();
17432 for (auto *srcProto : srcOPT->quals()) {
17433 PDecl = srcProto;
17434 break;
17435 }
17436 if (const ObjCInterfaceType *IFaceT =
17438 IFace = IFaceT->getDecl();
17439 }
17440 else if (DstType->isObjCQualifiedIdType()) {
17441 const ObjCObjectPointerType *dstOPT =
17442 DstType->castAs<ObjCObjectPointerType>();
17443 for (auto *dstProto : dstOPT->quals()) {
17444 PDecl = dstProto;
17445 break;
17446 }
17447 if (const ObjCInterfaceType *IFaceT =
17449 IFace = IFaceT->getDecl();
17450 }
17451 if (getLangOpts().CPlusPlus) {
17452 DiagKind = diag::err_incompatible_qualified_id;
17453 isInvalid = true;
17454 } else {
17455 DiagKind = diag::warn_incompatible_qualified_id;
17456 }
17457 break;
17458 }
17460 if (getLangOpts().CPlusPlus) {
17461 DiagKind = diag::err_incompatible_vectors;
17462 isInvalid = true;
17463 } else {
17464 DiagKind = diag::warn_incompatible_vectors;
17465 }
17466 break;
17468 DiagKind = diag::err_arc_weak_unavailable_assign;
17469 isInvalid = true;
17470 break;
17472 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17473 if (Complained)
17474 *Complained = true;
17475 return true;
17476 }
17477
17478 DiagKind = diag::err_typecheck_convert_incompatible;
17479 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17480 MayHaveConvFixit = true;
17481 isInvalid = true;
17482 MayHaveFunctionDiff = true;
17483 break;
17484 }
17485
17486 QualType FirstType, SecondType;
17487 switch (Action) {
17490 // The destination type comes first.
17491 FirstType = DstType;
17492 SecondType = SrcType;
17493 break;
17494
17501 // The source type comes first.
17502 FirstType = SrcType;
17503 SecondType = DstType;
17504 break;
17505 }
17506
17507 PartialDiagnostic FDiag = PDiag(DiagKind);
17508 AssignmentAction ActionForDiag = Action;
17510 ActionForDiag = AssignmentAction::Passing;
17511
17512 FDiag << FirstType << SecondType << ActionForDiag
17513 << SrcExpr->getSourceRange();
17514
17515 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17516 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17517 auto isPlainChar = [](const clang::Type *Type) {
17518 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17519 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17520 };
17521 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17522 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17523 }
17524
17525 // If we can fix the conversion, suggest the FixIts.
17526 if (!ConvHints.isNull()) {
17527 for (FixItHint &H : ConvHints.Hints)
17528 FDiag << H;
17529 }
17530
17531 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17532
17533 if (MayHaveFunctionDiff)
17534 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17535
17536 Diag(Loc, FDiag);
17537 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17538 DiagKind == diag::err_incompatible_qualified_id) &&
17539 PDecl && IFace && !IFace->hasDefinition())
17540 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17541 << IFace << PDecl;
17542
17543 if (SecondType == Context.OverloadTy)
17545 FirstType, /*TakingAddress=*/true);
17546
17547 if (CheckInferredResultType)
17549
17550 if (Action == AssignmentAction::Returning &&
17553
17554 if (Complained)
17555 *Complained = true;
17556 return isInvalid;
17557}
17558
17560 llvm::APSInt *Result,
17561 AllowFoldKind CanFold) {
17562 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17563 public:
17564 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17565 QualType T) override {
17566 return S.Diag(Loc, diag::err_ice_not_integral)
17567 << T << S.LangOpts.CPlusPlus;
17568 }
17569 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17570 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17571 }
17572 } Diagnoser;
17573
17574 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17575}
17576
17578 llvm::APSInt *Result,
17579 unsigned DiagID,
17580 AllowFoldKind CanFold) {
17581 class IDDiagnoser : public VerifyICEDiagnoser {
17582 unsigned DiagID;
17583
17584 public:
17585 IDDiagnoser(unsigned DiagID)
17586 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17587
17588 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17589 return S.Diag(Loc, DiagID);
17590 }
17591 } Diagnoser(DiagID);
17592
17593 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17594}
17595
17601
17604 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17605}
17606
17609 VerifyICEDiagnoser &Diagnoser,
17610 AllowFoldKind CanFold) {
17611 SourceLocation DiagLoc = E->getBeginLoc();
17612
17613 if (getLangOpts().CPlusPlus11) {
17614 // C++11 [expr.const]p5:
17615 // If an expression of literal class type is used in a context where an
17616 // integral constant expression is required, then that class type shall
17617 // have a single non-explicit conversion function to an integral or
17618 // unscoped enumeration type
17619 ExprResult Converted;
17620 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17621 VerifyICEDiagnoser &BaseDiagnoser;
17622 public:
17623 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17624 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17625 BaseDiagnoser.Suppress, true),
17626 BaseDiagnoser(BaseDiagnoser) {}
17627
17628 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17629 QualType T) override {
17630 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17631 }
17632
17633 SemaDiagnosticBuilder diagnoseIncomplete(
17634 Sema &S, SourceLocation Loc, QualType T) override {
17635 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17636 }
17637
17638 SemaDiagnosticBuilder diagnoseExplicitConv(
17639 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17640 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17641 }
17642
17643 SemaDiagnosticBuilder noteExplicitConv(
17644 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17645 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17646 << ConvTy->isEnumeralType() << ConvTy;
17647 }
17648
17649 SemaDiagnosticBuilder diagnoseAmbiguous(
17650 Sema &S, SourceLocation Loc, QualType T) override {
17651 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17652 }
17653
17654 SemaDiagnosticBuilder noteAmbiguous(
17655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17656 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17657 << ConvTy->isEnumeralType() << ConvTy;
17658 }
17659
17660 SemaDiagnosticBuilder diagnoseConversion(
17661 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17662 llvm_unreachable("conversion functions are permitted");
17663 }
17664 } ConvertDiagnoser(Diagnoser);
17665
17666 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17667 ConvertDiagnoser);
17668 if (Converted.isInvalid())
17669 return Converted;
17670 E = Converted.get();
17671 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17672 // don't try to evaluate it later. We also don't want to return the
17673 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17674 // this function will attempt to use 'Value'.
17675 if (isa<RecoveryExpr>(E))
17676 return ExprError();
17678 return ExprError();
17679 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17680 // An ICE must be of integral or unscoped enumeration type.
17681 if (!Diagnoser.Suppress)
17682 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17683 << E->getSourceRange();
17684 return ExprError();
17685 }
17686
17687 ExprResult RValueExpr = DefaultLvalueConversion(E);
17688 if (RValueExpr.isInvalid())
17689 return ExprError();
17690
17691 E = RValueExpr.get();
17692
17693 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17694 // in the non-ICE case.
17697 if (Result)
17699 if (!isa<ConstantExpr>(E))
17702
17703 if (Notes.empty())
17704 return E;
17705
17706 // If our only note is the usual "invalid subexpression" note, just point
17707 // the caret at its location rather than producing an essentially
17708 // redundant note.
17709 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17710 diag::note_invalid_subexpr_in_const_expr) {
17711 DiagLoc = Notes[0].first;
17712 Notes.clear();
17713 }
17714
17715 if (getLangOpts().CPlusPlus) {
17716 if (!Diagnoser.Suppress) {
17717 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17718 for (const PartialDiagnosticAt &Note : Notes)
17719 Diag(Note.first, Note.second);
17720 }
17721 return ExprError();
17722 }
17723
17724 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17725 for (const PartialDiagnosticAt &Note : Notes)
17726 Diag(Note.first, Note.second);
17727
17728 return E;
17729 }
17730
17731 Expr::EvalResult EvalResult;
17733 EvalResult.Diag = &Notes;
17734
17735 // Try to evaluate the expression, and produce diagnostics explaining why it's
17736 // not a constant expression as a side-effect.
17737 bool Folded =
17738 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17739 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17740 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17741
17742 if (!isa<ConstantExpr>(E))
17743 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17744
17745 // In C++11, we can rely on diagnostics being produced for any expression
17746 // which is not a constant expression. If no diagnostics were produced, then
17747 // this is a constant expression.
17748 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17749 if (Result)
17750 *Result = EvalResult.Val.getInt();
17751 return E;
17752 }
17753
17754 // If our only note is the usual "invalid subexpression" note, just point
17755 // the caret at its location rather than producing an essentially
17756 // redundant note.
17757 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17758 diag::note_invalid_subexpr_in_const_expr) {
17759 DiagLoc = Notes[0].first;
17760 Notes.clear();
17761 }
17762
17763 if (!Folded || CanFold == AllowFoldKind::No) {
17764 if (!Diagnoser.Suppress) {
17765 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17766 for (const PartialDiagnosticAt &Note : Notes)
17767 Diag(Note.first, Note.second);
17768 }
17769
17770 return ExprError();
17771 }
17772
17773 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17774 for (const PartialDiagnosticAt &Note : Notes)
17775 Diag(Note.first, Note.second);
17776
17777 if (Result)
17778 *Result = EvalResult.Val.getInt();
17779 return E;
17780}
17781
17782namespace {
17783 // Handle the case where we conclude a expression which we speculatively
17784 // considered to be unevaluated is actually evaluated.
17785 class TransformToPE : public TreeTransform<TransformToPE> {
17786 typedef TreeTransform<TransformToPE> BaseTransform;
17787
17788 public:
17789 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17790
17791 // Make sure we redo semantic analysis
17792 bool AlwaysRebuild() { return true; }
17793 bool ReplacingOriginal() { return true; }
17794
17795 // We need to special-case DeclRefExprs referring to FieldDecls which
17796 // are not part of a member pointer formation; normal TreeTransforming
17797 // doesn't catch this case because of the way we represent them in the AST.
17798 // FIXME: This is a bit ugly; is it really the best way to handle this
17799 // case?
17800 //
17801 // Error on DeclRefExprs referring to FieldDecls.
17802 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17803 if (isa<FieldDecl>(E->getDecl()) &&
17804 !SemaRef.isUnevaluatedContext())
17805 return SemaRef.Diag(E->getLocation(),
17806 diag::err_invalid_non_static_member_use)
17807 << E->getDecl() << E->getSourceRange();
17808
17809 return BaseTransform::TransformDeclRefExpr(E);
17810 }
17811
17812 // Exception: filter out member pointer formation
17813 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17814 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17815 return E;
17816
17817 return BaseTransform::TransformUnaryOperator(E);
17818 }
17819
17820 // The body of a lambda-expression is in a separate expression evaluation
17821 // context so never needs to be transformed.
17822 // FIXME: Ideally we wouldn't transform the closure type either, and would
17823 // just recreate the capture expressions and lambda expression.
17824 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17825 return SkipLambdaBody(E, Body);
17826 }
17827 };
17828}
17829
17831 assert(isUnevaluatedContext() &&
17832 "Should only transform unevaluated expressions");
17833 ExprEvalContexts.back().Context =
17834 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17836 return E;
17837 return TransformToPE(*this).TransformExpr(E);
17838}
17839
17841 assert(isUnevaluatedContext() &&
17842 "Should only transform unevaluated expressions");
17845 return TInfo;
17846 return TransformToPE(*this).TransformType(TInfo);
17847}
17848
17849void
17851 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17853 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17854 LambdaContextDecl, ExprContext);
17855
17856 // Discarded statements and immediate contexts nested in other
17857 // discarded statements or immediate context are themselves
17858 // a discarded statement or an immediate context, respectively.
17859 ExprEvalContexts.back().InDiscardedStatement =
17861
17862 // C++23 [expr.const]/p15
17863 // An expression or conversion is in an immediate function context if [...]
17864 // it is a subexpression of a manifestly constant-evaluated expression or
17865 // conversion.
17866 const auto &Prev = parentEvaluationContext();
17867 ExprEvalContexts.back().InImmediateFunctionContext =
17868 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17869
17870 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17871 Prev.InImmediateEscalatingFunctionContext;
17872
17873 Cleanup.reset();
17874 if (!MaybeODRUseExprs.empty())
17875 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17876}
17877
17878void
17882 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17883 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17884}
17885
17887 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17888 // [expr.const]/p14.1
17889 // An expression or conversion is in an immediate function context if it is
17890 // potentially evaluated and either: its innermost enclosing non-block scope
17891 // is a function parameter scope of an immediate function.
17893 FD && FD->isConsteval()
17895 : NewContext);
17899
17900 Current.InDiscardedStatement = false;
17901
17902 if (FD) {
17903
17904 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17905 // context is nested in an immediate function context, so smaller contexts
17906 // that appear inside immediate functions (like variable initializers) are
17907 // considered to be inside an immediate function context even though by
17908 // themselves they are not immediate function contexts. But when a new
17909 // function is entered, we need to reset this tracking, since the entered
17910 // function might be not an immediate function.
17911
17913 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17914
17915 if (isLambdaMethod(FD))
17917 FD->isConsteval() ||
17918 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
17919 Parent.isImmediateFunctionContext()));
17920 else
17922 }
17923}
17924
17925namespace {
17926
17927const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17928 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17929 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17930 if (E->getOpcode() == UO_Deref)
17931 return CheckPossibleDeref(S, E->getSubExpr());
17932 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17933 return CheckPossibleDeref(S, E->getBase());
17934 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17935 return CheckPossibleDeref(S, E->getBase());
17936 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17937 QualType Inner;
17938 QualType Ty = E->getType();
17939 if (const auto *Ptr = Ty->getAs<PointerType>())
17940 Inner = Ptr->getPointeeType();
17941 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17942 Inner = Arr->getElementType();
17943 else
17944 return nullptr;
17945
17946 if (Inner->hasAttr(attr::NoDeref))
17947 return E;
17948 }
17949 return nullptr;
17950}
17951
17952} // namespace
17953
17955 for (const Expr *E : Rec.PossibleDerefs) {
17956 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17957 if (DeclRef) {
17958 const ValueDecl *Decl = DeclRef->getDecl();
17959 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17960 << Decl->getName() << E->getSourceRange();
17961 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17962 } else {
17963 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17964 << E->getSourceRange();
17965 }
17966 }
17967 Rec.PossibleDerefs.clear();
17968}
17969
17972 return;
17973
17974 // Note: ignoring parens here is not justified by the standard rules, but
17975 // ignoring parentheses seems like a more reasonable approach, and this only
17976 // drives a deprecation warning so doesn't affect conformance.
17977 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17978 if (BO->getOpcode() == BO_Assign) {
17979 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17980 llvm::erase(LHSs, BO->getLHS());
17981 }
17982 }
17983}
17984
17986 assert(getLangOpts().CPlusPlus20 &&
17987 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17988 "Cannot mark an immediate escalating expression outside of an "
17989 "immediate escalating context");
17990 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17991 Call && Call->getCallee()) {
17992 if (auto *DeclRef =
17993 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17994 DeclRef->setIsImmediateEscalating(true);
17995 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17996 Ctr->setIsImmediateEscalating(true);
17997 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17998 DeclRef->setIsImmediateEscalating(true);
17999 } else {
18000 assert(false && "expected an immediately escalating expression");
18001 }
18003 FI->FoundImmediateEscalatingExpression = true;
18004}
18005
18007 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18008 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18011 return E;
18012
18013 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18014 /// It's OK if this fails; we'll also remove this in
18015 /// HandleImmediateInvocations, but catching it here allows us to avoid
18016 /// walking the AST looking for it in simple cases.
18017 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18018 if (auto *DeclRef =
18019 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18020 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18021
18022 // C++23 [expr.const]/p16
18023 // An expression or conversion is immediate-escalating if it is not initially
18024 // in an immediate function context and it is [...] an immediate invocation
18025 // that is not a constant expression and is not a subexpression of an
18026 // immediate invocation.
18027 APValue Cached;
18028 auto CheckConstantExpressionAndKeepResult = [&]() {
18030 Expr::EvalResult Eval;
18031 Eval.Diag = &Notes;
18032 bool Res = E.get()->EvaluateAsConstantExpr(
18033 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18034 if (Res && Notes.empty()) {
18035 Cached = std::move(Eval.Val);
18036 return true;
18037 }
18038 return false;
18039 };
18040
18041 if (!E.get()->isValueDependent() &&
18042 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18043 !CheckConstantExpressionAndKeepResult()) {
18045 return E;
18046 }
18047
18048 if (Cleanup.exprNeedsCleanups()) {
18049 // Since an immediate invocation is a full expression itself - it requires
18050 // an additional ExprWithCleanups node, but it can participate to a bigger
18051 // full expression which actually requires cleanups to be run after so
18052 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18053 // may discard cleanups for outer expression too early.
18054
18055 // Note that ExprWithCleanups created here must always have empty cleanup
18056 // objects:
18057 // - compound literals do not create cleanup objects in C++ and immediate
18058 // invocations are C++-only.
18059 // - blocks are not allowed inside constant expressions and compiler will
18060 // issue an error if they appear there.
18061 //
18062 // Hence, in correct code any cleanup objects created inside current
18063 // evaluation context must be outside the immediate invocation.
18065 Cleanup.cleanupsHaveSideEffects(), {});
18066 }
18067
18069 getASTContext(), E.get(),
18070 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18071 getASTContext()),
18072 /*IsImmediateInvocation*/ true);
18073 if (Cached.hasValue())
18074 Res->MoveIntoResult(Cached, getASTContext());
18075 /// Value-dependent constant expressions should not be immediately
18076 /// evaluated until they are instantiated.
18077 if (!Res->isValueDependent())
18078 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18079 return Res;
18080}
18081
18085 Expr::EvalResult Eval;
18086 Eval.Diag = &Notes;
18087 ConstantExpr *CE = Candidate.getPointer();
18088 bool Result = CE->EvaluateAsConstantExpr(
18089 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18090 if (!Result || !Notes.empty()) {
18092 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18093 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18094 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18095 FunctionDecl *FD = nullptr;
18096 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18097 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18098 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18099 FD = Call->getConstructor();
18100 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18101 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18102
18103 assert(FD && FD->isImmediateFunction() &&
18104 "could not find an immediate function in this expression");
18105 if (FD->isInvalidDecl())
18106 return;
18107 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18108 << FD << FD->isConsteval();
18109 if (auto Context =
18111 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18112 << Context->Decl;
18113 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18114 }
18115 if (!FD->isConsteval())
18117 for (auto &Note : Notes)
18118 SemaRef.Diag(Note.first, Note.second);
18119 return;
18120 }
18122}
18123
18127 struct ComplexRemove : TreeTransform<ComplexRemove> {
18129 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18132 CurrentII;
18133 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18136 4>::reverse_iterator Current)
18137 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18138 void RemoveImmediateInvocation(ConstantExpr* E) {
18139 auto It = std::find_if(CurrentII, IISet.rend(),
18141 return Elem.getPointer() == E;
18142 });
18143 // It is possible that some subexpression of the current immediate
18144 // invocation was handled from another expression evaluation context. Do
18145 // not handle the current immediate invocation if some of its
18146 // subexpressions failed before.
18147 if (It == IISet.rend()) {
18148 if (SemaRef.FailedImmediateInvocations.contains(E))
18149 CurrentII->setInt(1);
18150 } else {
18151 It->setInt(1); // Mark as deleted
18152 }
18153 }
18154 ExprResult TransformConstantExpr(ConstantExpr *E) {
18155 if (!E->isImmediateInvocation())
18156 return Base::TransformConstantExpr(E);
18157 RemoveImmediateInvocation(E);
18158 return Base::TransformExpr(E->getSubExpr());
18159 }
18160 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18161 /// we need to remove its DeclRefExpr from the DRSet.
18162 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18163 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18164 return Base::TransformCXXOperatorCallExpr(E);
18165 }
18166 /// Base::TransformUserDefinedLiteral doesn't preserve the
18167 /// UserDefinedLiteral node.
18168 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18169 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18170 /// here.
18171 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18172 if (!Init)
18173 return Init;
18174
18175 // We cannot use IgnoreImpCasts because we need to preserve
18176 // full expressions.
18177 while (true) {
18178 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18179 Init = ICE->getSubExpr();
18180 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18181 Init = ICE->getSubExpr();
18182 else
18183 break;
18184 }
18185 /// ConstantExprs are the first layer of implicit node to be removed so if
18186 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18187 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18188 CE && CE->isImmediateInvocation())
18189 RemoveImmediateInvocation(CE);
18190 return Base::TransformInitializer(Init, NotCopyInit);
18191 }
18192 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18193 DRSet.erase(E);
18194 return E;
18195 }
18196 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18197 // Do not rebuild lambdas to avoid creating a new type.
18198 // Lambdas have already been processed inside their eval contexts.
18199 return E;
18200 }
18201 bool AlwaysRebuild() { return false; }
18202 bool ReplacingOriginal() { return true; }
18203 bool AllowSkippingCXXConstructExpr() {
18204 bool Res = AllowSkippingFirstCXXConstructExpr;
18205 AllowSkippingFirstCXXConstructExpr = true;
18206 return Res;
18207 }
18208 bool AllowSkippingFirstCXXConstructExpr = true;
18209 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18211
18212 /// CXXConstructExpr with a single argument are getting skipped by
18213 /// TreeTransform in some situtation because they could be implicit. This
18214 /// can only occur for the top-level CXXConstructExpr because it is used
18215 /// nowhere in the expression being transformed therefore will not be rebuilt.
18216 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18217 /// skipping the first CXXConstructExpr.
18218 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18219 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18220
18221 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18222 // The result may not be usable in case of previous compilation errors.
18223 // In this case evaluation of the expression may result in crash so just
18224 // don't do anything further with the result.
18225 if (Res.isUsable()) {
18227 It->getPointer()->setSubExpr(Res.get());
18228 }
18229}
18230
18231static void
18234 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18235 Rec.ReferenceToConsteval.size() == 0) ||
18237 return;
18238
18239 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18240 // [...]
18241 // - the initializer of a variable that is usable in constant expressions or
18242 // has constant initialization.
18243 if (SemaRef.getLangOpts().CPlusPlus23 &&
18244 Rec.ExprContext ==
18246 auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);
18247 if (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18248 VD->hasConstantInitialization()) {
18249 // An expression or conversion is in an 'immediate function context' if it
18250 // is potentially evaluated and either:
18251 // [...]
18252 // - it is a subexpression of a manifestly constant-evaluated expression
18253 // or conversion.
18254 return;
18255 }
18256 }
18257
18258 /// When we have more than 1 ImmediateInvocationCandidates or previously
18259 /// failed immediate invocations, we need to check for nested
18260 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18261 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18262 /// invocation.
18263 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18265
18266 /// Prevent sema calls during the tree transform from adding pointers that
18267 /// are already in the sets.
18268 llvm::SaveAndRestore DisableIITracking(
18270
18271 /// Prevent diagnostic during tree transfrom as they are duplicates
18273
18274 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18275 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18276 if (!It->getInt())
18278 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18279 Rec.ReferenceToConsteval.size()) {
18280 struct SimpleRemove : DynamicRecursiveASTVisitor {
18281 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18282 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18283 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18284 DRSet.erase(E);
18285 return DRSet.size();
18286 }
18287 } Visitor(Rec.ReferenceToConsteval);
18288 Visitor.TraverseStmt(
18289 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18290 }
18291 for (auto CE : Rec.ImmediateInvocationCandidates)
18292 if (!CE.getInt())
18294 for (auto *DR : Rec.ReferenceToConsteval) {
18295 // If the expression is immediate escalating, it is not an error;
18296 // The outer context itself becomes immediate and further errors,
18297 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18298 if (DR->isImmediateEscalating())
18299 continue;
18300 auto *FD = cast<FunctionDecl>(DR->getDecl());
18301 const NamedDecl *ND = FD;
18302 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18303 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18304 ND = MD->getParent();
18305
18306 // C++23 [expr.const]/p16
18307 // An expression or conversion is immediate-escalating if it is not
18308 // initially in an immediate function context and it is [...] a
18309 // potentially-evaluated id-expression that denotes an immediate function
18310 // that is not a subexpression of an immediate invocation.
18311 bool ImmediateEscalating = false;
18312 bool IsPotentiallyEvaluated =
18313 Rec.Context ==
18315 Rec.Context ==
18317 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18318 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18319
18321 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18322 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18323 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18324 if (!FD->getBuiltinID())
18325 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18326 if (auto Context =
18328 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18329 << Context->Decl;
18330 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18331 }
18332 if (FD->isImmediateEscalating() && !FD->isConsteval())
18334
18335 } else {
18337 }
18338 }
18339}
18340
18343 if (!Rec.Lambdas.empty()) {
18345 if (!getLangOpts().CPlusPlus20 &&
18346 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18347 Rec.isUnevaluated() ||
18349 unsigned D;
18350 if (Rec.isUnevaluated()) {
18351 // C++11 [expr.prim.lambda]p2:
18352 // A lambda-expression shall not appear in an unevaluated operand
18353 // (Clause 5).
18354 D = diag::err_lambda_unevaluated_operand;
18355 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18356 // C++1y [expr.const]p2:
18357 // A conditional-expression e is a core constant expression unless the
18358 // evaluation of e, following the rules of the abstract machine, would
18359 // evaluate [...] a lambda-expression.
18360 D = diag::err_lambda_in_constant_expression;
18361 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18362 // C++17 [expr.prim.lamda]p2:
18363 // A lambda-expression shall not appear [...] in a template-argument.
18364 D = diag::err_lambda_in_invalid_context;
18365 } else
18366 llvm_unreachable("Couldn't infer lambda error message.");
18367
18368 for (const auto *L : Rec.Lambdas)
18369 Diag(L->getBeginLoc(), D);
18370 }
18371 }
18372
18373 // Append the collected materialized temporaries into previous context before
18374 // exit if the previous also is a lifetime extending context.
18376 parentEvaluationContext().InLifetimeExtendingContext &&
18377 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18380 }
18381
18383 HandleImmediateInvocations(*this, Rec);
18384
18385 // Warn on any volatile-qualified simple-assignments that are not discarded-
18386 // value expressions nor unevaluated operands (those cases get removed from
18387 // this list by CheckUnusedVolatileAssignment).
18388 for (auto *BO : Rec.VolatileAssignmentLHSs)
18389 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18390 << BO->getType();
18391
18392 // When are coming out of an unevaluated context, clear out any
18393 // temporaries that we may have created as part of the evaluation of
18394 // the expression in that context: they aren't relevant because they
18395 // will never be constructed.
18396 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18398 ExprCleanupObjects.end());
18399 Cleanup = Rec.ParentCleanup;
18402 // Otherwise, merge the contexts together.
18403 } else {
18404 Cleanup.mergeFrom(Rec.ParentCleanup);
18405 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18406 }
18407
18409
18410 // Pop the current expression evaluation context off the stack.
18411 ExprEvalContexts.pop_back();
18412}
18413
18415 ExprCleanupObjects.erase(
18416 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18417 ExprCleanupObjects.end());
18418 Cleanup.reset();
18419 MaybeODRUseExprs.clear();
18420}
18421
18424 if (Result.isInvalid())
18425 return ExprError();
18426 E = Result.get();
18427 if (!E->getType()->isVariablyModifiedType())
18428 return E;
18430}
18431
18432/// Are we in a context that is potentially constant evaluated per C++20
18433/// [expr.const]p12?
18435 /// C++2a [expr.const]p12:
18436 // An expression or conversion is potentially constant evaluated if it is
18437 switch (SemaRef.ExprEvalContexts.back().Context) {
18440
18441 // -- a manifestly constant-evaluated expression,
18445 // -- a potentially-evaluated expression,
18447 // -- an immediate subexpression of a braced-init-list,
18448
18449 // -- [FIXME] an expression of the form & cast-expression that occurs
18450 // within a templated entity
18451 // -- a subexpression of one of the above that is not a subexpression of
18452 // a nested unevaluated operand.
18453 return true;
18454
18457 // Expressions in this context are never evaluated.
18458 return false;
18459 }
18460 llvm_unreachable("Invalid context");
18461}
18462
18463/// Return true if this function has a calling convention that requires mangling
18464/// in the size of the parameter pack.
18466 // These manglings are only applicable for targets whcih use Microsoft
18467 // mangling scheme for C.
18469 return false;
18470
18471 // If this is C++ and this isn't an extern "C" function, parameters do not
18472 // need to be complete. In this case, C++ mangling will apply, which doesn't
18473 // use the size of the parameters.
18474 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18475 return false;
18476
18477 // Stdcall, fastcall, and vectorcall need this special treatment.
18478 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18479 switch (CC) {
18480 case CC_X86StdCall:
18481 case CC_X86FastCall:
18482 case CC_X86VectorCall:
18483 return true;
18484 default:
18485 break;
18486 }
18487 return false;
18488}
18489
18490/// Require that all of the parameter types of function be complete. Normally,
18491/// parameter types are only required to be complete when a function is called
18492/// or defined, but to mangle functions with certain calling conventions, the
18493/// mangler needs to know the size of the parameter list. In this situation,
18494/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18495/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18496/// result in a linker error. Clang doesn't implement this behavior, and instead
18497/// attempts to error at compile time.
18499 SourceLocation Loc) {
18500 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18501 FunctionDecl *FD;
18502 ParmVarDecl *Param;
18503
18504 public:
18505 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18506 : FD(FD), Param(Param) {}
18507
18508 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18509 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18510 StringRef CCName;
18511 switch (CC) {
18512 case CC_X86StdCall:
18513 CCName = "stdcall";
18514 break;
18515 case CC_X86FastCall:
18516 CCName = "fastcall";
18517 break;
18518 case CC_X86VectorCall:
18519 CCName = "vectorcall";
18520 break;
18521 default:
18522 llvm_unreachable("CC does not need mangling");
18523 }
18524
18525 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18526 << Param->getDeclName() << FD->getDeclName() << CCName;
18527 }
18528 };
18529
18530 for (ParmVarDecl *Param : FD->parameters()) {
18531 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18532 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18533 }
18534}
18535
18536namespace {
18537enum class OdrUseContext {
18538 /// Declarations in this context are not odr-used.
18539 None,
18540 /// Declarations in this context are formally odr-used, but this is a
18541 /// dependent context.
18542 Dependent,
18543 /// Declarations in this context are odr-used but not actually used (yet).
18544 FormallyOdrUsed,
18545 /// Declarations in this context are used.
18546 Used
18547};
18548}
18549
18550/// Are we within a context in which references to resolved functions or to
18551/// variables result in odr-use?
18552static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18555
18556 if (Context.isUnevaluated())
18557 return OdrUseContext::None;
18558
18560 return OdrUseContext::Dependent;
18561
18562 if (Context.isDiscardedStatementContext())
18563 return OdrUseContext::FormallyOdrUsed;
18564
18565 else if (Context.Context ==
18567 return OdrUseContext::FormallyOdrUsed;
18568
18569 return OdrUseContext::Used;
18570}
18571
18573 if (!Func->isConstexpr())
18574 return false;
18575
18576 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18577 return true;
18578
18579 // Lambda conversion operators are never user provided.
18580 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18581 return isLambdaConversionOperator(Conv);
18582
18583 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18584 return CCD && CCD->getInheritedConstructor();
18585}
18586
18588 bool MightBeOdrUse) {
18589 assert(Func && "No function?");
18590
18591 Func->setReferenced();
18592
18593 // Recursive functions aren't really used until they're used from some other
18594 // context.
18595 bool IsRecursiveCall = CurContext == Func;
18596
18597 // C++11 [basic.def.odr]p3:
18598 // A function whose name appears as a potentially-evaluated expression is
18599 // odr-used if it is the unique lookup result or the selected member of a
18600 // set of overloaded functions [...].
18601 //
18602 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18603 // can just check that here.
18604 OdrUseContext OdrUse =
18605 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18606 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18607 OdrUse = OdrUseContext::FormallyOdrUsed;
18608
18609 // Trivial default constructors and destructors are never actually used.
18610 // FIXME: What about other special members?
18611 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18612 OdrUse == OdrUseContext::Used) {
18613 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18614 if (Constructor->isDefaultConstructor())
18615 OdrUse = OdrUseContext::FormallyOdrUsed;
18617 OdrUse = OdrUseContext::FormallyOdrUsed;
18618 }
18619
18620 // C++20 [expr.const]p12:
18621 // A function [...] is needed for constant evaluation if it is [...] a
18622 // constexpr function that is named by an expression that is potentially
18623 // constant evaluated
18624 bool NeededForConstantEvaluation =
18627
18628 // Determine whether we require a function definition to exist, per
18629 // C++11 [temp.inst]p3:
18630 // Unless a function template specialization has been explicitly
18631 // instantiated or explicitly specialized, the function template
18632 // specialization is implicitly instantiated when the specialization is
18633 // referenced in a context that requires a function definition to exist.
18634 // C++20 [temp.inst]p7:
18635 // The existence of a definition of a [...] function is considered to
18636 // affect the semantics of the program if the [...] function is needed for
18637 // constant evaluation by an expression
18638 // C++20 [basic.def.odr]p10:
18639 // Every program shall contain exactly one definition of every non-inline
18640 // function or variable that is odr-used in that program outside of a
18641 // discarded statement
18642 // C++20 [special]p1:
18643 // The implementation will implicitly define [defaulted special members]
18644 // if they are odr-used or needed for constant evaluation.
18645 //
18646 // Note that we skip the implicit instantiation of templates that are only
18647 // used in unused default arguments or by recursive calls to themselves.
18648 // This is formally non-conforming, but seems reasonable in practice.
18649 bool NeedDefinition =
18650 !IsRecursiveCall &&
18651 (OdrUse == OdrUseContext::Used ||
18652 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18653
18654 // C++14 [temp.expl.spec]p6:
18655 // If a template [...] is explicitly specialized then that specialization
18656 // shall be declared before the first use of that specialization that would
18657 // cause an implicit instantiation to take place, in every translation unit
18658 // in which such a use occurs
18659 if (NeedDefinition &&
18660 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18661 Func->getMemberSpecializationInfo()))
18663
18664 if (getLangOpts().CUDA)
18665 CUDA().CheckCall(Loc, Func);
18666
18667 // If we need a definition, try to create one.
18668 if (NeedDefinition && !Func->getBody()) {
18671 dyn_cast<CXXConstructorDecl>(Func)) {
18673 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18674 if (Constructor->isDefaultConstructor()) {
18675 if (Constructor->isTrivial() &&
18676 !Constructor->hasAttr<DLLExportAttr>())
18677 return;
18679 } else if (Constructor->isCopyConstructor()) {
18681 } else if (Constructor->isMoveConstructor()) {
18683 }
18684 } else if (Constructor->getInheritedConstructor()) {
18686 }
18687 } else if (CXXDestructorDecl *Destructor =
18688 dyn_cast<CXXDestructorDecl>(Func)) {
18690 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18691 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18692 return;
18694 }
18695 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18696 MarkVTableUsed(Loc, Destructor->getParent());
18697 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18698 if (MethodDecl->isOverloadedOperator() &&
18699 MethodDecl->getOverloadedOperator() == OO_Equal) {
18700 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18701 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18702 if (MethodDecl->isCopyAssignmentOperator())
18703 DefineImplicitCopyAssignment(Loc, MethodDecl);
18704 else if (MethodDecl->isMoveAssignmentOperator())
18705 DefineImplicitMoveAssignment(Loc, MethodDecl);
18706 }
18707 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18708 MethodDecl->getParent()->isLambda()) {
18709 CXXConversionDecl *Conversion =
18710 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18711 if (Conversion->isLambdaToBlockPointerConversion())
18713 else
18715 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18716 MarkVTableUsed(Loc, MethodDecl->getParent());
18717 }
18718
18719 if (Func->isDefaulted() && !Func->isDeleted()) {
18723 }
18724
18725 // Implicit instantiation of function templates and member functions of
18726 // class templates.
18727 if (Func->isImplicitlyInstantiable()) {
18729 Func->getTemplateSpecializationKindForInstantiation();
18730 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18731 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18732 if (FirstInstantiation) {
18733 PointOfInstantiation = Loc;
18734 if (auto *MSI = Func->getMemberSpecializationInfo())
18735 MSI->setPointOfInstantiation(Loc);
18736 // FIXME: Notify listener.
18737 else
18738 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18739 } else if (TSK != TSK_ImplicitInstantiation) {
18740 // Use the point of use as the point of instantiation, instead of the
18741 // point of explicit instantiation (which we track as the actual point
18742 // of instantiation). This gives better backtraces in diagnostics.
18743 PointOfInstantiation = Loc;
18744 }
18745
18746 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18747 Func->isConstexpr()) {
18748 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18749 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18750 CodeSynthesisContexts.size())
18752 std::make_pair(Func, PointOfInstantiation));
18753 else if (Func->isConstexpr())
18754 // Do not defer instantiations of constexpr functions, to avoid the
18755 // expression evaluator needing to call back into Sema if it sees a
18756 // call to such a function.
18757 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18758 else {
18759 Func->setInstantiationIsPending(true);
18760 PendingInstantiations.push_back(
18761 std::make_pair(Func, PointOfInstantiation));
18762 if (llvm::isTimeTraceVerbose()) {
18763 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18764 std::string Name;
18765 llvm::raw_string_ostream OS(Name);
18766 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18767 /*Qualified=*/true);
18768 return Name;
18769 });
18770 }
18771 // Notify the consumer that a function was implicitly instantiated.
18772 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18773 }
18774 }
18775 } else {
18776 // Walk redefinitions, as some of them may be instantiable.
18777 for (auto *i : Func->redecls()) {
18778 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18779 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18780 }
18781 }
18782 });
18783 }
18784
18785 // If a constructor was defined in the context of a default parameter
18786 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18787 // context), its initializers may not be referenced yet.
18788 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18790 *this,
18791 Constructor->isImmediateFunction()
18794 Constructor);
18795 for (CXXCtorInitializer *Init : Constructor->inits()) {
18796 if (Init->isInClassMemberInitializer())
18797 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18798 MarkDeclarationsReferencedInExpr(Init->getInit());
18799 });
18800 }
18801 }
18802
18803 // C++14 [except.spec]p17:
18804 // An exception-specification is considered to be needed when:
18805 // - the function is odr-used or, if it appears in an unevaluated operand,
18806 // would be odr-used if the expression were potentially-evaluated;
18807 //
18808 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18809 // function is a pure virtual function we're calling, and in that case the
18810 // function was selected by overload resolution and we need to resolve its
18811 // exception specification for a different reason.
18812 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18814 ResolveExceptionSpec(Loc, FPT);
18815
18816 // A callee could be called by a host function then by a device function.
18817 // If we only try recording once, we will miss recording the use on device
18818 // side. Therefore keep trying until it is recorded.
18819 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18820 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18822
18823 // If this is the first "real" use, act on that.
18824 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18825 // Keep track of used but undefined functions.
18826 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18827 if (mightHaveNonExternalLinkage(Func))
18828 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18829 else if (Func->getMostRecentDecl()->isInlined() &&
18830 !LangOpts.GNUInline &&
18831 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18832 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18834 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18835 }
18836
18837 // Some x86 Windows calling conventions mangle the size of the parameter
18838 // pack into the name. Computing the size of the parameters requires the
18839 // parameter types to be complete. Check that now.
18842
18843 // In the MS C++ ABI, the compiler emits destructor variants where they are
18844 // used. If the destructor is used here but defined elsewhere, mark the
18845 // virtual base destructors referenced. If those virtual base destructors
18846 // are inline, this will ensure they are defined when emitting the complete
18847 // destructor variant. This checking may be redundant if the destructor is
18848 // provided later in this TU.
18849 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18850 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18851 CXXRecordDecl *Parent = Dtor->getParent();
18852 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18854 }
18855 }
18856
18857 Func->markUsed(Context);
18858 }
18859}
18860
18861/// Directly mark a variable odr-used. Given a choice, prefer to use
18862/// MarkVariableReferenced since it does additional checks and then
18863/// calls MarkVarDeclODRUsed.
18864/// If the variable must be captured:
18865/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18866/// - else capture it in the DeclContext that maps to the
18867/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18868static void
18870 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18871 // Keep track of used but undefined variables.
18872 // FIXME: We shouldn't suppress this warning for static data members.
18873 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18874 assert(Var && "expected a capturable variable");
18875
18877 (!Var->isExternallyVisible() || Var->isInline() ||
18879 !(Var->isStaticDataMember() && Var->hasInit())) {
18881 if (old.isInvalid())
18882 old = Loc;
18883 }
18884 QualType CaptureType, DeclRefType;
18885 if (SemaRef.LangOpts.OpenMP)
18888 /*EllipsisLoc*/ SourceLocation(),
18889 /*BuildAndDiagnose*/ true, CaptureType,
18890 DeclRefType, FunctionScopeIndexToStopAt);
18891
18892 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18893 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18894 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18895 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18896 if (VarTarget == SemaCUDA::CVT_Host &&
18897 (UserTarget == CUDAFunctionTarget::Device ||
18898 UserTarget == CUDAFunctionTarget::HostDevice ||
18899 UserTarget == CUDAFunctionTarget::Global)) {
18900 // Diagnose ODR-use of host global variables in device functions.
18901 // Reference of device global variables in host functions is allowed
18902 // through shadow variables therefore it is not diagnosed.
18903 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18904 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18905 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18907 Var->getType().isConstQualified()
18908 ? diag::note_cuda_const_var_unpromoted
18909 : diag::note_cuda_host_var);
18910 }
18911 } else if (VarTarget == SemaCUDA::CVT_Device &&
18912 !Var->hasAttr<CUDASharedAttr>() &&
18913 (UserTarget == CUDAFunctionTarget::Host ||
18914 UserTarget == CUDAFunctionTarget::HostDevice)) {
18915 // Record a CUDA/HIP device side variable if it is ODR-used
18916 // by host code. This is done conservatively, when the variable is
18917 // referenced in any of the following contexts:
18918 // - a non-function context
18919 // - a host function
18920 // - a host device function
18921 // This makes the ODR-use of the device side variable by host code to
18922 // be visible in the device compilation for the compiler to be able to
18923 // emit template variables instantiated by host code only and to
18924 // externalize the static device side variable ODR-used by host code.
18925 if (!Var->hasExternalStorage())
18927 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18928 (!FD || (!FD->getDescribedFunctionTemplate() &&
18932 }
18933 }
18934
18935 V->markUsed(SemaRef.Context);
18936}
18937
18939 SourceLocation Loc,
18940 unsigned CapturingScopeIndex) {
18941 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18942}
18943
18945 SourceLocation loc,
18946 ValueDecl *var) {
18947 DeclContext *VarDC = var->getDeclContext();
18948
18949 // If the parameter still belongs to the translation unit, then
18950 // we're actually just using one parameter in the declaration of
18951 // the next.
18952 if (isa<ParmVarDecl>(var) &&
18954 return;
18955
18956 // For C code, don't diagnose about capture if we're not actually in code
18957 // right now; it's impossible to write a non-constant expression outside of
18958 // function context, so we'll get other (more useful) diagnostics later.
18959 //
18960 // For C++, things get a bit more nasty... it would be nice to suppress this
18961 // diagnostic for certain cases like using a local variable in an array bound
18962 // for a member of a local class, but the correct predicate is not obvious.
18963 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18964 return;
18965
18966 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18967 unsigned ContextKind = 3; // unknown
18968 if (isa<CXXMethodDecl>(VarDC) &&
18969 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18970 ContextKind = 2;
18971 } else if (isa<FunctionDecl>(VarDC)) {
18972 ContextKind = 0;
18973 } else if (isa<BlockDecl>(VarDC)) {
18974 ContextKind = 1;
18975 }
18976
18977 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18978 << var << ValueKind << ContextKind << VarDC;
18979 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18980 << var;
18981
18982 // FIXME: Add additional diagnostic info about class etc. which prevents
18983 // capture.
18984}
18985
18987 ValueDecl *Var,
18988 bool &SubCapturesAreNested,
18989 QualType &CaptureType,
18990 QualType &DeclRefType) {
18991 // Check whether we've already captured it.
18992 if (CSI->CaptureMap.count(Var)) {
18993 // If we found a capture, any subcaptures are nested.
18994 SubCapturesAreNested = true;
18995
18996 // Retrieve the capture type for this variable.
18997 CaptureType = CSI->getCapture(Var).getCaptureType();
18998
18999 // Compute the type of an expression that refers to this variable.
19000 DeclRefType = CaptureType.getNonReferenceType();
19001
19002 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19003 // are mutable in the sense that user can change their value - they are
19004 // private instances of the captured declarations.
19005 const Capture &Cap = CSI->getCapture(Var);
19006 // C++ [expr.prim.lambda]p10:
19007 // The type of such a data member is [...] an lvalue reference to the
19008 // referenced function type if the entity is a reference to a function.
19009 // [...]
19010 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19011 !(isa<LambdaScopeInfo>(CSI) &&
19012 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19014 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19015 DeclRefType.addConst();
19016 return true;
19017 }
19018 return false;
19019}
19020
19021// Only block literals, captured statements, and lambda expressions can
19022// capture; other scopes don't work.
19024 ValueDecl *Var,
19025 SourceLocation Loc,
19026 const bool Diagnose,
19027 Sema &S) {
19030
19031 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19032 if (Underlying) {
19033 if (Underlying->hasLocalStorage() && Diagnose)
19035 }
19036 return nullptr;
19037}
19038
19039// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19040// certain types of variables (unnamed, variably modified types etc.)
19041// so check for eligibility.
19043 SourceLocation Loc, const bool Diagnose,
19044 Sema &S) {
19045
19046 assert((isa<VarDecl, BindingDecl>(Var)) &&
19047 "Only variables and structured bindings can be captured");
19048
19049 bool IsBlock = isa<BlockScopeInfo>(CSI);
19050 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19051
19052 // Lambdas are not allowed to capture unnamed variables
19053 // (e.g. anonymous unions).
19054 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19055 // assuming that's the intent.
19056 if (IsLambda && !Var->getDeclName()) {
19057 if (Diagnose) {
19058 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19059 S.Diag(Var->getLocation(), diag::note_declared_at);
19060 }
19061 return false;
19062 }
19063
19064 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19065 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19066 if (Diagnose) {
19067 S.Diag(Loc, diag::err_ref_vm_type);
19068 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19069 }
19070 return false;
19071 }
19072 // Prohibit structs with flexible array members too.
19073 // We cannot capture what is in the tail end of the struct.
19074 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19075 VTD && VTD->hasFlexibleArrayMember()) {
19076 if (Diagnose) {
19077 if (IsBlock)
19078 S.Diag(Loc, diag::err_ref_flexarray_type);
19079 else
19080 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19081 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19082 }
19083 return false;
19084 }
19085 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19086 // Lambdas and captured statements are not allowed to capture __block
19087 // variables; they don't support the expected semantics.
19088 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19089 if (Diagnose) {
19090 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19091 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19092 }
19093 return false;
19094 }
19095 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19096 if (S.getLangOpts().OpenCL && IsBlock &&
19097 Var->getType()->isBlockPointerType()) {
19098 if (Diagnose)
19099 S.Diag(Loc, diag::err_opencl_block_ref_block);
19100 return false;
19101 }
19102
19103 if (isa<BindingDecl>(Var)) {
19104 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19105 if (Diagnose)
19107 return false;
19108 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19109 S.Diag(Loc, S.LangOpts.CPlusPlus20
19110 ? diag::warn_cxx17_compat_capture_binding
19111 : diag::ext_capture_binding)
19112 << Var;
19113 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19114 }
19115 }
19116
19117 return true;
19118}
19119
19120// Returns true if the capture by block was successful.
19122 SourceLocation Loc, const bool BuildAndDiagnose,
19123 QualType &CaptureType, QualType &DeclRefType,
19124 const bool Nested, Sema &S, bool Invalid) {
19125 bool ByRef = false;
19126
19127 // Blocks are not allowed to capture arrays, excepting OpenCL.
19128 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19129 // (decayed to pointers).
19130 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19131 if (BuildAndDiagnose) {
19132 S.Diag(Loc, diag::err_ref_array_type);
19133 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19134 Invalid = true;
19135 } else {
19136 return false;
19137 }
19138 }
19139
19140 // Forbid the block-capture of autoreleasing variables.
19141 if (!Invalid &&
19143 if (BuildAndDiagnose) {
19144 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19145 << /*block*/ 0;
19146 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19147 Invalid = true;
19148 } else {
19149 return false;
19150 }
19151 }
19152
19153 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19154 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19155 QualType PointeeTy = PT->getPointeeType();
19156
19157 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19159 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19160 if (BuildAndDiagnose) {
19161 SourceLocation VarLoc = Var->getLocation();
19162 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19163 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19164 }
19165 }
19166 }
19167
19168 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19169 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19170 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19171 // Block capture by reference does not change the capture or
19172 // declaration reference types.
19173 ByRef = true;
19174 } else {
19175 // Block capture by copy introduces 'const'.
19176 CaptureType = CaptureType.getNonReferenceType().withConst();
19177 DeclRefType = CaptureType;
19178 }
19179
19180 // Actually capture the variable.
19181 if (BuildAndDiagnose)
19182 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19183 CaptureType, Invalid);
19184
19185 return !Invalid;
19186}
19187
19188/// Capture the given variable in the captured region.
19191 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19192 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19193 Sema &S, bool Invalid) {
19194 // By default, capture variables by reference.
19195 bool ByRef = true;
19196 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19197 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19198 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19199 // Using an LValue reference type is consistent with Lambdas (see below).
19200 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19201 bool HasConst = DeclRefType.isConstQualified();
19202 DeclRefType = DeclRefType.getUnqualifiedType();
19203 // Don't lose diagnostics about assignments to const.
19204 if (HasConst)
19205 DeclRefType.addConst();
19206 }
19207 // Do not capture firstprivates in tasks.
19208 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19209 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19210 return true;
19211 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19212 RSI->OpenMPCaptureLevel);
19213 }
19214
19215 if (ByRef)
19216 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19217 else
19218 CaptureType = DeclRefType;
19219
19220 // Actually capture the variable.
19221 if (BuildAndDiagnose)
19222 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19223 Loc, SourceLocation(), CaptureType, Invalid);
19224
19225 return !Invalid;
19226}
19227
19228/// Capture the given variable in the lambda.
19230 SourceLocation Loc, const bool BuildAndDiagnose,
19231 QualType &CaptureType, QualType &DeclRefType,
19232 const bool RefersToCapturedVariable,
19233 const TryCaptureKind Kind,
19234 SourceLocation EllipsisLoc, const bool IsTopScope,
19235 Sema &S, bool Invalid) {
19236 // Determine whether we are capturing by reference or by value.
19237 bool ByRef = false;
19238 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19239 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19240 } else {
19241 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19242 }
19243
19244 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19246 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19247 Invalid = true;
19248 }
19249
19250 // Compute the type of the field that will capture this variable.
19251 if (ByRef) {
19252 // C++11 [expr.prim.lambda]p15:
19253 // An entity is captured by reference if it is implicitly or
19254 // explicitly captured but not captured by copy. It is
19255 // unspecified whether additional unnamed non-static data
19256 // members are declared in the closure type for entities
19257 // captured by reference.
19258 //
19259 // FIXME: It is not clear whether we want to build an lvalue reference
19260 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19261 // to do the former, while EDG does the latter. Core issue 1249 will
19262 // clarify, but for now we follow GCC because it's a more permissive and
19263 // easily defensible position.
19264 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19265 } else {
19266 // C++11 [expr.prim.lambda]p14:
19267 // For each entity captured by copy, an unnamed non-static
19268 // data member is declared in the closure type. The
19269 // declaration order of these members is unspecified. The type
19270 // of such a data member is the type of the corresponding
19271 // captured entity if the entity is not a reference to an
19272 // object, or the referenced type otherwise. [Note: If the
19273 // captured entity is a reference to a function, the
19274 // corresponding data member is also a reference to a
19275 // function. - end note ]
19276 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19277 if (!RefType->getPointeeType()->isFunctionType())
19278 CaptureType = RefType->getPointeeType();
19279 }
19280
19281 // Forbid the lambda copy-capture of autoreleasing variables.
19282 if (!Invalid &&
19284 if (BuildAndDiagnose) {
19285 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19286 S.Diag(Var->getLocation(), diag::note_previous_decl)
19287 << Var->getDeclName();
19288 Invalid = true;
19289 } else {
19290 return false;
19291 }
19292 }
19293
19294 // Make sure that by-copy captures are of a complete and non-abstract type.
19295 if (!Invalid && BuildAndDiagnose) {
19296 if (!CaptureType->isDependentType() &&
19298 Loc, CaptureType,
19299 diag::err_capture_of_incomplete_or_sizeless_type,
19300 Var->getDeclName()))
19301 Invalid = true;
19302 else if (S.RequireNonAbstractType(Loc, CaptureType,
19303 diag::err_capture_of_abstract_type))
19304 Invalid = true;
19305 }
19306 }
19307
19308 // Compute the type of a reference to this captured variable.
19309 if (ByRef)
19310 DeclRefType = CaptureType.getNonReferenceType();
19311 else {
19312 // C++ [expr.prim.lambda]p5:
19313 // The closure type for a lambda-expression has a public inline
19314 // function call operator [...]. This function call operator is
19315 // declared const (9.3.1) if and only if the lambda-expression's
19316 // parameter-declaration-clause is not followed by mutable.
19317 DeclRefType = CaptureType.getNonReferenceType();
19318 bool Const = LSI->lambdaCaptureShouldBeConst();
19319 // C++ [expr.prim.lambda]p10:
19320 // The type of such a data member is [...] an lvalue reference to the
19321 // referenced function type if the entity is a reference to a function.
19322 // [...]
19323 if (Const && !CaptureType->isReferenceType() &&
19324 !DeclRefType->isFunctionType())
19325 DeclRefType.addConst();
19326 }
19327
19328 // Add the capture.
19329 if (BuildAndDiagnose)
19330 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19331 Loc, EllipsisLoc, CaptureType, Invalid);
19332
19333 return !Invalid;
19334}
19335
19337 const ASTContext &Context) {
19338 // Offer a Copy fix even if the type is dependent.
19339 if (Var->getType()->isDependentType())
19340 return true;
19342 if (T.isTriviallyCopyableType(Context))
19343 return true;
19344 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19345
19346 if (!(RD = RD->getDefinition()))
19347 return false;
19348 if (RD->hasSimpleCopyConstructor())
19349 return true;
19350 if (RD->hasUserDeclaredCopyConstructor())
19351 for (CXXConstructorDecl *Ctor : RD->ctors())
19352 if (Ctor->isCopyConstructor())
19353 return !Ctor->isDeleted();
19354 }
19355 return false;
19356}
19357
19358/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19359/// default capture. Fixes may be omitted if they aren't allowed by the
19360/// standard, for example we can't emit a default copy capture fix-it if we
19361/// already explicitly copy capture capture another variable.
19363 ValueDecl *Var) {
19365 // Don't offer Capture by copy of default capture by copy fixes if Var is
19366 // known not to be copy constructible.
19367 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19368
19369 SmallString<32> FixBuffer;
19370 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19371 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19372 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19373 if (ShouldOfferCopyFix) {
19374 // Offer fixes to insert an explicit capture for the variable.
19375 // [] -> [VarName]
19376 // [OtherCapture] -> [OtherCapture, VarName]
19377 FixBuffer.assign({Separator, Var->getName()});
19378 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19379 << Var << /*value*/ 0
19380 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19381 }
19382 // As above but capture by reference.
19383 FixBuffer.assign({Separator, "&", Var->getName()});
19384 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19385 << Var << /*reference*/ 1
19386 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19387 }
19388
19389 // Only try to offer default capture if there are no captures excluding this
19390 // and init captures.
19391 // [this]: OK.
19392 // [X = Y]: OK.
19393 // [&A, &B]: Don't offer.
19394 // [A, B]: Don't offer.
19395 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19396 return !C.isThisCapture() && !C.isInitCapture();
19397 }))
19398 return;
19399
19400 // The default capture specifiers, '=' or '&', must appear first in the
19401 // capture body.
19402 SourceLocation DefaultInsertLoc =
19404
19405 if (ShouldOfferCopyFix) {
19406 bool CanDefaultCopyCapture = true;
19407 // [=, *this] OK since c++17
19408 // [=, this] OK since c++20
19409 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19410 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19412 : false;
19413 // We can't use default capture by copy if any captures already specified
19414 // capture by copy.
19415 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19416 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19417 })) {
19418 FixBuffer.assign({"=", Separator});
19419 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19420 << /*value*/ 0
19421 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19422 }
19423 }
19424
19425 // We can't use default capture by reference if any captures already specified
19426 // capture by reference.
19427 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19428 return !C.isInitCapture() && C.isReferenceCapture() &&
19429 !C.isThisCapture();
19430 })) {
19431 FixBuffer.assign({"&", Separator});
19432 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19433 << /*reference*/ 1
19434 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19435 }
19436}
19437
19439 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19440 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19441 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19442 // An init-capture is notionally from the context surrounding its
19443 // declaration, but its parent DC is the lambda class.
19444 DeclContext *VarDC = Var->getDeclContext();
19445 DeclContext *DC = CurContext;
19446
19447 // Skip past RequiresExprBodys because they don't constitute function scopes.
19448 while (DC->isRequiresExprBody())
19449 DC = DC->getParent();
19450
19451 // tryCaptureVariable is called every time a DeclRef is formed,
19452 // it can therefore have non-negigible impact on performances.
19453 // For local variables and when there is no capturing scope,
19454 // we can bailout early.
19455 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19456 return true;
19457
19458 // Exception: Function parameters are not tied to the function's DeclContext
19459 // until we enter the function definition. Capturing them anyway would result
19460 // in an out-of-bounds error while traversing DC and its parents.
19461 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19462 return true;
19463
19464 const auto *VD = dyn_cast<VarDecl>(Var);
19465 if (VD) {
19466 if (VD->isInitCapture())
19467 VarDC = VarDC->getParent();
19468 } else {
19470 }
19471 assert(VD && "Cannot capture a null variable");
19472
19473 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19474 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19475 // We need to sync up the Declaration Context with the
19476 // FunctionScopeIndexToStopAt
19477 if (FunctionScopeIndexToStopAt) {
19478 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19479 unsigned FSIndex = FunctionScopes.size() - 1;
19480 // When we're parsing the lambda parameter list, the current DeclContext is
19481 // NOT the lambda but its parent. So move away the current LSI before
19482 // aligning DC and FunctionScopeIndexToStopAt.
19483 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19484 FSIndex && LSI && !LSI->AfterParameterList)
19485 --FSIndex;
19486 assert(MaxFunctionScopesIndex <= FSIndex &&
19487 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19488 "FunctionScopes.");
19489 while (FSIndex != MaxFunctionScopesIndex) {
19491 --FSIndex;
19492 }
19493 }
19494
19495 // Capture global variables if it is required to use private copy of this
19496 // variable.
19497 bool IsGlobal = !VD->hasLocalStorage();
19498 if (IsGlobal && !(LangOpts.OpenMP &&
19499 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19500 MaxFunctionScopesIndex)))
19501 return true;
19502
19503 if (isa<VarDecl>(Var))
19504 Var = cast<VarDecl>(Var->getCanonicalDecl());
19505
19506 // Walk up the stack to determine whether we can capture the variable,
19507 // performing the "simple" checks that don't depend on type. We stop when
19508 // we've either hit the declared scope of the variable or find an existing
19509 // capture of that variable. We start from the innermost capturing-entity
19510 // (the DC) and ensure that all intervening capturing-entities
19511 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19512 // declcontext can either capture the variable or have already captured
19513 // the variable.
19514 CaptureType = Var->getType();
19515 DeclRefType = CaptureType.getNonReferenceType();
19516 bool Nested = false;
19517 bool Explicit = (Kind != TryCaptureKind::Implicit);
19518 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19519 do {
19520
19521 LambdaScopeInfo *LSI = nullptr;
19522 if (!FunctionScopes.empty())
19523 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19524 FunctionScopes[FunctionScopesIndex]);
19525
19526 bool IsInScopeDeclarationContext =
19527 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19528
19529 if (LSI && !LSI->AfterParameterList) {
19530 // This allows capturing parameters from a default value which does not
19531 // seems correct
19532 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19533 return true;
19534 }
19535 // If the variable is declared in the current context, there is no need to
19536 // capture it.
19537 if (IsInScopeDeclarationContext &&
19538 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19539 return true;
19540
19541 // Only block literals, captured statements, and lambda expressions can
19542 // capture; other scopes don't work.
19543 DeclContext *ParentDC =
19544 !IsInScopeDeclarationContext
19545 ? DC->getParent()
19546 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19547 BuildAndDiagnose, *this);
19548 // We need to check for the parent *first* because, if we *have*
19549 // private-captured a global variable, we need to recursively capture it in
19550 // intermediate blocks, lambdas, etc.
19551 if (!ParentDC) {
19552 if (IsGlobal) {
19553 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19554 break;
19555 }
19556 return true;
19557 }
19558
19559 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19561
19562 // Check whether we've already captured it.
19563 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19564 DeclRefType)) {
19565 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19566 break;
19567 }
19568
19569 // When evaluating some attributes (like enable_if) we might refer to a
19570 // function parameter appertaining to the same declaration as that
19571 // attribute.
19572 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19573 Parm && Parm->getDeclContext() == DC)
19574 return true;
19575
19576 // If we are instantiating a generic lambda call operator body,
19577 // we do not want to capture new variables. What was captured
19578 // during either a lambdas transformation or initial parsing
19579 // should be used.
19581 if (BuildAndDiagnose) {
19584 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19585 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19586 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19587 buildLambdaCaptureFixit(*this, LSI, Var);
19588 } else
19590 }
19591 return true;
19592 }
19593
19594 // Try to capture variable-length arrays types.
19595 if (Var->getType()->isVariablyModifiedType()) {
19596 // We're going to walk down into the type and look for VLA
19597 // expressions.
19598 QualType QTy = Var->getType();
19599 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19600 QTy = PVD->getOriginalType();
19602 }
19603
19604 if (getLangOpts().OpenMP) {
19605 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19606 // OpenMP private variables should not be captured in outer scope, so
19607 // just break here. Similarly, global variables that are captured in a
19608 // target region should not be captured outside the scope of the region.
19609 if (RSI->CapRegionKind == CR_OpenMP) {
19610 // FIXME: We should support capturing structured bindings in OpenMP.
19611 if (isa<BindingDecl>(Var)) {
19612 if (BuildAndDiagnose) {
19613 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19614 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19615 }
19616 return true;
19617 }
19618 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19619 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19620 // If the variable is private (i.e. not captured) and has variably
19621 // modified type, we still need to capture the type for correct
19622 // codegen in all regions, associated with the construct. Currently,
19623 // it is captured in the innermost captured region only.
19624 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19625 Var->getType()->isVariablyModifiedType()) {
19626 QualType QTy = Var->getType();
19627 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19628 QTy = PVD->getOriginalType();
19629 for (int I = 1,
19630 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19631 I < E; ++I) {
19632 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19633 FunctionScopes[FunctionScopesIndex - I]);
19634 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19635 "Wrong number of captured regions associated with the "
19636 "OpenMP construct.");
19637 captureVariablyModifiedType(Context, QTy, OuterRSI);
19638 }
19639 }
19640 bool IsTargetCap =
19641 IsOpenMPPrivateDecl != OMPC_private &&
19642 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19643 RSI->OpenMPCaptureLevel);
19644 // Do not capture global if it is not privatized in outer regions.
19645 bool IsGlobalCap =
19646 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19647 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19648
19649 // When we detect target captures we are looking from inside the
19650 // target region, therefore we need to propagate the capture from the
19651 // enclosing region. Therefore, the capture is not initially nested.
19652 if (IsTargetCap)
19653 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19654 RSI->OpenMPLevel);
19655
19656 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19657 (IsGlobal && !IsGlobalCap)) {
19658 Nested = !IsTargetCap;
19659 bool HasConst = DeclRefType.isConstQualified();
19660 DeclRefType = DeclRefType.getUnqualifiedType();
19661 // Don't lose diagnostics about assignments to const.
19662 if (HasConst)
19663 DeclRefType.addConst();
19664 CaptureType = Context.getLValueReferenceType(DeclRefType);
19665 break;
19666 }
19667 }
19668 }
19669 }
19671 // No capture-default, and this is not an explicit capture
19672 // so cannot capture this variable.
19673 if (BuildAndDiagnose) {
19674 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19675 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19676 auto *LSI = cast<LambdaScopeInfo>(CSI);
19677 if (LSI->Lambda) {
19678 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19679 buildLambdaCaptureFixit(*this, LSI, Var);
19680 }
19681 // FIXME: If we error out because an outer lambda can not implicitly
19682 // capture a variable that an inner lambda explicitly captures, we
19683 // should have the inner lambda do the explicit capture - because
19684 // it makes for cleaner diagnostics later. This would purely be done
19685 // so that the diagnostic does not misleadingly claim that a variable
19686 // can not be captured by a lambda implicitly even though it is captured
19687 // explicitly. Suggestion:
19688 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19689 // at the function head
19690 // - cache the StartingDeclContext - this must be a lambda
19691 // - captureInLambda in the innermost lambda the variable.
19692 }
19693 return true;
19694 }
19695 Explicit = false;
19696 FunctionScopesIndex--;
19697 if (IsInScopeDeclarationContext)
19698 DC = ParentDC;
19699 } while (!VarDC->Equals(DC));
19700
19701 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19702 // computing the type of the capture at each step, checking type-specific
19703 // requirements, and adding captures if requested.
19704 // If the variable had already been captured previously, we start capturing
19705 // at the lambda nested within that one.
19706 bool Invalid = false;
19707 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19708 ++I) {
19710
19711 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19712 // certain types of variables (unnamed, variably modified types etc.)
19713 // so check for eligibility.
19714 if (!Invalid)
19715 Invalid =
19716 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19717
19718 // After encountering an error, if we're actually supposed to capture, keep
19719 // capturing in nested contexts to suppress any follow-on diagnostics.
19720 if (Invalid && !BuildAndDiagnose)
19721 return true;
19722
19723 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19724 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19725 DeclRefType, Nested, *this, Invalid);
19726 Nested = true;
19727 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19729 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19730 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19731 Nested = true;
19732 } else {
19734 Invalid =
19735 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19736 DeclRefType, Nested, Kind, EllipsisLoc,
19737 /*IsTopScope*/ I == N - 1, *this, Invalid);
19738 Nested = true;
19739 }
19740
19741 if (Invalid && !BuildAndDiagnose)
19742 return true;
19743 }
19744 return Invalid;
19745}
19746
19748 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19749 QualType CaptureType;
19750 QualType DeclRefType;
19751 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19752 /*BuildAndDiagnose=*/true, CaptureType,
19753 DeclRefType, nullptr);
19754}
19755
19757 QualType CaptureType;
19758 QualType DeclRefType;
19759 return !tryCaptureVariable(
19761 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19762}
19763
19765 assert(Var && "Null value cannot be captured");
19766
19767 QualType CaptureType;
19768 QualType DeclRefType;
19769
19770 // Determine whether we can capture this variable.
19772 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19773 nullptr))
19774 return QualType();
19775
19776 return DeclRefType;
19777}
19778
19779namespace {
19780// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19781// The produced TemplateArgumentListInfo* points to data stored within this
19782// object, so should only be used in contexts where the pointer will not be
19783// used after the CopiedTemplateArgs object is destroyed.
19784class CopiedTemplateArgs {
19785 bool HasArgs;
19786 TemplateArgumentListInfo TemplateArgStorage;
19787public:
19788 template<typename RefExpr>
19789 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19790 if (HasArgs)
19791 E->copyTemplateArgumentsInto(TemplateArgStorage);
19792 }
19793 operator TemplateArgumentListInfo*()
19794#ifdef __has_cpp_attribute
19795#if __has_cpp_attribute(clang::lifetimebound)
19796 [[clang::lifetimebound]]
19797#endif
19798#endif
19799 {
19800 return HasArgs ? &TemplateArgStorage : nullptr;
19801 }
19802};
19803}
19804
19805/// Walk the set of potential results of an expression and mark them all as
19806/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19807///
19808/// \return A new expression if we found any potential results, ExprEmpty() if
19809/// not, and ExprError() if we diagnosed an error.
19811 NonOdrUseReason NOUR) {
19812 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19813 // an object that satisfies the requirements for appearing in a
19814 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19815 // is immediately applied." This function handles the lvalue-to-rvalue
19816 // conversion part.
19817 //
19818 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19819 // transform it into the relevant kind of non-odr-use node and rebuild the
19820 // tree of nodes leading to it.
19821 //
19822 // This is a mini-TreeTransform that only transforms a restricted subset of
19823 // nodes (and only certain operands of them).
19824
19825 // Rebuild a subexpression.
19826 auto Rebuild = [&](Expr *Sub) {
19827 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19828 };
19829
19830 // Check whether a potential result satisfies the requirements of NOUR.
19831 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19832 // Any entity other than a VarDecl is always odr-used whenever it's named
19833 // in a potentially-evaluated expression.
19834 auto *VD = dyn_cast<VarDecl>(D);
19835 if (!VD)
19836 return true;
19837
19838 // C++2a [basic.def.odr]p4:
19839 // A variable x whose name appears as a potentially-evalauted expression
19840 // e is odr-used by e unless
19841 // -- x is a reference that is usable in constant expressions, or
19842 // -- x is a variable of non-reference type that is usable in constant
19843 // expressions and has no mutable subobjects, and e is an element of
19844 // the set of potential results of an expression of
19845 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19846 // conversion is applied, or
19847 // -- x is a variable of non-reference type, and e is an element of the
19848 // set of potential results of a discarded-value expression to which
19849 // the lvalue-to-rvalue conversion is not applied
19850 //
19851 // We check the first bullet and the "potentially-evaluated" condition in
19852 // BuildDeclRefExpr. We check the type requirements in the second bullet
19853 // in CheckLValueToRValueConversionOperand below.
19854 switch (NOUR) {
19855 case NOUR_None:
19856 case NOUR_Unevaluated:
19857 llvm_unreachable("unexpected non-odr-use-reason");
19858
19859 case NOUR_Constant:
19860 // Constant references were handled when they were built.
19861 if (VD->getType()->isReferenceType())
19862 return true;
19863 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19864 if (RD->hasDefinition() && RD->hasMutableFields())
19865 return true;
19866 if (!VD->isUsableInConstantExpressions(S.Context))
19867 return true;
19868 break;
19869
19870 case NOUR_Discarded:
19871 if (VD->getType()->isReferenceType())
19872 return true;
19873 break;
19874 }
19875 return false;
19876 };
19877
19878 // Check whether this expression may be odr-used in CUDA/HIP.
19879 auto MaybeCUDAODRUsed = [&]() -> bool {
19880 if (!S.LangOpts.CUDA)
19881 return false;
19882 LambdaScopeInfo *LSI = S.getCurLambda();
19883 if (!LSI)
19884 return false;
19885 auto *DRE = dyn_cast<DeclRefExpr>(E);
19886 if (!DRE)
19887 return false;
19888 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
19889 if (!VD)
19890 return false;
19891 return LSI->CUDAPotentialODRUsedVars.count(VD);
19892 };
19893
19894 // Mark that this expression does not constitute an odr-use.
19895 auto MarkNotOdrUsed = [&] {
19896 if (!MaybeCUDAODRUsed()) {
19897 S.MaybeODRUseExprs.remove(E);
19898 if (LambdaScopeInfo *LSI = S.getCurLambda())
19899 LSI->markVariableExprAsNonODRUsed(E);
19900 }
19901 };
19902
19903 // C++2a [basic.def.odr]p2:
19904 // The set of potential results of an expression e is defined as follows:
19905 switch (E->getStmtClass()) {
19906 // -- If e is an id-expression, ...
19907 case Expr::DeclRefExprClass: {
19908 auto *DRE = cast<DeclRefExpr>(E);
19909 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19910 break;
19911
19912 // Rebuild as a non-odr-use DeclRefExpr.
19913 MarkNotOdrUsed();
19914 return DeclRefExpr::Create(
19915 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19916 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19917 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19918 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19919 }
19920
19921 case Expr::FunctionParmPackExprClass: {
19922 auto *FPPE = cast<FunctionParmPackExpr>(E);
19923 // If any of the declarations in the pack is odr-used, then the expression
19924 // as a whole constitutes an odr-use.
19925 for (ValueDecl *D : *FPPE)
19926 if (IsPotentialResultOdrUsed(D))
19927 return ExprEmpty();
19928
19929 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19930 // nothing cares about whether we marked this as an odr-use, but it might
19931 // be useful for non-compiler tools.
19932 MarkNotOdrUsed();
19933 break;
19934 }
19935
19936 // -- If e is a subscripting operation with an array operand...
19937 case Expr::ArraySubscriptExprClass: {
19938 auto *ASE = cast<ArraySubscriptExpr>(E);
19939 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19940 if (!OldBase->getType()->isArrayType())
19941 break;
19942 ExprResult Base = Rebuild(OldBase);
19943 if (!Base.isUsable())
19944 return Base;
19945 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19946 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19947 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19948 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19949 ASE->getRBracketLoc());
19950 }
19951
19952 case Expr::MemberExprClass: {
19953 auto *ME = cast<MemberExpr>(E);
19954 // -- If e is a class member access expression [...] naming a non-static
19955 // data member...
19956 if (isa<FieldDecl>(ME->getMemberDecl())) {
19957 ExprResult Base = Rebuild(ME->getBase());
19958 if (!Base.isUsable())
19959 return Base;
19960 return MemberExpr::Create(
19961 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19962 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19963 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19964 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19965 ME->getObjectKind(), ME->isNonOdrUse());
19966 }
19967
19968 if (ME->getMemberDecl()->isCXXInstanceMember())
19969 break;
19970
19971 // -- If e is a class member access expression naming a static data member,
19972 // ...
19973 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19974 break;
19975
19976 // Rebuild as a non-odr-use MemberExpr.
19977 MarkNotOdrUsed();
19978 return MemberExpr::Create(
19979 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19980 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19981 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19982 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19983 }
19984
19985 case Expr::BinaryOperatorClass: {
19986 auto *BO = cast<BinaryOperator>(E);
19987 Expr *LHS = BO->getLHS();
19988 Expr *RHS = BO->getRHS();
19989 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19990 if (BO->getOpcode() == BO_PtrMemD) {
19991 ExprResult Sub = Rebuild(LHS);
19992 if (!Sub.isUsable())
19993 return Sub;
19994 BO->setLHS(Sub.get());
19995 // -- If e is a comma expression, ...
19996 } else if (BO->getOpcode() == BO_Comma) {
19997 ExprResult Sub = Rebuild(RHS);
19998 if (!Sub.isUsable())
19999 return Sub;
20000 BO->setRHS(Sub.get());
20001 } else {
20002 break;
20003 }
20004 return ExprResult(BO);
20005 }
20006
20007 // -- If e has the form (e1)...
20008 case Expr::ParenExprClass: {
20009 auto *PE = cast<ParenExpr>(E);
20010 ExprResult Sub = Rebuild(PE->getSubExpr());
20011 if (!Sub.isUsable())
20012 return Sub;
20013 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20014 }
20015
20016 // -- If e is a glvalue conditional expression, ...
20017 // We don't apply this to a binary conditional operator. FIXME: Should we?
20018 case Expr::ConditionalOperatorClass: {
20019 auto *CO = cast<ConditionalOperator>(E);
20020 ExprResult LHS = Rebuild(CO->getLHS());
20021 if (LHS.isInvalid())
20022 return ExprError();
20023 ExprResult RHS = Rebuild(CO->getRHS());
20024 if (RHS.isInvalid())
20025 return ExprError();
20026 if (!LHS.isUsable() && !RHS.isUsable())
20027 return ExprEmpty();
20028 if (!LHS.isUsable())
20029 LHS = CO->getLHS();
20030 if (!RHS.isUsable())
20031 RHS = CO->getRHS();
20032 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20033 CO->getCond(), LHS.get(), RHS.get());
20034 }
20035
20036 // [Clang extension]
20037 // -- If e has the form __extension__ e1...
20038 case Expr::UnaryOperatorClass: {
20039 auto *UO = cast<UnaryOperator>(E);
20040 if (UO->getOpcode() != UO_Extension)
20041 break;
20042 ExprResult Sub = Rebuild(UO->getSubExpr());
20043 if (!Sub.isUsable())
20044 return Sub;
20045 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20046 Sub.get());
20047 }
20048
20049 // [Clang extension]
20050 // -- If e has the form _Generic(...), the set of potential results is the
20051 // union of the sets of potential results of the associated expressions.
20052 case Expr::GenericSelectionExprClass: {
20053 auto *GSE = cast<GenericSelectionExpr>(E);
20054
20055 SmallVector<Expr *, 4> AssocExprs;
20056 bool AnyChanged = false;
20057 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20058 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20059 if (AssocExpr.isInvalid())
20060 return ExprError();
20061 if (AssocExpr.isUsable()) {
20062 AssocExprs.push_back(AssocExpr.get());
20063 AnyChanged = true;
20064 } else {
20065 AssocExprs.push_back(OrigAssocExpr);
20066 }
20067 }
20068
20069 void *ExOrTy = nullptr;
20070 bool IsExpr = GSE->isExprPredicate();
20071 if (IsExpr)
20072 ExOrTy = GSE->getControllingExpr();
20073 else
20074 ExOrTy = GSE->getControllingType();
20075 return AnyChanged ? S.CreateGenericSelectionExpr(
20076 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20077 GSE->getRParenLoc(), IsExpr, ExOrTy,
20078 GSE->getAssocTypeSourceInfos(), AssocExprs)
20079 : ExprEmpty();
20080 }
20081
20082 // [Clang extension]
20083 // -- If e has the form __builtin_choose_expr(...), the set of potential
20084 // results is the union of the sets of potential results of the
20085 // second and third subexpressions.
20086 case Expr::ChooseExprClass: {
20087 auto *CE = cast<ChooseExpr>(E);
20088
20089 ExprResult LHS = Rebuild(CE->getLHS());
20090 if (LHS.isInvalid())
20091 return ExprError();
20092
20093 ExprResult RHS = Rebuild(CE->getLHS());
20094 if (RHS.isInvalid())
20095 return ExprError();
20096
20097 if (!LHS.get() && !RHS.get())
20098 return ExprEmpty();
20099 if (!LHS.isUsable())
20100 LHS = CE->getLHS();
20101 if (!RHS.isUsable())
20102 RHS = CE->getRHS();
20103
20104 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20105 RHS.get(), CE->getRParenLoc());
20106 }
20107
20108 // Step through non-syntactic nodes.
20109 case Expr::ConstantExprClass: {
20110 auto *CE = cast<ConstantExpr>(E);
20111 ExprResult Sub = Rebuild(CE->getSubExpr());
20112 if (!Sub.isUsable())
20113 return Sub;
20114 return ConstantExpr::Create(S.Context, Sub.get());
20115 }
20116
20117 // We could mostly rely on the recursive rebuilding to rebuild implicit
20118 // casts, but not at the top level, so rebuild them here.
20119 case Expr::ImplicitCastExprClass: {
20120 auto *ICE = cast<ImplicitCastExpr>(E);
20121 // Only step through the narrow set of cast kinds we expect to encounter.
20122 // Anything else suggests we've left the region in which potential results
20123 // can be found.
20124 switch (ICE->getCastKind()) {
20125 case CK_NoOp:
20126 case CK_DerivedToBase:
20127 case CK_UncheckedDerivedToBase: {
20128 ExprResult Sub = Rebuild(ICE->getSubExpr());
20129 if (!Sub.isUsable())
20130 return Sub;
20131 CXXCastPath Path(ICE->path());
20132 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20133 ICE->getValueKind(), &Path);
20134 }
20135
20136 default:
20137 break;
20138 }
20139 break;
20140 }
20141
20142 default:
20143 break;
20144 }
20145
20146 // Can't traverse through this node. Nothing to do.
20147 return ExprEmpty();
20148}
20149
20151 // Check whether the operand is or contains an object of non-trivial C union
20152 // type.
20153 if (E->getType().isVolatileQualified() &&
20159
20160 // C++2a [basic.def.odr]p4:
20161 // [...] an expression of non-volatile-qualified non-class type to which
20162 // the lvalue-to-rvalue conversion is applied [...]
20163 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20164 return E;
20165
20168 if (Result.isInvalid())
20169 return ExprError();
20170 return Result.get() ? Result : E;
20171}
20172
20174 if (!Res.isUsable())
20175 return Res;
20176
20177 // If a constant-expression is a reference to a variable where we delay
20178 // deciding whether it is an odr-use, just assume we will apply the
20179 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20180 // (a non-type template argument), we have special handling anyway.
20182}
20183
20185 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20186 // call.
20187 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20188 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20189
20190 for (Expr *E : LocalMaybeODRUseExprs) {
20191 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20192 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20193 DRE->getLocation(), *this);
20194 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20195 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20196 *this);
20197 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20198 for (ValueDecl *VD : *FP)
20199 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20200 } else {
20201 llvm_unreachable("Unexpected expression");
20202 }
20203 }
20204
20205 assert(MaybeODRUseExprs.empty() &&
20206 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20207}
20208
20210 ValueDecl *Var, Expr *E) {
20212 if (!VD)
20213 return;
20214
20215 const bool RefersToEnclosingScope =
20216 (SemaRef.CurContext != VD->getDeclContext() &&
20218 if (RefersToEnclosingScope) {
20219 LambdaScopeInfo *const LSI =
20220 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20221 if (LSI && (!LSI->CallOperator ||
20222 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20223 // If a variable could potentially be odr-used, defer marking it so
20224 // until we finish analyzing the full expression for any
20225 // lvalue-to-rvalue
20226 // or discarded value conversions that would obviate odr-use.
20227 // Add it to the list of potential captures that will be analyzed
20228 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20229 // unless the variable is a reference that was initialized by a constant
20230 // expression (this will never need to be captured or odr-used).
20231 //
20232 // FIXME: We can simplify this a lot after implementing P0588R1.
20233 assert(E && "Capture variable should be used in an expression.");
20234 if (!Var->getType()->isReferenceType() ||
20237 }
20238 }
20239}
20240
20242 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20243 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20244 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20246 "Invalid Expr argument to DoMarkVarDeclReferenced");
20247 Var->setReferenced();
20248
20249 if (Var->isInvalidDecl())
20250 return;
20251
20252 auto *MSI = Var->getMemberSpecializationInfo();
20253 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20255
20256 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20257 bool UsableInConstantExpr =
20259
20260 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20261 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20262 }
20263
20264 // C++20 [expr.const]p12:
20265 // A variable [...] is needed for constant evaluation if it is [...] a
20266 // variable whose name appears as a potentially constant evaluated
20267 // expression that is either a contexpr variable or is of non-volatile
20268 // const-qualified integral type or of reference type
20269 bool NeededForConstantEvaluation =
20270 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20271
20272 bool NeedDefinition =
20273 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20274 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20275 Var->getType()->isUndeducedType());
20276
20278 "Can't instantiate a partial template specialization.");
20279
20280 // If this might be a member specialization of a static data member, check
20281 // the specialization is visible. We already did the checks for variable
20282 // template specializations when we created them.
20283 if (NeedDefinition && TSK != TSK_Undeclared &&
20286
20287 // Perform implicit instantiation of static data members, static data member
20288 // templates of class templates, and variable template specializations. Delay
20289 // instantiations of variable templates, except for those that could be used
20290 // in a constant expression.
20291 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20292 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20293 // instantiation declaration if a variable is usable in a constant
20294 // expression (among other cases).
20295 bool TryInstantiating =
20297 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20298
20299 if (TryInstantiating) {
20300 SourceLocation PointOfInstantiation =
20301 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20302 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20303 if (FirstInstantiation) {
20304 PointOfInstantiation = Loc;
20305 if (MSI)
20306 MSI->setPointOfInstantiation(PointOfInstantiation);
20307 // FIXME: Notify listener.
20308 else
20309 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20310 }
20311
20312 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20313 // Do not defer instantiations of variables that could be used in a
20314 // constant expression.
20315 // The type deduction also needs a complete initializer.
20316 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20317 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20318 });
20319
20320 // The size of an incomplete array type can be updated by
20321 // instantiating the initializer. The DeclRefExpr's type should be
20322 // updated accordingly too, or users of it would be confused!
20323 if (E)
20325
20326 // Re-set the member to trigger a recomputation of the dependence bits
20327 // for the expression.
20328 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20329 DRE->setDecl(DRE->getDecl());
20330 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20331 ME->setMemberDecl(ME->getMemberDecl());
20332 } else if (FirstInstantiation) {
20334 .push_back(std::make_pair(Var, PointOfInstantiation));
20335 } else {
20336 bool Inserted = false;
20337 for (auto &I : SemaRef.SavedPendingInstantiations) {
20338 auto Iter = llvm::find_if(
20339 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20340 return P.first == Var;
20341 });
20342 if (Iter != I.end()) {
20343 SemaRef.PendingInstantiations.push_back(*Iter);
20344 I.erase(Iter);
20345 Inserted = true;
20346 break;
20347 }
20348 }
20349
20350 // FIXME: For a specialization of a variable template, we don't
20351 // distinguish between "declaration and type implicitly instantiated"
20352 // and "implicit instantiation of definition requested", so we have
20353 // no direct way to avoid enqueueing the pending instantiation
20354 // multiple times.
20355 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20357 .push_back(std::make_pair(Var, PointOfInstantiation));
20358 }
20359 }
20360 }
20361
20362 // C++2a [basic.def.odr]p4:
20363 // A variable x whose name appears as a potentially-evaluated expression e
20364 // is odr-used by e unless
20365 // -- x is a reference that is usable in constant expressions
20366 // -- x is a variable of non-reference type that is usable in constant
20367 // expressions and has no mutable subobjects [FIXME], and e is an
20368 // element of the set of potential results of an expression of
20369 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20370 // conversion is applied
20371 // -- x is a variable of non-reference type, and e is an element of the set
20372 // of potential results of a discarded-value expression to which the
20373 // lvalue-to-rvalue conversion is not applied [FIXME]
20374 //
20375 // We check the first part of the second bullet here, and
20376 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20377 // FIXME: To get the third bullet right, we need to delay this even for
20378 // variables that are not usable in constant expressions.
20379
20380 // If we already know this isn't an odr-use, there's nothing more to do.
20381 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20382 if (DRE->isNonOdrUse())
20383 return;
20384 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20385 if (ME->isNonOdrUse())
20386 return;
20387
20388 switch (OdrUse) {
20389 case OdrUseContext::None:
20390 // In some cases, a variable may not have been marked unevaluated, if it
20391 // appears in a defaukt initializer.
20392 assert((!E || isa<FunctionParmPackExpr>(E) ||
20394 "missing non-odr-use marking for unevaluated decl ref");
20395 break;
20396
20397 case OdrUseContext::FormallyOdrUsed:
20398 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20399 // behavior.
20400 break;
20401
20402 case OdrUseContext::Used:
20403 // If we might later find that this expression isn't actually an odr-use,
20404 // delay the marking.
20406 SemaRef.MaybeODRUseExprs.insert(E);
20407 else
20408 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20409 break;
20410
20411 case OdrUseContext::Dependent:
20412 // If this is a dependent context, we don't need to mark variables as
20413 // odr-used, but we may still need to track them for lambda capture.
20414 // FIXME: Do we also need to do this inside dependent typeid expressions
20415 // (which are modeled as unevaluated at this point)?
20416 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20417 break;
20418 }
20419}
20420
20422 BindingDecl *BD, Expr *E) {
20423 BD->setReferenced();
20424
20425 if (BD->isInvalidDecl())
20426 return;
20427
20428 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20429 if (OdrUse == OdrUseContext::Used) {
20430 QualType CaptureType, DeclRefType;
20432 /*EllipsisLoc*/ SourceLocation(),
20433 /*BuildAndDiagnose*/ true, CaptureType,
20434 DeclRefType,
20435 /*FunctionScopeIndexToStopAt*/ nullptr);
20436 } else if (OdrUse == OdrUseContext::Dependent) {
20437 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20438 }
20439}
20440
20442 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20443}
20444
20445// C++ [temp.dep.expr]p3:
20446// An id-expression is type-dependent if it contains:
20447// - an identifier associated by name lookup with an entity captured by copy
20448// in a lambda-expression that has an explicit object parameter whose type
20449// is dependent ([dcl.fct]),
20451 Sema &SemaRef, ValueDecl *D, Expr *E) {
20452 auto *ID = dyn_cast<DeclRefExpr>(E);
20453 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20454 return;
20455
20456 // If any enclosing lambda with a dependent explicit object parameter either
20457 // explicitly captures the variable by value, or has a capture default of '='
20458 // and does not capture the variable by reference, then the type of the DRE
20459 // is dependent on the type of that lambda's explicit object parameter.
20460 auto IsDependent = [&]() {
20461 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20462 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20463 if (!LSI)
20464 continue;
20465
20466 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20467 LSI->AfterParameterList)
20468 return false;
20469
20470 const auto *MD = LSI->CallOperator;
20471 if (MD->getType().isNull())
20472 continue;
20473
20474 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20475 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20476 !Ty->getParamType(0)->isDependentType())
20477 continue;
20478
20479 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20480 if (C->isCopyCapture())
20481 return true;
20482 continue;
20483 }
20484
20485 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20486 return true;
20487 }
20488 return false;
20489 }();
20490
20491 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20492 IsDependent, SemaRef.getASTContext());
20493}
20494
20495static void
20497 bool MightBeOdrUse,
20498 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20501
20502 if (SemaRef.getLangOpts().OpenACC)
20503 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20504
20505 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20507 if (SemaRef.getLangOpts().CPlusPlus)
20509 Var, E);
20510 return;
20511 }
20512
20513 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20515 if (SemaRef.getLangOpts().CPlusPlus)
20517 Decl, E);
20518 return;
20519 }
20520 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20521
20522 // If this is a call to a method via a cast, also mark the method in the
20523 // derived class used in case codegen can devirtualize the call.
20524 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20525 if (!ME)
20526 return;
20527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20528 if (!MD)
20529 return;
20530 // Only attempt to devirtualize if this is truly a virtual call.
20531 bool IsVirtualCall = MD->isVirtual() &&
20533 if (!IsVirtualCall)
20534 return;
20535
20536 // If it's possible to devirtualize the call, mark the called function
20537 // referenced.
20539 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20540 if (DM)
20541 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20542}
20543
20545 // [basic.def.odr] (CWG 1614)
20546 // A function is named by an expression or conversion [...]
20547 // unless it is a pure virtual function and either the expression is not an
20548 // id-expression naming the function with an explicitly qualified name or
20549 // the expression forms a pointer to member
20550 bool OdrUse = true;
20551 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20552 if (Method->isVirtual() &&
20553 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20554 OdrUse = false;
20555
20556 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20560 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20561 !FD->isDependentContext())
20562 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20563 }
20564 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20566}
20567
20569 // C++11 [basic.def.odr]p2:
20570 // A non-overloaded function whose name appears as a potentially-evaluated
20571 // expression or a member of a set of candidate functions, if selected by
20572 // overload resolution when referred to from a potentially-evaluated
20573 // expression, is odr-used, unless it is a pure virtual function and its
20574 // name is not explicitly qualified.
20575 bool MightBeOdrUse = true;
20577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20578 if (Method->isPureVirtual())
20579 MightBeOdrUse = false;
20580 }
20581 SourceLocation Loc =
20582 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20583 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20585}
20586
20592
20593/// Perform marking for a reference to an arbitrary declaration. It
20594/// marks the declaration referenced, and performs odr-use checking for
20595/// functions and variables. This method should not be used when building a
20596/// normal expression which refers to a variable.
20598 bool MightBeOdrUse) {
20599 if (MightBeOdrUse) {
20600 if (auto *VD = dyn_cast<VarDecl>(D)) {
20601 MarkVariableReferenced(Loc, VD);
20602 return;
20603 }
20604 }
20605 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20606 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20607 return;
20608 }
20609 D->setReferenced();
20610}
20611
20612namespace {
20613 // Mark all of the declarations used by a type as referenced.
20614 // FIXME: Not fully implemented yet! We need to have a better understanding
20615 // of when we're entering a context we should not recurse into.
20616 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20617 // TreeTransforms rebuilding the type in a new context. Rather than
20618 // duplicating the TreeTransform logic, we should consider reusing it here.
20619 // Currently that causes problems when rebuilding LambdaExprs.
20620class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20621 Sema &S;
20622 SourceLocation Loc;
20623
20624public:
20625 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20626
20627 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20628};
20629}
20630
20631bool MarkReferencedDecls::TraverseTemplateArgument(
20632 const TemplateArgument &Arg) {
20633 {
20634 // A non-type template argument is a constant-evaluated context.
20635 EnterExpressionEvaluationContext Evaluated(
20638 if (Decl *D = Arg.getAsDecl())
20639 S.MarkAnyDeclReferenced(Loc, D, true);
20640 } else if (Arg.getKind() == TemplateArgument::Expression) {
20642 }
20643 }
20644
20646}
20647
20649 MarkReferencedDecls Marker(*this, Loc);
20650 Marker.TraverseType(T);
20651}
20652
20653namespace {
20654/// Helper class that marks all of the declarations referenced by
20655/// potentially-evaluated subexpressions as "referenced".
20656class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20657public:
20658 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20659 bool SkipLocalVariables;
20661
20662 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20664 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20665
20666 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20668 }
20669
20670 void Visit(Expr *E) {
20671 if (llvm::is_contained(StopAt, E))
20672 return;
20673 Inherited::Visit(E);
20674 }
20675
20676 void VisitConstantExpr(ConstantExpr *E) {
20677 // Don't mark declarations within a ConstantExpression, as this expression
20678 // will be evaluated and folded to a value.
20679 }
20680
20681 void VisitDeclRefExpr(DeclRefExpr *E) {
20682 // If we were asked not to visit local variables, don't.
20683 if (SkipLocalVariables) {
20684 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20685 if (VD->hasLocalStorage())
20686 return;
20687 }
20688
20689 // FIXME: This can trigger the instantiation of the initializer of a
20690 // variable, which can cause the expression to become value-dependent
20691 // or error-dependent. Do we need to propagate the new dependence bits?
20693 }
20694
20695 void VisitMemberExpr(MemberExpr *E) {
20697 Visit(E->getBase());
20698 }
20699};
20700} // namespace
20701
20703 bool SkipLocalVariables,
20704 ArrayRef<const Expr*> StopAt) {
20705 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20706}
20707
20708/// Emit a diagnostic when statements are reachable.
20710 const PartialDiagnostic &PD) {
20711 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20712 // The initializer of a constexpr variable or of the first declaration of a
20713 // static data member is not syntactically a constant evaluated constant,
20714 // but nonetheless is always required to be a constant expression, so we
20715 // can skip diagnosing.
20716 if (Decl &&
20717 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20718 Decl->isFirstDecl() && !Decl->isInline())))
20719 return false;
20720
20721 if (Stmts.empty()) {
20722 Diag(Loc, PD);
20723 return true;
20724 }
20725
20726 if (getCurFunction()) {
20727 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20728 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20729 return true;
20730 }
20731
20732 // For non-constexpr file-scope variables with reachability context (non-empty
20733 // Stmts), build a CFG for the initializer and check whether the context in
20734 // question is reachable.
20735 if (Decl && Decl->isFileVarDecl()) {
20736 AnalysisWarnings.registerVarDeclWarning(
20737 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20738 return true;
20739 }
20740
20741 Diag(Loc, PD);
20742 return true;
20743}
20744
20745/// Emit a diagnostic that describes an effect on the run-time behavior
20746/// of the program being compiled.
20747///
20748/// This routine emits the given diagnostic when the code currently being
20749/// type-checked is "potentially evaluated", meaning that there is a
20750/// possibility that the code will actually be executable. Code in sizeof()
20751/// expressions, code used only during overload resolution, etc., are not
20752/// potentially evaluated. This routine will suppress such diagnostics or,
20753/// in the absolutely nutty case of potentially potentially evaluated
20754/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20755/// later.
20756///
20757/// This routine should be used for all diagnostics that describe the run-time
20758/// behavior of a program, such as passing a non-POD value through an ellipsis.
20759/// Failure to do so will likely result in spurious diagnostics or failures
20760/// during overload resolution or within sizeof/alignof/typeof/typeid.
20762 const PartialDiagnostic &PD) {
20763
20764 if (ExprEvalContexts.back().isDiscardedStatementContext())
20765 return false;
20766
20767 switch (ExprEvalContexts.back().Context) {
20772 // The argument will never be evaluated, so don't complain.
20773 break;
20774
20777 // Relevant diagnostics should be produced by constant evaluation.
20778 break;
20779
20782 return DiagIfReachable(Loc, Stmts, PD);
20783 }
20784
20785 return false;
20786}
20787
20789 const PartialDiagnostic &PD) {
20790 return DiagRuntimeBehavior(
20791 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20792 PD);
20793}
20794
20796 CallExpr *CE, FunctionDecl *FD) {
20797 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20798 return false;
20799
20800 // If we're inside a decltype's expression, don't check for a valid return
20801 // type or construct temporaries until we know whether this is the last call.
20802 if (ExprEvalContexts.back().ExprContext ==
20804 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20805 return false;
20806 }
20807
20808 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20809 FunctionDecl *FD;
20810 CallExpr *CE;
20811
20812 public:
20813 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20814 : FD(FD), CE(CE) { }
20815
20816 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20817 if (!FD) {
20818 S.Diag(Loc, diag::err_call_incomplete_return)
20819 << T << CE->getSourceRange();
20820 return;
20821 }
20822
20823 S.Diag(Loc, diag::err_call_function_incomplete_return)
20824 << CE->getSourceRange() << FD << T;
20825 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20826 << FD->getDeclName();
20827 }
20828 } Diagnoser(FD, CE);
20829
20830 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20831 return true;
20832
20833 return false;
20834}
20835
20836// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20837// will prevent this condition from triggering, which is what we want.
20839 SourceLocation Loc;
20840
20841 unsigned diagnostic = diag::warn_condition_is_assignment;
20842 bool IsOrAssign = false;
20843
20844 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20845 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20846 return;
20847
20848 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20849
20850 // Greylist some idioms by putting them into a warning subcategory.
20851 if (ObjCMessageExpr *ME
20852 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20853 Selector Sel = ME->getSelector();
20854
20855 // self = [<foo> init...]
20856 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20857 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20858
20859 // <foo> = [<bar> nextObject]
20860 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20861 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20862 }
20863
20864 Loc = Op->getOperatorLoc();
20865 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20866 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20867 return;
20868
20869 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20870 Loc = Op->getOperatorLoc();
20871 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20872 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20873 else {
20874 // Not an assignment.
20875 return;
20876 }
20877
20878 Diag(Loc, diagnostic) << E->getSourceRange();
20879
20882 Diag(Loc, diag::note_condition_assign_silence)
20884 << FixItHint::CreateInsertion(Close, ")");
20885
20886 if (IsOrAssign)
20887 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20888 << FixItHint::CreateReplacement(Loc, "!=");
20889 else
20890 Diag(Loc, diag::note_condition_assign_to_comparison)
20891 << FixItHint::CreateReplacement(Loc, "==");
20892}
20893
20895 // Don't warn if the parens came from a macro.
20896 SourceLocation parenLoc = ParenE->getBeginLoc();
20897 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20898 return;
20899 // Don't warn for dependent expressions.
20900 if (ParenE->isTypeDependent())
20901 return;
20902
20903 Expr *E = ParenE->IgnoreParens();
20904 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20905 return;
20906
20907 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20908 if (opE->getOpcode() == BO_EQ &&
20909 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20910 == Expr::MLV_Valid) {
20911 SourceLocation Loc = opE->getOperatorLoc();
20912
20913 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20914 SourceRange ParenERange = ParenE->getSourceRange();
20915 Diag(Loc, diag::note_equality_comparison_silence)
20916 << FixItHint::CreateRemoval(ParenERange.getBegin())
20917 << FixItHint::CreateRemoval(ParenERange.getEnd());
20918 Diag(Loc, diag::note_equality_comparison_to_assign)
20919 << FixItHint::CreateReplacement(Loc, "=");
20920 }
20921}
20922
20924 bool IsConstexpr) {
20926 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20928
20929 ExprResult result = CheckPlaceholderExpr(E);
20930 if (result.isInvalid()) return ExprError();
20931 E = result.get();
20932
20933 if (!E->isTypeDependent()) {
20934 if (getLangOpts().CPlusPlus)
20935 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20936
20938 if (ERes.isInvalid())
20939 return ExprError();
20940 E = ERes.get();
20941
20942 QualType T = E->getType();
20943 if (!T->isScalarType()) { // C99 6.8.4.1p1
20944 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20945 << T << E->getSourceRange();
20946 return ExprError();
20947 }
20948 CheckBoolLikeConversion(E, Loc);
20949 }
20950
20951 return E;
20952}
20953
20955 Expr *SubExpr, ConditionKind CK,
20956 bool MissingOK) {
20957 // MissingOK indicates whether having no condition expression is valid
20958 // (for loop) or invalid (e.g. while loop).
20959 if (!SubExpr)
20960 return MissingOK ? ConditionResult() : ConditionError();
20961
20963 switch (CK) {
20965 Cond = CheckBooleanCondition(Loc, SubExpr);
20966 break;
20967
20969 // Note: this might produce a FullExpr
20970 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20971 break;
20972
20974 Cond = CheckSwitchCondition(Loc, SubExpr);
20975 break;
20976 }
20977 if (Cond.isInvalid()) {
20978 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20979 {SubExpr}, PreferredConditionType(CK));
20980 if (!Cond.get())
20981 return ConditionError();
20982 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
20983 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
20984
20985 if (!Cond.isUsable())
20986 return ConditionError();
20987
20988 return ConditionResult(*this, nullptr, Cond,
20990}
20991
20992namespace {
20993 /// A visitor for rebuilding a call to an __unknown_any expression
20994 /// to have an appropriate type.
20995 struct RebuildUnknownAnyFunction
20996 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20997
20998 Sema &S;
20999
21000 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21001
21002 ExprResult VisitStmt(Stmt *S) {
21003 llvm_unreachable("unexpected statement!");
21004 }
21005
21006 ExprResult VisitExpr(Expr *E) {
21007 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21008 << E->getSourceRange();
21009 return ExprError();
21010 }
21011
21012 /// Rebuild an expression which simply semantically wraps another
21013 /// expression which it shares the type and value kind of.
21014 template <class T> ExprResult rebuildSugarExpr(T *E) {
21015 ExprResult SubResult = Visit(E->getSubExpr());
21016 if (SubResult.isInvalid()) return ExprError();
21017
21018 Expr *SubExpr = SubResult.get();
21019 E->setSubExpr(SubExpr);
21020 E->setType(SubExpr->getType());
21021 E->setValueKind(SubExpr->getValueKind());
21022 assert(E->getObjectKind() == OK_Ordinary);
21023 return E;
21024 }
21025
21026 ExprResult VisitParenExpr(ParenExpr *E) {
21027 return rebuildSugarExpr(E);
21028 }
21029
21030 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21031 return rebuildSugarExpr(E);
21032 }
21033
21034 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21035 ExprResult SubResult = Visit(E->getSubExpr());
21036 if (SubResult.isInvalid()) return ExprError();
21037
21038 Expr *SubExpr = SubResult.get();
21039 E->setSubExpr(SubExpr);
21040 E->setType(S.Context.getPointerType(SubExpr->getType()));
21041 assert(E->isPRValue());
21042 assert(E->getObjectKind() == OK_Ordinary);
21043 return E;
21044 }
21045
21046 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21047 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21048
21049 E->setType(VD->getType());
21050
21051 assert(E->isPRValue());
21052 if (S.getLangOpts().CPlusPlus &&
21053 !(isa<CXXMethodDecl>(VD) &&
21054 cast<CXXMethodDecl>(VD)->isInstance()))
21056
21057 return E;
21058 }
21059
21060 ExprResult VisitMemberExpr(MemberExpr *E) {
21061 return resolveDecl(E, E->getMemberDecl());
21062 }
21063
21064 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21065 return resolveDecl(E, E->getDecl());
21066 }
21067 };
21068}
21069
21070/// Given a function expression of unknown-any type, try to rebuild it
21071/// to have a function type.
21073 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21074 if (Result.isInvalid()) return ExprError();
21075 return S.DefaultFunctionArrayConversion(Result.get());
21076}
21077
21078namespace {
21079 /// A visitor for rebuilding an expression of type __unknown_anytype
21080 /// into one which resolves the type directly on the referring
21081 /// expression. Strict preservation of the original source
21082 /// structure is not a goal.
21083 struct RebuildUnknownAnyExpr
21084 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21085
21086 Sema &S;
21087
21088 /// The current destination type.
21089 QualType DestType;
21090
21091 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21092 : S(S), DestType(CastType) {}
21093
21094 ExprResult VisitStmt(Stmt *S) {
21095 llvm_unreachable("unexpected statement!");
21096 }
21097
21098 ExprResult VisitExpr(Expr *E) {
21099 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21100 << E->getSourceRange();
21101 return ExprError();
21102 }
21103
21104 ExprResult VisitCallExpr(CallExpr *E);
21105 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21106
21107 /// Rebuild an expression which simply semantically wraps another
21108 /// expression which it shares the type and value kind of.
21109 template <class T> ExprResult rebuildSugarExpr(T *E) {
21110 ExprResult SubResult = Visit(E->getSubExpr());
21111 if (SubResult.isInvalid()) return ExprError();
21112 Expr *SubExpr = SubResult.get();
21113 E->setSubExpr(SubExpr);
21114 E->setType(SubExpr->getType());
21115 E->setValueKind(SubExpr->getValueKind());
21116 assert(E->getObjectKind() == OK_Ordinary);
21117 return E;
21118 }
21119
21120 ExprResult VisitParenExpr(ParenExpr *E) {
21121 return rebuildSugarExpr(E);
21122 }
21123
21124 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21125 return rebuildSugarExpr(E);
21126 }
21127
21128 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21129 const PointerType *Ptr = DestType->getAs<PointerType>();
21130 if (!Ptr) {
21131 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21132 << E->getSourceRange();
21133 return ExprError();
21134 }
21135
21136 if (isa<CallExpr>(E->getSubExpr())) {
21137 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21138 << E->getSourceRange();
21139 return ExprError();
21140 }
21141
21142 assert(E->isPRValue());
21143 assert(E->getObjectKind() == OK_Ordinary);
21144 E->setType(DestType);
21145
21146 // Build the sub-expression as if it were an object of the pointee type.
21147 DestType = Ptr->getPointeeType();
21148 ExprResult SubResult = Visit(E->getSubExpr());
21149 if (SubResult.isInvalid()) return ExprError();
21150 E->setSubExpr(SubResult.get());
21151 return E;
21152 }
21153
21154 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21155
21156 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21157
21158 ExprResult VisitMemberExpr(MemberExpr *E) {
21159 return resolveDecl(E, E->getMemberDecl());
21160 }
21161
21162 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21163 return resolveDecl(E, E->getDecl());
21164 }
21165 };
21166}
21167
21168/// Rebuilds a call expression which yielded __unknown_anytype.
21169ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21170 Expr *CalleeExpr = E->getCallee();
21171
21172 enum FnKind {
21173 FK_MemberFunction,
21174 FK_FunctionPointer,
21175 FK_BlockPointer
21176 };
21177
21178 FnKind Kind;
21179 QualType CalleeType = CalleeExpr->getType();
21180 if (CalleeType == S.Context.BoundMemberTy) {
21182 Kind = FK_MemberFunction;
21183 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21184 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21185 CalleeType = Ptr->getPointeeType();
21186 Kind = FK_FunctionPointer;
21187 } else {
21188 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21189 Kind = FK_BlockPointer;
21190 }
21191 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21192
21193 // Verify that this is a legal result type of a function.
21194 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21195 DestType->isFunctionType()) {
21196 unsigned diagID = diag::err_func_returning_array_function;
21197 if (Kind == FK_BlockPointer)
21198 diagID = diag::err_block_returning_array_function;
21199
21200 S.Diag(E->getExprLoc(), diagID)
21201 << DestType->isFunctionType() << DestType;
21202 return ExprError();
21203 }
21204
21205 // Otherwise, go ahead and set DestType as the call's result.
21206 E->setType(DestType.getNonLValueExprType(S.Context));
21208 assert(E->getObjectKind() == OK_Ordinary);
21209
21210 // Rebuild the function type, replacing the result type with DestType.
21211 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21212 if (Proto) {
21213 // __unknown_anytype(...) is a special case used by the debugger when
21214 // it has no idea what a function's signature is.
21215 //
21216 // We want to build this call essentially under the K&R
21217 // unprototyped rules, but making a FunctionNoProtoType in C++
21218 // would foul up all sorts of assumptions. However, we cannot
21219 // simply pass all arguments as variadic arguments, nor can we
21220 // portably just call the function under a non-variadic type; see
21221 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21222 // However, it turns out that in practice it is generally safe to
21223 // call a function declared as "A foo(B,C,D);" under the prototype
21224 // "A foo(B,C,D,...);". The only known exception is with the
21225 // Windows ABI, where any variadic function is implicitly cdecl
21226 // regardless of its normal CC. Therefore we change the parameter
21227 // types to match the types of the arguments.
21228 //
21229 // This is a hack, but it is far superior to moving the
21230 // corresponding target-specific code from IR-gen to Sema/AST.
21231
21232 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21233 SmallVector<QualType, 8> ArgTypes;
21234 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21235 ArgTypes.reserve(E->getNumArgs());
21236 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21237 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21238 }
21239 ParamTypes = ArgTypes;
21240 }
21241 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21242 Proto->getExtProtoInfo());
21243 } else {
21244 DestType = S.Context.getFunctionNoProtoType(DestType,
21245 FnType->getExtInfo());
21246 }
21247
21248 // Rebuild the appropriate pointer-to-function type.
21249 switch (Kind) {
21250 case FK_MemberFunction:
21251 // Nothing to do.
21252 break;
21253
21254 case FK_FunctionPointer:
21255 DestType = S.Context.getPointerType(DestType);
21256 break;
21257
21258 case FK_BlockPointer:
21259 DestType = S.Context.getBlockPointerType(DestType);
21260 break;
21261 }
21262
21263 // Finally, we can recurse.
21264 ExprResult CalleeResult = Visit(CalleeExpr);
21265 if (!CalleeResult.isUsable()) return ExprError();
21266 E->setCallee(CalleeResult.get());
21267
21268 // Bind a temporary if necessary.
21269 return S.MaybeBindToTemporary(E);
21270}
21271
21272ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21273 // Verify that this is a legal result type of a call.
21274 if (DestType->isArrayType() || DestType->isFunctionType()) {
21275 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21276 << DestType->isFunctionType() << DestType;
21277 return ExprError();
21278 }
21279
21280 // Rewrite the method result type if available.
21281 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21282 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21283 Method->setReturnType(DestType);
21284 }
21285
21286 // Change the type of the message.
21287 E->setType(DestType.getNonReferenceType());
21289
21290 return S.MaybeBindToTemporary(E);
21291}
21292
21293ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21294 // The only case we should ever see here is a function-to-pointer decay.
21295 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21296 assert(E->isPRValue());
21297 assert(E->getObjectKind() == OK_Ordinary);
21298
21299 E->setType(DestType);
21300
21301 // Rebuild the sub-expression as the pointee (function) type.
21302 DestType = DestType->castAs<PointerType>()->getPointeeType();
21303
21304 ExprResult Result = Visit(E->getSubExpr());
21305 if (!Result.isUsable()) return ExprError();
21306
21307 E->setSubExpr(Result.get());
21308 return E;
21309 } else if (E->getCastKind() == CK_LValueToRValue) {
21310 assert(E->isPRValue());
21311 assert(E->getObjectKind() == OK_Ordinary);
21312
21313 assert(isa<BlockPointerType>(E->getType()));
21314
21315 E->setType(DestType);
21316
21317 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21318 DestType = S.Context.getLValueReferenceType(DestType);
21319
21320 ExprResult Result = Visit(E->getSubExpr());
21321 if (!Result.isUsable()) return ExprError();
21322
21323 E->setSubExpr(Result.get());
21324 return E;
21325 } else {
21326 llvm_unreachable("Unhandled cast type!");
21327 }
21328}
21329
21330ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21331 ExprValueKind ValueKind = VK_LValue;
21332 QualType Type = DestType;
21333
21334 // We know how to make this work for certain kinds of decls:
21335
21336 // - functions
21337 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21338 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21339 DestType = Ptr->getPointeeType();
21340 ExprResult Result = resolveDecl(E, VD);
21341 if (Result.isInvalid()) return ExprError();
21342 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21343 VK_PRValue);
21344 }
21345
21346 if (!Type->isFunctionType()) {
21347 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21348 << VD << E->getSourceRange();
21349 return ExprError();
21350 }
21351 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21352 // We must match the FunctionDecl's type to the hack introduced in
21353 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21354 // type. See the lengthy commentary in that routine.
21355 QualType FDT = FD->getType();
21356 const FunctionType *FnType = FDT->castAs<FunctionType>();
21357 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21358 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21359 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21360 SourceLocation Loc = FD->getLocation();
21361 FunctionDecl *NewFD = FunctionDecl::Create(
21362 S.Context, FD->getDeclContext(), Loc, Loc,
21363 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21365 false /*isInlineSpecified*/, FD->hasPrototype(),
21366 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21367
21368 if (FD->getQualifier())
21369 NewFD->setQualifierInfo(FD->getQualifierLoc());
21370
21371 SmallVector<ParmVarDecl*, 16> Params;
21372 for (const auto &AI : FT->param_types()) {
21373 ParmVarDecl *Param =
21374 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21375 Param->setScopeInfo(0, Params.size());
21376 Params.push_back(Param);
21377 }
21378 NewFD->setParams(Params);
21379 DRE->setDecl(NewFD);
21380 VD = DRE->getDecl();
21381 }
21382 }
21383
21384 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21385 if (MD->isInstance()) {
21386 ValueKind = VK_PRValue;
21388 }
21389
21390 // Function references aren't l-values in C.
21391 if (!S.getLangOpts().CPlusPlus)
21392 ValueKind = VK_PRValue;
21393
21394 // - variables
21395 } else if (isa<VarDecl>(VD)) {
21396 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21397 Type = RefTy->getPointeeType();
21398 } else if (Type->isFunctionType()) {
21399 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21400 << VD << E->getSourceRange();
21401 return ExprError();
21402 }
21403
21404 // - nothing else
21405 } else {
21406 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21407 << VD << E->getSourceRange();
21408 return ExprError();
21409 }
21410
21411 // Modifying the declaration like this is friendly to IR-gen but
21412 // also really dangerous.
21413 VD->setType(DestType);
21414 E->setType(Type);
21415 E->setValueKind(ValueKind);
21416 return E;
21417}
21418
21421 ExprValueKind &VK, CXXCastPath &Path) {
21422 // The type we're casting to must be either void or complete.
21423 if (!CastType->isVoidType() &&
21425 diag::err_typecheck_cast_to_incomplete))
21426 return ExprError();
21427
21428 // Rewrite the casted expression from scratch.
21429 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21430 if (!result.isUsable()) return ExprError();
21431
21432 CastExpr = result.get();
21434 CastKind = CK_NoOp;
21435
21436 return CastExpr;
21437}
21438
21440 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21441}
21442
21444 Expr *arg, QualType &paramType) {
21445 // If the syntactic form of the argument is not an explicit cast of
21446 // any sort, just do default argument promotion.
21447 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21448 if (!castArg) {
21450 if (result.isInvalid()) return ExprError();
21451 paramType = result.get()->getType();
21452 return result;
21453 }
21454
21455 // Otherwise, use the type that was written in the explicit cast.
21456 assert(!arg->hasPlaceholderType());
21457 paramType = castArg->getTypeAsWritten();
21458
21459 // Copy-initialize a parameter of that type.
21460 InitializedEntity entity =
21462 /*consumed*/ false);
21463 return PerformCopyInitialization(entity, callLoc, arg);
21464}
21465
21467 Expr *orig = E;
21468 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21469 while (true) {
21470 E = E->IgnoreParenImpCasts();
21471 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21472 E = call->getCallee();
21473 diagID = diag::err_uncasted_call_of_unknown_any;
21474 } else {
21475 break;
21476 }
21477 }
21478
21479 SourceLocation loc;
21480 NamedDecl *d;
21481 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21482 loc = ref->getLocation();
21483 d = ref->getDecl();
21484 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21485 loc = mem->getMemberLoc();
21486 d = mem->getMemberDecl();
21487 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21488 diagID = diag::err_uncasted_call_of_unknown_any;
21489 loc = msg->getSelectorStartLoc();
21490 d = msg->getMethodDecl();
21491 if (!d) {
21492 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21493 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21494 << orig->getSourceRange();
21495 return ExprError();
21496 }
21497 } else {
21498 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21499 << E->getSourceRange();
21500 return ExprError();
21501 }
21502
21503 S.Diag(loc, diagID) << d << orig->getSourceRange();
21504
21505 // Never recoverable.
21506 return ExprError();
21507}
21508
21510 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21511 if (!placeholderType) return E;
21512
21513 switch (placeholderType->getKind()) {
21514 case BuiltinType::UnresolvedTemplate: {
21515 auto *ULE = cast<UnresolvedLookupExpr>(E);
21516 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21517 // There's only one FoundDecl for UnresolvedTemplate type. See
21518 // BuildTemplateIdExpr.
21519 NamedDecl *Temp = *ULE->decls_begin();
21520 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21521
21522 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21523 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21524 // as it models only the unqualified-id case, where this case can clearly be
21525 // qualified. Thus we can't just qualify an assumed template.
21526 TemplateName TN;
21527 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21528 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21529 TemplateName(TD));
21530 else
21531 TN = Context.getAssumedTemplateName(NameInfo.getName());
21532
21533 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21534 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21535 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21536 << IsTypeAliasTemplateDecl;
21537
21538 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21539 bool HasAnyDependentTA = false;
21540 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21541 HasAnyDependentTA |= Arg.getArgument().isDependent();
21542 TAL.addArgument(Arg);
21543 }
21544
21545 QualType TST;
21546 {
21547 SFINAETrap Trap(*this);
21548 TST = CheckTemplateIdType(
21549 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21550 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21551 }
21552 if (TST.isNull())
21553 TST = Context.getTemplateSpecializationType(
21554 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21555 /*CanonicalArgs=*/{},
21556 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21557 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21558 TST);
21559 }
21560
21561 // Overloaded expressions.
21562 case BuiltinType::Overload: {
21563 // Try to resolve a single function template specialization.
21564 // This is obligatory.
21565 ExprResult Result = E;
21567 return Result;
21568
21569 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21570 // leaves Result unchanged on failure.
21571 Result = E;
21573 return Result;
21574
21575 // If that failed, try to recover with a call.
21576 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21577 /*complain*/ true);
21578 return Result;
21579 }
21580
21581 // Bound member functions.
21582 case BuiltinType::BoundMember: {
21583 ExprResult result = E;
21584 const Expr *BME = E->IgnoreParens();
21585 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21586 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21588 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21589 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21590 if (ME->getMemberNameInfo().getName().getNameKind() ==
21592 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21593 }
21594 tryToRecoverWithCall(result, PD,
21595 /*complain*/ true);
21596 return result;
21597 }
21598
21599 // ARC unbridged casts.
21600 case BuiltinType::ARCUnbridgedCast: {
21601 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21602 ObjC().diagnoseARCUnbridgedCast(realCast);
21603 return realCast;
21604 }
21605
21606 // Expressions of unknown type.
21607 case BuiltinType::UnknownAny:
21608 return diagnoseUnknownAnyExpr(*this, E);
21609
21610 // Pseudo-objects.
21611 case BuiltinType::PseudoObject:
21612 return PseudoObject().checkRValue(E);
21613
21614 case BuiltinType::BuiltinFn: {
21615 // Accept __noop without parens by implicitly converting it to a call expr.
21616 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21617 if (DRE) {
21618 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21619 unsigned BuiltinID = FD->getBuiltinID();
21620 if (BuiltinID == Builtin::BI__noop) {
21621 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21622 CK_BuiltinFnToFnPtr)
21623 .get();
21624 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21627 }
21628
21629 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21630 // Any use of these other than a direct call is ill-formed as of C++20,
21631 // because they are not addressable functions. In earlier language
21632 // modes, warn and force an instantiation of the real body.
21633 Diag(E->getBeginLoc(),
21635 ? diag::err_use_of_unaddressable_function
21636 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21637 if (FD->isImplicitlyInstantiable()) {
21638 // Require a definition here because a normal attempt at
21639 // instantiation for a builtin will be ignored, and we won't try
21640 // again later. We assume that the definition of the template
21641 // precedes this use.
21643 /*Recursive=*/false,
21644 /*DefinitionRequired=*/true,
21645 /*AtEndOfTU=*/false);
21646 }
21647 // Produce a properly-typed reference to the function.
21648 CXXScopeSpec SS;
21649 SS.Adopt(DRE->getQualifierLoc());
21650 TemplateArgumentListInfo TemplateArgs;
21651 DRE->copyTemplateArgumentsInto(TemplateArgs);
21652 return BuildDeclRefExpr(
21653 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21654 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21655 DRE->getTemplateKeywordLoc(),
21656 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21657 }
21658 }
21659
21660 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21661 return ExprError();
21662 }
21663
21664 case BuiltinType::IncompleteMatrixIdx: {
21665 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21666 // At this point, we know there was no second [] to complete the operator.
21667 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21668 if (getLangOpts().HLSL) {
21670 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21671 }
21672 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21673 return ExprError();
21674 }
21675
21676 // Expressions of unknown type.
21677 case BuiltinType::ArraySection:
21678 // If we've already diagnosed something on the array section type, we
21679 // shouldn't need to do any further diagnostic here.
21680 if (!E->containsErrors())
21681 Diag(E->getBeginLoc(), diag::err_array_section_use)
21682 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21683 return ExprError();
21684
21685 // Expressions of unknown type.
21686 case BuiltinType::OMPArrayShaping:
21687 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21688
21689 case BuiltinType::OMPIterator:
21690 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21691
21692 // Everything else should be impossible.
21693#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21694 case BuiltinType::Id:
21695#include "clang/Basic/OpenCLImageTypes.def"
21696#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21697 case BuiltinType::Id:
21698#include "clang/Basic/OpenCLExtensionTypes.def"
21699#define SVE_TYPE(Name, Id, SingletonId) \
21700 case BuiltinType::Id:
21701#include "clang/Basic/AArch64ACLETypes.def"
21702#define PPC_VECTOR_TYPE(Name, Id, Size) \
21703 case BuiltinType::Id:
21704#include "clang/Basic/PPCTypes.def"
21705#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21706#include "clang/Basic/RISCVVTypes.def"
21707#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21708#include "clang/Basic/WebAssemblyReferenceTypes.def"
21709#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21710#include "clang/Basic/AMDGPUTypes.def"
21711#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21712#include "clang/Basic/HLSLIntangibleTypes.def"
21713#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21714#define PLACEHOLDER_TYPE(Id, SingletonId)
21715#include "clang/AST/BuiltinTypes.def"
21716 break;
21717 }
21718
21719 llvm_unreachable("invalid placeholder type!");
21720}
21721
21723 if (E->isTypeDependent())
21724 return true;
21726 return E->getType()->isIntegralOrEnumerationType();
21727 return false;
21728}
21729
21731 ArrayRef<Expr *> SubExprs, QualType T) {
21732 if (!Context.getLangOpts().RecoveryAST)
21733 return ExprError();
21734
21735 if (isSFINAEContext())
21736 return ExprError();
21737
21738 if (T.isNull() || T->isUndeducedType() ||
21739 !Context.getLangOpts().RecoveryASTType)
21740 // We don't know the concrete type, fallback to dependent type.
21741 T = Context.DependentTy;
21742
21743 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21744}
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:2702
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Token Tok
The Token.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:49
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstMethod
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp: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:558
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:583
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:489
bool hasValue() const
Definition APValue.h:465
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:794
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:790
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:912
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:909
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:4550
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2776
Wrapper for source info for arrays.
Definition TypeLoc.h:1749
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3737
QualType getElementType() const
Definition TypeBase.h:3735
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6685
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:4453
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
Expr * getLHS() const
Definition Expr.h:4088
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4132
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2179
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4138
StringRef getOpcodeStr() const
Definition Expr.h:4104
bool isRelationalOp() const
Definition Expr.h:4133
SourceLocation getOperatorLoc() const
Definition Expr.h:4080
bool isMultiplicativeOp() const
Definition Expr.h:4123
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
bool isShiftOp() const
Definition Expr.h:4127
Expr * getRHS() const
Definition Expr.h:4090
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:4982
bool isBitwiseOp() const
Definition Expr.h:4130
bool isAdditiveOp() const
Definition Expr.h:4125
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4174
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4179
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:2204
Opcode getOpcode() const
Definition Expr.h:4083
bool isAssignmentOp() const
Definition Expr.h:4177
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2141
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4135
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4129
BinaryOperatorKind Opcode
Definition Expr.h:4043
A binding in a decomposition declaration.
Definition DeclCXX.h:4181
A class which contains all the information about a particular captured value.
Definition Decl.h:4677
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4671
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5441
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4753
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4810
void setIsVariadic(bool value)
Definition Decl.h:4747
SourceLocation getCaretLocation() const
Definition Decl.h:4744
void setBody(CompoundStmt *B)
Definition Decl.h:4751
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4757
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5452
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5640
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6624
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
bool isSVEBool() const
Definition TypeBase.h:3242
Kind getKind() const
Definition TypeBase.h:3213
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:1956
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3237
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1270
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:1377
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1093
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isVirtual() const
Definition DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition DeclCXX.cpp:2508
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:152
SourceRange getSourceRange() const
Definition ExprCXX.h:164
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1987
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2745
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:600
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2075
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1154
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3160
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:1516
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3126
Expr * getCallee()
Definition Expr.h:3090
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3166
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
void setCallee(Expr *F)
Definition Expr.h:3092
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:3676
CastKind getCastKind() const
Definition Expr.h:3720
const char * getCastKindName() const
Definition Expr.h:3724
void setSubExpr(Expr *E)
Definition Expr.h:3728
Expr * getSubExpr()
Definition Expr.h:3726
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1629
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4848
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3276
QualType getElementType() const
Definition TypeBase.h:3286
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:5004
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3605
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:4391
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3837
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1082
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:301
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:377
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1132
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
bool isImmediateInvocation() const
Definition Expr.h:1154
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
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:1446
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isRequiresExprBody() const
Definition DeclBase.h:2194
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1381
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1425
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1371
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:543
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1429
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1342
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1397
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:487
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1359
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:775
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:590
bool 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:2011
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:845
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
DeclaratorContext getContext() const
Definition DeclSpec.h:2046
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isInvalidType() const
Definition DeclSpec.h:2688
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:723
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5126
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4183
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3928
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3955
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:299
@ LV_ClassTemporary
Definition Expr.h:298
@ LV_MemberFunction
Definition Expr.h:296
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3116
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3045
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:3094
void setType(QualType t)
Definition Expr.h:145
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3098
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:3085
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:3338
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:827
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
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:3069
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:817
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4047
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
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:4299
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
isModifiableLvalueResult
Definition Expr.h:304
@ MLV_DuplicateVectorComponents
Definition Expr.h:308
@ MLV_LValueCast
Definition Expr.h:310
@ MLV_InvalidMessageExpression
Definition Expr.h:319
@ MLV_ConstQualifiedField
Definition Expr.h:313
@ MLV_InvalidExpression
Definition Expr.h:309
@ MLV_IncompleteType
Definition Expr.h:311
@ MLV_Valid
Definition Expr.h:305
@ MLV_ConstQualified
Definition Expr.h:312
@ MLV_NoSetterProperty
Definition Expr.h:316
@ MLV_ArrayTemporary
Definition Expr.h:321
@ MLV_SubObjCPropertySetting
Definition Expr.h:318
@ MLV_ConstAddrSpace
Definition Expr.h:314
@ MLV_MemberFunction
Definition Expr.h:317
@ MLV_NotObjectType
Definition Expr.h:306
@ MLV_ArrayType
Definition Expr.h:315
@ MLV_ClassTemporary
Definition Expr.h:320
@ MLV_IncompleteVoidType
Definition Expr.h:307
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:455
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:136
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6564
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
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:996
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1075
const Expr * getSubExpr() const
Definition Expr.h:1062
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition Decl.h:2000
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3847
bool isImmediateFunction() const
Definition Decl.cpp:3340
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4024
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3762
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
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:3618
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3311
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:4130
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:3199
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4040
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:4841
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4870
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5773
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5576
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5787
unsigned getNumParams() const
Definition TypeBase.h:5547
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5709
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1688
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1694
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1640
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1697
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1632
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4576
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4504
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4813
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3572
QualType getReturnType() const
Definition TypeBase.h:4805
bool getCmseNSCallAttr() const
Definition TypeBase.h:4819
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4833
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4923
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:4604
One of these records is kept for each identifier that is lexed.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1731
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3853
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
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:5299
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:974
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:1968
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:1030
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
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4394
MS property subscript expression.
Definition ExprCXX.h:1006
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:2795
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2865
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4338
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4352
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3553
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
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:1749
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3582
Expr * getBase() const
Definition Expr.h:3441
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1793
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:7864
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:7920
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1841
qual_range quals() const
Definition TypeBase.h:8039
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:1652
Helper class for OffsetOfExpr.
Definition Expr.h:2421
void * getAsOpaquePtr() const
Definition Ownership.h:91
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h: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:3128
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3189
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2203
const Expr * getSubExpr() const
Definition Expr.h:2199
bool isProducedByFoldExpansion() const
Definition Expr.h:2224
Expr * getExpr(unsigned Init)
Definition Expr.h:6112
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4854
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6110
SourceLocation getLParenLoc() const
Definition Expr.h:6125
SourceLocation getRParenLoc() const
Definition Expr.h:6126
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:2957
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:632
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:672
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6756
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8386
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8391
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:3556
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2921
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1416
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8302
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8428
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:8342
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:2703
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8487
QualType getCanonicalType() const
Definition TypeBase.h:8354
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8396
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2940
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8494
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8375
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1671
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8359
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2695
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:8467
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8334
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:4324
bool hasFlexibleArrayMember() const
Definition Decl.h:4357
field_iterator field_end() const
Definition Decl.h:4530
field_range fields() const
Definition Decl.h:4527
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5340
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:3574
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:1749
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:811
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:987
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:120
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:855
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition SemaOpenMP.h:377
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8474
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12480
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12524
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7743
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:856
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:8227
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13601
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1121
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:8277
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8195
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:935
bool isAttrContext() const
Definition Sema.h:6976
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:8270
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9357
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9396
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9365
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:412
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:1508
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:1231
SemaCUDA & CUDA()
Definition Sema.h:1448
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:7864
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7866
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7865
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:8215
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:8357
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1224
Preprocessor & getPreprocessor() const
Definition Sema.h:926
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6954
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2318
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:8346
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8258
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:6783
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:2052
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6966
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:1660
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:834
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:1288
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:8182
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:924
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:1493
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:2828
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:755
bool isImmediateFunctionContext() const
Definition Sema.h:8207
ASTContext & getASTContext() const
Definition Sema.h:927
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1061
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:765
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:884
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:6101
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6103
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:1192
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1665
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:11442
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:507
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:8242
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:922
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8340
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:14475
const LangOptions & getLangOpts() const
Definition Sema.h:920
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:2449
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:1498
ReuseLambdaContextDecl_t
Definition Sema.h:7042
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:1287
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:2127
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:1286
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:2564
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:953
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6527
SemaHLSL & HLSL()
Definition Sema.h:1458
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:15681
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:5263
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:6987
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6557
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:14023
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:849
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:1321
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:6984
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:2301
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:640
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:8211
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:8078
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2519
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1421
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:12551
SemaOpenCL & OpenCL()
Definition Sema.h:1503
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:14032
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:8203
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1640
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:6786
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:13967
SourceManager & getSourceManager() const
Definition Sema.h:925
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:7497
@ NTCUK_Destruct
Definition Sema.h:4106
@ NTCUK_Copy
Definition Sema.h:4107
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8356
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:2349
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:6784
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:13700
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....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15454
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:2504
bool isConstantEvaluatedContext() const
Definition Sema.h:2614
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:1289
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4665
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:6991
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:1326
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14015
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:6728
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6750
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6740
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6755
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6745
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6765
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6734
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6760
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6775
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:1247
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:8193
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:8343
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:1291
@ TemplateNameIsRequired
Definition Sema.h:11419
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:784
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:1290
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:921
FPOptions CurFPFeatures
Definition Sema.h:1284
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:516
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:1563
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:6561
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:2110
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:8001
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9410
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9416
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9408
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9413
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9424
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9420
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:6442
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14011
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:7850
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:1518
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2495
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:8219
SemaARM & ARM()
Definition Sema.h:1428
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:10985
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:8685
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:5017
SourceLocation getBeginLoc() const
Definition Expr.h:5062
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5058
SourceLocation getEndLoc() const
Definition Expr.h:5063
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5037
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:4595
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:362
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:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
unsigned getLength() const
Definition Expr.h:1909
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1187
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3815
bool isUnion() const
Definition Decl.h:3925
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:98
void startToken()
Reset all flags to cleared.
Definition Token.h:185
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:2707
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8273
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:8284
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:8965
bool isBlockPointerType() const
Definition TypeBase.h:8559
bool isVoidType() const
Definition TypeBase.h:8901
bool isBooleanType() const
Definition TypeBase.h:9031
bool isObjCBuiltinType() const
Definition TypeBase.h:8765
bool isMFloat8Type() const
Definition TypeBase.h:8926
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:1952
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9081
bool isIncompleteArrayType() const
Definition TypeBase.h:8646
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:8877
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:2116
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:9061
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:2067
bool isVoidPointerType() const
Definition Type.cpp:713
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:746
bool isArrayType() const
Definition TypeBase.h:8638
bool isCharType() const
Definition Type.cpp:2133
bool isFunctionPointerType() const
Definition TypeBase.h:8606
bool isArithmeticType() const
Definition Type.cpp:2338
bool isConstantMatrixType() const
Definition TypeBase.h:8706
bool isPointerType() const
Definition TypeBase.h:8539
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8945
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2574
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9188
bool isReferenceType() const
Definition TypeBase.h:8563
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:8985
bool isEnumeralType() const
Definition TypeBase.h:8670
bool isScalarType() const
Definition TypeBase.h:9003
bool isVariableArrayType() const
Definition TypeBase.h:8650
bool isSizelessBuiltinType() const
Definition Type.cpp:2532
bool isClkEventT() const
Definition TypeBase.h:8787
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2104
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8735
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:9019
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2292
bool isExtVectorType() const
Definition TypeBase.h:8682
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2169
bool isExtVectorBoolType() const
Definition TypeBase.h:8686
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isImageType() const
Definition TypeBase.h:8799
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:8895
bool isPipeType() const
Definition TypeBase.h:8806
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2791
bool isBitIntType() const
Definition TypeBase.h:8810
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8870
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8662
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAnyComplexType() const
Definition TypeBase.h:8674
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8957
bool isHalfType() const
Definition TypeBase.h:8905
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8973
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2365
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8883
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2244
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool isQueueT() const
Definition TypeBase.h:8791
bool isMemberPointerType() const
Definition TypeBase.h:8620
bool isAtomicType() const
Definition TypeBase.h:8727
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9044
bool isObjCIdType() const
Definition TypeBase.h:8747
bool isMatrixType() const
Definition TypeBase.h:8702
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:2801
bool isComplexIntegerType() const
Definition Type.cpp:731
bool isUnscopedEnumerationType() const
Definition Type.cpp:2126
bool isObjCObjectType() const
Definition TypeBase.h:8718
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5214
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9174
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5303
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9037
bool isHLSLResourceRecord() const
Definition Type.cpp:5363
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:8918
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8535
bool isObjCObjectPointerType() const
Definition TypeBase.h:8714
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2313
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:8999
bool isVectorType() const
Definition TypeBase.h:8678
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8741
bool isObjCClassType() const
Definition TypeBase.h:8753
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2922
@ STK_FloatingComplex
Definition TypeBase.h:2765
@ STK_ObjCObjectPointer
Definition TypeBase.h:2759
@ STK_IntegralComplex
Definition TypeBase.h:2764
@ STK_MemberPointer
Definition TypeBase.h:2760
bool isFloatingType() const
Definition Type.cpp:2305
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:2254
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2929
bool isAnyPointerType() const
Definition TypeBase.h:8547
bool isRealType() const
Definition Type.cpp:2327
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSubscriptableVectorType() const
Definition TypeBase.h:8698
bool isSamplerT() const
Definition TypeBase.h:8779
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9121
bool isNullPtrType() const
Definition TypeBase.h:8938
bool isRecordType() const
Definition TypeBase.h:8666
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5367
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:736
bool isUnicodeCharacterType() const
Definition Type.cpp:2189
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2355
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
void setSubExpr(Expr *E)
Definition Expr.h:2286
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2289
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1429
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5039
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4451
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1683
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition ExprCXX.cpp:1645
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:640
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4957
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:5576
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3635
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool hasInit() const
Definition Decl.cpp:2409
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2268
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:2497
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:2918
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:2386
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:2539
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:2811
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:2790
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2909
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3967
Expr * getSizeExpr() const
Definition TypeBase.h:3981
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
VectorKind getVectorKind() const
Definition TypeBase.h:4196
QualType getElementType() const
Definition TypeBase.h:4190
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:790
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:796
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:800
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isBlockCapture() const
Definition ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:668
bool isInvalid() const
Definition ScopeInfo.h:661
bool isThisCapture() const
Definition ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:695
bool isCopyCapture() const
Definition ScopeInfo.h:654
bool isNested() const
Definition ScopeInfo.h:659
Retains information about a captured region.
Definition ScopeInfo.h:816
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:831
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:758
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:771
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition ScopeInfo.h:1090
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
void addBlock(const BlockDecl *BD)
Definition ScopeInfo.h:493
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
bool lambdaCaptureShouldBeConst() const
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition ScopeInfo.h:992
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:998
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:953
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:35
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h: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:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ AS_none
Definition Specifiers.h:127
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CR_OpenMP
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_None
Definition Specifiers.h:250
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
ExprResult ExprEmpty()
Definition Ownership.h:272
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h: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:775
@ 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:754
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:744
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:771
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:758
@ 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:767
@ 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
@ 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:750
@ 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:762
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:149
@ 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:1763
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4146
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4155
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4140
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4143
@ Neon
is ARM Neon vector
Definition TypeBase.h:4149
@ Generic
not a target-specific vector type
Definition TypeBase.h:4137
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4161
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4164
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4158
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:5004
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5889
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
PredefinedIdentKind
Definition Expr.h:1989
@ Implicit
An implicit conversion.
Definition Sema.h:440
CharacterLiteralKind
Definition Expr.h:1603
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:180
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5093
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:617
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5354
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13145
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6790
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6825
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6876
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6810
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6830
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:6838
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6834
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6844
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:6805
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6852
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6795
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6792
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6799
Abstract class used to diagnose incomplete types.
Definition Sema.h:8284
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.