clang 22.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attrs.inc"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
33#include "clang/AST/Type.h"
34#include "clang/AST/TypeLoc.h"
45#include "clang/Sema/DeclSpec.h"
50#include "clang/Sema/Lookup.h"
51#include "clang/Sema/Overload.h"
53#include "clang/Sema/Scope.h"
55#include "clang/Sema/SemaARM.h"
56#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaHLSL.h"
59#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/Template.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/ConvertUTF.h"
66#include "llvm/Support/SaveAndRestore.h"
67#include "llvm/Support/TimeProfiler.h"
68#include "llvm/Support/TypeSize.h"
69#include <limits>
70#include <optional>
71
72using namespace clang;
73using namespace sema;
74
75bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
76 // See if this is an auto-typed variable whose initializer we are parsing.
77 if (ParsingInitForAutoVars.count(D))
78 return false;
79
80 // See if this is a deleted function.
81 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
82 if (FD->isDeleted())
83 return false;
84
85 // If the function has a deduced return type, and we can't deduce it,
86 // then we can't use it either.
87 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
88 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
89 return false;
90
91 // See if this is an aligned allocation/deallocation function that is
92 // unavailable.
93 if (TreatUnavailableAsInvalid &&
95 return false;
96 }
97
98 // See if this function is unavailable.
99 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
100 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
101 return false;
102
103 if (isa<UnresolvedUsingIfExistsDecl>(D))
104 return false;
105
106 return true;
107}
108
110 // Warn if this is used but marked unused.
111 if (const auto *A = D->getAttr<UnusedAttr>()) {
112 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
113 // should diagnose them.
114 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
115 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
116 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
117 if (DC && !DC->hasAttr<UnusedAttr>())
118 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
119 }
120 }
121}
122
124 assert(Decl && Decl->isDeleted());
125
126 if (Decl->isDefaulted()) {
127 // If the method was explicitly defaulted, point at that declaration.
128 if (!Decl->isImplicit())
129 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
130
131 // Try to diagnose why this special member function was implicitly
132 // deleted. This might fail, if that reason no longer applies.
134 return;
135 }
136
137 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
138 if (Ctor && Ctor->isInheritingConstructor())
140
141 Diag(Decl->getLocation(), diag::note_availability_specified_here)
142 << Decl << 1;
143}
144
145/// Determine whether a FunctionDecl was ever declared with an
146/// explicit storage class.
148 for (auto *I : D->redecls()) {
149 if (I->getStorageClass() != SC_None)
150 return true;
151 }
152 return false;
153}
154
155/// Check whether we're in an extern inline function and referring to a
156/// variable or function with internal linkage (C11 6.7.4p3).
157///
158/// This is only a warning because we used to silently accept this code, but
159/// in many cases it will not behave correctly. This is not enabled in C++ mode
160/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
161/// and so while there may still be user mistakes, most of the time we can't
162/// prove that there are errors.
164 const NamedDecl *D,
166 // This is disabled under C++; there are too many ways for this to fire in
167 // contexts where the warning is a false positive, or where it is technically
168 // correct but benign.
169 if (S.getLangOpts().CPlusPlus)
170 return;
171
172 // Check if this is an inlined function or method.
173 FunctionDecl *Current = S.getCurFunctionDecl();
174 if (!Current)
175 return;
176 if (!Current->isInlined())
177 return;
178 if (!Current->isExternallyVisible())
179 return;
180
181 // Check if the decl has internal linkage.
182 if (D->getFormalLinkage() != Linkage::Internal)
183 return;
184
185 // Downgrade from ExtWarn to Extension if
186 // (1) the supposedly external inline function is in the main file,
187 // and probably won't be included anywhere else.
188 // (2) the thing we're referencing is a pure function.
189 // (3) the thing we're referencing is another inline function.
190 // This last can give us false negatives, but it's better than warning on
191 // wrappers for simple C library functions.
192 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
193 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
194 if (!DowngradeWarning && UsedFn)
195 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
196
197 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
198 : diag::ext_internal_in_extern_inline)
199 << /*IsVar=*/!UsedFn << D;
200
202
203 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
204 << D;
205}
206
208 const FunctionDecl *First = Cur->getFirstDecl();
209
210 // Suggest "static" on the function, if possible.
212 SourceLocation DeclBegin = First->getSourceRange().getBegin();
213 Diag(DeclBegin, diag::note_convert_inline_to_static)
214 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
215 }
216}
217
219 const ObjCInterfaceDecl *UnknownObjCClass,
220 bool ObjCPropertyAccess,
221 bool AvoidPartialAvailabilityChecks,
222 ObjCInterfaceDecl *ClassReceiver,
223 bool SkipTrailingRequiresClause) {
224 SourceLocation Loc = Locs.front();
225 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
226 // If there were any diagnostics suppressed by template argument deduction,
227 // emit them now.
228 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
229 if (Pos != SuppressedDiagnostics.end()) {
230 for (const auto &[DiagLoc, PD] : Pos->second) {
231 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
232 PD.Emit(Builder);
233 }
234 // Clear out the list of suppressed diagnostics, so that we don't emit
235 // them again for this specialization. However, we don't obsolete this
236 // entry from the table, because we want to avoid ever emitting these
237 // diagnostics again.
238 Pos->second.clear();
239 }
240
241 // C++ [basic.start.main]p3:
242 // The function 'main' shall not be used within a program.
243 if (cast<FunctionDecl>(D)->isMain())
244 Diag(Loc, diag::ext_main_used);
245
246 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
247 }
248
249 // See if this is an auto-typed variable whose initializer we are parsing.
250 if (ParsingInitForAutoVars.count(D)) {
251 if (isa<BindingDecl>(D)) {
252 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
253 << D->getDeclName();
254 } else {
255 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
256 << diag::ParsingInitFor::Var << D->getDeclName()
257 << cast<VarDecl>(D)->getType();
258 }
259 return true;
260 }
261
262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263 // See if this is a deleted function.
264 if (FD->isDeleted()) {
265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266 if (Ctor && Ctor->isInheritingConstructor())
267 Diag(Loc, diag::err_deleted_inherited_ctor_use)
268 << Ctor->getParent()
269 << Ctor->getInheritedConstructor().getConstructor()->getParent();
270 else {
271 StringLiteral *Msg = FD->getDeletedMessage();
272 Diag(Loc, diag::err_deleted_function_use)
273 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
274 }
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307 return true;
308
309 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *Concept = dyn_cast<ConceptDecl>(D);
316 return true;
317
318 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
319 // Lambdas are only default-constructible or assignable in C++2a onwards.
320 if (MD->getParent()->isLambda() &&
321 ((isa<CXXConstructorDecl>(MD) &&
322 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
323 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
324 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
325 << !isa<CXXConstructorDecl>(MD);
326 }
327 }
328
329 auto getReferencedObjCProp = [](const NamedDecl *D) ->
330 const ObjCPropertyDecl * {
331 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
332 return MD->findPropertyDecl();
333 return nullptr;
334 };
335 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
337 return true;
339 return true;
340 }
341
342 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
343 // Only the variables omp_in and omp_out are allowed in the combiner.
344 // Only the variables omp_priv and omp_orig are allowed in the
345 // initializer-clause.
346 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
347 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
348 isa<VarDecl>(D)) {
349 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
351 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
352 return true;
353 }
354
355 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
356 // List-items in map clauses on this construct may only refer to the declared
357 // variable var and entities that could be referenced by a procedure defined
358 // at the same location.
359 // [OpenMP 5.2] Also allow iterator declared variables.
360 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
361 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
362 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
364 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
365 return true;
366 }
367
368 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
369 Diag(Loc, diag::err_use_of_empty_using_if_exists);
370 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
371 return true;
372 }
373
374 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
375 AvoidPartialAvailabilityChecks, ClassReceiver);
376
377 DiagnoseUnusedOfDecl(*this, D, Loc);
378
380
381 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
382 if (getLangOpts().getFPEvalMethod() !=
385 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
386 Diag(D->getLocation(),
387 diag::err_type_available_only_in_default_eval_method)
388 << D->getName();
389 }
390
391 if (auto *VD = dyn_cast<ValueDecl>(D))
392 checkTypeSupport(VD->getType(), Loc, VD);
393
394 if (LangOpts.SYCLIsDevice ||
395 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
397 if (const auto *VD = dyn_cast<VarDecl>(D))
398 if (VD->getTLSKind() != VarDecl::TLS_None)
399 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
400 }
401
402 return false;
403}
404
406 ArrayRef<Expr *> Args) {
407 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
408 if (!Attr)
409 return;
410
411 // The number of formal parameters of the declaration.
412 unsigned NumFormalParams;
413
414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
417
418 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
419 NumFormalParams = MD->param_size();
420 CalleeKind = CK_Method;
421 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
422 NumFormalParams = FD->param_size();
423 CalleeKind = CK_Function;
424 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
425 QualType Ty = VD->getType();
426 const FunctionType *Fn = nullptr;
427 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
428 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
429 if (!Fn)
430 return;
431 CalleeKind = CK_Function;
432 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
433 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
434 CalleeKind = CK_Block;
435 } else {
436 return;
437 }
438
439 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
440 NumFormalParams = proto->getNumParams();
441 else
442 NumFormalParams = 0;
443 } else {
444 return;
445 }
446
447 // "NullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned NullPos = Attr->getNullPos();
452 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
453 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned NumArgsAfterSentinel = Attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
460 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
463 return;
464 }
465
466 // Otherwise, find the sentinel expression.
467 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
468 if (!SentinelExpr)
469 return;
470 if (SentinelExpr->isValueDependent())
471 return;
472 if (Context.isSentinelNullExpr(SentinelExpr))
473 return;
474
475 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
476 // or 'NULL' if those are actually defined in the context. Only use
477 // 'nil' for ObjC methods, where it's much more likely that the
478 // variadic arguments form a list of object pointers.
479 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
480 std::string NullValue;
481 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
482 NullValue = "nil";
483 else if (getLangOpts().CPlusPlus11)
484 NullValue = "nullptr";
485 else if (PP.isMacroDefined("NULL"))
486 NullValue = "NULL";
487 else
488 NullValue = "(void*) 0";
489
490 if (MissingNilLoc.isInvalid())
491 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
492 else
493 Diag(MissingNilLoc, diag::warn_missing_sentinel)
494 << int(CalleeKind)
495 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
496 Diag(D->getLocation(), diag::note_sentinel_here)
497 << int(CalleeKind) << Attr->getRange();
498}
499
501 return E ? E->getSourceRange() : SourceRange();
502}
503
504//===----------------------------------------------------------------------===//
505// Standard Promotions and Conversions
506//===----------------------------------------------------------------------===//
507
508/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510 // Handle any placeholder expressions which made it here.
511 if (E->hasPlaceholderType()) {
513 if (result.isInvalid()) return ExprError();
514 E = result.get();
515 }
516
517 QualType Ty = E->getType();
518 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
519
520 if (Ty->isFunctionType()) {
521 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
522 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
524 return ExprError();
525
527 CK_FunctionToPointerDecay).get();
528 } else if (Ty->isArrayType()) {
529 // In C90 mode, arrays only promote to pointers if the array expression is
530 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
531 // type 'array of type' is converted to an expression that has type 'pointer
532 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
533 // that has type 'array of type' ...". The relevant change is "an lvalue"
534 // (C90) to "an expression" (C99).
535 //
536 // C++ 4.2p1:
537 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
538 // T" can be converted to an rvalue of type "pointer to T".
539 //
540 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
542 CK_ArrayToPointerDecay);
543 if (Res.isInvalid())
544 return ExprError();
545 E = Res.get();
546 }
547 }
548 return E;
549}
550
552 // Check to see if we are dereferencing a null pointer. If so,
553 // and if not volatile-qualified, this is undefined behavior that the
554 // optimizer will delete, so warn about it. People sometimes try to use this
555 // to get a deterministic trap and are surprised by clang's behavior. This
556 // only handles the pattern "*null", which is a very syntactic check.
557 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
558 if (UO && UO->getOpcode() == UO_Deref &&
559 UO->getSubExpr()->getType()->isPointerType()) {
560 const LangAS AS =
561 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
562 if ((!isTargetAddressSpace(AS) ||
563 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
564 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
566 !UO->getType().isVolatileQualified()) {
567 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568 S.PDiag(diag::warn_indirection_through_null)
569 << UO->getSubExpr()->getSourceRange());
570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571 S.PDiag(diag::note_indirection_through_null));
572 }
573 }
574}
575
576static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
577 SourceLocation AssignLoc,
578 const Expr* RHS) {
579 const ObjCIvarDecl *IV = OIRE->getDecl();
580 if (!IV)
581 return;
582
583 DeclarationName MemberName = IV->getDeclName();
585 if (!Member || !Member->isStr("isa"))
586 return;
587
588 const Expr *Base = OIRE->getBase();
589 QualType BaseType = Base->getType();
590 if (OIRE->isArrow())
591 BaseType = BaseType->getPointeeType();
592 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
593 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
594 ObjCInterfaceDecl *ClassDeclared = nullptr;
595 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
596 if (!ClassDeclared->getSuperClass()
597 && (*ClassDeclared->ivar_begin()) == IV) {
598 if (RHS) {
599 NamedDecl *ObjectSetClass =
601 &S.Context.Idents.get("object_setClass"),
603 if (ObjectSetClass) {
604 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
605 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
607 "object_setClass(")
609 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
610 << FixItHint::CreateInsertion(RHSLocEnd, ")");
611 }
612 else
613 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
614 } else {
615 NamedDecl *ObjectGetClass =
617 &S.Context.Idents.get("object_getClass"),
619 if (ObjectGetClass)
620 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
622 "object_getClass(")
624 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
625 else
626 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
627 }
628 S.Diag(IV->getLocation(), diag::note_ivar_decl);
629 }
630 }
631}
632
634 // Handle any placeholder expressions which made it here.
635 if (E->hasPlaceholderType()) {
637 if (result.isInvalid()) return ExprError();
638 E = result.get();
639 }
640
641 // C++ [conv.lval]p1:
642 // A glvalue of a non-function, non-array type T can be
643 // converted to a prvalue.
644 if (!E->isGLValue()) return E;
645
646 QualType T = E->getType();
647 assert(!T.isNull() && "r-value conversion on typeless expression?");
648
649 // lvalue-to-rvalue conversion cannot be applied to types that decay to
650 // pointers (i.e. function or array types).
652 return E;
653
654 // We don't want to throw lvalue-to-rvalue casts on top of
655 // expressions of certain types in C++.
656 if (getLangOpts().CPlusPlus) {
657 if (T == Context.OverloadTy || T->isRecordType() ||
658 (T->isDependentType() && !T->isAnyPointerType() &&
660 return E;
661 }
662
663 // The C standard is actually really unclear on this point, and
664 // DR106 tells us what the result should be but not why. It's
665 // generally best to say that void types just doesn't undergo
666 // lvalue-to-rvalue at all. Note that expressions of unqualified
667 // 'void' type are never l-values, but qualified void can be.
668 if (T->isVoidType())
669 return E;
670
671 // OpenCL usually rejects direct accesses to values of 'half' type.
672 if (getLangOpts().OpenCL &&
673 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
674 T->isHalfType()) {
675 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
676 << 0 << T;
677 return ExprError();
678 }
679
681 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
682 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
683 &Context.Idents.get("object_getClass"),
685 if (ObjectGetClass)
686 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
687 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
689 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
690 else
691 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
692 }
693 else if (const ObjCIvarRefExpr *OIRE =
694 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
695 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
696
697 // C++ [conv.lval]p1:
698 // [...] If T is a non-class type, the type of the prvalue is the
699 // cv-unqualified version of T. Otherwise, the type of the
700 // rvalue is T.
701 //
702 // C99 6.3.2.1p2:
703 // If the lvalue has qualified type, the value has the unqualified
704 // version of the type of the lvalue; otherwise, the value has the
705 // type of the lvalue.
706 if (T.hasQualifiers())
707 T = T.getUnqualifiedType();
708
709 // Under the MS ABI, lock down the inheritance model now.
710 if (T->isMemberPointerType() &&
712 (void)isCompleteType(E->getExprLoc(), T);
713
715 if (Res.isInvalid())
716 return Res;
717 E = Res.get();
718
719 // Loading a __weak object implicitly retains the value, so we need a cleanup to
720 // balance that.
723
726
728 return ExprError();
729
730 // C++ [conv.lval]p3:
731 // If T is cv std::nullptr_t, the result is a null pointer constant.
732 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
733 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
735
736 // C11 6.3.2.1p2:
737 // ... if the lvalue has atomic type, the value has the non-atomic version
738 // of the type of the lvalue ...
739 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
740 T = Atomic->getValueType().getUnqualifiedType();
741 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
742 nullptr, VK_PRValue, FPOptionsOverride());
743 }
744
745 return Res;
746}
747
750 if (Res.isInvalid())
751 return ExprError();
752 Res = DefaultLvalueConversion(Res.get());
753 if (Res.isInvalid())
754 return ExprError();
755 return Res;
756}
757
759 QualType Ty = E->getType();
760 ExprResult Res = E;
761 // Only do implicit cast for a function type, but not for a pointer
762 // to function type.
763 if (Ty->isFunctionType()) {
765 CK_FunctionToPointerDecay);
766 if (Res.isInvalid())
767 return ExprError();
768 }
769 Res = DefaultLvalueConversion(Res.get());
770 if (Res.isInvalid())
771 return ExprError();
772 return Res.get();
773}
774
775/// UsualUnaryFPConversions - Promotes floating-point types according to the
776/// current language semantics.
778 QualType Ty = E->getType();
779 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
780
781 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
782 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
783 (getLangOpts().getFPEvalMethod() !=
786 switch (EvalMethod) {
787 default:
788 llvm_unreachable("Unrecognized float evaluation method");
789 break;
791 llvm_unreachable("Float evaluation method should be set by now");
792 break;
795 // Widen the expression to double.
796 return Ty->isComplexType()
799 CK_FloatingComplexCast)
800 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
801 break;
804 // Widen the expression to long double.
805 return Ty->isComplexType()
808 CK_FloatingComplexCast)
810 CK_FloatingCast);
811 break;
812 }
813 }
814
815 // Half FP have to be promoted to float unless it is natively supported
816 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
817 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
818
819 return E;
820}
821
822/// UsualUnaryConversions - Performs various conversions that are common to most
823/// operators (C99 6.3). The conversions of array and function types are
824/// sometimes suppressed. For example, the array->pointer conversion doesn't
825/// apply if the array is an argument to the sizeof or address (&) operators.
826/// In these instances, this routine should *not* be called.
828 // First, convert to an r-value.
830 if (Res.isInvalid())
831 return ExprError();
832
833 // Promote floating-point types.
834 Res = UsualUnaryFPConversions(Res.get());
835 if (Res.isInvalid())
836 return ExprError();
837 E = Res.get();
838
839 QualType Ty = E->getType();
840 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
841
842 // Try to perform integral promotions if the object has a theoretically
843 // promotable type.
845 // C99 6.3.1.1p2:
846 //
847 // The following may be used in an expression wherever an int or
848 // unsigned int may be used:
849 // - an object or expression with an integer type whose integer
850 // conversion rank is less than or equal to the rank of int
851 // and unsigned int.
852 // - A bit-field of type _Bool, int, signed int, or unsigned int.
853 //
854 // If an int can represent all values of the original type, the
855 // value is converted to an int; otherwise, it is converted to an
856 // unsigned int. These are called the integer promotions. All
857 // other types are unchanged by the integer promotions.
858
860 if (!PTy.isNull()) {
861 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
862 return E;
863 }
866 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
867 return E;
868 }
869 }
870 return E;
871}
872
873/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
874/// do not have a prototype. Arguments that have type float or __fp16
875/// are promoted to double. All other argument types are converted by
876/// UsualUnaryConversions().
878 QualType Ty = E->getType();
879 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
880
882 if (Res.isInvalid())
883 return ExprError();
884 E = Res.get();
885
886 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
887 // promote to double.
888 // Note that default argument promotion applies only to float (and
889 // half/fp16); it does not apply to _Float16.
890 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
891 if (BTy && (BTy->getKind() == BuiltinType::Half ||
892 BTy->getKind() == BuiltinType::Float)) {
893 if (getLangOpts().OpenCL &&
894 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
895 if (BTy->getKind() == BuiltinType::Half) {
896 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
897 }
898 } else {
899 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
900 }
901 }
902 if (BTy &&
903 getLangOpts().getExtendIntArgs() ==
908 E = (Ty->isUnsignedIntegerType())
909 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
910 .get()
911 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
913 "Unexpected typesize for LongLongTy");
914 }
915
916 // C++ performs lvalue-to-rvalue conversion as a default argument
917 // promotion, even on class types, but note:
918 // C++11 [conv.lval]p2:
919 // When an lvalue-to-rvalue conversion occurs in an unevaluated
920 // operand or a subexpression thereof the value contained in the
921 // referenced object is not accessed. Otherwise, if the glvalue
922 // has a class type, the conversion copy-initializes a temporary
923 // of type T from the glvalue and the result of the conversion
924 // is a prvalue for the temporary.
925 // FIXME: add some way to gate this entire thing for correctness in
926 // potentially potentially evaluated contexts.
930 E->getExprLoc(), E);
931 if (Temp.isInvalid())
932 return ExprError();
933 E = Temp.get();
934 }
935
936 // C++ [expr.call]p7, per CWG722:
937 // An argument that has (possibly cv-qualified) type std::nullptr_t is
938 // converted to void* ([conv.ptr]).
939 // (This does not apply to C23 nullptr)
941 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
942
943 return E;
944}
945
947 if (Ty->isIncompleteType()) {
948 // C++11 [expr.call]p7:
949 // After these conversions, if the argument does not have arithmetic,
950 // enumeration, pointer, pointer to member, or class type, the program
951 // is ill-formed.
952 //
953 // Since we've already performed null pointer conversion, array-to-pointer
954 // decay and function-to-pointer decay, the only such type in C++ is cv
955 // void. This also handles initializer lists as variadic arguments.
956 if (Ty->isVoidType())
957 return VarArgKind::Invalid;
958
959 if (Ty->isObjCObjectType())
960 return VarArgKind::Invalid;
961 return VarArgKind::Valid;
962 }
963
965 return VarArgKind::Invalid;
966
967 if (Context.getTargetInfo().getTriple().isWasm() &&
969 return VarArgKind::Invalid;
970 }
971
972 if (Ty.isCXX98PODType(Context))
973 return VarArgKind::Valid;
974
975 // C++11 [expr.call]p7:
976 // Passing a potentially-evaluated argument of class type (Clause 9)
977 // having a non-trivial copy constructor, a non-trivial move constructor,
978 // or a non-trivial destructor, with no corresponding parameter,
979 // is conditionally-supported with implementation-defined semantics.
982 if (!Record->hasNonTrivialCopyConstructor() &&
983 !Record->hasNonTrivialMoveConstructor() &&
984 !Record->hasNonTrivialDestructor())
986
987 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
988 return VarArgKind::Valid;
989
990 if (Ty->isObjCObjectType())
991 return VarArgKind::Invalid;
992
994 return VarArgKind::Valid;
995
996 if (getLangOpts().MSVCCompat)
998
1000 return VarArgKind::Valid;
1001
1002 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1003 // permitted to reject them. We should consider doing so.
1004 return VarArgKind::Undefined;
1005}
1006
1008 // Don't allow one to pass an Objective-C interface to a vararg.
1009 const QualType &Ty = E->getType();
1010 VarArgKind VAK = isValidVarArgType(Ty);
1011
1012 // Complain about passing non-POD types through varargs.
1013 switch (VAK) {
1016 E->getBeginLoc(), nullptr,
1017 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1018 [[fallthrough]];
1019 case VarArgKind::Valid:
1020 if (Ty->isRecordType()) {
1021 // This is unlikely to be what the user intended. If the class has a
1022 // 'c_str' member function, the user probably meant to call that.
1023 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_pass_class_arg_to_vararg)
1025 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1026 }
1027 break;
1028
1031 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1032 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1033 << getLangOpts().CPlusPlus11 << Ty << CT);
1034 break;
1035
1038 Diag(E->getBeginLoc(),
1039 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1040 << Ty << CT;
1041 else if (Ty->isObjCObjectType())
1042 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1043 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1044 << Ty << CT);
1045 else
1046 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1047 << isa<InitListExpr>(E) << Ty << CT;
1048 break;
1049 }
1050}
1051
1053 FunctionDecl *FDecl) {
1054 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1055 // Strip the unbridged-cast placeholder expression off, if applicable.
1056 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1057 (CT == VariadicCallType::Method ||
1058 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1060
1061 // Otherwise, do normal placeholder checking.
1062 } else {
1064 if (ExprRes.isInvalid())
1065 return ExprError();
1066 E = ExprRes.get();
1067 }
1068 }
1069
1071 if (ExprRes.isInvalid())
1072 return ExprError();
1073
1074 // Copy blocks to the heap.
1075 if (ExprRes.get()->getType()->isBlockPointerType())
1076 maybeExtendBlockObject(ExprRes);
1077
1078 E = ExprRes.get();
1079
1080 // Diagnostics regarding non-POD argument types are
1081 // emitted along with format string checking in Sema::CheckFunctionCall().
1083 // Turn this into a trap.
1084 CXXScopeSpec SS;
1085 SourceLocation TemplateKWLoc;
1086 UnqualifiedId Name;
1087 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1088 E->getBeginLoc());
1089 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1090 /*HasTrailingLParen=*/true,
1091 /*IsAddressOfOperand=*/false);
1092 if (TrapFn.isInvalid())
1093 return ExprError();
1094
1095 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1096 E->getEndLoc());
1097 if (Call.isInvalid())
1098 return ExprError();
1099
1100 ExprResult Comma =
1101 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1102 if (Comma.isInvalid())
1103 return ExprError();
1104 return Comma.get();
1105 }
1106
1107 if (!getLangOpts().CPlusPlus &&
1109 diag::err_call_incomplete_argument))
1110 return ExprError();
1111
1112 return E;
1113}
1114
1115/// Convert complex integers to complex floats and real integers to
1116/// real floats as required for complex arithmetic. Helper function of
1117/// UsualArithmeticConversions()
1118///
1119/// \return false if the integer expression is an integer type and is
1120/// successfully converted to the (complex) float type.
1122 ExprResult &ComplexExpr,
1123 QualType IntTy,
1124 QualType ComplexTy,
1125 bool SkipCast) {
1126 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1127 if (SkipCast) return false;
1128 if (IntTy->isIntegerType()) {
1129 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1131 } else {
1132 assert(IntTy->isComplexIntegerType());
1133 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1134 CK_IntegralComplexToFloatingComplex);
1135 }
1136 return false;
1137}
1138
1139// This handles complex/complex, complex/float, or float/complex.
1140// When both operands are complex, the shorter operand is converted to the
1141// type of the longer, and that is the type of the result. This corresponds
1142// to what is done when combining two real floating-point operands.
1143// The fun begins when size promotion occur across type domains.
1144// From H&S 6.3.4: When one operand is complex and the other is a real
1145// floating-point type, the less precise type is converted, within it's
1146// real or complex domain, to the precision of the other type. For example,
1147// when combining a "long double" with a "double _Complex", the
1148// "double _Complex" is promoted to "long double _Complex".
1150 QualType ShorterType,
1151 QualType LongerType,
1152 bool PromotePrecision) {
1153 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1155 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1156
1157 if (PromotePrecision) {
1158 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1159 Shorter =
1160 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1161 } else {
1162 if (LongerIsComplex)
1163 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1164 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1165 }
1166 }
1167 return Result;
1168}
1169
1170/// Handle arithmetic conversion with complex types. Helper function of
1171/// UsualArithmeticConversions()
1173 ExprResult &RHS, QualType LHSType,
1174 QualType RHSType, bool IsCompAssign) {
1175 // Handle (complex) integer types.
1176 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1177 /*SkipCast=*/false))
1178 return LHSType;
1179 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1180 /*SkipCast=*/IsCompAssign))
1181 return RHSType;
1182
1183 // Compute the rank of the two types, regardless of whether they are complex.
1184 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1185 if (Order < 0)
1186 // Promote the precision of the LHS if not an assignment.
1187 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1188 /*PromotePrecision=*/!IsCompAssign);
1189 // Promote the precision of the RHS unless it is already the same as the LHS.
1190 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1191 /*PromotePrecision=*/Order > 0);
1192}
1193
1194/// Handle arithmetic conversion from integer to float. Helper function
1195/// of UsualArithmeticConversions()
1197 ExprResult &IntExpr,
1198 QualType FloatTy, QualType IntTy,
1199 bool ConvertFloat, bool ConvertInt) {
1200 if (IntTy->isIntegerType()) {
1201 if (ConvertInt)
1202 // Convert intExpr to the lhs floating point type.
1203 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1204 CK_IntegralToFloating);
1205 return FloatTy;
1206 }
1207
1208 // Convert both sides to the appropriate complex float.
1209 assert(IntTy->isComplexIntegerType());
1210 QualType result = S.Context.getComplexType(FloatTy);
1211
1212 // _Complex int -> _Complex float
1213 if (ConvertInt)
1214 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1215 CK_IntegralComplexToFloatingComplex);
1216
1217 // float -> _Complex float
1218 if (ConvertFloat)
1219 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1220 CK_FloatingRealToComplex);
1221
1222 return result;
1223}
1224
1225/// Handle arithmethic conversion with floating point types. Helper
1226/// function of UsualArithmeticConversions()
1228 ExprResult &RHS, QualType LHSType,
1229 QualType RHSType, bool IsCompAssign) {
1230 bool LHSFloat = LHSType->isRealFloatingType();
1231 bool RHSFloat = RHSType->isRealFloatingType();
1232
1233 // N1169 4.1.4: If one of the operands has a floating type and the other
1234 // operand has a fixed-point type, the fixed-point operand
1235 // is converted to the floating type [...]
1236 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1237 if (LHSFloat)
1238 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1239 else if (!IsCompAssign)
1240 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1241 return LHSFloat ? LHSType : RHSType;
1242 }
1243
1244 // If we have two real floating types, convert the smaller operand
1245 // to the bigger result.
1246 if (LHSFloat && RHSFloat) {
1247 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1248 if (order > 0) {
1249 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1250 return LHSType;
1251 }
1252
1253 assert(order < 0 && "illegal float comparison");
1254 if (!IsCompAssign)
1255 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1256 return RHSType;
1257 }
1258
1259 if (LHSFloat) {
1260 // Half FP has to be promoted to float unless it is natively supported
1261 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1262 LHSType = S.Context.FloatTy;
1263
1264 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1265 /*ConvertFloat=*/!IsCompAssign,
1266 /*ConvertInt=*/ true);
1267 }
1268 assert(RHSFloat);
1269 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1270 /*ConvertFloat=*/ true,
1271 /*ConvertInt=*/!IsCompAssign);
1272}
1273
1274/// Diagnose attempts to convert between __float128, __ibm128 and
1275/// long double if there is no support for such conversion.
1276/// Helper function of UsualArithmeticConversions().
1277static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1278 QualType RHSType) {
1279 // No issue if either is not a floating point type.
1280 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1281 return false;
1282
1283 // No issue if both have the same 128-bit float semantics.
1284 auto *LHSComplex = LHSType->getAs<ComplexType>();
1285 auto *RHSComplex = RHSType->getAs<ComplexType>();
1286
1287 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1288 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1289
1290 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1291 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1292
1293 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1294 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1295 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1296 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1297 return false;
1298
1299 return true;
1300}
1301
1302typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1303
1304namespace {
1305/// These helper callbacks are placed in an anonymous namespace to
1306/// permit their use as function template parameters.
1307ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1308 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1309}
1310
1311ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1312 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1313 CK_IntegralComplexCast);
1314}
1315}
1316
1317/// Handle integer arithmetic conversions. Helper function of
1318/// UsualArithmeticConversions()
1319template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1321 ExprResult &RHS, QualType LHSType,
1322 QualType RHSType, bool IsCompAssign) {
1323 // The rules for this case are in C99 6.3.1.8
1324 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1325 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1326 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1327 if (LHSSigned == RHSSigned) {
1328 // Same signedness; use the higher-ranked type
1329 if (order >= 0) {
1330 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1331 return LHSType;
1332 } else if (!IsCompAssign)
1333 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1334 return RHSType;
1335 } else if (order != (LHSSigned ? 1 : -1)) {
1336 // The unsigned type has greater than or equal rank to the
1337 // signed type, so use the unsigned type
1338 if (RHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1345 // The two types are different widths; if we are here, that
1346 // means the signed type is larger than the unsigned type, so
1347 // use the signed type.
1348 if (LHSSigned) {
1349 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1350 return LHSType;
1351 } else if (!IsCompAssign)
1352 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1353 return RHSType;
1354 } else {
1355 // The signed type is higher-ranked than the unsigned type,
1356 // but isn't actually any bigger (like unsigned int and long
1357 // on most 32-bit systems). Use the unsigned type corresponding
1358 // to the signed type.
1359 QualType result =
1360 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1361 RHS = (*doRHSCast)(S, RHS.get(), result);
1362 if (!IsCompAssign)
1363 LHS = (*doLHSCast)(S, LHS.get(), result);
1364 return result;
1365 }
1366}
1367
1368/// Handle conversions with GCC complex int extension. Helper function
1369/// of UsualArithmeticConversions()
1371 ExprResult &RHS, QualType LHSType,
1372 QualType RHSType,
1373 bool IsCompAssign) {
1374 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1375 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1376
1377 if (LHSComplexInt && RHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType RHSEltType = RHSComplexInt->getElementType();
1380 QualType ScalarType =
1381 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1382 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1383
1384 return S.Context.getComplexType(ScalarType);
1385 }
1386
1387 if (LHSComplexInt) {
1388 QualType LHSEltType = LHSComplexInt->getElementType();
1389 QualType ScalarType =
1390 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1391 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1393 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1394 CK_IntegralRealToComplex);
1395
1396 return ComplexType;
1397 }
1398
1399 assert(RHSComplexInt);
1400
1401 QualType RHSEltType = RHSComplexInt->getElementType();
1402 QualType ScalarType =
1403 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1404 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1406
1407 if (!IsCompAssign)
1408 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1409 CK_IntegralRealToComplex);
1410 return ComplexType;
1411}
1412
1413/// Return the rank of a given fixed point or integer type. The value itself
1414/// doesn't matter, but the values must be increasing with proper increasing
1415/// rank as described in N1169 4.1.1.
1416static unsigned GetFixedPointRank(QualType Ty) {
1417 const auto *BTy = Ty->getAs<BuiltinType>();
1418 assert(BTy && "Expected a builtin type.");
1419
1420 switch (BTy->getKind()) {
1421 case BuiltinType::ShortFract:
1422 case BuiltinType::UShortFract:
1423 case BuiltinType::SatShortFract:
1424 case BuiltinType::SatUShortFract:
1425 return 1;
1426 case BuiltinType::Fract:
1427 case BuiltinType::UFract:
1428 case BuiltinType::SatFract:
1429 case BuiltinType::SatUFract:
1430 return 2;
1431 case BuiltinType::LongFract:
1432 case BuiltinType::ULongFract:
1433 case BuiltinType::SatLongFract:
1434 case BuiltinType::SatULongFract:
1435 return 3;
1436 case BuiltinType::ShortAccum:
1437 case BuiltinType::UShortAccum:
1438 case BuiltinType::SatShortAccum:
1439 case BuiltinType::SatUShortAccum:
1440 return 4;
1441 case BuiltinType::Accum:
1442 case BuiltinType::UAccum:
1443 case BuiltinType::SatAccum:
1444 case BuiltinType::SatUAccum:
1445 return 5;
1446 case BuiltinType::LongAccum:
1447 case BuiltinType::ULongAccum:
1448 case BuiltinType::SatLongAccum:
1449 case BuiltinType::SatULongAccum:
1450 return 6;
1451 default:
1452 if (BTy->isInteger())
1453 return 0;
1454 llvm_unreachable("Unexpected fixed point or integer type");
1455 }
1456}
1457
1458/// handleFixedPointConversion - Fixed point operations between fixed
1459/// point types and integers or other fixed point types do not fall under
1460/// usual arithmetic conversion since these conversions could result in loss
1461/// of precsision (N1169 4.1.4). These operations should be calculated with
1462/// the full precision of their result type (N1169 4.1.6.2.1).
1464 QualType RHSTy) {
1465 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1466 "Expected at least one of the operands to be a fixed point type");
1467 assert((LHSTy->isFixedPointOrIntegerType() ||
1468 RHSTy->isFixedPointOrIntegerType()) &&
1469 "Special fixed point arithmetic operation conversions are only "
1470 "applied to ints or other fixed point types");
1471
1472 // If one operand has signed fixed-point type and the other operand has
1473 // unsigned fixed-point type, then the unsigned fixed-point operand is
1474 // converted to its corresponding signed fixed-point type and the resulting
1475 // type is the type of the converted operand.
1476 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1478 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1480
1481 // The result type is the type with the highest rank, whereby a fixed-point
1482 // conversion rank is always greater than an integer conversion rank; if the
1483 // type of either of the operands is a saturating fixedpoint type, the result
1484 // type shall be the saturating fixed-point type corresponding to the type
1485 // with the highest rank; the resulting value is converted (taking into
1486 // account rounding and overflow) to the precision of the resulting type.
1487 // Same ranks between signed and unsigned types are resolved earlier, so both
1488 // types are either signed or both unsigned at this point.
1489 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1490 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1491
1492 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1493
1495 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1496
1497 return ResultTy;
1498}
1499
1500/// Check that the usual arithmetic conversions can be performed on this pair of
1501/// expressions that might be of enumeration type.
1504 ArithConvKind ACK) {
1505 // C++2a [expr.arith.conv]p1:
1506 // If one operand is of enumeration type and the other operand is of a
1507 // different enumeration type or a floating-point type, this behavior is
1508 // deprecated ([depr.arith.conv.enum]).
1509 //
1510 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1511 // Eventually we will presumably reject these cases (in C++23 onwards?).
1513 R = RHS->getEnumCoercedType(Context);
1514 bool LEnum = L->isUnscopedEnumerationType(),
1515 REnum = R->isUnscopedEnumerationType();
1516 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1517 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1518 (REnum && L->isFloatingType())) {
1519 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1521 ? diag::warn_arith_conv_enum_float_cxx20
1522 : diag::warn_arith_conv_enum_float)
1523 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1524 << L << R;
1525 } else if (!IsCompAssign && LEnum && REnum &&
1527 unsigned DiagID;
1528 // In C++ 26, usual arithmetic conversions between 2 different enum types
1529 // are ill-formed.
1530 if (getLangOpts().CPlusPlus26)
1531 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1532 else if (!L->castAsCanonical<EnumType>()
1533 ->getOriginalDecl()
1534 ->hasNameForLinkage() ||
1535 !R->castAsCanonical<EnumType>()
1536 ->getOriginalDecl()
1537 ->hasNameForLinkage()) {
1538 // If either enumeration type is unnamed, it's less likely that the
1539 // user cares about this, but this situation is still deprecated in
1540 // C++2a. Use a different warning group.
1541 DiagID = getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_anon_enum_types;
1544 } else if (ACK == ArithConvKind::Conditional) {
1545 // Conditional expressions are separated out because they have
1546 // historically had a different warning flag.
1547 DiagID = getLangOpts().CPlusPlus20
1548 ? diag::warn_conditional_mixed_enum_types_cxx20
1549 : diag::warn_conditional_mixed_enum_types;
1550 } else if (ACK == ArithConvKind::Comparison) {
1551 // Comparison expressions are separated out because they have
1552 // historically had a different warning flag.
1553 DiagID = getLangOpts().CPlusPlus20
1554 ? diag::warn_comparison_mixed_enum_types_cxx20
1555 : diag::warn_comparison_mixed_enum_types;
1556 } else {
1557 DiagID = getLangOpts().CPlusPlus20
1558 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1559 : diag::warn_arith_conv_mixed_enum_types;
1560 }
1561 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1562 << (int)ACK << L << R;
1563 }
1564}
1565
1567 Expr *RHS, SourceLocation Loc,
1568 ArithConvKind ACK) {
1569 QualType LHSType = LHS->getType().getUnqualifiedType();
1570 QualType RHSType = RHS->getType().getUnqualifiedType();
1571
1572 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1573 !RHSType->isUnicodeCharacterType())
1574 return;
1575
1576 if (ACK == ArithConvKind::Comparison) {
1577 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1578 return;
1579
1580 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1581 if (T->isChar8Type())
1582 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1583 if (T->isChar16Type())
1584 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1585 assert(T->isChar32Type());
1586 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1587 };
1588
1589 Expr::EvalResult LHSRes, RHSRes;
1590 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1592 SemaRef.isConstantEvaluatedContext());
1593 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1595 SemaRef.isConstantEvaluatedContext());
1596
1597 // Don't warn if the one known value is a representable
1598 // in the type of both expressions.
1599 if (LHSSuccess != RHSuccess) {
1600 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1601 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1602 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1603 return;
1604 }
1605
1606 if (!LHSSuccess || !RHSuccess) {
1607 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1608 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1609 << RHSType;
1610 return;
1611 }
1612
1613 llvm::APSInt LHSValue(32);
1614 LHSValue = LHSRes.Val.getInt();
1615 llvm::APSInt RHSValue(32);
1616 RHSValue = RHSRes.Val.getInt();
1617
1618 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1619 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1620 if (LHSSafe && RHSSafe)
1621 return;
1622
1623 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1624 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1625 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1626 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1627 return;
1628 }
1629
1630 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1631 return;
1632
1633 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1634 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1635 << RHSType;
1636}
1637
1638/// UsualArithmeticConversions - Performs various conversions that are common to
1639/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1640/// routine returns the first non-arithmetic type found. The client is
1641/// responsible for emitting appropriate error diagnostics.
1644 ArithConvKind ACK) {
1645
1646 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1647
1648 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1649
1650 if (ACK != ArithConvKind::CompAssign) {
1651 LHS = UsualUnaryConversions(LHS.get());
1652 if (LHS.isInvalid())
1653 return QualType();
1654 }
1655
1656 RHS = UsualUnaryConversions(RHS.get());
1657 if (RHS.isInvalid())
1658 return QualType();
1659
1660 // For conversion purposes, we ignore any qualifiers.
1661 // For example, "const float" and "float" are equivalent.
1662 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1663 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1664
1665 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1666 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1667 LHSType = AtomicLHS->getValueType();
1668
1669 // If both types are identical, no conversion is needed.
1670 if (Context.hasSameType(LHSType, RHSType))
1671 return Context.getCommonSugaredType(LHSType, RHSType);
1672
1673 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1674 // The caller can deal with this (e.g. pointer + int).
1675 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1676 return QualType();
1677
1678 // Apply unary and bitfield promotions to the LHS's type.
1679 QualType LHSUnpromotedType = LHSType;
1680 if (Context.isPromotableIntegerType(LHSType))
1681 LHSType = Context.getPromotedIntegerType(LHSType);
1682 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1683 if (!LHSBitfieldPromoteTy.isNull())
1684 LHSType = LHSBitfieldPromoteTy;
1685 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1686 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1687
1688 // If both types are identical, no conversion is needed.
1689 if (Context.hasSameType(LHSType, RHSType))
1690 return Context.getCommonSugaredType(LHSType, RHSType);
1691
1692 // At this point, we have two different arithmetic types.
1693
1694 // Diagnose attempts to convert between __ibm128, __float128 and long double
1695 // where such conversions currently can't be handled.
1696 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1697 return QualType();
1698
1699 // Handle complex types first (C99 6.3.1.8p1).
1700 if (LHSType->isComplexType() || RHSType->isComplexType())
1701 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1703
1704 // Now handle "real" floating types (i.e. float, double, long double).
1705 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1706 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1708
1709 // Handle GCC complex int extension.
1710 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1711 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1713
1714 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1715 return handleFixedPointConversion(*this, LHSType, RHSType);
1716
1717 // Finally, we have two differing integer types.
1718 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1719 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1720}
1721
1722//===----------------------------------------------------------------------===//
1723// Semantic Analysis for various Expression Types
1724//===----------------------------------------------------------------------===//
1725
1726
1728 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1729 bool PredicateIsExpr, void *ControllingExprOrType,
1730 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1731 unsigned NumAssocs = ArgTypes.size();
1732 assert(NumAssocs == ArgExprs.size());
1733
1734 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1735 for (unsigned i = 0; i < NumAssocs; ++i) {
1736 if (ArgTypes[i])
1737 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1738 else
1739 Types[i] = nullptr;
1740 }
1741
1742 // If we have a controlling type, we need to convert it from a parsed type
1743 // into a semantic type and then pass that along.
1744 if (!PredicateIsExpr) {
1745 TypeSourceInfo *ControllingType;
1746 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1747 &ControllingType);
1748 assert(ControllingType && "couldn't get the type out of the parser");
1749 ControllingExprOrType = ControllingType;
1750 }
1751
1753 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1754 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1755 delete [] Types;
1756 return ER;
1757}
1758
1760 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1761 bool PredicateIsExpr, void *ControllingExprOrType,
1763 unsigned NumAssocs = Types.size();
1764 assert(NumAssocs == Exprs.size());
1765 assert(ControllingExprOrType &&
1766 "Must have either a controlling expression or a controlling type");
1767
1768 Expr *ControllingExpr = nullptr;
1769 TypeSourceInfo *ControllingType = nullptr;
1770 if (PredicateIsExpr) {
1771 // Decay and strip qualifiers for the controlling expression type, and
1772 // handle placeholder type replacement. See committee discussion from WG14
1773 // DR423.
1777 reinterpret_cast<Expr *>(ControllingExprOrType));
1778 if (R.isInvalid())
1779 return ExprError();
1780 ControllingExpr = R.get();
1781 } else {
1782 // The extension form uses the type directly rather than converting it.
1783 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1784 if (!ControllingType)
1785 return ExprError();
1786 }
1787
1788 bool TypeErrorFound = false,
1789 IsResultDependent = ControllingExpr
1790 ? ControllingExpr->isTypeDependent()
1791 : ControllingType->getType()->isDependentType(),
1792 ContainsUnexpandedParameterPack =
1793 ControllingExpr
1794 ? ControllingExpr->containsUnexpandedParameterPack()
1795 : ControllingType->getType()->containsUnexpandedParameterPack();
1796
1797 // The controlling expression is an unevaluated operand, so side effects are
1798 // likely unintended.
1799 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1800 ControllingExpr->HasSideEffects(Context, false))
1801 Diag(ControllingExpr->getExprLoc(),
1802 diag::warn_side_effects_unevaluated_context);
1803
1804 for (unsigned i = 0; i < NumAssocs; ++i) {
1805 if (Exprs[i]->containsUnexpandedParameterPack())
1806 ContainsUnexpandedParameterPack = true;
1807
1808 if (Types[i]) {
1809 if (Types[i]->getType()->containsUnexpandedParameterPack())
1810 ContainsUnexpandedParameterPack = true;
1811
1812 if (Types[i]->getType()->isDependentType()) {
1813 IsResultDependent = true;
1814 } else {
1815 // We relax the restriction on use of incomplete types and non-object
1816 // types with the type-based extension of _Generic. Allowing incomplete
1817 // objects means those can be used as "tags" for a type-safe way to map
1818 // to a value. Similarly, matching on function types rather than
1819 // function pointer types can be useful. However, the restriction on VM
1820 // types makes sense to retain as there are open questions about how
1821 // the selection can be made at compile time.
1822 //
1823 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1824 // complete object type other than a variably modified type."
1825 // C2y removed the requirement that an expression form must
1826 // use a complete type, though it's still as-if the type has undergone
1827 // lvalue conversion. We support this as an extension in C23 and
1828 // earlier because GCC does so.
1829 unsigned D = 0;
1830 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1831 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1832 : diag::ext_assoc_type_incomplete;
1833 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1834 D = diag::err_assoc_type_nonobject;
1835 else if (Types[i]->getType()->isVariablyModifiedType())
1836 D = diag::err_assoc_type_variably_modified;
1837 else if (ControllingExpr) {
1838 // Because the controlling expression undergoes lvalue conversion,
1839 // array conversion, and function conversion, an association which is
1840 // of array type, function type, or is qualified can never be
1841 // reached. We will warn about this so users are less surprised by
1842 // the unreachable association. However, we don't have to handle
1843 // function types; that's not an object type, so it's handled above.
1844 //
1845 // The logic is somewhat different for C++ because C++ has different
1846 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1847 // If T is a non-class type, the type of the prvalue is the cv-
1848 // unqualified version of T. Otherwise, the type of the prvalue is T.
1849 // The result of these rules is that all qualified types in an
1850 // association in C are unreachable, and in C++, only qualified non-
1851 // class types are unreachable.
1852 //
1853 // NB: this does not apply when the first operand is a type rather
1854 // than an expression, because the type form does not undergo
1855 // conversion.
1856 unsigned Reason = 0;
1857 QualType QT = Types[i]->getType();
1858 if (QT->isArrayType())
1859 Reason = 1;
1860 else if (QT.hasQualifiers() &&
1861 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1862 Reason = 2;
1863
1864 if (Reason)
1865 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1866 diag::warn_unreachable_association)
1867 << QT << (Reason - 1);
1868 }
1869
1870 if (D != 0) {
1871 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1872 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1873 if (getDiagnostics().getDiagnosticLevel(
1874 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1876 TypeErrorFound = true;
1877 }
1878
1879 // C11 6.5.1.1p2 "No two generic associations in the same generic
1880 // selection shall specify compatible types."
1881 for (unsigned j = i+1; j < NumAssocs; ++j)
1882 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1883 Context.typesAreCompatible(Types[i]->getType(),
1884 Types[j]->getType())) {
1885 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1886 diag::err_assoc_compatible_types)
1887 << Types[j]->getTypeLoc().getSourceRange()
1888 << Types[j]->getType()
1889 << Types[i]->getType();
1890 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1891 diag::note_compat_assoc)
1892 << Types[i]->getTypeLoc().getSourceRange()
1893 << Types[i]->getType();
1894 TypeErrorFound = true;
1895 }
1896 }
1897 }
1898 }
1899 if (TypeErrorFound)
1900 return ExprError();
1901
1902 // If we determined that the generic selection is result-dependent, don't
1903 // try to compute the result expression.
1904 if (IsResultDependent) {
1905 if (ControllingExpr)
1906 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1907 Types, Exprs, DefaultLoc, RParenLoc,
1908 ContainsUnexpandedParameterPack);
1909 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1910 Exprs, DefaultLoc, RParenLoc,
1911 ContainsUnexpandedParameterPack);
1912 }
1913
1914 SmallVector<unsigned, 1> CompatIndices;
1915 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1916 // Look at the canonical type of the controlling expression in case it was a
1917 // deduced type like __auto_type. However, when issuing diagnostics, use the
1918 // type the user wrote in source rather than the canonical one.
1919 for (unsigned i = 0; i < NumAssocs; ++i) {
1920 if (!Types[i])
1921 DefaultIndex = i;
1922 else if (ControllingExpr &&
1924 ControllingExpr->getType().getCanonicalType(),
1925 Types[i]->getType()))
1926 CompatIndices.push_back(i);
1927 else if (ControllingType &&
1929 ControllingType->getType().getCanonicalType(),
1930 Types[i]->getType()))
1931 CompatIndices.push_back(i);
1932 }
1933
1934 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1935 TypeSourceInfo *ControllingType) {
1936 // We strip parens here because the controlling expression is typically
1937 // parenthesized in macro definitions.
1938 if (ControllingExpr)
1939 ControllingExpr = ControllingExpr->IgnoreParens();
1940
1941 SourceRange SR = ControllingExpr
1942 ? ControllingExpr->getSourceRange()
1943 : ControllingType->getTypeLoc().getSourceRange();
1944 QualType QT = ControllingExpr ? ControllingExpr->getType()
1945 : ControllingType->getType();
1946
1947 return std::make_pair(SR, QT);
1948 };
1949
1950 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1951 // type compatible with at most one of the types named in its generic
1952 // association list."
1953 if (CompatIndices.size() > 1) {
1954 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1955 SourceRange SR = P.first;
1956 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1957 << SR << P.second << (unsigned)CompatIndices.size();
1958 for (unsigned I : CompatIndices) {
1959 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1960 diag::note_compat_assoc)
1961 << Types[I]->getTypeLoc().getSourceRange()
1962 << Types[I]->getType();
1963 }
1964 return ExprError();
1965 }
1966
1967 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1968 // its controlling expression shall have type compatible with exactly one of
1969 // the types named in its generic association list."
1970 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1971 CompatIndices.size() == 0) {
1972 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1973 SourceRange SR = P.first;
1974 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1975 return ExprError();
1976 }
1977
1978 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1979 // type name that is compatible with the type of the controlling expression,
1980 // then the result expression of the generic selection is the expression
1981 // in that generic association. Otherwise, the result expression of the
1982 // generic selection is the expression in the default generic association."
1983 unsigned ResultIndex =
1984 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1985
1986 if (ControllingExpr) {
1988 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1989 ContainsUnexpandedParameterPack, ResultIndex);
1990 }
1992 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1993 ContainsUnexpandedParameterPack, ResultIndex);
1994}
1995
1997 switch (Kind) {
1998 default:
1999 llvm_unreachable("unexpected TokenKind");
2000 case tok::kw___func__:
2001 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2002 case tok::kw___FUNCTION__:
2004 case tok::kw___FUNCDNAME__:
2005 return PredefinedIdentKind::FuncDName; // [MS]
2006 case tok::kw___FUNCSIG__:
2007 return PredefinedIdentKind::FuncSig; // [MS]
2008 case tok::kw_L__FUNCTION__:
2009 return PredefinedIdentKind::LFunction; // [MS]
2010 case tok::kw_L__FUNCSIG__:
2011 return PredefinedIdentKind::LFuncSig; // [MS]
2012 case tok::kw___PRETTY_FUNCTION__:
2014 }
2015}
2016
2017/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2018/// to determine the value of a PredefinedExpr. This can be either a
2019/// block, lambda, captured statement, function, otherwise a nullptr.
2021 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
2022 DC = DC->getParent();
2023 return cast_or_null<Decl>(DC);
2024}
2025
2026/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2027/// location of the token and the offset of the ud-suffix within it.
2029 unsigned Offset) {
2030 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2031 S.getLangOpts());
2032}
2033
2034/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2035/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2037 IdentifierInfo *UDSuffix,
2038 SourceLocation UDSuffixLoc,
2039 ArrayRef<Expr*> Args,
2040 SourceLocation LitEndLoc) {
2041 assert(Args.size() <= 2 && "too many arguments for literal operator");
2042
2043 QualType ArgTy[2];
2044 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2045 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2046 if (ArgTy[ArgIdx]->isArrayType())
2047 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2048 }
2049
2050 DeclarationName OpName =
2052 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2053 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2054
2055 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2056 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2057 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2058 /*AllowStringTemplatePack*/ false,
2059 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2060 return ExprError();
2061
2062 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2063}
2064
2066 // StringToks needs backing storage as it doesn't hold array elements itself
2067 std::vector<Token> ExpandedToks;
2068 if (getLangOpts().MicrosoftExt)
2069 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2070
2071 StringLiteralParser Literal(StringToks, PP,
2073 if (Literal.hadError)
2074 return ExprError();
2075
2076 SmallVector<SourceLocation, 4> StringTokLocs;
2077 for (const Token &Tok : StringToks)
2078 StringTokLocs.push_back(Tok.getLocation());
2079
2080 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2082 false, {}, StringTokLocs);
2083
2084 if (!Literal.getUDSuffix().empty()) {
2085 SourceLocation UDSuffixLoc =
2086 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2087 Literal.getUDSuffixOffset());
2088 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2089 }
2090
2091 return Lit;
2092}
2093
2094std::vector<Token>
2096 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2097 // local macros that expand to string literals that may be concatenated.
2098 // These macros are expanded here (in Sema), because StringLiteralParser
2099 // (in Lex) doesn't know the enclosing function (because it hasn't been
2100 // parsed yet).
2101 assert(getLangOpts().MicrosoftExt);
2102
2103 // Note: Although function local macros are defined only inside functions,
2104 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2105 // expansion of macros into empty string literals without additional checks.
2106 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2107 if (!CurrentDecl)
2108 CurrentDecl = Context.getTranslationUnitDecl();
2109
2110 std::vector<Token> ExpandedToks;
2111 ExpandedToks.reserve(Toks.size());
2112 for (const Token &Tok : Toks) {
2113 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2114 assert(tok::isStringLiteral(Tok.getKind()));
2115 ExpandedToks.emplace_back(Tok);
2116 continue;
2117 }
2118 if (isa<TranslationUnitDecl>(CurrentDecl))
2119 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2120 // Stringify predefined expression
2121 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2122 << Tok.getKind();
2123 SmallString<64> Str;
2124 llvm::raw_svector_ostream OS(Str);
2125 Token &Exp = ExpandedToks.emplace_back();
2126 Exp.startToken();
2127 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2128 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2129 OS << 'L';
2130 Exp.setKind(tok::wide_string_literal);
2131 } else {
2132 Exp.setKind(tok::string_literal);
2133 }
2134 OS << '"'
2136 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2137 << '"';
2138 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2139 }
2140 return ExpandedToks;
2141}
2142
2145 assert(!StringToks.empty() && "Must have at least one string!");
2146
2147 // StringToks needs backing storage as it doesn't hold array elements itself
2148 std::vector<Token> ExpandedToks;
2149 if (getLangOpts().MicrosoftExt)
2150 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2151
2152 StringLiteralParser Literal(StringToks, PP);
2153 if (Literal.hadError)
2154 return ExprError();
2155
2156 SmallVector<SourceLocation, 4> StringTokLocs;
2157 for (const Token &Tok : StringToks)
2158 StringTokLocs.push_back(Tok.getLocation());
2159
2160 QualType CharTy = Context.CharTy;
2162 if (Literal.isWide()) {
2163 CharTy = Context.getWideCharType();
2165 } else if (Literal.isUTF8()) {
2166 if (getLangOpts().Char8)
2167 CharTy = Context.Char8Ty;
2168 else if (getLangOpts().C23)
2169 CharTy = Context.UnsignedCharTy;
2171 } else if (Literal.isUTF16()) {
2172 CharTy = Context.Char16Ty;
2174 } else if (Literal.isUTF32()) {
2175 CharTy = Context.Char32Ty;
2177 } else if (Literal.isPascal()) {
2178 CharTy = Context.UnsignedCharTy;
2179 }
2180
2181 // Warn on u8 string literals before C++20 and C23, whose type
2182 // was an array of char before but becomes an array of char8_t.
2183 // In C++20, it cannot be used where a pointer to char is expected.
2184 // In C23, it might have an unexpected value if char was signed.
2185 if (Kind == StringLiteralKind::UTF8 &&
2187 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2188 : !getLangOpts().C23)) {
2189 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2190 ? diag::warn_cxx20_compat_utf8_string
2191 : diag::warn_c23_compat_utf8_string);
2192
2193 // Create removals for all 'u8' prefixes in the string literal(s). This
2194 // ensures C++20/C23 compatibility (but may change the program behavior when
2195 // built by non-Clang compilers for which the execution character set is
2196 // not always UTF-8).
2197 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2198 SourceLocation RemovalDiagLoc;
2199 for (const Token &Tok : StringToks) {
2200 if (Tok.getKind() == tok::utf8_string_literal) {
2201 if (RemovalDiagLoc.isInvalid())
2202 RemovalDiagLoc = Tok.getLocation();
2204 Tok.getLocation(),
2205 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2207 }
2208 }
2209 Diag(RemovalDiagLoc, RemovalDiag);
2210 }
2211
2212 QualType StrTy =
2213 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2214
2215 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2217 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2218 if (Literal.getUDSuffix().empty())
2219 return Lit;
2220
2221 // We're building a user-defined literal.
2222 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2223 SourceLocation UDSuffixLoc =
2224 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2225 Literal.getUDSuffixOffset());
2226
2227 // Make sure we're allowed user-defined literals here.
2228 if (!UDLScope)
2229 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2230
2231 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2232 // operator "" X (str, len)
2233 QualType SizeType = Context.getSizeType();
2234
2235 DeclarationName OpName =
2237 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2238 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2239
2240 QualType ArgTy[] = {
2241 Context.getArrayDecayedType(StrTy), SizeType
2242 };
2243
2244 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2245 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2246 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2247 /*AllowStringTemplatePack*/ true,
2248 /*DiagnoseMissing*/ true, Lit)) {
2249
2250 case LOLR_Cooked: {
2251 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2252 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2253 StringTokLocs[0]);
2254 Expr *Args[] = { Lit, LenArg };
2255
2256 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2257 }
2258
2259 case LOLR_Template: {
2260 TemplateArgumentListInfo ExplicitArgs;
2261 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2262 TemplateArgumentLocInfo ArgInfo(Lit);
2263 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2264 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2265 &ExplicitArgs);
2266 }
2267
2269 TemplateArgumentListInfo ExplicitArgs;
2270
2271 unsigned CharBits = Context.getIntWidth(CharTy);
2272 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2273 llvm::APSInt Value(CharBits, CharIsUnsigned);
2274
2275 TemplateArgument TypeArg(CharTy);
2277 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2278
2279 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2280 Value = Lit->getCodeUnit(I);
2281 TemplateArgument Arg(Context, Value, CharTy);
2283 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2284 }
2285 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2286 &ExplicitArgs);
2287 }
2288 case LOLR_Raw:
2290 llvm_unreachable("unexpected literal operator lookup result");
2291 case LOLR_Error:
2292 return ExprError();
2293 }
2294 llvm_unreachable("unexpected literal operator lookup result");
2295}
2296
2300 const CXXScopeSpec *SS) {
2301 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2302 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2303}
2304
2307 const DeclarationNameInfo &NameInfo,
2308 const CXXScopeSpec *SS, NamedDecl *FoundD,
2309 SourceLocation TemplateKWLoc,
2310 const TemplateArgumentListInfo *TemplateArgs) {
2313 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2314 TemplateArgs);
2315}
2316
2317// CUDA/HIP: Check whether a captured reference variable is referencing a
2318// host variable in a device or host device lambda.
2320 VarDecl *VD) {
2321 if (!S.getLangOpts().CUDA || !VD->hasInit())
2322 return false;
2323 assert(VD->getType()->isReferenceType());
2324
2325 // Check whether the reference variable is referencing a host variable.
2326 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2327 if (!DRE)
2328 return false;
2329 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2330 if (!Referee || !Referee->hasGlobalStorage() ||
2331 Referee->hasAttr<CUDADeviceAttr>())
2332 return false;
2333
2334 // Check whether the current function is a device or host device lambda.
2335 // Check whether the reference variable is a capture by getDeclContext()
2336 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2337 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2338 if (MD && MD->getParent()->isLambda() &&
2339 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2340 VD->getDeclContext() != MD)
2341 return true;
2342
2343 return false;
2344}
2345
2347 // A declaration named in an unevaluated operand never constitutes an odr-use.
2349 return NOUR_Unevaluated;
2350
2351 // C++2a [basic.def.odr]p4:
2352 // A variable x whose name appears as a potentially-evaluated expression e
2353 // is odr-used by e unless [...] x is a reference that is usable in
2354 // constant expressions.
2355 // CUDA/HIP:
2356 // If a reference variable referencing a host variable is captured in a
2357 // device or host device lambda, the value of the referee must be copied
2358 // to the capture and the reference variable must be treated as odr-use
2359 // since the value of the referee is not known at compile time and must
2360 // be loaded from the captured.
2361 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2362 if (VD->getType()->isReferenceType() &&
2363 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2365 VD->isUsableInConstantExpressions(Context))
2366 return NOUR_Constant;
2367 }
2368
2369 // All remaining non-variable cases constitute an odr-use. For variables, we
2370 // need to wait and see how the expression is used.
2371 return NOUR_None;
2372}
2373
2376 const DeclarationNameInfo &NameInfo,
2377 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2378 SourceLocation TemplateKWLoc,
2379 const TemplateArgumentListInfo *TemplateArgs) {
2380 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2381 NeedToCaptureVariable(D, NameInfo.getLoc());
2382
2384 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2385 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2387
2388 // C++ [except.spec]p17:
2389 // An exception-specification is considered to be needed when:
2390 // - in an expression, the function is the unique lookup result or
2391 // the selected member of a set of overloaded functions.
2392 //
2393 // We delay doing this until after we've built the function reference and
2394 // marked it as used so that:
2395 // a) if the function is defaulted, we get errors from defining it before /
2396 // instead of errors from computing its exception specification, and
2397 // b) if the function is a defaulted comparison, we can use the body we
2398 // build when defining it as input to the exception specification
2399 // computation rather than computing a new body.
2400 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2401 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2402 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2404 }
2405 }
2406
2407 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2409 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2411
2412 const auto *FD = dyn_cast<FieldDecl>(D);
2413 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2414 FD = IFD->getAnonField();
2415 if (FD) {
2416 UnusedPrivateFields.remove(FD);
2417 // Just in case we're building an illegal pointer-to-member.
2418 if (FD->isBitField())
2420 }
2421
2422 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2423 // designates a bit-field.
2424 if (const auto *BD = dyn_cast<BindingDecl>(D))
2425 if (const auto *BE = BD->getBinding())
2426 E->setObjectKind(BE->getObjectKind());
2427
2428 return E;
2429}
2430
2431void
2434 DeclarationNameInfo &NameInfo,
2435 const TemplateArgumentListInfo *&TemplateArgs) {
2436 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2437 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2438 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2439
2440 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2441 Id.TemplateId->NumArgs);
2442 translateTemplateArguments(TemplateArgsPtr, Buffer);
2443
2444 TemplateName TName = Id.TemplateId->Template.get();
2445 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2446 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2447 TemplateArgs = &Buffer;
2448 } else {
2449 NameInfo = GetNameFromUnqualifiedId(Id);
2450 TemplateArgs = nullptr;
2451 }
2452}
2453
2455 // During a default argument instantiation the CurContext points
2456 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2457 // function parameter list, hence add an explicit check.
2458 bool isDefaultArgument =
2459 !CodeSynthesisContexts.empty() &&
2460 CodeSynthesisContexts.back().Kind ==
2462 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2463 bool isInstance = CurMethod && CurMethod->isInstance() &&
2464 R.getNamingClass() == CurMethod->getParent() &&
2465 !isDefaultArgument;
2466
2467 // There are two ways we can find a class-scope declaration during template
2468 // instantiation that we did not find in the template definition: if it is a
2469 // member of a dependent base class, or if it is declared after the point of
2470 // use in the same class. Distinguish these by comparing the class in which
2471 // the member was found to the naming class of the lookup.
2472 unsigned DiagID = diag::err_found_in_dependent_base;
2473 unsigned NoteID = diag::note_member_declared_at;
2475 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2476 : diag::err_found_later_in_class;
2477 } else if (getLangOpts().MSVCCompat) {
2478 DiagID = diag::ext_found_in_dependent_base;
2479 NoteID = diag::note_dependent_member_use;
2480 }
2481
2482 if (isInstance) {
2483 // Give a code modification hint to insert 'this->'.
2484 Diag(R.getNameLoc(), DiagID)
2485 << R.getLookupName()
2486 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2488 } else {
2489 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2490 // they're not shadowed).
2491 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2492 }
2493
2494 for (const NamedDecl *D : R)
2495 Diag(D->getLocation(), NoteID);
2496
2497 // Return true if we are inside a default argument instantiation
2498 // and the found name refers to an instance member function, otherwise
2499 // the caller will try to create an implicit member call and this is wrong
2500 // for default arguments.
2501 //
2502 // FIXME: Is this special case necessary? We could allow the caller to
2503 // diagnose this.
2504 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2505 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2506 return true;
2507 }
2508
2509 // Tell the callee to try to recover.
2510 return false;
2511}
2512
2515 TemplateArgumentListInfo *ExplicitTemplateArgs,
2516 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2517 DeclarationName Name = R.getLookupName();
2519
2520 unsigned diagnostic = diag::err_undeclared_var_use;
2521 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2522 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2523 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2524 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2525 diagnostic = diag::err_undeclared_use;
2526 diagnostic_suggest = diag::err_undeclared_use_suggest;
2527 }
2528
2529 // If the original lookup was an unqualified lookup, fake an
2530 // unqualified lookup. This is useful when (for example) the
2531 // original lookup would not have found something because it was a
2532 // dependent name.
2533 DeclContext *DC =
2534 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2535 while (DC) {
2536 if (isa<CXXRecordDecl>(DC)) {
2537 if (ExplicitTemplateArgs) {
2539 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2540 /*EnteringContext*/ false, TemplateNameIsRequired,
2541 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2542 return true;
2543 } else {
2544 LookupQualifiedName(R, DC);
2545 }
2546
2547 if (!R.empty()) {
2548 // Don't give errors about ambiguities in this lookup.
2550
2551 // If there's a best viable function among the results, only mention
2552 // that one in the notes.
2553 OverloadCandidateSet Candidates(R.getNameLoc(),
2555 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2557 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2558 OR_Success) {
2559 R.clear();
2560 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2561 R.resolveKind();
2562 }
2563
2565 }
2566
2567 R.clear();
2568 }
2569
2570 DC = DC->getLookupParent();
2571 }
2572
2573 // We didn't find anything, so try to correct for a typo.
2574 TypoCorrection Corrected;
2575 if (S && (Corrected =
2577 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2578 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2579 bool DroppedSpecifier =
2580 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2581 R.setLookupName(Corrected.getCorrection());
2582
2583 bool AcceptableWithRecovery = false;
2584 bool AcceptableWithoutRecovery = false;
2585 NamedDecl *ND = Corrected.getFoundDecl();
2586 if (ND) {
2587 if (Corrected.isOverloaded()) {
2591 for (NamedDecl *CD : Corrected) {
2592 if (FunctionTemplateDecl *FTD =
2593 dyn_cast<FunctionTemplateDecl>(CD))
2595 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2596 Args, OCS);
2597 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2598 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2600 Args, OCS);
2601 }
2602 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2603 case OR_Success:
2604 ND = Best->FoundDecl;
2605 Corrected.setCorrectionDecl(ND);
2606 break;
2607 default:
2608 // FIXME: Arbitrarily pick the first declaration for the note.
2609 Corrected.setCorrectionDecl(ND);
2610 break;
2611 }
2612 }
2613 R.addDecl(ND);
2614 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2617 if (!Record)
2618 Record = cast<CXXRecordDecl>(
2621 }
2622
2623 auto *UnderlyingND = ND->getUnderlyingDecl();
2624 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2625 isa<FunctionTemplateDecl>(UnderlyingND);
2626 // FIXME: If we ended up with a typo for a type name or
2627 // Objective-C class name, we're in trouble because the parser
2628 // is in the wrong place to recover. Suggest the typo
2629 // correction, but don't make it a fix-it since we're not going
2630 // to recover well anyway.
2631 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2632 getAsTypeTemplateDecl(UnderlyingND) ||
2633 isa<ObjCInterfaceDecl>(UnderlyingND);
2634 } else {
2635 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2636 // because we aren't able to recover.
2637 AcceptableWithoutRecovery = true;
2638 }
2639
2640 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2641 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2642 ? diag::note_implicit_param_decl
2643 : diag::note_previous_decl;
2644 if (SS.isEmpty())
2645 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2646 PDiag(NoteID), AcceptableWithRecovery);
2647 else
2648 diagnoseTypo(Corrected,
2649 PDiag(diag::err_no_member_suggest)
2650 << Name << computeDeclContext(SS, false)
2651 << DroppedSpecifier << NameRange,
2652 PDiag(NoteID), AcceptableWithRecovery);
2653
2654 // Tell the callee whether to try to recover.
2655 return !AcceptableWithRecovery;
2656 }
2657 }
2658 R.clear();
2659
2660 // Emit a special diagnostic for failed member lookups.
2661 // FIXME: computing the declaration context might fail here (?)
2662 if (!SS.isEmpty()) {
2663 Diag(R.getNameLoc(), diag::err_no_member)
2664 << Name << computeDeclContext(SS, false) << NameRange;
2665 return true;
2666 }
2667
2668 // Give up, we can't recover.
2669 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2670 return true;
2671}
2672
2673/// In Microsoft mode, if we are inside a template class whose parent class has
2674/// dependent base classes, and we can't resolve an unqualified identifier, then
2675/// assume the identifier is a member of a dependent base class. We can only
2676/// recover successfully in static methods, instance methods, and other contexts
2677/// where 'this' is available. This doesn't precisely match MSVC's
2678/// instantiation model, but it's close enough.
2679static Expr *
2681 DeclarationNameInfo &NameInfo,
2682 SourceLocation TemplateKWLoc,
2683 const TemplateArgumentListInfo *TemplateArgs) {
2684 // Only try to recover from lookup into dependent bases in static methods or
2685 // contexts where 'this' is available.
2686 QualType ThisType = S.getCurrentThisType();
2687 const CXXRecordDecl *RD = nullptr;
2688 if (!ThisType.isNull())
2689 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2690 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2691 RD = MD->getParent();
2692 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2693 return nullptr;
2694
2695 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2696 // is available, suggest inserting 'this->' as a fixit.
2697 SourceLocation Loc = NameInfo.getLoc();
2698 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2699 DB << NameInfo.getName() << RD;
2700
2701 if (!ThisType.isNull()) {
2702 DB << FixItHint::CreateInsertion(Loc, "this->");
2704 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2705 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2706 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2707 }
2708
2709 // Synthesize a fake NNS that points to the derived class. This will
2710 // perform name lookup during template instantiation.
2711 CXXScopeSpec SS;
2713 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2715 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2716 TemplateArgs);
2717}
2718
2721 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2722 bool HasTrailingLParen, bool IsAddressOfOperand,
2724 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2725 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2726 "cannot be direct & operand and have a trailing lparen");
2727 if (SS.isInvalid())
2728 return ExprError();
2729
2730 TemplateArgumentListInfo TemplateArgsBuffer;
2731
2732 // Decompose the UnqualifiedId into the following data.
2733 DeclarationNameInfo NameInfo;
2734 const TemplateArgumentListInfo *TemplateArgs;
2735 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2736
2737 DeclarationName Name = NameInfo.getName();
2738 IdentifierInfo *II = Name.getAsIdentifierInfo();
2739 SourceLocation NameLoc = NameInfo.getLoc();
2740
2741 if (II && II->isEditorPlaceholder()) {
2742 // FIXME: When typed placeholders are supported we can create a typed
2743 // placeholder expression node.
2744 return ExprError();
2745 }
2746
2747 // This specially handles arguments of attributes appertains to a type of C
2748 // struct field such that the name lookup within a struct finds the member
2749 // name, which is not the case for other contexts in C.
2750 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2751 // See if this is reference to a field of struct.
2752 LookupResult R(*this, NameInfo, LookupMemberName);
2753 // LookupName handles a name lookup from within anonymous struct.
2754 if (LookupName(R, S)) {
2755 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2756 QualType type = VD->getType().getNonReferenceType();
2757 // This will eventually be translated into MemberExpr upon
2758 // the use of instantiated struct fields.
2759 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2760 }
2761 }
2762 }
2763
2764 // Perform the required lookup.
2765 LookupResult R(*this, NameInfo,
2769 if (TemplateKWLoc.isValid() || TemplateArgs) {
2770 // Lookup the template name again to correctly establish the context in
2771 // which it was found. This is really unfortunate as we already did the
2772 // lookup to determine that it was a template name in the first place. If
2773 // this becomes a performance hit, we can work harder to preserve those
2774 // results until we get here but it's likely not worth it.
2775 AssumedTemplateKind AssumedTemplate;
2776 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2777 /*EnteringContext=*/false, TemplateKWLoc,
2778 &AssumedTemplate))
2779 return ExprError();
2780
2782 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2783 IsAddressOfOperand, TemplateArgs);
2784 } else {
2785 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2786 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2787 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2788
2789 // If the result might be in a dependent base class, this is a dependent
2790 // id-expression.
2792 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2793 IsAddressOfOperand, TemplateArgs);
2794
2795 // If this reference is in an Objective-C method, then we need to do
2796 // some special Objective-C lookup, too.
2797 if (IvarLookupFollowUp) {
2798 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2799 if (E.isInvalid())
2800 return ExprError();
2801
2802 if (Expr *Ex = E.getAs<Expr>())
2803 return Ex;
2804 }
2805 }
2806
2807 if (R.isAmbiguous())
2808 return ExprError();
2809
2810 // This could be an implicitly declared function reference if the language
2811 // mode allows it as a feature.
2812 if (R.empty() && HasTrailingLParen && II &&
2813 getLangOpts().implicitFunctionsAllowed()) {
2814 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2815 if (D) R.addDecl(D);
2816 }
2817
2818 // Determine whether this name might be a candidate for
2819 // argument-dependent lookup.
2820 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2821
2822 if (R.empty() && !ADL) {
2823 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2824 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2825 TemplateKWLoc, TemplateArgs))
2826 return E;
2827 }
2828
2829 // Don't diagnose an empty lookup for inline assembly.
2830 if (IsInlineAsmIdentifier)
2831 return ExprError();
2832
2833 // If this name wasn't predeclared and if this is not a function
2834 // call, diagnose the problem.
2835 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2836 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2837 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2838 "Typo correction callback misconfigured");
2839 if (CCC) {
2840 // Make sure the callback knows what the typo being diagnosed is.
2841 CCC->setTypoName(II);
2842 if (SS.isValid())
2843 CCC->setTypoNNS(SS.getScopeRep());
2844 }
2845 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2846 // a template name, but we happen to have always already looked up the name
2847 // before we get here if it must be a template name.
2848 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2849 {}, nullptr))
2850 return ExprError();
2851
2852 assert(!R.empty() &&
2853 "DiagnoseEmptyLookup returned false but added no results");
2854
2855 // If we found an Objective-C instance variable, let
2856 // LookupInObjCMethod build the appropriate expression to
2857 // reference the ivar.
2858 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2859 R.clear();
2860 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2861 // In a hopelessly buggy code, Objective-C instance variable
2862 // lookup fails and no expression will be built to reference it.
2863 if (!E.isInvalid() && !E.get())
2864 return ExprError();
2865 return E;
2866 }
2867 }
2868
2869 // This is guaranteed from this point on.
2870 assert(!R.empty() || ADL);
2871
2872 // Check whether this might be a C++ implicit instance member access.
2873 // C++ [class.mfct.non-static]p3:
2874 // When an id-expression that is not part of a class member access
2875 // syntax and not used to form a pointer to member is used in the
2876 // body of a non-static member function of class X, if name lookup
2877 // resolves the name in the id-expression to a non-static non-type
2878 // member of some class C, the id-expression is transformed into a
2879 // class member access expression using (*this) as the
2880 // postfix-expression to the left of the . operator.
2881 //
2882 // But we don't actually need to do this for '&' operands if R
2883 // resolved to a function or overloaded function set, because the
2884 // expression is ill-formed if it actually works out to be a
2885 // non-static member function:
2886 //
2887 // C++ [expr.ref]p4:
2888 // Otherwise, if E1.E2 refers to a non-static member function. . .
2889 // [t]he expression can be used only as the left-hand operand of a
2890 // member function call.
2891 //
2892 // There are other safeguards against such uses, but it's important
2893 // to get this right here so that we don't end up making a
2894 // spuriously dependent expression if we're inside a dependent
2895 // instance method.
2896 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2897 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2898 S);
2899
2900 if (TemplateArgs || TemplateKWLoc.isValid()) {
2901
2902 // In C++1y, if this is a variable template id, then check it
2903 // in BuildTemplateIdExpr().
2904 // The single lookup result must be a variable template declaration.
2905 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2906 (Id.TemplateId->Kind == TNK_Var_template ||
2907 Id.TemplateId->Kind == TNK_Concept_template)) {
2908 assert(R.getAsSingle<TemplateDecl>() &&
2909 "There should only be one declaration found.");
2910 }
2911
2912 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2913 }
2914
2915 return BuildDeclarationNameExpr(SS, R, ADL);
2916}
2917
2919 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2920 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2921 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2922 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2923
2924 if (R.isAmbiguous())
2925 return ExprError();
2926
2928 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2929 NameInfo, /*TemplateArgs=*/nullptr);
2930
2931 if (R.empty()) {
2932 // Don't diagnose problems with invalid record decl, the secondary no_member
2933 // diagnostic during template instantiation is likely bogus, e.g. if a class
2934 // is invalid because it's derived from an invalid base class, then missing
2935 // members were likely supposed to be inherited.
2937 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2938 if (CD->isInvalidDecl())
2939 return ExprError();
2940 Diag(NameInfo.getLoc(), diag::err_no_member)
2941 << NameInfo.getName() << DC << SS.getRange();
2942 return ExprError();
2943 }
2944
2945 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2946 QualType ET;
2947 TypeLocBuilder TLB;
2948 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
2950 SS.getScopeRep(), TagD,
2951 /*OwnsTag=*/false);
2952 auto TL = TLB.push<TagTypeLoc>(ET);
2954 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2955 TL.setNameLoc(NameInfo.getLoc());
2956 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
2958 SS.getScopeRep(), TypedefD);
2959 TLB.push<TypedefTypeLoc>(ET).set(
2960 /*ElaboratedKeywordLoc=*/SourceLocation(),
2961 SS.getWithLocInContext(Context), NameInfo.getLoc());
2962 } else {
2963 // FIXME: What else can appear here?
2965 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
2966 assert(SS.isEmpty());
2967 }
2968
2969 // Diagnose a missing typename if this resolved unambiguously to a type in
2970 // a dependent context. If we can recover with a type, downgrade this to
2971 // a warning in Microsoft compatibility mode.
2972 unsigned DiagID = diag::err_typename_missing;
2973 if (RecoveryTSI && getLangOpts().MSVCCompat)
2974 DiagID = diag::ext_typename_missing;
2976 auto D = Diag(Loc, DiagID);
2977 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2978
2979 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2980 // context.
2981 if (!RecoveryTSI)
2982 return ExprError();
2983
2984 // Only issue the fixit if we're prepared to recover.
2985 D << FixItHint::CreateInsertion(Loc, "typename ");
2986
2987 // Recover by pretending this was an elaborated type.
2988 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2989
2990 return ExprEmpty();
2991 }
2992
2993 // If necessary, build an implicit class member access.
2994 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2996 /*TemplateKWLoc=*/SourceLocation(),
2997 R, /*TemplateArgs=*/nullptr,
2998 /*S=*/nullptr);
2999
3000 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3001}
3002
3004 NestedNameSpecifier Qualifier,
3005 NamedDecl *FoundDecl,
3006 NamedDecl *Member) {
3007 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3008 if (!RD)
3009 return From;
3010
3011 QualType DestRecordType;
3012 QualType DestType;
3013 QualType FromRecordType;
3014 QualType FromType = From->getType();
3015 bool PointerConversions = false;
3016 if (isa<FieldDecl>(Member)) {
3017 DestRecordType = Context.getCanonicalTagType(RD);
3018 auto FromPtrType = FromType->getAs<PointerType>();
3019 DestRecordType = Context.getAddrSpaceQualType(
3020 DestRecordType, FromPtrType
3021 ? FromType->getPointeeType().getAddressSpace()
3022 : FromType.getAddressSpace());
3023
3024 if (FromPtrType) {
3025 DestType = Context.getPointerType(DestRecordType);
3026 FromRecordType = FromPtrType->getPointeeType();
3027 PointerConversions = true;
3028 } else {
3029 DestType = DestRecordType;
3030 FromRecordType = FromType;
3031 }
3032 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3033 if (!Method->isImplicitObjectMemberFunction())
3034 return From;
3035
3036 DestType = Method->getThisType().getNonReferenceType();
3037 DestRecordType = Method->getFunctionObjectParameterType();
3038
3039 if (FromType->getAs<PointerType>()) {
3040 FromRecordType = FromType->getPointeeType();
3041 PointerConversions = true;
3042 } else {
3043 FromRecordType = FromType;
3044 DestType = DestRecordType;
3045 }
3046
3047 LangAS FromAS = FromRecordType.getAddressSpace();
3048 LangAS DestAS = DestRecordType.getAddressSpace();
3049 if (FromAS != DestAS) {
3050 QualType FromRecordTypeWithoutAS =
3051 Context.removeAddrSpaceQualType(FromRecordType);
3052 QualType FromTypeWithDestAS =
3053 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3054 if (PointerConversions)
3055 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3056 From = ImpCastExprToType(From, FromTypeWithDestAS,
3057 CK_AddressSpaceConversion, From->getValueKind())
3058 .get();
3059 }
3060 } else {
3061 // No conversion necessary.
3062 return From;
3063 }
3064
3065 if (DestType->isDependentType() || FromType->isDependentType())
3066 return From;
3067
3068 // If the unqualified types are the same, no conversion is necessary.
3069 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3070 return From;
3071
3072 SourceRange FromRange = From->getSourceRange();
3073 SourceLocation FromLoc = FromRange.getBegin();
3074
3075 ExprValueKind VK = From->getValueKind();
3076
3077 // C++ [class.member.lookup]p8:
3078 // [...] Ambiguities can often be resolved by qualifying a name with its
3079 // class name.
3080 //
3081 // If the member was a qualified name and the qualified referred to a
3082 // specific base subobject type, we'll cast to that intermediate type
3083 // first and then to the object in which the member is declared. That allows
3084 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3085 //
3086 // class Base { public: int x; };
3087 // class Derived1 : public Base { };
3088 // class Derived2 : public Base { };
3089 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3090 //
3091 // void VeryDerived::f() {
3092 // x = 17; // error: ambiguous base subobjects
3093 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3094 // }
3095 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3096 QualType QType = QualType(Qualifier.getAsType(), 0);
3097 assert(QType->isRecordType() && "lookup done with non-record type");
3098
3099 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3100
3101 // In C++98, the qualifier type doesn't actually have to be a base
3102 // type of the object type, in which case we just ignore it.
3103 // Otherwise build the appropriate casts.
3104 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3105 CXXCastPath BasePath;
3106 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3107 FromLoc, FromRange, &BasePath))
3108 return ExprError();
3109
3110 if (PointerConversions)
3111 QType = Context.getPointerType(QType);
3112 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3113 VK, &BasePath).get();
3114
3115 FromType = QType;
3116 FromRecordType = QRecordType;
3117
3118 // If the qualifier type was the same as the destination type,
3119 // we're done.
3120 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3121 return From;
3122 }
3123 }
3124
3125 CXXCastPath BasePath;
3126 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3127 FromLoc, FromRange, &BasePath,
3128 /*IgnoreAccess=*/true))
3129 return ExprError();
3130
3131 // Propagate qualifiers to base subobjects as per:
3132 // C++ [basic.type.qualifier]p1.2:
3133 // A volatile object is [...] a subobject of a volatile object.
3134 Qualifiers FromTypeQuals = FromType.getQualifiers();
3135 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3136 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3137
3138 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3139 &BasePath);
3140}
3141
3143 const LookupResult &R,
3144 bool HasTrailingLParen) {
3145 // Only when used directly as the postfix-expression of a call.
3146 if (!HasTrailingLParen)
3147 return false;
3148
3149 // Never if a scope specifier was provided.
3150 if (SS.isNotEmpty())
3151 return false;
3152
3153 // Only in C++ or ObjC++.
3154 if (!getLangOpts().CPlusPlus)
3155 return false;
3156
3157 // Turn off ADL when we find certain kinds of declarations during
3158 // normal lookup:
3159 for (const NamedDecl *D : R) {
3160 // C++0x [basic.lookup.argdep]p3:
3161 // -- a declaration of a class member
3162 // Since using decls preserve this property, we check this on the
3163 // original decl.
3164 if (D->isCXXClassMember())
3165 return false;
3166
3167 // C++0x [basic.lookup.argdep]p3:
3168 // -- a block-scope function declaration that is not a
3169 // using-declaration
3170 // NOTE: we also trigger this for function templates (in fact, we
3171 // don't check the decl type at all, since all other decl types
3172 // turn off ADL anyway).
3173 if (isa<UsingShadowDecl>(D))
3174 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3176 return false;
3177
3178 // C++0x [basic.lookup.argdep]p3:
3179 // -- a declaration that is neither a function or a function
3180 // template
3181 // And also for builtin functions.
3182 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3183 // But also builtin functions.
3184 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3185 return false;
3186 } else if (!isa<FunctionTemplateDecl>(D))
3187 return false;
3188 }
3189
3190 return true;
3191}
3192
3193
3194/// Diagnoses obvious problems with the use of the given declaration
3195/// as an expression. This is only actually called for lookups that
3196/// were not overloaded, and it doesn't promise that the declaration
3197/// will in fact be used.
3199 bool AcceptInvalid) {
3200 if (D->isInvalidDecl() && !AcceptInvalid)
3201 return true;
3202
3203 if (isa<TypedefNameDecl>(D)) {
3204 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3205 return true;
3206 }
3207
3208 if (isa<ObjCInterfaceDecl>(D)) {
3209 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3210 return true;
3211 }
3212
3213 if (isa<NamespaceDecl>(D)) {
3214 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3215 return true;
3216 }
3217
3218 return false;
3219}
3220
3221// Certain multiversion types should be treated as overloaded even when there is
3222// only one result.
3224 assert(R.isSingleResult() && "Expected only a single result");
3225 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3226 return FD &&
3227 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3228}
3229
3231 LookupResult &R, bool NeedsADL,
3232 bool AcceptInvalidDecl) {
3233 // If this is a single, fully-resolved result and we don't need ADL,
3234 // just build an ordinary singleton decl ref.
3235 if (!NeedsADL && R.isSingleResult() &&
3239 R.getRepresentativeDecl(), nullptr,
3240 AcceptInvalidDecl);
3241
3242 // We only need to check the declaration if there's exactly one
3243 // result, because in the overloaded case the results can only be
3244 // functions and function templates.
3246 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3247 AcceptInvalidDecl))
3248 return ExprError();
3249
3250 // Otherwise, just build an unresolved lookup expression. Suppress
3251 // any lookup-related diagnostics; we'll hash these out later, when
3252 // we've picked a target.
3254
3257 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3258 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3259
3260 return ULE;
3261}
3262
3264 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3265 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3266 bool AcceptInvalidDecl) {
3267 assert(D && "Cannot refer to a NULL declaration");
3268 assert(!isa<FunctionTemplateDecl>(D) &&
3269 "Cannot refer unambiguously to a function template");
3270
3271 SourceLocation Loc = NameInfo.getLoc();
3272 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3273 // Recovery from invalid cases (e.g. D is an invalid Decl).
3274 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3275 // diagnostics, as invalid decls use int as a fallback type.
3276 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3277 }
3278
3279 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3280 // Specifically diagnose references to class templates that are missing
3281 // a template argument list.
3282 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3283 return ExprError();
3284 }
3285
3286 // Make sure that we're referring to a value.
3287 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3288 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3289 Diag(D->getLocation(), diag::note_declared_at);
3290 return ExprError();
3291 }
3292
3293 // Check whether this declaration can be used. Note that we suppress
3294 // this check when we're going to perform argument-dependent lookup
3295 // on this function name, because this might not be the function
3296 // that overload resolution actually selects.
3297 if (DiagnoseUseOfDecl(D, Loc))
3298 return ExprError();
3299
3300 auto *VD = cast<ValueDecl>(D);
3301
3302 // Only create DeclRefExpr's for valid Decl's.
3303 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3304 return ExprError();
3305
3306 // Handle members of anonymous structs and unions. If we got here,
3307 // and the reference is to a class member indirect field, then this
3308 // must be the subject of a pointer-to-member expression.
3309 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3310 IndirectField && !IndirectField->isCXXClassMember())
3312 IndirectField);
3313
3314 QualType type = VD->getType();
3315 if (type.isNull())
3316 return ExprError();
3317 ExprValueKind valueKind = VK_PRValue;
3318
3319 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3320 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3321 // is expanded by some outer '...' in the context of the use.
3322 type = type.getNonPackExpansionType();
3323
3324 switch (D->getKind()) {
3325 // Ignore all the non-ValueDecl kinds.
3326#define ABSTRACT_DECL(kind)
3327#define VALUE(type, base)
3328#define DECL(type, base) case Decl::type:
3329#include "clang/AST/DeclNodes.inc"
3330 llvm_unreachable("invalid value decl kind");
3331
3332 // These shouldn't make it here.
3333 case Decl::ObjCAtDefsField:
3334 llvm_unreachable("forming non-member reference to ivar?");
3335
3336 // Enum constants are always r-values and never references.
3337 // Unresolved using declarations are dependent.
3338 case Decl::EnumConstant:
3339 case Decl::UnresolvedUsingValue:
3340 case Decl::OMPDeclareReduction:
3341 case Decl::OMPDeclareMapper:
3342 valueKind = VK_PRValue;
3343 break;
3344
3345 // Fields and indirect fields that got here must be for
3346 // pointer-to-member expressions; we just call them l-values for
3347 // internal consistency, because this subexpression doesn't really
3348 // exist in the high-level semantics.
3349 case Decl::Field:
3350 case Decl::IndirectField:
3351 case Decl::ObjCIvar:
3352 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3353 "building reference to field in C?");
3354
3355 // These can't have reference type in well-formed programs, but
3356 // for internal consistency we do this anyway.
3357 type = type.getNonReferenceType();
3358 valueKind = VK_LValue;
3359 break;
3360
3361 // Non-type template parameters are either l-values or r-values
3362 // depending on the type.
3363 case Decl::NonTypeTemplateParm: {
3364 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3365 type = reftype->getPointeeType();
3366 valueKind = VK_LValue; // even if the parameter is an r-value reference
3367 break;
3368 }
3369
3370 // [expr.prim.id.unqual]p2:
3371 // If the entity is a template parameter object for a template
3372 // parameter of type T, the type of the expression is const T.
3373 // [...] The expression is an lvalue if the entity is a [...] template
3374 // parameter object.
3375 if (type->isRecordType()) {
3376 type = type.getUnqualifiedType().withConst();
3377 valueKind = VK_LValue;
3378 break;
3379 }
3380
3381 // For non-references, we need to strip qualifiers just in case
3382 // the template parameter was declared as 'const int' or whatever.
3383 valueKind = VK_PRValue;
3384 type = type.getUnqualifiedType();
3385 break;
3386 }
3387
3388 case Decl::Var:
3389 case Decl::VarTemplateSpecialization:
3390 case Decl::VarTemplatePartialSpecialization:
3391 case Decl::Decomposition:
3392 case Decl::Binding:
3393 case Decl::OMPCapturedExpr:
3394 // In C, "extern void blah;" is valid and is an r-value.
3395 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3396 type->isVoidType()) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400 [[fallthrough]];
3401
3402 case Decl::ImplicitParam:
3403 case Decl::ParmVar: {
3404 // These are always l-values.
3405 valueKind = VK_LValue;
3406 type = type.getNonReferenceType();
3407
3408 // FIXME: Does the addition of const really only apply in
3409 // potentially-evaluated contexts? Since the variable isn't actually
3410 // captured in an unevaluated context, it seems that the answer is no.
3411 if (!isUnevaluatedContext()) {
3412 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3413 if (!CapturedType.isNull())
3414 type = CapturedType;
3415 }
3416 break;
3417 }
3418
3419 case Decl::Function: {
3420 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3423 valueKind = VK_PRValue;
3424 break;
3425 }
3426 }
3427
3428 const FunctionType *fty = type->castAs<FunctionType>();
3429
3430 // If we're referring to a function with an __unknown_anytype
3431 // result type, make the entire expression __unknown_anytype.
3432 if (fty->getReturnType() == Context.UnknownAnyTy) {
3434 valueKind = VK_PRValue;
3435 break;
3436 }
3437
3438 // Functions are l-values in C++.
3439 if (getLangOpts().CPlusPlus) {
3440 valueKind = VK_LValue;
3441 break;
3442 }
3443
3444 // C99 DR 316 says that, if a function type comes from a
3445 // function definition (without a prototype), that type is only
3446 // used for checking compatibility. Therefore, when referencing
3447 // the function, we pretend that we don't have the full function
3448 // type.
3449 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3451 fty->getExtInfo());
3452
3453 // Functions are r-values in C.
3454 valueKind = VK_PRValue;
3455 break;
3456 }
3457
3458 case Decl::CXXDeductionGuide:
3459 llvm_unreachable("building reference to deduction guide");
3460
3461 case Decl::MSProperty:
3462 case Decl::MSGuid:
3463 case Decl::TemplateParamObject:
3464 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3465 // capture in OpenMP, or duplicated between host and device?
3466 valueKind = VK_LValue;
3467 break;
3468
3469 case Decl::UnnamedGlobalConstant:
3470 valueKind = VK_LValue;
3471 break;
3472
3473 case Decl::CXXMethod:
3474 // If we're referring to a method with an __unknown_anytype
3475 // result type, make the entire expression __unknown_anytype.
3476 // This should only be possible with a type written directly.
3477 if (const FunctionProtoType *proto =
3478 dyn_cast<FunctionProtoType>(VD->getType()))
3479 if (proto->getReturnType() == Context.UnknownAnyTy) {
3481 valueKind = VK_PRValue;
3482 break;
3483 }
3484
3485 // C++ methods are l-values if static, r-values if non-static.
3486 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3487 valueKind = VK_LValue;
3488 break;
3489 }
3490 [[fallthrough]];
3491
3492 case Decl::CXXConversion:
3493 case Decl::CXXDestructor:
3494 case Decl::CXXConstructor:
3495 valueKind = VK_PRValue;
3496 break;
3497 }
3498
3499 auto *E =
3500 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3501 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3502 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3503 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3504 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3505 // diagnostics).
3506 if (VD->isInvalidDecl() && E)
3507 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3508 return E;
3509}
3510
3511static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3513 Target.resize(CharByteWidth * (Source.size() + 1));
3514 char *ResultPtr = &Target[0];
3515 const llvm::UTF8 *ErrorPtr;
3516 bool success =
3517 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3518 (void)success;
3519 assert(success);
3520 Target.resize(ResultPtr - &Target[0]);
3521}
3522
3525 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3526 if (!currentDecl) {
3527 Diag(Loc, diag::ext_predef_outside_function);
3528 currentDecl = Context.getTranslationUnitDecl();
3529 }
3530
3531 QualType ResTy;
3532 StringLiteral *SL = nullptr;
3533 if (cast<DeclContext>(currentDecl)->isDependentContext())
3534 ResTy = Context.DependentTy;
3535 else {
3536 // Pre-defined identifiers are of type char[x], where x is the length of
3537 // the string.
3538 bool ForceElaboratedPrinting =
3539 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3540 auto Str =
3541 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3542 unsigned Length = Str.length();
3543
3544 llvm::APInt LengthI(32, Length + 1);
3547 ResTy =
3549 SmallString<32> RawChars;
3551 Str, RawChars);
3552 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3554 /*IndexTypeQuals*/ 0);
3556 /*Pascal*/ false, ResTy, Loc);
3557 } else {
3559 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3561 /*IndexTypeQuals*/ 0);
3563 /*Pascal*/ false, ResTy, Loc);
3564 }
3565 }
3566
3567 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3568 SL);
3569}
3570
3573}
3574
3576 SmallString<16> CharBuffer;
3577 bool Invalid = false;
3578 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3579 if (Invalid)
3580 return ExprError();
3581
3582 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3583 PP, Tok.getKind());
3584 if (Literal.hadError())
3585 return ExprError();
3586
3587 QualType Ty;
3588 if (Literal.isWide())
3589 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3590 else if (Literal.isUTF8() && getLangOpts().C23)
3591 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3592 else if (Literal.isUTF8() && getLangOpts().Char8)
3593 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3594 else if (Literal.isUTF16())
3595 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3596 else if (Literal.isUTF32())
3597 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3598 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3599 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3600 else
3601 Ty = Context.CharTy; // 'x' -> char in C++;
3602 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3603
3605 if (Literal.isWide())
3607 else if (Literal.isUTF16())
3609 else if (Literal.isUTF32())
3611 else if (Literal.isUTF8())
3613
3614 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3615 Tok.getLocation());
3616
3617 if (Literal.getUDSuffix().empty())
3618 return Lit;
3619
3620 // We're building a user-defined literal.
3621 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3622 SourceLocation UDSuffixLoc =
3623 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3624
3625 // Make sure we're allowed user-defined literals here.
3626 if (!UDLScope)
3627 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3628
3629 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3630 // operator "" X (ch)
3631 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3632 Lit, Tok.getLocation());
3633}
3634
3636 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3638 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3639 Context.IntTy, Loc);
3640}
3641
3644 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3645
3646 using llvm::APFloat;
3647 APFloat Val(Format);
3648
3649 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3650 if (RM == llvm::RoundingMode::Dynamic)
3651 RM = llvm::RoundingMode::NearestTiesToEven;
3652 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3653
3654 // Overflow is always an error, but underflow is only an error if
3655 // we underflowed to zero (APFloat reports denormals as underflow).
3656 if ((result & APFloat::opOverflow) ||
3657 ((result & APFloat::opUnderflow) && Val.isZero())) {
3658 unsigned diagnostic;
3659 SmallString<20> buffer;
3660 if (result & APFloat::opOverflow) {
3661 diagnostic = diag::warn_float_overflow;
3662 APFloat::getLargest(Format).toString(buffer);
3663 } else {
3664 diagnostic = diag::warn_float_underflow;
3665 APFloat::getSmallest(Format).toString(buffer);
3666 }
3667
3668 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3669 }
3670
3671 bool isExact = (result == APFloat::opOK);
3672 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3673}
3674
3676 assert(E && "Invalid expression");
3677
3678 if (E->isValueDependent())
3679 return false;
3680
3681 QualType QT = E->getType();
3682 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3683 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3684 return true;
3685 }
3686
3687 llvm::APSInt ValueAPS;
3689
3690 if (R.isInvalid())
3691 return true;
3692
3693 // GCC allows the value of unroll count to be 0.
3694 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3695 // "The values of 0 and 1 block any unrolling of the loop."
3696 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3697 // '#pragma unroll' cases.
3698 bool ValueIsPositive =
3699 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3700 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3701 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3702 << toString(ValueAPS, 10) << ValueIsPositive;
3703 return true;
3704 }
3705
3706 return false;
3707}
3708
3710 // Fast path for a single digit (which is quite common). A single digit
3711 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3712 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3713 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3714 return ActOnIntegerConstant(Tok.getLocation(), Val);
3715 }
3716
3717 SmallString<128> SpellingBuffer;
3718 // NumericLiteralParser wants to overread by one character. Add padding to
3719 // the buffer in case the token is copied to the buffer. If getSpelling()
3720 // returns a StringRef to the memory buffer, it should have a null char at
3721 // the EOF, so it is also safe.
3722 SpellingBuffer.resize(Tok.getLength() + 1);
3723
3724 // Get the spelling of the token, which eliminates trigraphs, etc.
3725 bool Invalid = false;
3726 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3727 if (Invalid)
3728 return ExprError();
3729
3730 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3733 if (Literal.hadError)
3734 return ExprError();
3735
3736 if (Literal.hasUDSuffix()) {
3737 // We're building a user-defined literal.
3738 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3739 SourceLocation UDSuffixLoc =
3740 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3741
3742 // Make sure we're allowed user-defined literals here.
3743 if (!UDLScope)
3744 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3745
3746 QualType CookedTy;
3747 if (Literal.isFloatingLiteral()) {
3748 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3749 // long double, the literal is treated as a call of the form
3750 // operator "" X (f L)
3751 CookedTy = Context.LongDoubleTy;
3752 } else {
3753 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3754 // unsigned long long, the literal is treated as a call of the form
3755 // operator "" X (n ULL)
3756 CookedTy = Context.UnsignedLongLongTy;
3757 }
3758
3759 DeclarationName OpName =
3761 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3762 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3763
3764 SourceLocation TokLoc = Tok.getLocation();
3765
3766 // Perform literal operator lookup to determine if we're building a raw
3767 // literal or a cooked one.
3768 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3769 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3770 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3771 /*AllowStringTemplatePack*/ false,
3772 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3774 // Lookup failure for imaginary constants isn't fatal, there's still the
3775 // GNU extension producing _Complex types.
3776 break;
3777 case LOLR_Error:
3778 return ExprError();
3779 case LOLR_Cooked: {
3780 Expr *Lit;
3781 if (Literal.isFloatingLiteral()) {
3782 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3783 } else {
3784 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3785 if (Literal.GetIntegerValue(ResultVal))
3786 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3787 << /* Unsigned */ 1;
3788 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3789 Tok.getLocation());
3790 }
3791 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3792 }
3793
3794 case LOLR_Raw: {
3795 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3796 // literal is treated as a call of the form
3797 // operator "" X ("n")
3798 unsigned Length = Literal.getUDSuffixOffset();
3801 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3802 Expr *Lit =
3803 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3805 /*Pascal*/ false, StrTy, TokLoc);
3806 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3807 }
3808
3809 case LOLR_Template: {
3810 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3811 // template), L is treated as a call fo the form
3812 // operator "" X <'c1', 'c2', ... 'ck'>()
3813 // where n is the source character sequence c1 c2 ... ck.
3814 TemplateArgumentListInfo ExplicitArgs;
3815 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3816 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3817 llvm::APSInt Value(CharBits, CharIsUnsigned);
3818 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3819 Value = TokSpelling[I];
3822 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3823 }
3824 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3825 }
3827 llvm_unreachable("unexpected literal operator lookup result");
3828 }
3829 }
3830
3831 Expr *Res;
3832
3833 if (Literal.isFixedPointLiteral()) {
3834 QualType Ty;
3835
3836 if (Literal.isAccum) {
3837 if (Literal.isHalf) {
3838 Ty = Context.ShortAccumTy;
3839 } else if (Literal.isLong) {
3840 Ty = Context.LongAccumTy;
3841 } else {
3842 Ty = Context.AccumTy;
3843 }
3844 } else if (Literal.isFract) {
3845 if (Literal.isHalf) {
3846 Ty = Context.ShortFractTy;
3847 } else if (Literal.isLong) {
3848 Ty = Context.LongFractTy;
3849 } else {
3850 Ty = Context.FractTy;
3851 }
3852 }
3853
3854 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3855
3856 bool isSigned = !Literal.isUnsigned;
3857 unsigned scale = Context.getFixedPointScale(Ty);
3858 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3859
3860 llvm::APInt Val(bit_width, 0, isSigned);
3861 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3862 bool ValIsZero = Val.isZero() && !Overflowed;
3863
3864 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3865 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3866 // Clause 6.4.4 - The value of a constant shall be in the range of
3867 // representable values for its type, with exception for constants of a
3868 // fract type with a value of exactly 1; such a constant shall denote
3869 // the maximal value for the type.
3870 --Val;
3871 else if (Val.ugt(MaxVal) || Overflowed)
3872 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3873
3875 Tok.getLocation(), scale);
3876 } else if (Literal.isFloatingLiteral()) {
3877 QualType Ty;
3878 if (Literal.isHalf){
3879 if (getLangOpts().HLSL ||
3880 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3881 Ty = Context.HalfTy;
3882 else {
3883 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3884 return ExprError();
3885 }
3886 } else if (Literal.isFloat)
3887 Ty = Context.FloatTy;
3888 else if (Literal.isLong)
3890 else if (Literal.isFloat16)
3891 Ty = Context.Float16Ty;
3892 else if (Literal.isFloat128)
3893 Ty = Context.Float128Ty;
3894 else if (getLangOpts().HLSL)
3895 Ty = Context.FloatTy;
3896 else
3897 Ty = Context.DoubleTy;
3898
3899 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3900
3901 if (Ty == Context.DoubleTy) {
3902 if (getLangOpts().SinglePrecisionConstants) {
3903 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3904 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3905 }
3906 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3907 "cl_khr_fp64", getLangOpts())) {
3908 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3909 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3911 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3912 }
3913 }
3914 } else if (!Literal.isIntegerLiteral()) {
3915 return ExprError();
3916 } else {
3917 QualType Ty;
3918
3919 // 'z/uz' literals are a C++23 feature.
3920 if (Literal.isSizeT)
3923 ? diag::warn_cxx20_compat_size_t_suffix
3924 : diag::ext_cxx23_size_t_suffix
3925 : diag::err_cxx23_size_t_suffix);
3926
3927 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3928 // but we do not currently support the suffix in C++ mode because it's not
3929 // entirely clear whether WG21 will prefer this suffix to return a library
3930 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3931 // literals are a C++ extension.
3932 if (Literal.isBitInt)
3933 PP.Diag(Tok.getLocation(),
3934 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3935 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3936 : diag::ext_c23_bitint_suffix);
3937
3938 // Get the value in the widest-possible width. What is "widest" depends on
3939 // whether the literal is a bit-precise integer or not. For a bit-precise
3940 // integer type, try to scan the source to determine how many bits are
3941 // needed to represent the value. This may seem a bit expensive, but trying
3942 // to get the integer value from an overly-wide APInt is *extremely*
3943 // expensive, so the naive approach of assuming
3944 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3945 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3946 if (Literal.isBitInt)
3947 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3948 Literal.getLiteralDigits(), Literal.getRadix());
3949 if (Literal.MicrosoftInteger) {
3950 if (Literal.MicrosoftInteger == 128 &&
3952 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3953 << Literal.isUnsigned;
3954 BitsNeeded = Literal.MicrosoftInteger;
3955 }
3956
3957 llvm::APInt ResultVal(BitsNeeded, 0);
3958
3959 if (Literal.GetIntegerValue(ResultVal)) {
3960 // If this value didn't fit into uintmax_t, error and force to ull.
3961 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3962 << /* Unsigned */ 1;
3964 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3965 "long long is not intmax_t?");
3966 } else {
3967 // If this value fits into a ULL, try to figure out what else it fits into
3968 // according to the rules of C99 6.4.4.1p5.
3969
3970 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3971 // be an unsigned int.
3972 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3973
3974 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3975 // suffix for portability of code with C++, but both `l` and `ll` are
3976 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3977 // same.
3978 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3979 Literal.isLong = true;
3980 Literal.isLongLong = false;
3981 }
3982
3983 // Check from smallest to largest, picking the smallest type we can.
3984 unsigned Width = 0;
3985
3986 // Microsoft specific integer suffixes are explicitly sized.
3987 if (Literal.MicrosoftInteger) {
3988 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3989 Width = 8;
3990 Ty = Context.CharTy;
3991 } else {
3992 Width = Literal.MicrosoftInteger;
3993 Ty = Context.getIntTypeForBitwidth(Width,
3994 /*Signed=*/!Literal.isUnsigned);
3995 }
3996 }
3997
3998 // Bit-precise integer literals are automagically-sized based on the
3999 // width required by the literal.
4000 if (Literal.isBitInt) {
4001 // The signed version has one more bit for the sign value. There are no
4002 // zero-width bit-precise integers, even if the literal value is 0.
4003 Width = std::max(ResultVal.getActiveBits(), 1u) +
4004 (Literal.isUnsigned ? 0u : 1u);
4005
4006 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4007 // and reset the type to the largest supported width.
4008 unsigned int MaxBitIntWidth =
4010 if (Width > MaxBitIntWidth) {
4011 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4012 << Literal.isUnsigned;
4013 Width = MaxBitIntWidth;
4014 }
4015
4016 // Reset the result value to the smaller APInt and select the correct
4017 // type to be used. Note, we zext even for signed values because the
4018 // literal itself is always an unsigned value (a preceeding - is a
4019 // unary operator, not part of the literal).
4020 ResultVal = ResultVal.zextOrTrunc(Width);
4021 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4022 }
4023
4024 // Check C++23 size_t literals.
4025 if (Literal.isSizeT) {
4026 assert(!Literal.MicrosoftInteger &&
4027 "size_t literals can't be Microsoft literals");
4028 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4030
4031 // Does it fit in size_t?
4032 if (ResultVal.isIntN(SizeTSize)) {
4033 // Does it fit in ssize_t?
4034 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4036 else if (AllowUnsigned)
4037 Ty = Context.getSizeType();
4038 Width = SizeTSize;
4039 }
4040 }
4041
4042 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4043 !Literal.isSizeT) {
4044 // Are int/unsigned possibilities?
4045 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4046
4047 // Does it fit in a unsigned int?
4048 if (ResultVal.isIntN(IntSize)) {
4049 // Does it fit in a signed int?
4050 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4051 Ty = Context.IntTy;
4052 else if (AllowUnsigned)
4054 Width = IntSize;
4055 }
4056 }
4057
4058 // Are long/unsigned long possibilities?
4059 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4060 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4061
4062 // Does it fit in a unsigned long?
4063 if (ResultVal.isIntN(LongSize)) {
4064 // Does it fit in a signed long?
4065 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4066 Ty = Context.LongTy;
4067 else if (AllowUnsigned)
4069 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4070 // is compatible.
4071 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4072 const unsigned LongLongSize =
4074 Diag(Tok.getLocation(),
4076 ? Literal.isLong
4077 ? diag::warn_old_implicitly_unsigned_long_cxx
4078 : /*C++98 UB*/ diag::
4079 ext_old_implicitly_unsigned_long_cxx
4080 : diag::warn_old_implicitly_unsigned_long)
4081 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4082 : /*will be ill-formed*/ 1);
4084 }
4085 Width = LongSize;
4086 }
4087 }
4088
4089 // Check long long if needed.
4090 if (Ty.isNull() && !Literal.isSizeT) {
4091 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4092
4093 // Does it fit in a unsigned long long?
4094 if (ResultVal.isIntN(LongLongSize)) {
4095 // Does it fit in a signed long long?
4096 // To be compatible with MSVC, hex integer literals ending with the
4097 // LL or i64 suffix are always signed in Microsoft mode.
4098 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4099 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4100 Ty = Context.LongLongTy;
4101 else if (AllowUnsigned)
4103 Width = LongLongSize;
4104
4105 // 'long long' is a C99 or C++11 feature, whether the literal
4106 // explicitly specified 'long long' or we needed the extra width.
4107 if (getLangOpts().CPlusPlus)
4108 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4109 ? diag::warn_cxx98_compat_longlong
4110 : diag::ext_cxx11_longlong);
4111 else if (!getLangOpts().C99)
4112 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4113 }
4114 }
4115
4116 // If we still couldn't decide a type, we either have 'size_t' literal
4117 // that is out of range, or a decimal literal that does not fit in a
4118 // signed long long and has no U suffix.
4119 if (Ty.isNull()) {
4120 if (Literal.isSizeT)
4121 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4122 << Literal.isUnsigned;
4123 else
4124 Diag(Tok.getLocation(),
4125 diag::ext_integer_literal_too_large_for_signed);
4128 }
4129
4130 if (ResultVal.getBitWidth() != Width)
4131 ResultVal = ResultVal.trunc(Width);
4132 }
4133 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4134 }
4135
4136 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4137 if (Literal.isImaginary) {
4138 Res = new (Context) ImaginaryLiteral(Res,
4140
4141 // In C++, this is a GNU extension. In C, it's a C2y extension.
4142 unsigned DiagId;
4143 if (getLangOpts().CPlusPlus)
4144 DiagId = diag::ext_gnu_imaginary_constant;
4145 else if (getLangOpts().C2y)
4146 DiagId = diag::warn_c23_compat_imaginary_constant;
4147 else
4148 DiagId = diag::ext_c2y_imaginary_constant;
4149 Diag(Tok.getLocation(), DiagId);
4150 }
4151 return Res;
4152}
4153
4155 assert(E && "ActOnParenExpr() missing expr");
4156 QualType ExprTy = E->getType();
4157 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4158 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4159 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4160 return new (Context) ParenExpr(L, R, E);
4161}
4162
4165 SourceRange ArgRange) {
4166 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4167 // scalar or vector data type argument..."
4168 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4169 // type (C99 6.2.5p18) or void.
4170 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4171 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4172 << T << ArgRange;
4173 return true;
4174 }
4175
4176 assert((T->isVoidType() || !T->isIncompleteType()) &&
4177 "Scalar types should always be complete");
4178 return false;
4179}
4180
4183 SourceRange ArgRange) {
4184 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4185 if (!T->isVectorType() && !T->isSizelessVectorType())
4186 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4187 << ""
4188 << "__builtin_vectorelements" << T << ArgRange;
4189
4190 return false;
4191}
4192
4195 SourceRange ArgRange) {
4196 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4197 return true;
4198
4199 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4201 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4202 return true;
4203 }
4204
4205 return false;
4206}
4207
4210 SourceRange ArgRange,
4211 UnaryExprOrTypeTrait TraitKind) {
4212 // Invalid types must be hard errors for SFINAE in C++.
4213 if (S.LangOpts.CPlusPlus)
4214 return true;
4215
4216 // C99 6.5.3.4p1:
4217 if (T->isFunctionType() &&
4218 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4219 TraitKind == UETT_PreferredAlignOf)) {
4220 // sizeof(function)/alignof(function) is allowed as an extension.
4221 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4222 << getTraitSpelling(TraitKind) << ArgRange;
4223 return false;
4224 }
4225
4226 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4227 // this is an error (OpenCL v1.1 s6.3.k)
4228 if (T->isVoidType()) {
4229 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4230 : diag::ext_sizeof_alignof_void_type;
4231 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4232 return false;
4233 }
4234
4235 return true;
4236}
4237
4240 SourceRange ArgRange,
4241 UnaryExprOrTypeTrait TraitKind) {
4242 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4243 // runtime doesn't allow it.
4245 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4246 << T << (TraitKind == UETT_SizeOf)
4247 << ArgRange;
4248 return true;
4249 }
4250
4251 return false;
4252}
4253
4254/// Check whether E is a pointer from a decayed array type (the decayed
4255/// pointer type is equal to T) and emit a warning if it is.
4257 const Expr *E) {
4258 // Don't warn if the operation changed the type.
4259 if (T != E->getType())
4260 return;
4261
4262 // Now look for array decays.
4263 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4264 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4265 return;
4266
4267 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4268 << ICE->getType()
4269 << ICE->getSubExpr()->getType();
4270}
4271
4273 UnaryExprOrTypeTrait ExprKind) {
4274 QualType ExprTy = E->getType();
4275 assert(!ExprTy->isReferenceType());
4276
4277 bool IsUnevaluatedOperand =
4278 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4279 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4280 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4281 if (IsUnevaluatedOperand) {
4283 if (Result.isInvalid())
4284 return true;
4285 E = Result.get();
4286 }
4287
4288 // The operand for sizeof and alignof is in an unevaluated expression context,
4289 // so side effects could result in unintended consequences.
4290 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4291 // used to build SFINAE gadgets.
4292 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4293 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4295 !E->getType()->isVariableArrayType() &&
4296 E->HasSideEffects(Context, false))
4297 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4298
4299 if (ExprKind == UETT_VecStep)
4300 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4301 E->getSourceRange());
4302
4303 if (ExprKind == UETT_VectorElements)
4304 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4305 E->getSourceRange());
4306
4307 // Explicitly list some types as extensions.
4308 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4309 E->getSourceRange(), ExprKind))
4310 return false;
4311
4312 // WebAssembly tables are always illegal operands to unary expressions and
4313 // type traits.
4314 if (Context.getTargetInfo().getTriple().isWasm() &&
4316 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4317 << getTraitSpelling(ExprKind);
4318 return true;
4319 }
4320
4321 // 'alignof' applied to an expression only requires the base element type of
4322 // the expression to be complete. 'sizeof' requires the expression's type to
4323 // be complete (and will attempt to complete it if it's an array of unknown
4324 // bound).
4325 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4328 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4329 getTraitSpelling(ExprKind), E->getSourceRange()))
4330 return true;
4331 } else {
4333 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4334 getTraitSpelling(ExprKind), E->getSourceRange()))
4335 return true;
4336 }
4337
4338 // Completing the expression's type may have changed it.
4339 ExprTy = E->getType();
4340 assert(!ExprTy->isReferenceType());
4341
4342 if (ExprTy->isFunctionType()) {
4343 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4344 << getTraitSpelling(ExprKind) << E->getSourceRange();
4345 return true;
4346 }
4347
4348 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4349 E->getSourceRange(), ExprKind))
4350 return true;
4351
4352 if (ExprKind == UETT_CountOf) {
4353 // The type has to be an array type. We already checked for incomplete
4354 // types above.
4355 QualType ExprType = E->IgnoreParens()->getType();
4356 if (!ExprType->isArrayType()) {
4357 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4358 return true;
4359 }
4360 // FIXME: warn on _Countof on an array parameter. Not warning on it
4361 // currently because there are papers in WG14 about array types which do
4362 // not decay that could impact this behavior, so we want to see if anything
4363 // changes here before coming up with a warning group for _Countof-related
4364 // diagnostics.
4365 }
4366
4367 if (ExprKind == UETT_SizeOf) {
4368 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4369 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4370 QualType OType = PVD->getOriginalType();
4371 QualType Type = PVD->getType();
4372 if (Type->isPointerType() && OType->isArrayType()) {
4373 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4374 << Type << OType;
4375 Diag(PVD->getLocation(), diag::note_declared_at);
4376 }
4377 }
4378 }
4379
4380 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4381 // decays into a pointer and returns an unintended result. This is most
4382 // likely a typo for "sizeof(array) op x".
4383 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4384 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4385 BO->getLHS());
4386 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4387 BO->getRHS());
4388 }
4389 }
4390
4391 return false;
4392}
4393
4394static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4395 // Cannot know anything else if the expression is dependent.
4396 if (E->isTypeDependent())
4397 return false;
4398
4399 if (E->getObjectKind() == OK_BitField) {
4400 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4401 << 1 << E->getSourceRange();
4402 return true;
4403 }
4404
4405 ValueDecl *D = nullptr;
4406 Expr *Inner = E->IgnoreParens();
4407 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4408 D = DRE->getDecl();
4409 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4410 D = ME->getMemberDecl();
4411 }
4412
4413 // If it's a field, require the containing struct to have a
4414 // complete definition so that we can compute the layout.
4415 //
4416 // This can happen in C++11 onwards, either by naming the member
4417 // in a way that is not transformed into a member access expression
4418 // (in an unevaluated operand, for instance), or by naming the member
4419 // in a trailing-return-type.
4420 //
4421 // For the record, since __alignof__ on expressions is a GCC
4422 // extension, GCC seems to permit this but always gives the
4423 // nonsensical answer 0.
4424 //
4425 // We don't really need the layout here --- we could instead just
4426 // directly check for all the appropriate alignment-lowing
4427 // attributes --- but that would require duplicating a lot of
4428 // logic that just isn't worth duplicating for such a marginal
4429 // use-case.
4430 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4431 // Fast path this check, since we at least know the record has a
4432 // definition if we can find a member of it.
4433 if (!FD->getParent()->isCompleteDefinition()) {
4434 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4435 << E->getSourceRange();
4436 return true;
4437 }
4438
4439 // Otherwise, if it's a field, and the field doesn't have
4440 // reference type, then it must have a complete type (or be a
4441 // flexible array member, which we explicitly want to
4442 // white-list anyway), which makes the following checks trivial.
4443 if (!FD->getType()->isReferenceType())
4444 return false;
4445 }
4446
4447 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4448}
4449
4451 E = E->IgnoreParens();
4452
4453 // Cannot know anything else if the expression is dependent.
4454 if (E->isTypeDependent())
4455 return false;
4456
4457 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4458}
4459
4461 CapturingScopeInfo *CSI) {
4462 assert(T->isVariablyModifiedType());
4463 assert(CSI != nullptr);
4464
4465 // We're going to walk down into the type and look for VLA expressions.
4466 do {
4467 const Type *Ty = T.getTypePtr();
4468 switch (Ty->getTypeClass()) {
4469#define TYPE(Class, Base)
4470#define ABSTRACT_TYPE(Class, Base)
4471#define NON_CANONICAL_TYPE(Class, Base)
4472#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4473#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4474#include "clang/AST/TypeNodes.inc"
4475 T = QualType();
4476 break;
4477 // These types are never variably-modified.
4478 case Type::Builtin:
4479 case Type::Complex:
4480 case Type::Vector:
4481 case Type::ExtVector:
4482 case Type::ConstantMatrix:
4483 case Type::Record:
4484 case Type::Enum:
4485 case Type::TemplateSpecialization:
4486 case Type::ObjCObject:
4487 case Type::ObjCInterface:
4488 case Type::ObjCObjectPointer:
4489 case Type::ObjCTypeParam:
4490 case Type::Pipe:
4491 case Type::BitInt:
4492 case Type::HLSLInlineSpirv:
4493 llvm_unreachable("type class is never variably-modified!");
4494 case Type::Adjusted:
4495 T = cast<AdjustedType>(Ty)->getOriginalType();
4496 break;
4497 case Type::Decayed:
4498 T = cast<DecayedType>(Ty)->getPointeeType();
4499 break;
4500 case Type::ArrayParameter:
4501 T = cast<ArrayParameterType>(Ty)->getElementType();
4502 break;
4503 case Type::Pointer:
4504 T = cast<PointerType>(Ty)->getPointeeType();
4505 break;
4506 case Type::BlockPointer:
4507 T = cast<BlockPointerType>(Ty)->getPointeeType();
4508 break;
4509 case Type::LValueReference:
4510 case Type::RValueReference:
4511 T = cast<ReferenceType>(Ty)->getPointeeType();
4512 break;
4513 case Type::MemberPointer:
4514 T = cast<MemberPointerType>(Ty)->getPointeeType();
4515 break;
4516 case Type::ConstantArray:
4517 case Type::IncompleteArray:
4518 // Losing element qualification here is fine.
4519 T = cast<ArrayType>(Ty)->getElementType();
4520 break;
4521 case Type::VariableArray: {
4522 // Losing element qualification here is fine.
4523 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4524
4525 // Unknown size indication requires no size computation.
4526 // Otherwise, evaluate and record it.
4527 auto Size = VAT->getSizeExpr();
4528 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4529 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4530 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4531
4532 T = VAT->getElementType();
4533 break;
4534 }
4535 case Type::FunctionProto:
4536 case Type::FunctionNoProto:
4537 T = cast<FunctionType>(Ty)->getReturnType();
4538 break;
4539 case Type::Paren:
4540 case Type::TypeOf:
4541 case Type::UnaryTransform:
4542 case Type::Attributed:
4543 case Type::BTFTagAttributed:
4544 case Type::HLSLAttributedResource:
4545 case Type::SubstTemplateTypeParm:
4546 case Type::MacroQualified:
4547 case Type::CountAttributed:
4548 // Keep walking after single level desugaring.
4549 T = T.getSingleStepDesugaredType(Context);
4550 break;
4551 case Type::Typedef:
4552 T = cast<TypedefType>(Ty)->desugar();
4553 break;
4554 case Type::Decltype:
4555 T = cast<DecltypeType>(Ty)->desugar();
4556 break;
4557 case Type::PackIndexing:
4558 T = cast<PackIndexingType>(Ty)->desugar();
4559 break;
4560 case Type::Using:
4561 T = cast<UsingType>(Ty)->desugar();
4562 break;
4563 case Type::Auto:
4564 case Type::DeducedTemplateSpecialization:
4565 T = cast<DeducedType>(Ty)->getDeducedType();
4566 break;
4567 case Type::TypeOfExpr:
4568 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4569 break;
4570 case Type::Atomic:
4571 T = cast<AtomicType>(Ty)->getValueType();
4572 break;
4573 case Type::PredefinedSugar:
4574 T = cast<PredefinedSugarType>(Ty)->desugar();
4575 break;
4576 }
4577 } while (!T.isNull() && T->isVariablyModifiedType());
4578}
4579
4581 SourceLocation OpLoc,
4582 SourceRange ExprRange,
4583 UnaryExprOrTypeTrait ExprKind,
4584 StringRef KWName) {
4585 if (ExprType->isDependentType())
4586 return false;
4587
4588 // C++ [expr.sizeof]p2:
4589 // When applied to a reference or a reference type, the result
4590 // is the size of the referenced type.
4591 // C++11 [expr.alignof]p3:
4592 // When alignof is applied to a reference type, the result
4593 // shall be the alignment of the referenced type.
4594 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4595 ExprType = Ref->getPointeeType();
4596
4597 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4598 // When alignof or _Alignof is applied to an array type, the result
4599 // is the alignment of the element type.
4600 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4601 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4602 // If the trait is 'alignof' in C before C2y, the ability to apply the
4603 // trait to an incomplete array is an extension.
4604 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4605 ExprType->isIncompleteArrayType())
4606 Diag(OpLoc, getLangOpts().C2y
4607 ? diag::warn_c2y_compat_alignof_incomplete_array
4608 : diag::ext_c2y_alignof_incomplete_array);
4609 ExprType = Context.getBaseElementType(ExprType);
4610 }
4611
4612 if (ExprKind == UETT_VecStep)
4613 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4614
4615 if (ExprKind == UETT_VectorElements)
4616 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4617 ExprRange);
4618
4619 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4620 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4621 ExprRange);
4622
4623 // Explicitly list some types as extensions.
4624 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4625 ExprKind))
4626 return false;
4627
4629 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4630 KWName, ExprRange))
4631 return true;
4632
4633 if (ExprType->isFunctionType()) {
4634 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4635 return true;
4636 }
4637
4638 if (ExprKind == UETT_CountOf) {
4639 // The type has to be an array type. We already checked for incomplete
4640 // types above.
4641 if (!ExprType->isArrayType()) {
4642 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4643 return true;
4644 }
4645 }
4646
4647 // WebAssembly tables are always illegal operands to unary expressions and
4648 // type traits.
4649 if (Context.getTargetInfo().getTriple().isWasm() &&
4650 ExprType->isWebAssemblyTableType()) {
4651 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4652 << getTraitSpelling(ExprKind);
4653 return true;
4654 }
4655
4656 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4657 ExprKind))
4658 return true;
4659
4660 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4661 if (auto *TT = ExprType->getAs<TypedefType>()) {
4662 for (auto I = FunctionScopes.rbegin(),
4663 E = std::prev(FunctionScopes.rend());
4664 I != E; ++I) {
4665 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4666 if (CSI == nullptr)
4667 break;
4668 DeclContext *DC = nullptr;
4669 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4670 DC = LSI->CallOperator;
4671 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4672 DC = CRSI->TheCapturedDecl;
4673 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4674 DC = BSI->TheDecl;
4675 if (DC) {
4676 if (DC->containsDecl(TT->getDecl()))
4677 break;
4678 captureVariablyModifiedType(Context, ExprType, CSI);
4679 }
4680 }
4681 }
4682 }
4683
4684 return false;
4685}
4686
4688 SourceLocation OpLoc,
4689 UnaryExprOrTypeTrait ExprKind,
4690 SourceRange R) {
4691 if (!TInfo)
4692 return ExprError();
4693
4694 QualType T = TInfo->getType();
4695
4696 if (!T->isDependentType() &&
4697 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4698 getTraitSpelling(ExprKind)))
4699 return ExprError();
4700
4701 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4702 // properly deal with VLAs in nested calls of sizeof and typeof.
4703 if (currentEvaluationContext().isUnevaluated() &&
4704 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4705 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4706 TInfo->getType()->isVariablyModifiedType())
4707 TInfo = TransformToPotentiallyEvaluated(TInfo);
4708
4709 // It's possible that the transformation above failed.
4710 if (!TInfo)
4711 return ExprError();
4712
4713 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4714 return new (Context) UnaryExprOrTypeTraitExpr(
4715 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4716}
4717
4720 UnaryExprOrTypeTrait ExprKind) {
4722 if (PE.isInvalid())
4723 return ExprError();
4724
4725 E = PE.get();
4726
4727 // Verify that the operand is valid.
4728 bool isInvalid = false;
4729 if (E->isTypeDependent()) {
4730 // Delay type-checking for type-dependent expressions.
4731 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4732 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4733 } else if (ExprKind == UETT_VecStep) {
4735 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4736 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4737 isInvalid = true;
4738 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4739 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4740 isInvalid = true;
4741 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4742 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4744 }
4745
4746 if (isInvalid)
4747 return ExprError();
4748
4749 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4752 if (PE.isInvalid()) return ExprError();
4753 E = PE.get();
4754 }
4755
4756 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4757 return new (Context) UnaryExprOrTypeTraitExpr(
4758 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4759}
4760
4763 UnaryExprOrTypeTrait ExprKind, bool IsType,
4764 void *TyOrEx, SourceRange ArgRange) {
4765 // If error parsing type, ignore.
4766 if (!TyOrEx) return ExprError();
4767
4768 if (IsType) {
4769 TypeSourceInfo *TInfo;
4770 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4771 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4772 }
4773
4774 Expr *ArgEx = (Expr *)TyOrEx;
4775 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4776 return Result;
4777}
4778
4780 SourceLocation OpLoc, SourceRange R) {
4781 if (!TInfo)
4782 return true;
4783 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4784 UETT_AlignOf, KWName);
4785}
4786
4788 SourceLocation OpLoc, SourceRange R) {
4789 TypeSourceInfo *TInfo;
4791 &TInfo);
4792 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4793}
4794
4796 bool IsReal) {
4797 if (V.get()->isTypeDependent())
4798 return S.Context.DependentTy;
4799
4800 // _Real and _Imag are only l-values for normal l-values.
4801 if (V.get()->getObjectKind() != OK_Ordinary) {
4802 V = S.DefaultLvalueConversion(V.get());
4803 if (V.isInvalid())
4804 return QualType();
4805 }
4806
4807 // These operators return the element type of a complex type.
4808 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4809 return CT->getElementType();
4810
4811 // Otherwise they pass through real integer and floating point types here.
4812 if (V.get()->getType()->isArithmeticType())
4813 return V.get()->getType();
4814
4815 // Test for placeholders.
4816 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4817 if (PR.isInvalid()) return QualType();
4818 if (PR.get() != V.get()) {
4819 V = PR;
4820 return CheckRealImagOperand(S, V, Loc, IsReal);
4821 }
4822
4823 // Reject anything else.
4824 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4825 << (IsReal ? "__real" : "__imag");
4826 return QualType();
4827}
4828
4829
4830
4833 tok::TokenKind Kind, Expr *Input) {
4835 switch (Kind) {
4836 default: llvm_unreachable("Unknown unary op!");
4837 case tok::plusplus: Opc = UO_PostInc; break;
4838 case tok::minusminus: Opc = UO_PostDec; break;
4839 }
4840
4841 // Since this might is a postfix expression, get rid of ParenListExprs.
4843 if (Result.isInvalid()) return ExprError();
4844 Input = Result.get();
4845
4846 return BuildUnaryOp(S, OpLoc, Opc, Input);
4847}
4848
4849/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4850///
4851/// \return true on error
4853 SourceLocation opLoc,
4854 Expr *op) {
4855 assert(op->getType()->isObjCObjectPointerType());
4857 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4858 return false;
4859
4860 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4862 << op->getSourceRange();
4863 return true;
4864}
4865
4867 auto *BaseNoParens = Base->IgnoreParens();
4868 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4869 return MSProp->getPropertyDecl()->getType()->isArrayType();
4870 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4871}
4872
4873// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4874// Typically this is DependentTy, but can sometimes be more precise.
4875//
4876// There are cases when we could determine a non-dependent type:
4877// - LHS and RHS may have non-dependent types despite being type-dependent
4878// (e.g. unbounded array static members of the current instantiation)
4879// - one may be a dependent-sized array with known element type
4880// - one may be a dependent-typed valid index (enum in current instantiation)
4881//
4882// We *always* return a dependent type, in such cases it is DependentTy.
4883// This avoids creating type-dependent expressions with non-dependent types.
4884// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4886 const ASTContext &Ctx) {
4887 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4888 QualType LTy = LHS->getType(), RTy = RHS->getType();
4890 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4891 if (const PointerType *PT = LTy->getAs<PointerType>())
4892 Result = PT->getPointeeType();
4893 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4894 Result = AT->getElementType();
4895 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4896 if (const PointerType *PT = RTy->getAs<PointerType>())
4897 Result = PT->getPointeeType();
4898 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4899 Result = AT->getElementType();
4900 }
4901 // Ensure we return a dependent type.
4902 return Result->isDependentType() ? Result : Ctx.DependentTy;
4903}
4904
4906 SourceLocation lbLoc,
4907 MultiExprArg ArgExprs,
4908 SourceLocation rbLoc) {
4909
4910 if (base && !base->getType().isNull() &&
4911 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4912 auto *AS = cast<ArraySectionExpr>(base);
4913 if (AS->isOMPArraySection())
4915 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4916 /*Length*/ nullptr,
4917 /*Stride=*/nullptr, rbLoc);
4918
4919 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4920 SourceLocation(), /*Length*/ nullptr,
4921 rbLoc);
4922 }
4923
4924 // Since this might be a postfix expression, get rid of ParenListExprs.
4925 if (isa<ParenListExpr>(base)) {
4927 if (result.isInvalid())
4928 return ExprError();
4929 base = result.get();
4930 }
4931
4932 // Check if base and idx form a MatrixSubscriptExpr.
4933 //
4934 // Helper to check for comma expressions, which are not allowed as indices for
4935 // matrix subscript expressions.
4936 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4937 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4938 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4939 << SourceRange(base->getBeginLoc(), rbLoc);
4940 return true;
4941 }
4942 return false;
4943 };
4944 // The matrix subscript operator ([][])is considered a single operator.
4945 // Separating the index expressions by parenthesis is not allowed.
4946 if (base && !base->getType().isNull() &&
4947 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4948 !isa<MatrixSubscriptExpr>(base)) {
4949 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4950 << SourceRange(base->getBeginLoc(), rbLoc);
4951 return ExprError();
4952 }
4953 // If the base is a MatrixSubscriptExpr, try to create a new
4954 // MatrixSubscriptExpr.
4955 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4956 if (matSubscriptE) {
4957 assert(ArgExprs.size() == 1);
4958 if (CheckAndReportCommaError(ArgExprs.front()))
4959 return ExprError();
4960
4961 assert(matSubscriptE->isIncomplete() &&
4962 "base has to be an incomplete matrix subscript");
4963 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4964 matSubscriptE->getRowIdx(),
4965 ArgExprs.front(), rbLoc);
4966 }
4967 if (base->getType()->isWebAssemblyTableType()) {
4968 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4969 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4970 return ExprError();
4971 }
4972
4973 CheckInvalidBuiltinCountedByRef(base,
4975
4976 // Handle any non-overload placeholder types in the base and index
4977 // expressions. We can't handle overloads here because the other
4978 // operand might be an overloadable type, in which case the overload
4979 // resolution for the operator overload should get the first crack
4980 // at the overload.
4981 bool IsMSPropertySubscript = false;
4982 if (base->getType()->isNonOverloadPlaceholderType()) {
4983 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4984 if (!IsMSPropertySubscript) {
4985 ExprResult result = CheckPlaceholderExpr(base);
4986 if (result.isInvalid())
4987 return ExprError();
4988 base = result.get();
4989 }
4990 }
4991
4992 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4993 if (base->getType()->isMatrixType()) {
4994 assert(ArgExprs.size() == 1);
4995 if (CheckAndReportCommaError(ArgExprs.front()))
4996 return ExprError();
4997
4998 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4999 rbLoc);
5000 }
5001
5002 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5003 Expr *idx = ArgExprs[0];
5004 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5005 (isa<CXXOperatorCallExpr>(idx) &&
5006 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5007 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5008 << SourceRange(base->getBeginLoc(), rbLoc);
5009 }
5010 }
5011
5012 if (ArgExprs.size() == 1 &&
5013 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5014 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5015 if (result.isInvalid())
5016 return ExprError();
5017 ArgExprs[0] = result.get();
5018 } else {
5019 if (CheckArgsForPlaceholders(ArgExprs))
5020 return ExprError();
5021 }
5022
5023 // Build an unanalyzed expression if either operand is type-dependent.
5024 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5025 (base->isTypeDependent() ||
5027 !isa<PackExpansionExpr>(ArgExprs[0])) {
5028 return new (Context) ArraySubscriptExpr(
5029 base, ArgExprs.front(),
5030 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5031 VK_LValue, OK_Ordinary, rbLoc);
5032 }
5033
5034 // MSDN, property (C++)
5035 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5036 // This attribute can also be used in the declaration of an empty array in a
5037 // class or structure definition. For example:
5038 // __declspec(property(get=GetX, put=PutX)) int x[];
5039 // The above statement indicates that x[] can be used with one or more array
5040 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5041 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5042 if (IsMSPropertySubscript) {
5043 assert(ArgExprs.size() == 1);
5044 // Build MS property subscript expression if base is MS property reference
5045 // or MS property subscript.
5046 return new (Context)
5047 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5048 VK_LValue, OK_Ordinary, rbLoc);
5049 }
5050
5051 // Use C++ overloaded-operator rules if either operand has record
5052 // type. The spec says to do this if either type is *overloadable*,
5053 // but enum types can't declare subscript operators or conversion
5054 // operators, so there's nothing interesting for overload resolution
5055 // to do if there aren't any record types involved.
5056 //
5057 // ObjC pointers have their own subscripting logic that is not tied
5058 // to overload resolution and so should not take this path.
5059 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5060 ((base->getType()->isRecordType() ||
5061 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5062 ArgExprs[0]->getType()->isRecordType())))) {
5063 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5064 }
5065
5066 ExprResult Res =
5067 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5068
5069 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5070 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5071
5072 return Res;
5073}
5074
5077 InitializationKind Kind =
5079 InitializationSequence InitSeq(*this, Entity, Kind, E);
5080 return InitSeq.Perform(*this, Entity, Kind, E);
5081}
5082
5084 Expr *ColumnIdx,
5085 SourceLocation RBLoc) {
5087 if (BaseR.isInvalid())
5088 return BaseR;
5089 Base = BaseR.get();
5090
5091 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5092 if (RowR.isInvalid())
5093 return RowR;
5094 RowIdx = RowR.get();
5095
5096 if (!ColumnIdx)
5097 return new (Context) MatrixSubscriptExpr(
5098 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5099
5100 // Build an unanalyzed expression if any of the operands is type-dependent.
5101 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5102 ColumnIdx->isTypeDependent())
5103 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5104 Context.DependentTy, RBLoc);
5105
5106 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5107 if (ColumnR.isInvalid())
5108 return ColumnR;
5109 ColumnIdx = ColumnR.get();
5110
5111 // Check that IndexExpr is an integer expression. If it is a constant
5112 // expression, check that it is less than Dim (= the number of elements in the
5113 // corresponding dimension).
5114 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5115 bool IsColumnIdx) -> Expr * {
5116 if (!IndexExpr->getType()->isIntegerType() &&
5117 !IndexExpr->isTypeDependent()) {
5118 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5119 << IsColumnIdx;
5120 return nullptr;
5121 }
5122
5123 if (std::optional<llvm::APSInt> Idx =
5124 IndexExpr->getIntegerConstantExpr(Context)) {
5125 if ((*Idx < 0 || *Idx >= Dim)) {
5126 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5127 << IsColumnIdx << Dim;
5128 return nullptr;
5129 }
5130 }
5131
5132 ExprResult ConvExpr = IndexExpr;
5133 assert(!ConvExpr.isInvalid() &&
5134 "should be able to convert any integer type to size type");
5135 return ConvExpr.get();
5136 };
5137
5138 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5139 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5140 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5141 if (!RowIdx || !ColumnIdx)
5142 return ExprError();
5143
5144 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5145 MTy->getElementType(), RBLoc);
5146}
5147
5148void Sema::CheckAddressOfNoDeref(const Expr *E) {
5149 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5150 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5151
5152 // For expressions like `&(*s).b`, the base is recorded and what should be
5153 // checked.
5154 const MemberExpr *Member = nullptr;
5155 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5156 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5157
5158 LastRecord.PossibleDerefs.erase(StrippedExpr);
5159}
5160
5161void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5163 return;
5164
5165 QualType ResultTy = E->getType();
5166 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5167
5168 // Bail if the element is an array since it is not memory access.
5169 if (isa<ArrayType>(ResultTy))
5170 return;
5171
5172 if (ResultTy->hasAttr(attr::NoDeref)) {
5173 LastRecord.PossibleDerefs.insert(E);
5174 return;
5175 }
5176
5177 // Check if the base type is a pointer to a member access of a struct
5178 // marked with noderef.
5179 const Expr *Base = E->getBase();
5180 QualType BaseTy = Base->getType();
5181 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5182 // Not a pointer access
5183 return;
5184
5185 const MemberExpr *Member = nullptr;
5186 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5187 Member->isArrow())
5188 Base = Member->getBase();
5189
5190 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5191 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5192 LastRecord.PossibleDerefs.insert(E);
5193 }
5194}
5195
5198 Expr *Idx, SourceLocation RLoc) {
5199 Expr *LHSExp = Base;
5200 Expr *RHSExp = Idx;
5201
5204
5205 // Per C++ core issue 1213, the result is an xvalue if either operand is
5206 // a non-lvalue array, and an lvalue otherwise.
5207 if (getLangOpts().CPlusPlus11) {
5208 for (auto *Op : {LHSExp, RHSExp}) {
5209 Op = Op->IgnoreImplicit();
5210 if (Op->getType()->isArrayType() && !Op->isLValue())
5211 VK = VK_XValue;
5212 }
5213 }
5214
5215 // Perform default conversions.
5216 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5218 if (Result.isInvalid())
5219 return ExprError();
5220 LHSExp = Result.get();
5221 }
5223 if (Result.isInvalid())
5224 return ExprError();
5225 RHSExp = Result.get();
5226
5227 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5228
5229 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5230 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5231 // in the subscript position. As a result, we need to derive the array base
5232 // and index from the expression types.
5233 Expr *BaseExpr, *IndexExpr;
5234 QualType ResultType;
5235 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5236 BaseExpr = LHSExp;
5237 IndexExpr = RHSExp;
5238 ResultType =
5240 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5241 BaseExpr = LHSExp;
5242 IndexExpr = RHSExp;
5243 ResultType = PTy->getPointeeType();
5244 } else if (const ObjCObjectPointerType *PTy =
5245 LHSTy->getAs<ObjCObjectPointerType>()) {
5246 BaseExpr = LHSExp;
5247 IndexExpr = RHSExp;
5248
5249 // Use custom logic if this should be the pseudo-object subscript
5250 // expression.
5252 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5253 nullptr, nullptr);
5254
5255 ResultType = PTy->getPointeeType();
5256 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5257 // Handle the uncommon case of "123[Ptr]".
5258 BaseExpr = RHSExp;
5259 IndexExpr = LHSExp;
5260 ResultType = PTy->getPointeeType();
5261 } else if (const ObjCObjectPointerType *PTy =
5262 RHSTy->getAs<ObjCObjectPointerType>()) {
5263 // Handle the uncommon case of "123[Ptr]".
5264 BaseExpr = RHSExp;
5265 IndexExpr = LHSExp;
5266 ResultType = PTy->getPointeeType();
5268 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5269 << ResultType << BaseExpr->getSourceRange();
5270 return ExprError();
5271 }
5272 } else if (LHSTy->isSubscriptableVectorType()) {
5273 if (LHSTy->isBuiltinType() &&
5274 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5275 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5276 if (BTy->isSVEBool())
5277 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5278 << LHSExp->getSourceRange()
5279 << RHSExp->getSourceRange());
5280 ResultType = BTy->getSveEltType(Context);
5281 } else {
5282 const VectorType *VTy = LHSTy->getAs<VectorType>();
5283 ResultType = VTy->getElementType();
5284 }
5285 BaseExpr = LHSExp; // vectors: V[123]
5286 IndexExpr = RHSExp;
5287 // We apply C++ DR1213 to vector subscripting too.
5288 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5289 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5290 if (Materialized.isInvalid())
5291 return ExprError();
5292 LHSExp = Materialized.get();
5293 }
5294 VK = LHSExp->getValueKind();
5295 if (VK != VK_PRValue)
5296 OK = OK_VectorComponent;
5297
5298 QualType BaseType = BaseExpr->getType();
5299 Qualifiers BaseQuals = BaseType.getQualifiers();
5300 Qualifiers MemberQuals = ResultType.getQualifiers();
5301 Qualifiers Combined = BaseQuals + MemberQuals;
5302 if (Combined != MemberQuals)
5303 ResultType = Context.getQualifiedType(ResultType, Combined);
5304 } else if (LHSTy->isArrayType()) {
5305 // If we see an array that wasn't promoted by
5306 // DefaultFunctionArrayLvalueConversion, it must be an array that
5307 // wasn't promoted because of the C90 rule that doesn't
5308 // allow promoting non-lvalue arrays. Warn, then
5309 // force the promotion here.
5310 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5311 << LHSExp->getSourceRange();
5312 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5313 CK_ArrayToPointerDecay).get();
5314 LHSTy = LHSExp->getType();
5315
5316 BaseExpr = LHSExp;
5317 IndexExpr = RHSExp;
5318 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5319 } else if (RHSTy->isArrayType()) {
5320 // Same as previous, except for 123[f().a] case
5321 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5322 << RHSExp->getSourceRange();
5323 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5324 CK_ArrayToPointerDecay).get();
5325 RHSTy = RHSExp->getType();
5326
5327 BaseExpr = RHSExp;
5328 IndexExpr = LHSExp;
5329 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5330 } else {
5331 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5332 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5333 }
5334 // C99 6.5.2.1p1
5335 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5336 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5337 << IndexExpr->getSourceRange());
5338
5339 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5340 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5341 !IndexExpr->isTypeDependent()) {
5342 std::optional<llvm::APSInt> IntegerContantExpr =
5344 if (!IntegerContantExpr.has_value() ||
5345 IntegerContantExpr.value().isNegative())
5346 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5347 }
5348
5349 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5350 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5351 // type. Note that Functions are not objects, and that (in C99 parlance)
5352 // incomplete types are not object types.
5353 if (ResultType->isFunctionType()) {
5354 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5355 << ResultType << BaseExpr->getSourceRange();
5356 return ExprError();
5357 }
5358
5359 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5360 // GNU extension: subscripting on pointer to void
5361 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5362 << BaseExpr->getSourceRange();
5363
5364 // C forbids expressions of unqualified void type from being l-values.
5365 // See IsCForbiddenLValueType.
5366 if (!ResultType.hasQualifiers())
5367 VK = VK_PRValue;
5368 } else if (!ResultType->isDependentType() &&
5369 !ResultType.isWebAssemblyReferenceType() &&
5371 LLoc, ResultType,
5372 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5373 return ExprError();
5374
5375 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5376 !ResultType.isCForbiddenLValueType());
5377
5379 FunctionScopes.size() > 1) {
5380 if (auto *TT =
5381 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5382 for (auto I = FunctionScopes.rbegin(),
5383 E = std::prev(FunctionScopes.rend());
5384 I != E; ++I) {
5385 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5386 if (CSI == nullptr)
5387 break;
5388 DeclContext *DC = nullptr;
5389 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5390 DC = LSI->CallOperator;
5391 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5392 DC = CRSI->TheCapturedDecl;
5393 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5394 DC = BSI->TheDecl;
5395 if (DC) {
5396 if (DC->containsDecl(TT->getDecl()))
5397 break;
5399 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5400 }
5401 }
5402 }
5403 }
5404
5405 return new (Context)
5406 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5407}
5408
5410 ParmVarDecl *Param, Expr *RewrittenInit,
5411 bool SkipImmediateInvocations) {
5412 if (Param->hasUnparsedDefaultArg()) {
5413 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5414 // If we've already cleared out the location for the default argument,
5415 // that means we're parsing it right now.
5416 if (!UnparsedDefaultArgLocs.count(Param)) {
5417 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5418 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5419 Param->setInvalidDecl();
5420 return true;
5421 }
5422
5423 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5424 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5426 diag::note_default_argument_declared_here);
5427 return true;
5428 }
5429
5430 if (Param->hasUninstantiatedDefaultArg()) {
5431 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5432 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5433 return true;
5434 }
5435
5436 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5437 assert(Init && "default argument but no initializer?");
5438
5439 // If the default expression creates temporaries, we need to
5440 // push them to the current stack of expression temporaries so they'll
5441 // be properly destroyed.
5442 // FIXME: We should really be rebuilding the default argument with new
5443 // bound temporaries; see the comment in PR5810.
5444 // We don't need to do that with block decls, though, because
5445 // blocks in default argument expression can never capture anything.
5446 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5447 // Set the "needs cleanups" bit regardless of whether there are
5448 // any explicit objects.
5449 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5450 // Append all the objects to the cleanup list. Right now, this
5451 // should always be a no-op, because blocks in default argument
5452 // expressions should never be able to capture anything.
5453 assert(!InitWithCleanup->getNumObjects() &&
5454 "default argument expression has capturing blocks?");
5455 }
5456 // C++ [expr.const]p15.1:
5457 // An expression or conversion is in an immediate function context if it is
5458 // potentially evaluated and [...] its innermost enclosing non-block scope
5459 // is a function parameter scope of an immediate function.
5461 *this,
5465 Param);
5466 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5467 SkipImmediateInvocations;
5468 runWithSufficientStackSpace(CallLoc, [&] {
5469 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5470 });
5471 return false;
5472}
5473
5476 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5477 ShouldVisitImplicitCode = true;
5478 }
5479
5480 bool HasImmediateCalls = false;
5481
5482 bool VisitCallExpr(CallExpr *E) override {
5483 if (const FunctionDecl *FD = E->getDirectCallee())
5484 HasImmediateCalls |= FD->isImmediateFunction();
5486 }
5487
5489 if (const FunctionDecl *FD = E->getConstructor())
5490 HasImmediateCalls |= FD->isImmediateFunction();
5492 }
5493
5494 // SourceLocExpr are not immediate invocations
5495 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5496 // need to be rebuilt so that they refer to the correct SourceLocation and
5497 // DeclContext.
5499 HasImmediateCalls = true;
5501 }
5502
5503 // A nested lambda might have parameters with immediate invocations
5504 // in their default arguments.
5505 // The compound statement is not visited (as it does not constitute a
5506 // subexpression).
5507 // FIXME: We should consider visiting and transforming captures
5508 // with init expressions.
5509 bool VisitLambdaExpr(LambdaExpr *E) override {
5510 return VisitCXXMethodDecl(E->getCallOperator());
5511 }
5512
5514 return TraverseStmt(E->getExpr());
5515 }
5516
5518 return TraverseStmt(E->getExpr());
5519 }
5520};
5521
5523 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5525 : TreeTransform(SemaRef) {}
5526
5527 bool AlwaysRebuild() { return true; }
5528
5529 // Lambda can only have immediate invocations in the default
5530 // args of their parameters, which is transformed upon calling the closure.
5531 // The body is not a subexpression, so we have nothing to do.
5532 // FIXME: Immediate calls in capture initializers should be transformed.
5535
5536 // Make sure we don't rebuild the this pointer as it would
5537 // cause it to incorrectly point it to the outermost class
5538 // in the case of nested struct initialization.
5540
5541 // Rewrite to source location to refer to the context in which they are used.
5543 DeclContext *DC = E->getParentContext();
5544 if (DC == SemaRef.CurContext)
5545 return E;
5546
5547 // FIXME: During instantiation, because the rebuild of defaults arguments
5548 // is not always done in the context of the template instantiator,
5549 // we run the risk of producing a dependent source location
5550 // that would never be rebuilt.
5551 // This usually happens during overload resolution, or in contexts
5552 // where the value of the source location does not matter.
5553 // However, we should find a better way to deal with source location
5554 // of function templates.
5555 if (!SemaRef.CurrentInstantiationScope ||
5556 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5557 DC = SemaRef.CurContext;
5558
5559 return getDerived().RebuildSourceLocExpr(
5560 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5561 }
5562};
5563
5565 FunctionDecl *FD, ParmVarDecl *Param,
5566 Expr *Init) {
5567 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5568
5569 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5570 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5571 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5572 InitializationContext =
5574 if (!InitializationContext.has_value())
5575 InitializationContext.emplace(CallLoc, Param, CurContext);
5576
5577 if (!Init && !Param->hasUnparsedDefaultArg()) {
5578 // Mark that we are replacing a default argument first.
5579 // If we are instantiating a template we won't have to
5580 // retransform immediate calls.
5581 // C++ [expr.const]p15.1:
5582 // An expression or conversion is in an immediate function context if it
5583 // is potentially evaluated and [...] its innermost enclosing non-block
5584 // scope is a function parameter scope of an immediate function.
5586 *this,
5590 Param);
5591
5592 if (Param->hasUninstantiatedDefaultArg()) {
5593 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5594 return ExprError();
5595 }
5596 // CWG2631
5597 // An immediate invocation that is not evaluated where it appears is
5598 // evaluated and checked for whether it is a constant expression at the
5599 // point where the enclosing initializer is used in a function call.
5601 if (!NestedDefaultChecking)
5602 V.TraverseDecl(Param);
5603
5604 // Rewrite the call argument that was created from the corresponding
5605 // parameter's default argument.
5606 if (V.HasImmediateCalls ||
5607 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5608 if (V.HasImmediateCalls)
5609 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5610 CallLoc, Param, CurContext};
5611 // Pass down lifetime extending flag, and collect temporaries in
5612 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5616 ExprResult Res;
5617 runWithSufficientStackSpace(CallLoc, [&] {
5618 Res = Immediate.TransformInitializer(Param->getInit(),
5619 /*NotCopy=*/false);
5620 });
5621 if (Res.isInvalid())
5622 return ExprError();
5623 Res = ConvertParamDefaultArgument(Param, Res.get(),
5624 Res.get()->getBeginLoc());
5625 if (Res.isInvalid())
5626 return ExprError();
5627 Init = Res.get();
5628 }
5629 }
5630
5632 CallLoc, FD, Param, Init,
5633 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5634 return ExprError();
5635
5636 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5637 Init, InitializationContext->Context);
5638}
5639
5641 FieldDecl *Field) {
5642 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5643 return Pattern;
5644 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5645 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5647 ClassPattern->lookup(Field->getDeclName());
5648 auto Rng = llvm::make_filter_range(
5649 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5650 if (Rng.empty())
5651 return nullptr;
5652 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5653 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5654 // && "Duplicated instantiation pattern for field decl");
5655 return cast<FieldDecl>(*Rng.begin());
5656}
5657
5659 assert(Field->hasInClassInitializer());
5660
5661 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5662
5663 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5664
5665 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5666 InitializationContext =
5668 if (!InitializationContext.has_value())
5669 InitializationContext.emplace(Loc, Field, CurContext);
5670
5671 Expr *Init = nullptr;
5672
5673 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5674 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5677
5678 if (!Field->getInClassInitializer()) {
5679 // Maybe we haven't instantiated the in-class initializer. Go check the
5680 // pattern FieldDecl to see if it has one.
5681 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5682 FieldDecl *Pattern =
5684 assert(Pattern && "We must have set the Pattern!");
5685 if (!Pattern->hasInClassInitializer() ||
5686 InstantiateInClassInitializer(Loc, Field, Pattern,
5688 Field->setInvalidDecl();
5689 return ExprError();
5690 }
5691 }
5692 }
5693
5694 // CWG2631
5695 // An immediate invocation that is not evaluated where it appears is
5696 // evaluated and checked for whether it is a constant expression at the
5697 // point where the enclosing initializer is used in a [...] a constructor
5698 // definition, or an aggregate initialization.
5700 if (!NestedDefaultChecking)
5701 V.TraverseDecl(Field);
5702
5703 // CWG1815
5704 // Support lifetime extension of temporary created by aggregate
5705 // initialization using a default member initializer. We should rebuild
5706 // the initializer in a lifetime extension context if the initializer
5707 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5708 // extension code recurses into the default initializer and does lifetime
5709 // extension when warranted.
5710 bool ContainsAnyTemporaries =
5711 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5712 if (Field->getInClassInitializer() &&
5713 !Field->getInClassInitializer()->containsErrors() &&
5714 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5715 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5716 CurContext};
5717 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5718 NestedDefaultChecking;
5719 // Pass down lifetime extending flag, and collect temporaries in
5720 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5724 ExprResult Res;
5726 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5727 /*CXXDirectInit=*/false);
5728 });
5729 if (!Res.isInvalid())
5730 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5731 if (Res.isInvalid()) {
5732 Field->setInvalidDecl();
5733 return ExprError();
5734 }
5735 Init = Res.get();
5736 }
5737
5738 if (Field->getInClassInitializer()) {
5739 Expr *E = Init ? Init : Field->getInClassInitializer();
5740 if (!NestedDefaultChecking)
5742 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5743 });
5746 // C++11 [class.base.init]p7:
5747 // The initialization of each base and member constitutes a
5748 // full-expression.
5749 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5750 if (Res.isInvalid()) {
5751 Field->setInvalidDecl();
5752 return ExprError();
5753 }
5754 Init = Res.get();
5755
5756 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5757 Field, InitializationContext->Context,
5758 Init);
5759 }
5760
5761 // DR1351:
5762 // If the brace-or-equal-initializer of a non-static data member
5763 // invokes a defaulted default constructor of its class or of an
5764 // enclosing class in a potentially evaluated subexpression, the
5765 // program is ill-formed.
5766 //
5767 // This resolution is unworkable: the exception specification of the
5768 // default constructor can be needed in an unevaluated context, in
5769 // particular, in the operand of a noexcept-expression, and we can be
5770 // unable to compute an exception specification for an enclosed class.
5771 //
5772 // Any attempt to resolve the exception specification of a defaulted default
5773 // constructor before the initializer is lexically complete will ultimately
5774 // come here at which point we can diagnose it.
5775 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5776 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5777 << OutermostClass << Field;
5778 Diag(Field->getEndLoc(),
5779 diag::note_default_member_initializer_not_yet_parsed);
5780 // Recover by marking the field invalid, unless we're in a SFINAE context.
5781 if (!isSFINAEContext())
5782 Field->setInvalidDecl();
5783 return ExprError();
5784}
5785
5787 const FunctionProtoType *Proto,
5788 Expr *Fn) {
5789 if (Proto && Proto->isVariadic()) {
5790 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5792 else if (Fn && Fn->getType()->isBlockPointerType())
5794 else if (FDecl) {
5795 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5796 if (Method->isInstance())
5798 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5801 }
5803}
5804
5805namespace {
5806class FunctionCallCCC final : public FunctionCallFilterCCC {
5807public:
5808 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5809 unsigned NumArgs, MemberExpr *ME)
5810 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5811 FunctionName(FuncName) {}
5812
5813 bool ValidateCandidate(const TypoCorrection &candidate) override {
5814 if (!candidate.getCorrectionSpecifier() ||
5815 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5816 return false;
5817 }
5818
5820 }
5821
5822 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5823 return std::make_unique<FunctionCallCCC>(*this);
5824 }
5825
5826private:
5827 const IdentifierInfo *const FunctionName;
5828};
5829}
5830
5832 FunctionDecl *FDecl,
5833 ArrayRef<Expr *> Args) {
5834 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5835 DeclarationName FuncName = FDecl->getDeclName();
5836 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5837
5838 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5839 if (TypoCorrection Corrected = S.CorrectTypo(
5841 S.getScopeForContext(S.CurContext), nullptr, CCC,
5843 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5844 if (Corrected.isOverloaded()) {
5847 for (NamedDecl *CD : Corrected) {
5848 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5850 OCS);
5851 }
5852 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5853 case OR_Success:
5854 ND = Best->FoundDecl;
5855 Corrected.setCorrectionDecl(ND);
5856 break;
5857 default:
5858 break;
5859 }
5860 }
5861 ND = ND->getUnderlyingDecl();
5862 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5863 return Corrected;
5864 }
5865 }
5866 return TypoCorrection();
5867}
5868
5869// [C++26][[expr.unary.op]/p4
5870// A pointer to member is only formed when an explicit &
5871// is used and its operand is a qualified-id not enclosed in parentheses.
5873 if (!isa<ParenExpr>(Fn))
5874 return false;
5875
5876 Fn = Fn->IgnoreParens();
5877
5878 auto *UO = dyn_cast<UnaryOperator>(Fn);
5879 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5880 return false;
5881 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5882 return DRE->hasQualifier();
5883 }
5884 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5885 return bool(OVL->getQualifier());
5886 return false;
5887}
5888
5889bool
5891 FunctionDecl *FDecl,
5892 const FunctionProtoType *Proto,
5893 ArrayRef<Expr *> Args,
5894 SourceLocation RParenLoc,
5895 bool IsExecConfig) {
5896 // Bail out early if calling a builtin with custom typechecking.
5897 if (FDecl)
5898 if (unsigned ID = FDecl->getBuiltinID())
5900 return false;
5901
5902 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5903 // assignment, to the types of the corresponding parameter, ...
5904
5905 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5906 bool HasExplicitObjectParameter =
5907 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5908 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5909 unsigned NumParams = Proto->getNumParams();
5910 bool Invalid = false;
5911 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5912 unsigned FnKind = Fn->getType()->isBlockPointerType()
5913 ? 1 /* block */
5914 : (IsExecConfig ? 3 /* kernel function (exec config) */
5915 : 0 /* function */);
5916
5917 // If too few arguments are available (and we don't have default
5918 // arguments for the remaining parameters), don't make the call.
5919 if (Args.size() < NumParams) {
5920 if (Args.size() < MinArgs) {
5921 TypoCorrection TC;
5922 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5923 unsigned diag_id =
5924 MinArgs == NumParams && !Proto->isVariadic()
5925 ? diag::err_typecheck_call_too_few_args_suggest
5926 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5928 TC, PDiag(diag_id)
5929 << FnKind << MinArgs - ExplicitObjectParameterOffset
5930 << static_cast<unsigned>(Args.size()) -
5931 ExplicitObjectParameterOffset
5932 << HasExplicitObjectParameter << TC.getCorrectionRange());
5933 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5934 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5935 ->getDeclName())
5936 Diag(RParenLoc,
5937 MinArgs == NumParams && !Proto->isVariadic()
5938 ? diag::err_typecheck_call_too_few_args_one
5939 : diag::err_typecheck_call_too_few_args_at_least_one)
5940 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5941 << HasExplicitObjectParameter << Fn->getSourceRange();
5942 else
5943 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5944 ? diag::err_typecheck_call_too_few_args
5945 : diag::err_typecheck_call_too_few_args_at_least)
5946 << FnKind << MinArgs - ExplicitObjectParameterOffset
5947 << static_cast<unsigned>(Args.size()) -
5948 ExplicitObjectParameterOffset
5949 << HasExplicitObjectParameter << Fn->getSourceRange();
5950
5951 // Emit the location of the prototype.
5952 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5953 Diag(FDecl->getLocation(), diag::note_callee_decl)
5954 << FDecl << FDecl->getParametersSourceRange();
5955
5956 return true;
5957 }
5958 // We reserve space for the default arguments when we create
5959 // the call expression, before calling ConvertArgumentsForCall.
5960 assert((Call->getNumArgs() == NumParams) &&
5961 "We should have reserved space for the default arguments before!");
5962 }
5963
5964 // If too many are passed and not variadic, error on the extras and drop
5965 // them.
5966 if (Args.size() > NumParams) {
5967 if (!Proto->isVariadic()) {
5968 TypoCorrection TC;
5969 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5970 unsigned diag_id =
5971 MinArgs == NumParams && !Proto->isVariadic()
5972 ? diag::err_typecheck_call_too_many_args_suggest
5973 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5975 TC, PDiag(diag_id)
5976 << FnKind << NumParams - ExplicitObjectParameterOffset
5977 << static_cast<unsigned>(Args.size()) -
5978 ExplicitObjectParameterOffset
5979 << HasExplicitObjectParameter << TC.getCorrectionRange());
5980 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5981 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5982 ->getDeclName())
5983 Diag(Args[NumParams]->getBeginLoc(),
5984 MinArgs == NumParams
5985 ? diag::err_typecheck_call_too_many_args_one
5986 : diag::err_typecheck_call_too_many_args_at_most_one)
5987 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5988 << static_cast<unsigned>(Args.size()) -
5989 ExplicitObjectParameterOffset
5990 << HasExplicitObjectParameter << Fn->getSourceRange()
5991 << SourceRange(Args[NumParams]->getBeginLoc(),
5992 Args.back()->getEndLoc());
5993 else
5994 Diag(Args[NumParams]->getBeginLoc(),
5995 MinArgs == NumParams
5996 ? diag::err_typecheck_call_too_many_args
5997 : diag::err_typecheck_call_too_many_args_at_most)
5998 << FnKind << NumParams - ExplicitObjectParameterOffset
5999 << static_cast<unsigned>(Args.size()) -
6000 ExplicitObjectParameterOffset
6001 << HasExplicitObjectParameter << Fn->getSourceRange()
6002 << SourceRange(Args[NumParams]->getBeginLoc(),
6003 Args.back()->getEndLoc());
6004
6005 // Emit the location of the prototype.
6006 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6007 Diag(FDecl->getLocation(), diag::note_callee_decl)
6008 << FDecl << FDecl->getParametersSourceRange();
6009
6010 // This deletes the extra arguments.
6011 Call->shrinkNumArgs(NumParams);
6012 return true;
6013 }
6014 }
6015 SmallVector<Expr *, 8> AllArgs;
6016 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6017
6018 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6019 AllArgs, CallType);
6020 if (Invalid)
6021 return true;
6022 unsigned TotalNumArgs = AllArgs.size();
6023 for (unsigned i = 0; i < TotalNumArgs; ++i)
6024 Call->setArg(i, AllArgs[i]);
6025
6026 Call->computeDependence();
6027 return false;
6028}
6029
6031 const FunctionProtoType *Proto,
6032 unsigned FirstParam, ArrayRef<Expr *> Args,
6033 SmallVectorImpl<Expr *> &AllArgs,
6034 VariadicCallType CallType, bool AllowExplicit,
6035 bool IsListInitialization) {
6036 unsigned NumParams = Proto->getNumParams();
6037 bool Invalid = false;
6038 size_t ArgIx = 0;
6039 // Continue to check argument types (even if we have too few/many args).
6040 for (unsigned i = FirstParam; i < NumParams; i++) {
6041 QualType ProtoArgType = Proto->getParamType(i);
6042
6043 Expr *Arg;
6044 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6045 if (ArgIx < Args.size()) {
6046 Arg = Args[ArgIx++];
6047
6048 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6049 diag::err_call_incomplete_argument, Arg))
6050 return true;
6051
6052 // Strip the unbridged-cast placeholder expression off, if applicable.
6053 bool CFAudited = false;
6054 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6055 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6056 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6057 Arg = ObjC().stripARCUnbridgedCast(Arg);
6058 else if (getLangOpts().ObjCAutoRefCount &&
6059 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6060 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6061 CFAudited = true;
6062
6063 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6064 ProtoArgType->isBlockPointerType())
6065 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6066 BE->getBlockDecl()->setDoesNotEscape();
6067 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6069 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6070 if (ArgExpr.isInvalid())
6071 return true;
6072 Arg = ArgExpr.getAs<Expr>();
6073 }
6074
6075 InitializedEntity Entity =
6077 ProtoArgType)
6079 Context, ProtoArgType, Proto->isParamConsumed(i));
6080
6081 // Remember that parameter belongs to a CF audited API.
6082 if (CFAudited)
6083 Entity.setParameterCFAudited();
6084
6086 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6087 if (ArgE.isInvalid())
6088 return true;
6089
6090 Arg = ArgE.getAs<Expr>();
6091 } else {
6092 assert(Param && "can't use default arguments without a known callee");
6093
6094 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6095 if (ArgExpr.isInvalid())
6096 return true;
6097
6098 Arg = ArgExpr.getAs<Expr>();
6099 }
6100
6101 // Check for array bounds violations for each argument to the call. This
6102 // check only triggers warnings when the argument isn't a more complex Expr
6103 // with its own checking, such as a BinaryOperator.
6104 CheckArrayAccess(Arg);
6105
6106 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6107 CheckStaticArrayArgument(CallLoc, Param, Arg);
6108
6109 AllArgs.push_back(Arg);
6110 }
6111
6112 // If this is a variadic call, handle args passed through "...".
6113 if (CallType != VariadicCallType::DoesNotApply) {
6114 // Assume that extern "C" functions with variadic arguments that
6115 // return __unknown_anytype aren't *really* variadic.
6116 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6117 FDecl->isExternC()) {
6118 for (Expr *A : Args.slice(ArgIx)) {
6119 QualType paramType; // ignored
6120 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6121 Invalid |= arg.isInvalid();
6122 AllArgs.push_back(arg.get());
6123 }
6124
6125 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6126 } else {
6127 for (Expr *A : Args.slice(ArgIx)) {
6128 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6129 Invalid |= Arg.isInvalid();
6130 AllArgs.push_back(Arg.get());
6131 }
6132 }
6133
6134 // Check for array bounds violations.
6135 for (Expr *A : Args.slice(ArgIx))
6136 CheckArrayAccess(A);
6137 }
6138 return Invalid;
6139}
6140
6142 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6143 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6144 TL = DTL.getOriginalLoc();
6145 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6146 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6147 << ATL.getLocalSourceRange();
6148}
6149
6150void
6152 ParmVarDecl *Param,
6153 const Expr *ArgExpr) {
6154 // Static array parameters are not supported in C++.
6155 if (!Param || getLangOpts().CPlusPlus)
6156 return;
6157
6158 QualType OrigTy = Param->getOriginalType();
6159
6160 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6161 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6162 return;
6163
6164 if (ArgExpr->isNullPointerConstant(Context,
6166 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6167 DiagnoseCalleeStaticArrayParam(*this, Param);
6168 return;
6169 }
6170
6171 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6172 if (!CAT)
6173 return;
6174
6175 const ConstantArrayType *ArgCAT =
6177 if (!ArgCAT)
6178 return;
6179
6180 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6181 ArgCAT->getElementType())) {
6182 if (ArgCAT->getSize().ult(CAT->getSize())) {
6183 Diag(CallLoc, diag::warn_static_array_too_small)
6184 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6185 << (unsigned)CAT->getZExtSize() << 0;
6186 DiagnoseCalleeStaticArrayParam(*this, Param);
6187 }
6188 return;
6189 }
6190
6191 std::optional<CharUnits> ArgSize =
6193 std::optional<CharUnits> ParmSize =
6195 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6196 Diag(CallLoc, diag::warn_static_array_too_small)
6197 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6198 << (unsigned)ParmSize->getQuantity() << 1;
6199 DiagnoseCalleeStaticArrayParam(*this, Param);
6200 }
6201}
6202
6203/// Given a function expression of unknown-any type, try to rebuild it
6204/// to have a function type.
6206
6207/// Is the given type a placeholder that we need to lower out
6208/// immediately during argument processing?
6210 // Placeholders are never sugared.
6211 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6212 if (!placeholder) return false;
6213
6214 switch (placeholder->getKind()) {
6215 // Ignore all the non-placeholder types.
6216#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6217 case BuiltinType::Id:
6218#include "clang/Basic/OpenCLImageTypes.def"
6219#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6220 case BuiltinType::Id:
6221#include "clang/Basic/OpenCLExtensionTypes.def"
6222 // In practice we'll never use this, since all SVE types are sugared
6223 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6224#define SVE_TYPE(Name, Id, SingletonId) \
6225 case BuiltinType::Id:
6226#include "clang/Basic/AArch64ACLETypes.def"
6227#define PPC_VECTOR_TYPE(Name, Id, Size) \
6228 case BuiltinType::Id:
6229#include "clang/Basic/PPCTypes.def"
6230#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6231#include "clang/Basic/RISCVVTypes.def"
6232#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6233#include "clang/Basic/WebAssemblyReferenceTypes.def"
6234#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6235#include "clang/Basic/AMDGPUTypes.def"
6236#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6237#include "clang/Basic/HLSLIntangibleTypes.def"
6238#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6239#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6240#include "clang/AST/BuiltinTypes.def"
6241 return false;
6242
6243 case BuiltinType::UnresolvedTemplate:
6244 // We cannot lower out overload sets; they might validly be resolved
6245 // by the call machinery.
6246 case BuiltinType::Overload:
6247 return false;
6248
6249 // Unbridged casts in ARC can be handled in some call positions and
6250 // should be left in place.
6251 case BuiltinType::ARCUnbridgedCast:
6252 return false;
6253
6254 // Pseudo-objects should be converted as soon as possible.
6255 case BuiltinType::PseudoObject:
6256 return true;
6257
6258 // The debugger mode could theoretically but currently does not try
6259 // to resolve unknown-typed arguments based on known parameter types.
6260 case BuiltinType::UnknownAny:
6261 return true;
6262
6263 // These are always invalid as call arguments and should be reported.
6264 case BuiltinType::BoundMember:
6265 case BuiltinType::BuiltinFn:
6266 case BuiltinType::IncompleteMatrixIdx:
6267 case BuiltinType::ArraySection:
6268 case BuiltinType::OMPArrayShaping:
6269 case BuiltinType::OMPIterator:
6270 return true;
6271
6272 }
6273 llvm_unreachable("bad builtin type kind");
6274}
6275
6277 // Apply this processing to all the arguments at once instead of
6278 // dying at the first failure.
6279 bool hasInvalid = false;
6280 for (size_t i = 0, e = args.size(); i != e; i++) {
6281 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6282 ExprResult result = CheckPlaceholderExpr(args[i]);
6283 if (result.isInvalid()) hasInvalid = true;
6284 else args[i] = result.get();
6285 }
6286 }
6287 return hasInvalid;
6288}
6289
6290/// If a builtin function has a pointer argument with no explicit address
6291/// space, then it should be able to accept a pointer to any address
6292/// space as input. In order to do this, we need to replace the
6293/// standard builtin declaration with one that uses the same address space
6294/// as the call.
6295///
6296/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6297/// it does not contain any pointer arguments without
6298/// an address space qualifer. Otherwise the rewritten
6299/// FunctionDecl is returned.
6300/// TODO: Handle pointer return types.
6302 FunctionDecl *FDecl,
6303 MultiExprArg ArgExprs) {
6304
6305 QualType DeclType = FDecl->getType();
6306 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6307
6308 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6309 ArgExprs.size() < FT->getNumParams())
6310 return nullptr;
6311
6312 bool NeedsNewDecl = false;
6313 unsigned i = 0;
6314 SmallVector<QualType, 8> OverloadParams;
6315
6316 for (QualType ParamType : FT->param_types()) {
6317
6318 // Convert array arguments to pointer to simplify type lookup.
6319 ExprResult ArgRes =
6321 if (ArgRes.isInvalid())
6322 return nullptr;
6323 Expr *Arg = ArgRes.get();
6324 QualType ArgType = Arg->getType();
6325 if (!ParamType->isPointerType() ||
6326 ParamType->getPointeeType().hasAddressSpace() ||
6327 !ArgType->isPointerType() ||
6328 !ArgType->getPointeeType().hasAddressSpace() ||
6330 OverloadParams.push_back(ParamType);
6331 continue;
6332 }
6333
6334 QualType PointeeType = ParamType->getPointeeType();
6335 NeedsNewDecl = true;
6336 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6337
6338 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6339 OverloadParams.push_back(Context.getPointerType(PointeeType));
6340 }
6341
6342 if (!NeedsNewDecl)
6343 return nullptr;
6344
6346 EPI.Variadic = FT->isVariadic();
6347 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6348 OverloadParams, EPI);
6349 DeclContext *Parent = FDecl->getParent();
6350 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6351 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6352 FDecl->getIdentifier(), OverloadTy,
6353 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6354 false,
6355 /*hasPrototype=*/true);
6357 FT = cast<FunctionProtoType>(OverloadTy);
6358 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6359 QualType ParamType = FT->getParamType(i);
6360 ParmVarDecl *Parm =
6361 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6362 SourceLocation(), nullptr, ParamType,
6363 /*TInfo=*/nullptr, SC_None, nullptr);
6364 Parm->setScopeInfo(0, i);
6365 Params.push_back(Parm);
6366 }
6367 OverloadDecl->setParams(Params);
6368 // We cannot merge host/device attributes of redeclarations. They have to
6369 // be consistent when created.
6370 if (Sema->LangOpts.CUDA) {
6371 if (FDecl->hasAttr<CUDAHostAttr>())
6372 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6373 if (FDecl->hasAttr<CUDADeviceAttr>())
6374 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6375 }
6376 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6377 return OverloadDecl;
6378}
6379
6380static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6381 FunctionDecl *Callee,
6382 MultiExprArg ArgExprs) {
6383 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6384 // similar attributes) really don't like it when functions are called with an
6385 // invalid number of args.
6386 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6387 /*PartialOverloading=*/false) &&
6388 !Callee->isVariadic())
6389 return;
6390 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6391 return;
6392
6393 if (const EnableIfAttr *Attr =
6394 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6395 S.Diag(Fn->getBeginLoc(),
6396 isa<CXXMethodDecl>(Callee)
6397 ? diag::err_ovl_no_viable_member_function_in_call
6398 : diag::err_ovl_no_viable_function_in_call)
6399 << Callee << Callee->getSourceRange();
6400 S.Diag(Callee->getLocation(),
6401 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6402 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6403 return;
6404 }
6405}
6406
6408 const UnresolvedMemberExpr *const UME, Sema &S) {
6409
6410 const auto GetFunctionLevelDCIfCXXClass =
6411 [](Sema &S) -> const CXXRecordDecl * {
6412 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6413 if (!DC || !DC->getParent())
6414 return nullptr;
6415
6416 // If the call to some member function was made from within a member
6417 // function body 'M' return return 'M's parent.
6418 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6419 return MD->getParent()->getCanonicalDecl();
6420 // else the call was made from within a default member initializer of a
6421 // class, so return the class.
6422 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6423 return RD->getCanonicalDecl();
6424 return nullptr;
6425 };
6426 // If our DeclContext is neither a member function nor a class (in the
6427 // case of a lambda in a default member initializer), we can't have an
6428 // enclosing 'this'.
6429
6430 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6431 if (!CurParentClass)
6432 return false;
6433
6434 // The naming class for implicit member functions call is the class in which
6435 // name lookup starts.
6436 const CXXRecordDecl *const NamingClass =
6438 assert(NamingClass && "Must have naming class even for implicit access");
6439
6440 // If the unresolved member functions were found in a 'naming class' that is
6441 // related (either the same or derived from) to the class that contains the
6442 // member function that itself contained the implicit member access.
6443
6444 return CurParentClass == NamingClass ||
6445 CurParentClass->isDerivedFrom(NamingClass);
6446}
6447
6448static void
6450 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6451
6452 if (!UME)
6453 return;
6454
6455 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6456 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6457 // already been captured, or if this is an implicit member function call (if
6458 // it isn't, an attempt to capture 'this' should already have been made).
6459 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6460 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6461 return;
6462
6463 // Check if the naming class in which the unresolved members were found is
6464 // related (same as or is a base of) to the enclosing class.
6465
6467 return;
6468
6469
6470 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6471 // If the enclosing function is not dependent, then this lambda is
6472 // capture ready, so if we can capture this, do so.
6473 if (!EnclosingFunctionCtx->isDependentContext()) {
6474 // If the current lambda and all enclosing lambdas can capture 'this' -
6475 // then go ahead and capture 'this' (since our unresolved overload set
6476 // contains at least one non-static member function).
6477 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6478 S.CheckCXXThisCapture(CallLoc);
6479 } else if (S.CurContext->isDependentContext()) {
6480 // ... since this is an implicit member reference, that might potentially
6481 // involve a 'this' capture, mark 'this' for potential capture in
6482 // enclosing lambdas.
6483 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6484 CurLSI->addPotentialThisCapture(CallLoc);
6485 }
6486}
6487
6488// Once a call is fully resolved, warn for unqualified calls to specific
6489// C++ standard functions, like move and forward.
6491 const CallExpr *Call) {
6492 // We are only checking unary move and forward so exit early here.
6493 if (Call->getNumArgs() != 1)
6494 return;
6495
6496 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6497 if (!E || isa<UnresolvedLookupExpr>(E))
6498 return;
6499 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6500 if (!DRE || !DRE->getLocation().isValid())
6501 return;
6502
6503 if (DRE->getQualifier())
6504 return;
6505
6506 const FunctionDecl *FD = Call->getDirectCallee();
6507 if (!FD)
6508 return;
6509
6510 // Only warn for some functions deemed more frequent or problematic.
6511 unsigned BuiltinID = FD->getBuiltinID();
6512 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6513 return;
6514
6515 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6517 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6518}
6519
6521 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6522 Expr *ExecConfig) {
6524 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6525 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6526 if (Call.isInvalid())
6527 return Call;
6528
6529 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6530 // language modes.
6531 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6532 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6533 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6534 << ULE->getName();
6535 }
6536
6537 if (LangOpts.OpenMP)
6538 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6539 ExecConfig);
6540 if (LangOpts.CPlusPlus) {
6541 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6543
6544 // If we previously found that the id-expression of this call refers to a
6545 // consteval function but the call is dependent, we should not treat is an
6546 // an invalid immediate call.
6547 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6548 DRE && Call.get()->isValueDependent()) {
6550 }
6551 }
6552 return Call;
6553}
6554
6555// Any type that could be used to form a callable expression
6556static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6557 QualType T = E->getType();
6558 if (T->isDependentType())
6559 return true;
6560
6561 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6562 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6566 return true;
6567
6570}
6571
6573 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6574 Expr *ExecConfig, bool IsExecConfig,
6575 bool AllowRecovery) {
6576 // Since this might be a postfix expression, get rid of ParenListExprs.
6578 if (Result.isInvalid()) return ExprError();
6579 Fn = Result.get();
6580
6581 if (CheckArgsForPlaceholders(ArgExprs))
6582 return ExprError();
6583
6584 // The result of __builtin_counted_by_ref cannot be used as a function
6585 // argument. It allows leaking and modification of bounds safety information.
6586 for (const Expr *Arg : ArgExprs)
6587 if (CheckInvalidBuiltinCountedByRef(Arg,
6589 return ExprError();
6590
6591 if (getLangOpts().CPlusPlus) {
6592 // If this is a pseudo-destructor expression, build the call immediately.
6593 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6594 if (!ArgExprs.empty()) {
6595 // Pseudo-destructor calls should not have any arguments.
6596 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6598 SourceRange(ArgExprs.front()->getBeginLoc(),
6599 ArgExprs.back()->getEndLoc()));
6600 }
6601
6602 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6603 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6604 }
6605 if (Fn->getType() == Context.PseudoObjectTy) {
6606 ExprResult result = CheckPlaceholderExpr(Fn);
6607 if (result.isInvalid()) return ExprError();
6608 Fn = result.get();
6609 }
6610
6611 // Determine whether this is a dependent call inside a C++ template,
6612 // in which case we won't do any semantic analysis now.
6613 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6614 if (ExecConfig) {
6616 cast<CallExpr>(ExecConfig), ArgExprs,
6618 RParenLoc, CurFPFeatureOverrides());
6619 } else {
6620
6622 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6623 Fn->getBeginLoc());
6624
6625 // If the type of the function itself is not dependent
6626 // check that it is a reasonable as a function, as type deduction
6627 // later assume the CallExpr has a sensible TYPE.
6628 if (!MayBeFunctionType(Context, Fn))
6629 return ExprError(
6630 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6631 << Fn->getType() << Fn->getSourceRange());
6632
6633 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6634 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6635 }
6636 }
6637
6638 // Determine whether this is a call to an object (C++ [over.call.object]).
6639 if (Fn->getType()->isRecordType())
6640 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6641 RParenLoc);
6642
6643 if (Fn->getType() == Context.UnknownAnyTy) {
6644 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6645 if (result.isInvalid()) return ExprError();
6646 Fn = result.get();
6647 }
6648
6649 if (Fn->getType() == Context.BoundMemberTy) {
6650 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6651 RParenLoc, ExecConfig, IsExecConfig,
6652 AllowRecovery);
6653 }
6654 }
6655
6656 // Check for overloaded calls. This can happen even in C due to extensions.
6657 if (Fn->getType() == Context.OverloadTy) {
6659
6660 // We aren't supposed to apply this logic if there's an '&' involved.
6663 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6664 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6665 OverloadExpr *ovl = find.Expression;
6666 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6668 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6669 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6670 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6671 RParenLoc, ExecConfig, IsExecConfig,
6672 AllowRecovery);
6673 }
6674 }
6675
6676 // If we're directly calling a function, get the appropriate declaration.
6677 if (Fn->getType() == Context.UnknownAnyTy) {
6678 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6679 if (result.isInvalid()) return ExprError();
6680 Fn = result.get();
6681 }
6682
6683 Expr *NakedFn = Fn->IgnoreParens();
6684
6685 bool CallingNDeclIndirectly = false;
6686 NamedDecl *NDecl = nullptr;
6687 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6688 if (UnOp->getOpcode() == UO_AddrOf) {
6689 CallingNDeclIndirectly = true;
6690 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6691 }
6692 }
6693
6694 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6695 NDecl = DRE->getDecl();
6696
6697 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6698 if (FDecl && FDecl->getBuiltinID()) {
6699 // Rewrite the function decl for this builtin by replacing parameters
6700 // with no explicit address space with the address space of the arguments
6701 // in ArgExprs.
6702 if ((FDecl =
6703 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6704 NDecl = FDecl;
6706 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6707 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6708 nullptr, DRE->isNonOdrUse());
6709 }
6710 }
6711 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6712 NDecl = ME->getMemberDecl();
6713
6714 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6715 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6716 FD, /*Complain=*/true, Fn->getBeginLoc()))
6717 return ExprError();
6718
6719 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6720
6721 // If this expression is a call to a builtin function in HIP device
6722 // compilation, allow a pointer-type argument to default address space to be
6723 // passed as a pointer-type parameter to a non-default address space.
6724 // If Arg is declared in the default address space and Param is declared
6725 // in a non-default address space, perform an implicit address space cast to
6726 // the parameter type.
6727 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6728 FD->getBuiltinID()) {
6729 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6730 ++Idx) {
6731 ParmVarDecl *Param = FD->getParamDecl(Idx);
6732 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6733 !ArgExprs[Idx]->getType()->isPointerType())
6734 continue;
6735
6736 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6737 auto ArgTy = ArgExprs[Idx]->getType();
6738 auto ArgPtTy = ArgTy->getPointeeType();
6739 auto ArgAS = ArgPtTy.getAddressSpace();
6740
6741 // Add address space cast if target address spaces are different
6742 bool NeedImplicitASC =
6743 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6744 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6745 // or from specific AS which has target AS matching that of Param.
6747 if (!NeedImplicitASC)
6748 continue;
6749
6750 // First, ensure that the Arg is an RValue.
6751 if (ArgExprs[Idx]->isGLValue()) {
6752 ArgExprs[Idx] = ImplicitCastExpr::Create(
6753 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6754 nullptr, VK_PRValue, FPOptionsOverride());
6755 }
6756
6757 // Construct a new arg type with address space of Param
6758 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6759 ArgPtQuals.setAddressSpace(ParamAS);
6760 auto NewArgPtTy =
6761 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6762 auto NewArgTy =
6764 ArgTy.getQualifiers());
6765
6766 // Finally perform an implicit address space cast
6767 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6768 CK_AddressSpaceConversion)
6769 .get();
6770 }
6771 }
6772 }
6773
6775 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6776 assert(!getLangOpts().CPlusPlus);
6777 assert((Fn->containsErrors() ||
6778 llvm::any_of(ArgExprs,
6779 [](clang::Expr *E) { return E->containsErrors(); })) &&
6780 "should only occur in error-recovery path.");
6781 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6782 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6783 }
6784 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6785 ExecConfig, IsExecConfig);
6786}
6787
6789 MultiExprArg CallArgs) {
6790 std::string Name = Context.BuiltinInfo.getName(Id);
6791 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6793 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6794
6795 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6796 assert(BuiltInDecl && "failed to find builtin declaration");
6797
6798 ExprResult DeclRef =
6799 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6800 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6801
6803 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6804
6805 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6806 return Call.get();
6807}
6808
6810 SourceLocation BuiltinLoc,
6811 SourceLocation RParenLoc) {
6812 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6813 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6814}
6815
6817 SourceLocation BuiltinLoc,
6818 SourceLocation RParenLoc) {
6821 QualType SrcTy = E->getType();
6822 if (!SrcTy->isDependentType() &&
6823 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6824 return ExprError(
6825 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6826 << DestTy << SrcTy << E->getSourceRange());
6827 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6828}
6829
6831 SourceLocation BuiltinLoc,
6832 SourceLocation RParenLoc) {
6833 TypeSourceInfo *TInfo;
6834 GetTypeFromParser(ParsedDestTy, &TInfo);
6835 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6836}
6837
6839 SourceLocation LParenLoc,
6840 ArrayRef<Expr *> Args,
6841 SourceLocation RParenLoc, Expr *Config,
6842 bool IsExecConfig, ADLCallKind UsesADL) {
6843 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6844 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6845
6846 // Functions with 'interrupt' attribute cannot be called directly.
6847 if (FDecl) {
6848 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6849 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6850 return ExprError();
6851 }
6852 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6853 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6854 return ExprError();
6855 }
6856 }
6857
6858 // X86 interrupt handlers may only call routines with attribute
6859 // no_caller_saved_registers since there is no efficient way to
6860 // save and restore the non-GPR state.
6861 if (auto *Caller = getCurFunctionDecl()) {
6862 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6863 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6864 const TargetInfo &TI = Context.getTargetInfo();
6865 bool HasNonGPRRegisters =
6866 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6867 if (HasNonGPRRegisters &&
6868 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6869 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6870 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6871 if (FDecl)
6872 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6873 }
6874 }
6875 }
6876
6877 // Promote the function operand.
6878 // We special-case function promotion here because we only allow promoting
6879 // builtin functions to function pointers in the callee of a call.
6881 QualType ResultTy;
6882 if (BuiltinID &&
6883 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6884 // Extract the return type from the (builtin) function pointer type.
6885 // FIXME Several builtins still have setType in
6886 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6887 // Builtins.td to ensure they are correct before removing setType calls.
6888 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6889 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6890 ResultTy = FDecl->getCallResultType();
6891 } else {
6893 ResultTy = Context.BoolTy;
6894 }
6895 if (Result.isInvalid())
6896 return ExprError();
6897 Fn = Result.get();
6898
6899 // Check for a valid function type, but only if it is not a builtin which
6900 // requires custom type checking. These will be handled by
6901 // CheckBuiltinFunctionCall below just after creation of the call expression.
6902 const FunctionType *FuncT = nullptr;
6903 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6904 retry:
6905 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6906 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6907 // have type pointer to function".
6908 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6909 if (!FuncT)
6910 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6911 << Fn->getType() << Fn->getSourceRange());
6912 } else if (const BlockPointerType *BPT =
6913 Fn->getType()->getAs<BlockPointerType>()) {
6914 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6915 } else {
6916 // Handle calls to expressions of unknown-any type.
6917 if (Fn->getType() == Context.UnknownAnyTy) {
6918 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6919 if (rewrite.isInvalid())
6920 return ExprError();
6921 Fn = rewrite.get();
6922 goto retry;
6923 }
6924
6925 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6926 << Fn->getType() << Fn->getSourceRange());
6927 }
6928 }
6929
6930 // Get the number of parameters in the function prototype, if any.
6931 // We will allocate space for max(Args.size(), NumParams) arguments
6932 // in the call expression.
6933 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6934 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6935
6936 CallExpr *TheCall;
6937 if (Config) {
6938 assert(UsesADL == ADLCallKind::NotADL &&
6939 "CUDAKernelCallExpr should not use ADL");
6940 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6941 Args, ResultTy, VK_PRValue, RParenLoc,
6942 CurFPFeatureOverrides(), NumParams);
6943 } else {
6944 TheCall =
6945 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6946 CurFPFeatureOverrides(), NumParams, UsesADL);
6947 }
6948
6949 // Bail out early if calling a builtin with custom type checking.
6950 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6951 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6952 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6954 return E;
6955 }
6956
6957 if (getLangOpts().CUDA) {
6958 if (Config) {
6959 // CUDA: Kernel calls must be to global functions
6960 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6961 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6962 << FDecl << Fn->getSourceRange());
6963
6964 // CUDA: Kernel function must have 'void' return type
6965 if (!FuncT->getReturnType()->isVoidType() &&
6966 !FuncT->getReturnType()->getAs<AutoType>() &&
6968 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6969 << Fn->getType() << Fn->getSourceRange());
6970 } else {
6971 // CUDA: Calls to global functions must be configured
6972 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6973 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6974 << FDecl << Fn->getSourceRange());
6975 }
6976 }
6977
6978 // Check for a valid return type
6979 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6980 FDecl))
6981 return ExprError();
6982
6983 // We know the result type of the call, set it.
6984 TheCall->setType(FuncT->getCallResultType(Context));
6986
6987 // WebAssembly tables can't be used as arguments.
6988 if (Context.getTargetInfo().getTriple().isWasm()) {
6989 for (const Expr *Arg : Args) {
6990 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6991 return ExprError(Diag(Arg->getExprLoc(),
6992 diag::err_wasm_table_as_function_parameter));
6993 }
6994 }
6995 }
6996
6997 if (Proto) {
6998 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6999 IsExecConfig))
7000 return ExprError();
7001 } else {
7002 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7003
7004 if (FDecl) {
7005 // Check if we have too few/too many template arguments, based
7006 // on our knowledge of the function definition.
7007 const FunctionDecl *Def = nullptr;
7008 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7009 Proto = Def->getType()->getAs<FunctionProtoType>();
7010 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7011 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7012 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7013 }
7014
7015 // If the function we're calling isn't a function prototype, but we have
7016 // a function prototype from a prior declaratiom, use that prototype.
7017 if (!FDecl->hasPrototype())
7018 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7019 }
7020
7021 // If we still haven't found a prototype to use but there are arguments to
7022 // the call, diagnose this as calling a function without a prototype.
7023 // However, if we found a function declaration, check to see if
7024 // -Wdeprecated-non-prototype was disabled where the function was declared.
7025 // If so, we will silence the diagnostic here on the assumption that this
7026 // interface is intentional and the user knows what they're doing. We will
7027 // also silence the diagnostic if there is a function declaration but it
7028 // was implicitly defined (the user already gets diagnostics about the
7029 // creation of the implicit function declaration, so the additional warning
7030 // is not helpful).
7031 if (!Proto && !Args.empty() &&
7032 (!FDecl || (!FDecl->isImplicit() &&
7033 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7034 FDecl->getLocation()))))
7035 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7036 << (FDecl != nullptr) << FDecl;
7037
7038 // Promote the arguments (C99 6.5.2.2p6).
7039 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7040 Expr *Arg = Args[i];
7041
7042 if (Proto && i < Proto->getNumParams()) {
7044 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7045 ExprResult ArgE =
7047 if (ArgE.isInvalid())
7048 return true;
7049
7050 Arg = ArgE.getAs<Expr>();
7051
7052 } else {
7054
7055 if (ArgE.isInvalid())
7056 return true;
7057
7058 Arg = ArgE.getAs<Expr>();
7059 }
7060
7061 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7062 diag::err_call_incomplete_argument, Arg))
7063 return ExprError();
7064
7065 TheCall->setArg(i, Arg);
7066 }
7067 TheCall->computeDependence();
7068 }
7069
7070 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7071 if (Method->isImplicitObjectMemberFunction())
7072 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7073 << Fn->getSourceRange() << 0);
7074
7075 // Check for sentinels
7076 if (NDecl)
7077 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7078
7079 // Warn for unions passing across security boundary (CMSE).
7080 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7081 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7082 if (const auto *RT =
7083 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7084 if (RT->getOriginalDecl()->isOrContainsUnion())
7085 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7086 << 0 << i;
7087 }
7088 }
7089 }
7090
7091 // Do special checking on direct calls to functions.
7092 if (FDecl) {
7093 if (CheckFunctionCall(FDecl, TheCall, Proto))
7094 return ExprError();
7095
7096 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7097
7098 if (BuiltinID)
7099 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7100 } else if (NDecl) {
7101 if (CheckPointerCall(NDecl, TheCall, Proto))
7102 return ExprError();
7103 } else {
7104 if (CheckOtherCall(TheCall, Proto))
7105 return ExprError();
7106 }
7107
7108 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7109}
7110
7113 SourceLocation RParenLoc, Expr *InitExpr) {
7114 assert(Ty && "ActOnCompoundLiteral(): missing type");
7115 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7116
7117 TypeSourceInfo *TInfo;
7118 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7119 if (!TInfo)
7120 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7121
7122 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7123}
7124
7127 SourceLocation RParenLoc, Expr *LiteralExpr) {
7128 QualType literalType = TInfo->getType();
7129
7130 if (literalType->isArrayType()) {
7132 LParenLoc, Context.getBaseElementType(literalType),
7133 diag::err_array_incomplete_or_sizeless_type,
7134 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7135 return ExprError();
7136 if (literalType->isVariableArrayType()) {
7137 // C23 6.7.10p4: An entity of variable length array type shall not be
7138 // initialized except by an empty initializer.
7139 //
7140 // The C extension warnings are issued from ParseBraceInitializer() and
7141 // do not need to be issued here. However, we continue to issue an error
7142 // in the case there are initializers or we are compiling C++. We allow
7143 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7144 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7145 // FIXME: should we allow this construct in C++ when it makes sense to do
7146 // so?
7147 //
7148 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7149 // shall specify an object type or an array of unknown size, but not a
7150 // variable length array type. This seems odd, as it allows 'int a[size] =
7151 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7152 // says, this is what's implemented here for C (except for the extension
7153 // that permits constant foldable size arrays)
7154
7155 auto diagID = LangOpts.CPlusPlus
7156 ? diag::err_variable_object_no_init
7157 : diag::err_compound_literal_with_vla_type;
7158 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7159 diagID))
7160 return ExprError();
7161 }
7162 } else if (!literalType->isDependentType() &&
7163 RequireCompleteType(LParenLoc, literalType,
7164 diag::err_typecheck_decl_incomplete_type,
7165 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7166 return ExprError();
7167
7168 InitializedEntity Entity
7172 SourceRange(LParenLoc, RParenLoc),
7173 /*InitList=*/true);
7174 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7175 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7176 &literalType);
7177 if (Result.isInvalid())
7178 return ExprError();
7179 LiteralExpr = Result.get();
7180
7181 // We treat the compound literal as being at file scope if it's not in a
7182 // function or method body, or within the function's prototype scope. This
7183 // means the following compound literal is not at file scope:
7184 // void func(char *para[(int [1]){ 0 }[0]);
7185 const Scope *S = getCurScope();
7186 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7187 !S->isInCFunctionScope() &&
7188 (!S || !S->isFunctionPrototypeScope());
7189
7190 // In C, compound literals are l-values for some reason.
7191 // For GCC compatibility, in C++, file-scope array compound literals with
7192 // constant initializers are also l-values, and compound literals are
7193 // otherwise prvalues.
7194 //
7195 // (GCC also treats C++ list-initialized file-scope array prvalues with
7196 // constant initializers as l-values, but that's non-conforming, so we don't
7197 // follow it there.)
7198 //
7199 // FIXME: It would be better to handle the lvalue cases as materializing and
7200 // lifetime-extending a temporary object, but our materialized temporaries
7201 // representation only supports lifetime extension from a variable, not "out
7202 // of thin air".
7203 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7204 // is bound to the result of applying array-to-pointer decay to the compound
7205 // literal.
7206 // FIXME: GCC supports compound literals of reference type, which should
7207 // obviously have a value kind derived from the kind of reference involved.
7209 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7210 ? VK_PRValue
7211 : VK_LValue;
7212
7213 // C99 6.5.2.5
7214 // "If the compound literal occurs outside the body of a function, the
7215 // initializer list shall consist of constant expressions."
7216 if (IsFileScope)
7217 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7218 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7219 Expr *Init = ILE->getInit(i);
7220 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7221 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7222 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7223 << Init->getSourceBitField();
7224 return ExprError();
7225 }
7226
7227 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7228 }
7229
7230 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7231 LiteralExpr, IsFileScope);
7232 if (IsFileScope) {
7233 if (!LiteralExpr->isTypeDependent() &&
7234 !LiteralExpr->isValueDependent() &&
7235 !literalType->isDependentType()) // C99 6.5.2.5p3
7236 if (CheckForConstantInitializer(LiteralExpr))
7237 return ExprError();
7238 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7239 literalType.getAddressSpace() != LangAS::Default) {
7240 // Embedded-C extensions to C99 6.5.2.5:
7241 // "If the compound literal occurs inside the body of a function, the
7242 // type name shall not be qualified by an address-space qualifier."
7243 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7244 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7245 return ExprError();
7246 }
7247
7248 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7249 // Compound literals that have automatic storage duration are destroyed at
7250 // the end of the scope in C; in C++, they're just temporaries.
7251
7252 // Emit diagnostics if it is or contains a C union type that is non-trivial
7253 // to destruct.
7258
7259 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7260 if (literalType.isDestructedType()) {
7262 ExprCleanupObjects.push_back(E);
7264 }
7265 }
7266
7269 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7270 E->getInitializer()->getExprLoc());
7271
7272 return MaybeBindToTemporary(E);
7273}
7274
7277 SourceLocation RBraceLoc) {
7278 // Only produce each kind of designated initialization diagnostic once.
7279 SourceLocation FirstDesignator;
7280 bool DiagnosedArrayDesignator = false;
7281 bool DiagnosedNestedDesignator = false;
7282 bool DiagnosedMixedDesignator = false;
7283
7284 // Check that any designated initializers are syntactically valid in the
7285 // current language mode.
7286 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7287 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7288 if (FirstDesignator.isInvalid())
7289 FirstDesignator = DIE->getBeginLoc();
7290
7291 if (!getLangOpts().CPlusPlus)
7292 break;
7293
7294 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7295 DiagnosedNestedDesignator = true;
7296 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7297 << DIE->getDesignatorsSourceRange();
7298 }
7299
7300 for (auto &Desig : DIE->designators()) {
7301 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7302 DiagnosedArrayDesignator = true;
7303 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7304 << Desig.getSourceRange();
7305 }
7306 }
7307
7308 if (!DiagnosedMixedDesignator &&
7309 !isa<DesignatedInitExpr>(InitArgList[0])) {
7310 DiagnosedMixedDesignator = true;
7311 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7312 << DIE->getSourceRange();
7313 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7314 << InitArgList[0]->getSourceRange();
7315 }
7316 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7317 isa<DesignatedInitExpr>(InitArgList[0])) {
7318 DiagnosedMixedDesignator = true;
7319 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7320 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7321 << DIE->getSourceRange();
7322 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7323 << InitArgList[I]->getSourceRange();
7324 }
7325 }
7326
7327 if (FirstDesignator.isValid()) {
7328 // Only diagnose designated initiaization as a C++20 extension if we didn't
7329 // already diagnose use of (non-C++20) C99 designator syntax.
7330 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7331 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7332 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7333 ? diag::warn_cxx17_compat_designated_init
7334 : diag::ext_cxx_designated_init);
7335 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7336 Diag(FirstDesignator, diag::ext_designated_init);
7337 }
7338 }
7339
7340 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7341}
7342
7345 SourceLocation RBraceLoc) {
7346 // Semantic analysis for initializers is done by ActOnDeclarator() and
7347 // CheckInitializer() - it requires knowledge of the object being initialized.
7348
7349 // Immediately handle non-overload placeholders. Overloads can be
7350 // resolved contextually, but everything else here can't.
7351 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7352 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7353 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7354
7355 // Ignore failures; dropping the entire initializer list because
7356 // of one failure would be terrible for indexing/etc.
7357 if (result.isInvalid()) continue;
7358
7359 InitArgList[I] = result.get();
7360 }
7361 }
7362
7363 InitListExpr *E =
7364 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7365 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7366 return E;
7367}
7368
7370 assert(E.get()->getType()->isBlockPointerType());
7371 assert(E.get()->isPRValue());
7372
7373 // Only do this in an r-value context.
7374 if (!getLangOpts().ObjCAutoRefCount) return;
7375
7377 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7378 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7380}
7381
7383 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7384 // Also, callers should have filtered out the invalid cases with
7385 // pointers. Everything else should be possible.
7386
7387 QualType SrcTy = Src.get()->getType();
7388 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7389 return CK_NoOp;
7390
7391 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7393 llvm_unreachable("member pointer type in C");
7394
7395 case Type::STK_CPointer:
7398 switch (DestTy->getScalarTypeKind()) {
7399 case Type::STK_CPointer: {
7400 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7401 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7402 if (SrcAS != DestAS)
7403 return CK_AddressSpaceConversion;
7404 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7405 return CK_NoOp;
7406 return CK_BitCast;
7407 }
7409 return (SrcKind == Type::STK_BlockPointer
7410 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7412 if (SrcKind == Type::STK_ObjCObjectPointer)
7413 return CK_BitCast;
7414 if (SrcKind == Type::STK_CPointer)
7415 return CK_CPointerToObjCPointerCast;
7417 return CK_BlockPointerToObjCPointerCast;
7418 case Type::STK_Bool:
7419 return CK_PointerToBoolean;
7420 case Type::STK_Integral:
7421 return CK_PointerToIntegral;
7422 case Type::STK_Floating:
7427 llvm_unreachable("illegal cast from pointer");
7428 }
7429 llvm_unreachable("Should have returned before this");
7430
7432 switch (DestTy->getScalarTypeKind()) {
7434 return CK_FixedPointCast;
7435 case Type::STK_Bool:
7436 return CK_FixedPointToBoolean;
7437 case Type::STK_Integral:
7438 return CK_FixedPointToIntegral;
7439 case Type::STK_Floating:
7440 return CK_FixedPointToFloating;
7443 Diag(Src.get()->getExprLoc(),
7444 diag::err_unimplemented_conversion_with_fixed_point_type)
7445 << DestTy;
7446 return CK_IntegralCast;
7447 case Type::STK_CPointer:
7451 llvm_unreachable("illegal cast to pointer type");
7452 }
7453 llvm_unreachable("Should have returned before this");
7454
7455 case Type::STK_Bool: // casting from bool is like casting from an integer
7456 case Type::STK_Integral:
7457 switch (DestTy->getScalarTypeKind()) {
7458 case Type::STK_CPointer:
7463 return CK_NullToPointer;
7464 return CK_IntegralToPointer;
7465 case Type::STK_Bool:
7466 return CK_IntegralToBoolean;
7467 case Type::STK_Integral:
7468 return CK_IntegralCast;
7469 case Type::STK_Floating:
7470 return CK_IntegralToFloating;
7472 Src = ImpCastExprToType(Src.get(),
7473 DestTy->castAs<ComplexType>()->getElementType(),
7474 CK_IntegralCast);
7475 return CK_IntegralRealToComplex;
7477 Src = ImpCastExprToType(Src.get(),
7478 DestTy->castAs<ComplexType>()->getElementType(),
7479 CK_IntegralToFloating);
7480 return CK_FloatingRealToComplex;
7482 llvm_unreachable("member pointer type in C");
7484 return CK_IntegralToFixedPoint;
7485 }
7486 llvm_unreachable("Should have returned before this");
7487
7488 case Type::STK_Floating:
7489 switch (DestTy->getScalarTypeKind()) {
7490 case Type::STK_Floating:
7491 return CK_FloatingCast;
7492 case Type::STK_Bool:
7493 return CK_FloatingToBoolean;
7494 case Type::STK_Integral:
7495 return CK_FloatingToIntegral;
7497 Src = ImpCastExprToType(Src.get(),
7498 DestTy->castAs<ComplexType>()->getElementType(),
7499 CK_FloatingCast);
7500 return CK_FloatingRealToComplex;
7502 Src = ImpCastExprToType(Src.get(),
7503 DestTy->castAs<ComplexType>()->getElementType(),
7504 CK_FloatingToIntegral);
7505 return CK_IntegralRealToComplex;
7506 case Type::STK_CPointer:
7509 llvm_unreachable("valid float->pointer cast?");
7511 llvm_unreachable("member pointer type in C");
7513 return CK_FloatingToFixedPoint;
7514 }
7515 llvm_unreachable("Should have returned before this");
7516
7518 switch (DestTy->getScalarTypeKind()) {
7520 return CK_FloatingComplexCast;
7522 return CK_FloatingComplexToIntegralComplex;
7523 case Type::STK_Floating: {
7524 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7525 if (Context.hasSameType(ET, DestTy))
7526 return CK_FloatingComplexToReal;
7527 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7528 return CK_FloatingCast;
7529 }
7530 case Type::STK_Bool:
7531 return CK_FloatingComplexToBoolean;
7532 case Type::STK_Integral:
7533 Src = ImpCastExprToType(Src.get(),
7534 SrcTy->castAs<ComplexType>()->getElementType(),
7535 CK_FloatingComplexToReal);
7536 return CK_FloatingToIntegral;
7537 case Type::STK_CPointer:
7540 llvm_unreachable("valid complex float->pointer cast?");
7542 llvm_unreachable("member pointer type in C");
7544 Diag(Src.get()->getExprLoc(),
7545 diag::err_unimplemented_conversion_with_fixed_point_type)
7546 << SrcTy;
7547 return CK_IntegralCast;
7548 }
7549 llvm_unreachable("Should have returned before this");
7550
7552 switch (DestTy->getScalarTypeKind()) {
7554 return CK_IntegralComplexToFloatingComplex;
7556 return CK_IntegralComplexCast;
7557 case Type::STK_Integral: {
7558 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7559 if (Context.hasSameType(ET, DestTy))
7560 return CK_IntegralComplexToReal;
7561 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7562 return CK_IntegralCast;
7563 }
7564 case Type::STK_Bool:
7565 return CK_IntegralComplexToBoolean;
7566 case Type::STK_Floating:
7567 Src = ImpCastExprToType(Src.get(),
7568 SrcTy->castAs<ComplexType>()->getElementType(),
7569 CK_IntegralComplexToReal);
7570 return CK_IntegralToFloating;
7571 case Type::STK_CPointer:
7574 llvm_unreachable("valid complex int->pointer cast?");
7576 llvm_unreachable("member pointer type in C");
7578 Diag(Src.get()->getExprLoc(),
7579 diag::err_unimplemented_conversion_with_fixed_point_type)
7580 << SrcTy;
7581 return CK_IntegralCast;
7582 }
7583 llvm_unreachable("Should have returned before this");
7584 }
7585
7586 llvm_unreachable("Unhandled scalar cast");
7587}
7588
7589static bool breakDownVectorType(QualType type, uint64_t &len,
7590 QualType &eltType) {
7591 // Vectors are simple.
7592 if (const VectorType *vecType = type->getAs<VectorType>()) {
7593 len = vecType->getNumElements();
7594 eltType = vecType->getElementType();
7595 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7596 return true;
7597 }
7598
7599 // We allow lax conversion to and from non-vector types, but only if
7600 // they're real types (i.e. non-complex, non-pointer scalar types).
7601 if (!type->isRealType()) return false;
7602
7603 len = 1;
7604 eltType = type;
7605 return true;
7606}
7607
7609 assert(srcTy->isVectorType() || destTy->isVectorType());
7610
7611 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7612 if (!FirstType->isSVESizelessBuiltinType())
7613 return false;
7614
7615 const auto *VecTy = SecondType->getAs<VectorType>();
7616 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7617 };
7618
7619 return ValidScalableConversion(srcTy, destTy) ||
7620 ValidScalableConversion(destTy, srcTy);
7621}
7622
7624 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7625 return false;
7626
7627 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7628 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7629
7630 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7631 matSrcType->getNumColumns() == matDestType->getNumColumns();
7632}
7633
7635 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7636
7637 uint64_t SrcLen, DestLen;
7638 QualType SrcEltTy, DestEltTy;
7639 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7640 return false;
7641 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7642 return false;
7643
7644 // ASTContext::getTypeSize will return the size rounded up to a
7645 // power of 2, so instead of using that, we need to use the raw
7646 // element size multiplied by the element count.
7647 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7648 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7649
7650 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7651}
7652
7654 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7655 "expected at least one type to be a vector here");
7656
7657 bool IsSrcTyAltivec =
7658 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7660 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7662 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7664
7665 bool IsDestTyAltivec = DestTy->isVectorType() &&
7666 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7668 (DestTy->castAs<VectorType>()->getVectorKind() ==
7670 (DestTy->castAs<VectorType>()->getVectorKind() ==
7672
7673 return (IsSrcTyAltivec || IsDestTyAltivec);
7674}
7675
7677 assert(destTy->isVectorType() || srcTy->isVectorType());
7678
7679 // Disallow lax conversions between scalars and ExtVectors (these
7680 // conversions are allowed for other vector types because common headers
7681 // depend on them). Most scalar OP ExtVector cases are handled by the
7682 // splat path anyway, which does what we want (convert, not bitcast).
7683 // What this rules out for ExtVectors is crazy things like char4*float.
7684 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7685 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7686
7687 return areVectorTypesSameSize(srcTy, destTy);
7688}
7689
7691 assert(destTy->isVectorType() || srcTy->isVectorType());
7692
7693 switch (Context.getLangOpts().getLaxVectorConversions()) {
7695 return false;
7696
7698 if (!srcTy->isIntegralOrEnumerationType()) {
7699 auto *Vec = srcTy->getAs<VectorType>();
7700 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7701 return false;
7702 }
7703 if (!destTy->isIntegralOrEnumerationType()) {
7704 auto *Vec = destTy->getAs<VectorType>();
7705 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7706 return false;
7707 }
7708 // OK, integer (vector) -> integer (vector) bitcast.
7709 break;
7710
7712 break;
7713 }
7714
7715 return areLaxCompatibleVectorTypes(srcTy, destTy);
7716}
7717
7719 CastKind &Kind) {
7720 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7721 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7722 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7723 << DestTy << SrcTy << R;
7724 }
7725 } else if (SrcTy->isMatrixType()) {
7726 return Diag(R.getBegin(),
7727 diag::err_invalid_conversion_between_matrix_and_type)
7728 << SrcTy << DestTy << R;
7729 } else if (DestTy->isMatrixType()) {
7730 return Diag(R.getBegin(),
7731 diag::err_invalid_conversion_between_matrix_and_type)
7732 << DestTy << SrcTy << R;
7733 }
7734
7735 Kind = CK_MatrixCast;
7736 return false;
7737}
7738
7740 CastKind &Kind) {
7741 assert(VectorTy->isVectorType() && "Not a vector type!");
7742
7743 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7744 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7745 return Diag(R.getBegin(),
7746 Ty->isVectorType() ?
7747 diag::err_invalid_conversion_between_vectors :
7748 diag::err_invalid_conversion_between_vector_and_integer)
7749 << VectorTy << Ty << R;
7750 } else
7751 return Diag(R.getBegin(),
7752 diag::err_invalid_conversion_between_vector_and_scalar)
7753 << VectorTy << Ty << R;
7754
7755 Kind = CK_BitCast;
7756 return false;
7757}
7758
7760 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7761
7762 if (DestElemTy == SplattedExpr->getType())
7763 return SplattedExpr;
7764
7765 assert(DestElemTy->isFloatingType() ||
7766 DestElemTy->isIntegralOrEnumerationType());
7767
7768 CastKind CK;
7769 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7770 // OpenCL requires that we convert `true` boolean expressions to -1, but
7771 // only when splatting vectors.
7772 if (DestElemTy->isFloatingType()) {
7773 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7774 // in two steps: boolean to signed integral, then to floating.
7775 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7776 CK_BooleanToSignedIntegral);
7777 SplattedExpr = CastExprRes.get();
7778 CK = CK_IntegralToFloating;
7779 } else {
7780 CK = CK_BooleanToSignedIntegral;
7781 }
7782 } else {
7783 ExprResult CastExprRes = SplattedExpr;
7784 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7785 if (CastExprRes.isInvalid())
7786 return ExprError();
7787 SplattedExpr = CastExprRes.get();
7788 }
7789 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7790}
7791
7793 Expr *CastExpr, CastKind &Kind) {
7794 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7795
7796 QualType SrcTy = CastExpr->getType();
7797
7798 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7799 // an ExtVectorType.
7800 // In OpenCL, casts between vectors of different types are not allowed.
7801 // (See OpenCL 6.2).
7802 if (SrcTy->isVectorType()) {
7803 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7804 (getLangOpts().OpenCL &&
7805 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7806 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7807 << DestTy << SrcTy << R;
7808 return ExprError();
7809 }
7810 Kind = CK_BitCast;
7811 return CastExpr;
7812 }
7813
7814 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7815 // conversion will take place first from scalar to elt type, and then
7816 // splat from elt type to vector.
7817 if (SrcTy->isPointerType())
7818 return Diag(R.getBegin(),
7819 diag::err_invalid_conversion_between_vector_and_scalar)
7820 << DestTy << SrcTy << R;
7821
7822 Kind = CK_VectorSplat;
7823 return prepareVectorSplat(DestTy, CastExpr);
7824}
7825
7826/// Check that a call to alloc_size function specifies sufficient space for the
7827/// destination type.
7828static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7829 const Expr *E) {
7830 QualType SourceType = E->getType();
7831 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7832 DestType == SourceType)
7833 return;
7834
7835 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
7836 if (!CE)
7837 return;
7838
7839 // Find the total size allocated by the function call.
7840 if (!CE->getCalleeAllocSizeAttr())
7841 return;
7842 std::optional<llvm::APInt> AllocSize =
7843 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
7844 // Allocations of size zero are permitted as a special case. They are usually
7845 // done intentionally.
7846 if (!AllocSize || AllocSize->isZero())
7847 return;
7848 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
7849
7850 QualType TargetType = DestType->getPointeeType();
7851 // Find the destination size. As a special case function types have size of
7852 // one byte to match the sizeof operator behavior.
7853 auto LhsSize = TargetType->isFunctionType()
7854 ? CharUnits::One()
7855 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
7856 if (LhsSize && Size < LhsSize)
7857 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
7858 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7859}
7860
7863 Declarator &D, ParsedType &Ty,
7864 SourceLocation RParenLoc, Expr *CastExpr) {
7865 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7866 "ActOnCastExpr(): missing type or expr");
7867
7869 if (D.isInvalidType())
7870 return ExprError();
7871
7872 if (getLangOpts().CPlusPlus) {
7873 // Check that there are no default arguments (C++ only).
7875 }
7876
7878
7879 QualType castType = castTInfo->getType();
7880 Ty = CreateParsedType(castType, castTInfo);
7881
7882 bool isVectorLiteral = false;
7883
7884 // Check for an altivec or OpenCL literal,
7885 // i.e. all the elements are integer constants.
7886 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7887 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7888 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7889 && castType->isVectorType() && (PE || PLE)) {
7890 if (PLE && PLE->getNumExprs() == 0) {
7891 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7892 return ExprError();
7893 }
7894 if (PE || PLE->getNumExprs() == 1) {
7895 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7896 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7897 isVectorLiteral = true;
7898 }
7899 else
7900 isVectorLiteral = true;
7901 }
7902
7903 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7904 // then handle it as such.
7905 if (isVectorLiteral)
7906 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7907
7908 // If the Expr being casted is a ParenListExpr, handle it specially.
7909 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7910 // sequence of BinOp comma operators.
7911 if (isa<ParenListExpr>(CastExpr)) {
7913 if (Result.isInvalid()) return ExprError();
7914 CastExpr = Result.get();
7915 }
7916
7917 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7918 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7919
7921
7923
7925
7926 CheckSufficientAllocSize(*this, castType, CastExpr);
7927
7928 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7929}
7930
7932 SourceLocation RParenLoc, Expr *E,
7933 TypeSourceInfo *TInfo) {
7934 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7935 "Expected paren or paren list expression");
7936
7937 Expr **exprs;
7938 unsigned numExprs;
7939 Expr *subExpr;
7940 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7941 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7942 LiteralLParenLoc = PE->getLParenLoc();
7943 LiteralRParenLoc = PE->getRParenLoc();
7944 exprs = PE->getExprs();
7945 numExprs = PE->getNumExprs();
7946 } else { // isa<ParenExpr> by assertion at function entrance
7947 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7948 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7949 subExpr = cast<ParenExpr>(E)->getSubExpr();
7950 exprs = &subExpr;
7951 numExprs = 1;
7952 }
7953
7954 QualType Ty = TInfo->getType();
7955 assert(Ty->isVectorType() && "Expected vector type");
7956
7957 SmallVector<Expr *, 8> initExprs;
7958 const VectorType *VTy = Ty->castAs<VectorType>();
7959 unsigned numElems = VTy->getNumElements();
7960
7961 // '(...)' form of vector initialization in AltiVec: the number of
7962 // initializers must be one or must match the size of the vector.
7963 // If a single value is specified in the initializer then it will be
7964 // replicated to all the components of the vector
7966 VTy->getElementType()))
7967 return ExprError();
7969 // The number of initializers must be one or must match the size of the
7970 // vector. If a single value is specified in the initializer then it will
7971 // be replicated to all the components of the vector
7972 if (numExprs == 1) {
7973 QualType ElemTy = VTy->getElementType();
7974 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7975 if (Literal.isInvalid())
7976 return ExprError();
7977 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7978 PrepareScalarCast(Literal, ElemTy));
7979 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7980 }
7981 else if (numExprs < numElems) {
7982 Diag(E->getExprLoc(),
7983 diag::err_incorrect_number_of_vector_initializers);
7984 return ExprError();
7985 }
7986 else
7987 initExprs.append(exprs, exprs + numExprs);
7988 }
7989 else {
7990 // For OpenCL, when the number of initializers is a single value,
7991 // it will be replicated to all components of the vector.
7993 numExprs == 1) {
7994 QualType ElemTy = VTy->getElementType();
7995 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7996 if (Literal.isInvalid())
7997 return ExprError();
7998 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7999 PrepareScalarCast(Literal, ElemTy));
8000 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8001 }
8002
8003 initExprs.append(exprs, exprs + numExprs);
8004 }
8005 // FIXME: This means that pretty-printing the final AST will produce curly
8006 // braces instead of the original commas.
8007 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8008 initExprs, LiteralRParenLoc);
8009 initE->setType(Ty);
8010 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8011}
8012
8015 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8016 if (!E)
8017 return OrigExpr;
8018
8019 ExprResult Result(E->getExpr(0));
8020
8021 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8022 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8023 E->getExpr(i));
8024
8025 if (Result.isInvalid()) return ExprError();
8026
8027 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8028}
8029
8032 MultiExprArg Val) {
8033 return ParenListExpr::Create(Context, L, Val, R);
8034}
8035
8037 unsigned NumUserSpecifiedExprs,
8038 SourceLocation InitLoc,
8039 SourceLocation LParenLoc,
8040 SourceLocation RParenLoc) {
8041 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8042 InitLoc, LParenLoc, RParenLoc);
8043}
8044
8045bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8046 SourceLocation QuestionLoc) {
8047 const Expr *NullExpr = LHSExpr;
8048 const Expr *NonPointerExpr = RHSExpr;
8052
8053 if (NullKind == Expr::NPCK_NotNull) {
8054 NullExpr = RHSExpr;
8055 NonPointerExpr = LHSExpr;
8056 NullKind =
8059 }
8060
8061 if (NullKind == Expr::NPCK_NotNull)
8062 return false;
8063
8064 if (NullKind == Expr::NPCK_ZeroExpression)
8065 return false;
8066
8067 if (NullKind == Expr::NPCK_ZeroLiteral) {
8068 // In this case, check to make sure that we got here from a "NULL"
8069 // string in the source code.
8070 NullExpr = NullExpr->IgnoreParenImpCasts();
8071 SourceLocation loc = NullExpr->getExprLoc();
8072 if (!findMacroSpelling(loc, "NULL"))
8073 return false;
8074 }
8075
8076 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8077 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8078 << NonPointerExpr->getType() << DiagType
8079 << NonPointerExpr->getSourceRange();
8080 return true;
8081}
8082
8083/// Return false if the condition expression is valid, true otherwise.
8084static bool checkCondition(Sema &S, const Expr *Cond,
8085 SourceLocation QuestionLoc) {
8086 QualType CondTy = Cond->getType();
8087
8088 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8089 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8090 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8091 << CondTy << Cond->getSourceRange();
8092 return true;
8093 }
8094
8095 // C99 6.5.15p2
8096 if (CondTy->isScalarType()) return false;
8097
8098 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8099 << CondTy << Cond->getSourceRange();
8100 return true;
8101}
8102
8103/// Return false if the NullExpr can be promoted to PointerTy,
8104/// true otherwise.
8106 QualType PointerTy) {
8107 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8108 !NullExpr.get()->isNullPointerConstant(S.Context,
8110 return true;
8111
8112 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8113 return false;
8114}
8115
8116/// Checks compatibility between two pointers and return the resulting
8117/// type.
8119 ExprResult &RHS,
8121 QualType LHSTy = LHS.get()->getType();
8122 QualType RHSTy = RHS.get()->getType();
8123
8124 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8125 // Two identical pointers types are always compatible.
8126 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8127 }
8128
8129 QualType lhptee, rhptee;
8130
8131 // Get the pointee types.
8132 bool IsBlockPointer = false;
8133 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8134 lhptee = LHSBTy->getPointeeType();
8135 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8136 IsBlockPointer = true;
8137 } else {
8138 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8139 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8140 }
8141
8142 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8143 // differently qualified versions of compatible types, the result type is
8144 // a pointer to an appropriately qualified version of the composite
8145 // type.
8146
8147 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8148 // clause doesn't make sense for our extensions. E.g. address space 2 should
8149 // be incompatible with address space 3: they may live on different devices or
8150 // anything.
8151 Qualifiers lhQual = lhptee.getQualifiers();
8152 Qualifiers rhQual = rhptee.getQualifiers();
8153
8154 LangAS ResultAddrSpace = LangAS::Default;
8155 LangAS LAddrSpace = lhQual.getAddressSpace();
8156 LangAS RAddrSpace = rhQual.getAddressSpace();
8157
8158 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8159 // spaces is disallowed.
8160 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8161 ResultAddrSpace = LAddrSpace;
8162 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8163 ResultAddrSpace = RAddrSpace;
8164 else {
8165 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8166 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8167 << RHS.get()->getSourceRange();
8168 return QualType();
8169 }
8170
8171 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8172 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8173 lhQual.removeCVRQualifiers();
8174 rhQual.removeCVRQualifiers();
8175
8176 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8177 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8178 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8179 << RHS.get()->getSourceRange();
8180 return QualType();
8181 }
8182
8183 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8184 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8185 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8186 // qual types are compatible iff
8187 // * corresponded types are compatible
8188 // * CVR qualifiers are equal
8189 // * address spaces are equal
8190 // Thus for conditional operator we merge CVR and address space unqualified
8191 // pointees and if there is a composite type we return a pointer to it with
8192 // merged qualifiers.
8193 LHSCastKind =
8194 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8195 RHSCastKind =
8196 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8197 lhQual.removeAddressSpace();
8198 rhQual.removeAddressSpace();
8199
8200 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8201 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8202
8203 QualType CompositeTy = S.Context.mergeTypes(
8204 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8205 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8206
8207 if (CompositeTy.isNull()) {
8208 // In this situation, we assume void* type. No especially good
8209 // reason, but this is what gcc does, and we do have to pick
8210 // to get a consistent AST.
8211 QualType incompatTy;
8212 incompatTy = S.Context.getPointerType(
8213 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8214 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8215 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8216
8217 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8218 // for casts between types with incompatible address space qualifiers.
8219 // For the following code the compiler produces casts between global and
8220 // local address spaces of the corresponded innermost pointees:
8221 // local int *global *a;
8222 // global int *global *b;
8223 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8224 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8225 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8226 << RHS.get()->getSourceRange();
8227
8228 return incompatTy;
8229 }
8230
8231 // The pointer types are compatible.
8232 // In case of OpenCL ResultTy should have the address space qualifier
8233 // which is a superset of address spaces of both the 2nd and the 3rd
8234 // operands of the conditional operator.
8235 QualType ResultTy = [&, ResultAddrSpace]() {
8236 if (S.getLangOpts().OpenCL) {
8237 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8238 CompositeQuals.setAddressSpace(ResultAddrSpace);
8239 return S.Context
8240 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8241 .withCVRQualifiers(MergedCVRQual);
8242 }
8243 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8244 }();
8245 if (IsBlockPointer)
8246 ResultTy = S.Context.getBlockPointerType(ResultTy);
8247 else
8248 ResultTy = S.Context.getPointerType(ResultTy);
8249
8250 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8251 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8252 return ResultTy;
8253}
8254
8255/// Return the resulting type when the operands are both block pointers.
8257 ExprResult &LHS,
8258 ExprResult &RHS,
8260 QualType LHSTy = LHS.get()->getType();
8261 QualType RHSTy = RHS.get()->getType();
8262
8263 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8264 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8266 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8267 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8268 return destType;
8269 }
8270 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8271 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8272 << RHS.get()->getSourceRange();
8273 return QualType();
8274 }
8275
8276 // We have 2 block pointer types.
8277 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8278}
8279
8280/// Return the resulting type when the operands are both pointers.
8281static QualType
8283 ExprResult &RHS,
8285 // get the pointer types
8286 QualType LHSTy = LHS.get()->getType();
8287 QualType RHSTy = RHS.get()->getType();
8288
8289 // get the "pointed to" types
8290 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8291 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8292
8293 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8294 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8295 // Figure out necessary qualifiers (C99 6.5.15p6)
8296 QualType destPointee
8297 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8298 QualType destType = S.Context.getPointerType(destPointee);
8299 // Add qualifiers if necessary.
8300 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8301 // Promote to void*.
8302 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8303 return destType;
8304 }
8305 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8306 QualType destPointee
8307 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8308 QualType destType = S.Context.getPointerType(destPointee);
8309 // Add qualifiers if necessary.
8310 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8311 // Promote to void*.
8312 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8313 return destType;
8314 }
8315
8316 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8317}
8318
8319/// Return false if the first expression is not an integer and the second
8320/// expression is not a pointer, true otherwise.
8322 Expr* PointerExpr, SourceLocation Loc,
8323 bool IsIntFirstExpr) {
8324 if (!PointerExpr->getType()->isPointerType() ||
8325 !Int.get()->getType()->isIntegerType())
8326 return false;
8327
8328 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8329 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8330
8331 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8332 << Expr1->getType() << Expr2->getType()
8333 << Expr1->getSourceRange() << Expr2->getSourceRange();
8334 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8335 CK_IntegralToPointer);
8336 return true;
8337}
8338
8339/// Simple conversion between integer and floating point types.
8340///
8341/// Used when handling the OpenCL conditional operator where the
8342/// condition is a vector while the other operands are scalar.
8343///
8344/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8345/// types are either integer or floating type. Between the two
8346/// operands, the type with the higher rank is defined as the "result
8347/// type". The other operand needs to be promoted to the same type. No
8348/// other type promotion is allowed. We cannot use
8349/// UsualArithmeticConversions() for this purpose, since it always
8350/// promotes promotable types.
8352 ExprResult &RHS,
8353 SourceLocation QuestionLoc) {
8355 if (LHS.isInvalid())
8356 return QualType();
8358 if (RHS.isInvalid())
8359 return QualType();
8360
8361 // For conversion purposes, we ignore any qualifiers.
8362 // For example, "const float" and "float" are equivalent.
8363 QualType LHSType =
8365 QualType RHSType =
8367
8368 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8369 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8370 << LHSType << LHS.get()->getSourceRange();
8371 return QualType();
8372 }
8373
8374 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8375 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8376 << RHSType << RHS.get()->getSourceRange();
8377 return QualType();
8378 }
8379
8380 // If both types are identical, no conversion is needed.
8381 if (LHSType == RHSType)
8382 return LHSType;
8383
8384 // Now handle "real" floating types (i.e. float, double, long double).
8385 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8386 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8387 /*IsCompAssign = */ false);
8388
8389 // Finally, we have two differing integer types.
8390 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8391 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8392}
8393
8394/// Convert scalar operands to a vector that matches the
8395/// condition in length.
8396///
8397/// Used when handling the OpenCL conditional operator where the
8398/// condition is a vector while the other operands are scalar.
8399///
8400/// We first compute the "result type" for the scalar operands
8401/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8402/// into a vector of that type where the length matches the condition
8403/// vector type. s6.11.6 requires that the element types of the result
8404/// and the condition must have the same number of bits.
8405static QualType
8407 QualType CondTy, SourceLocation QuestionLoc) {
8408 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8409 if (ResTy.isNull()) return QualType();
8410
8411 const VectorType *CV = CondTy->getAs<VectorType>();
8412 assert(CV);
8413
8414 // Determine the vector result type
8415 unsigned NumElements = CV->getNumElements();
8416 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8417
8418 // Ensure that all types have the same number of bits
8420 != S.Context.getTypeSize(ResTy)) {
8421 // Since VectorTy is created internally, it does not pretty print
8422 // with an OpenCL name. Instead, we just print a description.
8423 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8424 SmallString<64> Str;
8425 llvm::raw_svector_ostream OS(Str);
8426 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8427 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8428 << CondTy << OS.str();
8429 return QualType();
8430 }
8431
8432 // Convert operands to the vector result type
8433 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8434 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8435
8436 return VectorTy;
8437}
8438
8439/// Return false if this is a valid OpenCL condition vector
8441 SourceLocation QuestionLoc) {
8442 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8443 // integral type.
8444 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8445 assert(CondTy);
8446 QualType EleTy = CondTy->getElementType();
8447 if (EleTy->isIntegerType()) return false;
8448
8449 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8450 << Cond->getType() << Cond->getSourceRange();
8451 return true;
8452}
8453
8454/// Return false if the vector condition type and the vector
8455/// result type are compatible.
8456///
8457/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8458/// number of elements, and their element types have the same number
8459/// of bits.
8460static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8461 SourceLocation QuestionLoc) {
8462 const VectorType *CV = CondTy->getAs<VectorType>();
8463 const VectorType *RV = VecResTy->getAs<VectorType>();
8464 assert(CV && RV);
8465
8466 if (CV->getNumElements() != RV->getNumElements()) {
8467 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8468 << CondTy << VecResTy;
8469 return true;
8470 }
8471
8472 QualType CVE = CV->getElementType();
8473 QualType RVE = RV->getElementType();
8474
8475 // Boolean vectors are permitted outside of OpenCL mode.
8476 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8477 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8478 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8479 << CondTy << VecResTy;
8480 return true;
8481 }
8482
8483 return false;
8484}
8485
8486/// Return the resulting type for the conditional operator in
8487/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8488/// s6.3.i) when the condition is a vector type.
8489static QualType
8491 ExprResult &LHS, ExprResult &RHS,
8492 SourceLocation QuestionLoc) {
8494 if (Cond.isInvalid())
8495 return QualType();
8496 QualType CondTy = Cond.get()->getType();
8497
8498 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8499 return QualType();
8500
8501 // If either operand is a vector then find the vector type of the
8502 // result as specified in OpenCL v1.1 s6.3.i.
8503 if (LHS.get()->getType()->isVectorType() ||
8504 RHS.get()->getType()->isVectorType()) {
8505 bool IsBoolVecLang =
8506 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8507 QualType VecResTy =
8508 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8509 /*isCompAssign*/ false,
8510 /*AllowBothBool*/ true,
8511 /*AllowBoolConversions*/ false,
8512 /*AllowBooleanOperation*/ IsBoolVecLang,
8513 /*ReportInvalid*/ true);
8514 if (VecResTy.isNull())
8515 return QualType();
8516 // The result type must match the condition type as specified in
8517 // OpenCL v1.1 s6.11.6.
8518 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8519 return QualType();
8520 return VecResTy;
8521 }
8522
8523 // Both operands are scalar.
8524 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8525}
8526
8527/// Return true if the Expr is block type
8528static bool checkBlockType(Sema &S, const Expr *E) {
8529 if (E->getType()->isBlockPointerType()) {
8530 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8531 return true;
8532 }
8533
8534 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8535 QualType Ty = CE->getCallee()->getType();
8536 if (Ty->isBlockPointerType()) {
8537 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8538 return true;
8539 }
8540 }
8541 return false;
8542}
8543
8544/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8545/// In that case, LHS = cond.
8546/// C99 6.5.15
8549 ExprObjectKind &OK,
8550 SourceLocation QuestionLoc) {
8551
8552 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8553 if (!LHSResult.isUsable()) return QualType();
8554 LHS = LHSResult;
8555
8556 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8557 if (!RHSResult.isUsable()) return QualType();
8558 RHS = RHSResult;
8559
8560 // C++ is sufficiently different to merit its own checker.
8561 if (getLangOpts().CPlusPlus)
8562 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8563
8564 VK = VK_PRValue;
8565 OK = OK_Ordinary;
8566
8568 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8569 RHS.get()->isTypeDependent())) {
8570 assert(!getLangOpts().CPlusPlus);
8571 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8572 RHS.get()->containsErrors()) &&
8573 "should only occur in error-recovery path.");
8574 return Context.DependentTy;
8575 }
8576
8577 // The OpenCL operator with a vector condition is sufficiently
8578 // different to merit its own checker.
8579 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8580 Cond.get()->getType()->isExtVectorType())
8581 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8582
8583 // First, check the condition.
8584 Cond = UsualUnaryConversions(Cond.get());
8585 if (Cond.isInvalid())
8586 return QualType();
8587 if (checkCondition(*this, Cond.get(), QuestionLoc))
8588 return QualType();
8589
8590 // Handle vectors.
8591 if (LHS.get()->getType()->isVectorType() ||
8592 RHS.get()->getType()->isVectorType())
8593 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8594 /*AllowBothBool*/ true,
8595 /*AllowBoolConversions*/ false,
8596 /*AllowBooleanOperation*/ false,
8597 /*ReportInvalid*/ true);
8598
8599 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8601 if (LHS.isInvalid() || RHS.isInvalid())
8602 return QualType();
8603
8604 // WebAssembly tables are not allowed as conditional LHS or RHS.
8605 QualType LHSTy = LHS.get()->getType();
8606 QualType RHSTy = RHS.get()->getType();
8607 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8608 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8609 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8610 return QualType();
8611 }
8612
8613 // Diagnose attempts to convert between __ibm128, __float128 and long double
8614 // where such conversions currently can't be handled.
8615 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8616 Diag(QuestionLoc,
8617 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8618 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8619 return QualType();
8620 }
8621
8622 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8623 // selection operator (?:).
8624 if (getLangOpts().OpenCL &&
8625 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8626 return QualType();
8627 }
8628
8629 // If both operands have arithmetic type, do the usual arithmetic conversions
8630 // to find a common type: C99 6.5.15p3,5.
8631 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8632 // Disallow invalid arithmetic conversions, such as those between bit-
8633 // precise integers types of different sizes, or between a bit-precise
8634 // integer and another type.
8635 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8636 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8637 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8638 << RHS.get()->getSourceRange();
8639 return QualType();
8640 }
8641
8642 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8643 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8644
8645 return ResTy;
8646 }
8647
8648 // If both operands are the same structure or union type, the result is that
8649 // type.
8650 // FIXME: Type of conditional expression must be complete in C mode.
8651 if (LHSTy->isRecordType() &&
8652 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8654 RHSTy.getUnqualifiedType());
8655
8656 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8657 // The following || allows only one side to be void (a GCC-ism).
8658 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8659 QualType ResTy;
8660 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8661 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8662 } else if (RHSTy->isVoidType()) {
8663 ResTy = RHSTy;
8664 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8665 << RHS.get()->getSourceRange();
8666 } else {
8667 ResTy = LHSTy;
8668 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8669 << LHS.get()->getSourceRange();
8670 }
8671 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8672 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8673 return ResTy;
8674 }
8675
8676 // C23 6.5.15p7:
8677 // ... if both the second and third operands have nullptr_t type, the
8678 // result also has that type.
8679 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8680 return ResTy;
8681
8682 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8683 // the type of the other operand."
8684 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8685 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8686
8687 // All objective-c pointer type analysis is done here.
8688 QualType compositeType =
8689 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8690 if (LHS.isInvalid() || RHS.isInvalid())
8691 return QualType();
8692 if (!compositeType.isNull())
8693 return compositeType;
8694
8695
8696 // Handle block pointer types.
8697 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8698 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8699 QuestionLoc);
8700
8701 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8702 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8703 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8704 QuestionLoc);
8705
8706 // GCC compatibility: soften pointer/integer mismatch. Note that
8707 // null pointers have been filtered out by this point.
8708 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8709 /*IsIntFirstExpr=*/true))
8710 return RHSTy;
8711 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8712 /*IsIntFirstExpr=*/false))
8713 return LHSTy;
8714
8715 // Emit a better diagnostic if one of the expressions is a null pointer
8716 // constant and the other is not a pointer type. In this case, the user most
8717 // likely forgot to take the address of the other expression.
8718 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8719 return QualType();
8720
8721 // Finally, if the LHS and RHS types are canonically the same type, we can
8722 // use the common sugared type.
8723 if (Context.hasSameType(LHSTy, RHSTy))
8724 return Context.getCommonSugaredType(LHSTy, RHSTy);
8725
8726 // Otherwise, the operands are not compatible.
8727 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8728 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8729 << RHS.get()->getSourceRange();
8730 return QualType();
8731}
8732
8733/// SuggestParentheses - Emit a note with a fixit hint that wraps
8734/// ParenRange in parentheses.
8736 const PartialDiagnostic &Note,
8737 SourceRange ParenRange) {
8738 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8739 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8740 EndLoc.isValid()) {
8741 Self.Diag(Loc, Note)
8742 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8743 << FixItHint::CreateInsertion(EndLoc, ")");
8744 } else {
8745 // We can't display the parentheses, so just show the bare note.
8746 Self.Diag(Loc, Note) << ParenRange;
8747 }
8748}
8749
8751 return BinaryOperator::isAdditiveOp(Opc) ||
8753 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8754 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8755 // not any of the logical operators. Bitwise-xor is commonly used as a
8756 // logical-xor because there is no logical-xor operator. The logical
8757 // operators, including uses of xor, have a high false positive rate for
8758 // precedence warnings.
8759}
8760
8761/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8762/// expression, either using a built-in or overloaded operator,
8763/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8764/// expression.
8766 const Expr **RHSExprs) {
8767 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8768 E = E->IgnoreImpCasts();
8770 E = E->IgnoreImpCasts();
8771 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8772 E = MTE->getSubExpr();
8773 E = E->IgnoreImpCasts();
8774 }
8775
8776 // Built-in binary operator.
8777 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8778 OP && IsArithmeticOp(OP->getOpcode())) {
8779 *Opcode = OP->getOpcode();
8780 *RHSExprs = OP->getRHS();
8781 return true;
8782 }
8783
8784 // Overloaded operator.
8785 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8786 if (Call->getNumArgs() != 2)
8787 return false;
8788
8789 // Make sure this is really a binary operator that is safe to pass into
8790 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8791 OverloadedOperatorKind OO = Call->getOperator();
8792 if (OO < OO_Plus || OO > OO_Arrow ||
8793 OO == OO_PlusPlus || OO == OO_MinusMinus)
8794 return false;
8795
8797 if (IsArithmeticOp(OpKind)) {
8798 *Opcode = OpKind;
8799 *RHSExprs = Call->getArg(1);
8800 return true;
8801 }
8802 }
8803
8804 return false;
8805}
8806
8807/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8808/// or is a logical expression such as (x==y) which has int type, but is
8809/// commonly interpreted as boolean.
8810static bool ExprLooksBoolean(const Expr *E) {
8811 E = E->IgnoreParenImpCasts();
8812
8813 if (E->getType()->isBooleanType())
8814 return true;
8815 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8816 return OP->isComparisonOp() || OP->isLogicalOp();
8817 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8818 return OP->getOpcode() == UO_LNot;
8819 if (E->getType()->isPointerType())
8820 return true;
8821 // FIXME: What about overloaded operator calls returning "unspecified boolean
8822 // type"s (commonly pointer-to-members)?
8823
8824 return false;
8825}
8826
8827/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8828/// and binary operator are mixed in a way that suggests the programmer assumed
8829/// the conditional operator has higher precedence, for example:
8830/// "int x = a + someBinaryCondition ? 1 : 2".
8832 Expr *Condition, const Expr *LHSExpr,
8833 const Expr *RHSExpr) {
8834 BinaryOperatorKind CondOpcode;
8835 const Expr *CondRHS;
8836
8837 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8838 return;
8839 if (!ExprLooksBoolean(CondRHS))
8840 return;
8841
8842 // The condition is an arithmetic binary expression, with a right-
8843 // hand side that looks boolean, so warn.
8844
8845 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8846 ? diag::warn_precedence_bitwise_conditional
8847 : diag::warn_precedence_conditional;
8848
8849 Self.Diag(OpLoc, DiagID)
8850 << Condition->getSourceRange()
8851 << BinaryOperator::getOpcodeStr(CondOpcode);
8852
8854 Self, OpLoc,
8855 Self.PDiag(diag::note_precedence_silence)
8856 << BinaryOperator::getOpcodeStr(CondOpcode),
8857 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8858
8859 SuggestParentheses(Self, OpLoc,
8860 Self.PDiag(diag::note_precedence_conditional_first),
8861 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8862}
8863
8864/// Compute the nullability of a conditional expression.
8866 QualType LHSTy, QualType RHSTy,
8867 ASTContext &Ctx) {
8868 if (!ResTy->isAnyPointerType())
8869 return ResTy;
8870
8871 auto GetNullability = [](QualType Ty) {
8872 std::optional<NullabilityKind> Kind = Ty->getNullability();
8873 if (Kind) {
8874 // For our purposes, treat _Nullable_result as _Nullable.
8877 return *Kind;
8878 }
8880 };
8881
8882 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8883 NullabilityKind MergedKind;
8884
8885 // Compute nullability of a binary conditional expression.
8886 if (IsBin) {
8887 if (LHSKind == NullabilityKind::NonNull)
8888 MergedKind = NullabilityKind::NonNull;
8889 else
8890 MergedKind = RHSKind;
8891 // Compute nullability of a normal conditional expression.
8892 } else {
8893 if (LHSKind == NullabilityKind::Nullable ||
8894 RHSKind == NullabilityKind::Nullable)
8895 MergedKind = NullabilityKind::Nullable;
8896 else if (LHSKind == NullabilityKind::NonNull)
8897 MergedKind = RHSKind;
8898 else if (RHSKind == NullabilityKind::NonNull)
8899 MergedKind = LHSKind;
8900 else
8901 MergedKind = NullabilityKind::Unspecified;
8902 }
8903
8904 // Return if ResTy already has the correct nullability.
8905 if (GetNullability(ResTy) == MergedKind)
8906 return ResTy;
8907
8908 // Strip all nullability from ResTy.
8909 while (ResTy->getNullability())
8910 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8911
8912 // Create a new AttributedType with the new nullability kind.
8913 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8914}
8915
8917 SourceLocation ColonLoc,
8918 Expr *CondExpr, Expr *LHSExpr,
8919 Expr *RHSExpr) {
8920 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8921 // was the condition.
8922 OpaqueValueExpr *opaqueValue = nullptr;
8923 Expr *commonExpr = nullptr;
8924 if (!LHSExpr) {
8925 commonExpr = CondExpr;
8926 // Lower out placeholder types first. This is important so that we don't
8927 // try to capture a placeholder. This happens in few cases in C++; such
8928 // as Objective-C++'s dictionary subscripting syntax.
8929 if (commonExpr->hasPlaceholderType()) {
8930 ExprResult result = CheckPlaceholderExpr(commonExpr);
8931 if (!result.isUsable()) return ExprError();
8932 commonExpr = result.get();
8933 }
8934 // We usually want to apply unary conversions *before* saving, except
8935 // in the special case of a C++ l-value conditional.
8936 if (!(getLangOpts().CPlusPlus
8937 && !commonExpr->isTypeDependent()
8938 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8939 && commonExpr->isGLValue()
8940 && commonExpr->isOrdinaryOrBitFieldObject()
8941 && RHSExpr->isOrdinaryOrBitFieldObject()
8942 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8943 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8944 if (commonRes.isInvalid())
8945 return ExprError();
8946 commonExpr = commonRes.get();
8947 }
8948
8949 // If the common expression is a class or array prvalue, materialize it
8950 // so that we can safely refer to it multiple times.
8951 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8952 commonExpr->getType()->isArrayType())) {
8953 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8954 if (MatExpr.isInvalid())
8955 return ExprError();
8956 commonExpr = MatExpr.get();
8957 }
8958
8959 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8960 commonExpr->getType(),
8961 commonExpr->getValueKind(),
8962 commonExpr->getObjectKind(),
8963 commonExpr);
8964 LHSExpr = CondExpr = opaqueValue;
8965 }
8966
8967 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8970 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8971 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8972 VK, OK, QuestionLoc);
8973 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8974 RHS.isInvalid())
8975 return ExprError();
8976
8977 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8978 RHS.get());
8979
8980 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8981
8982 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8983 Context);
8984
8985 if (!commonExpr)
8986 return new (Context)
8987 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8988 RHS.get(), result, VK, OK);
8989
8991 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8992 ColonLoc, result, VK, OK);
8993}
8994
8996 unsigned FromAttributes = 0, ToAttributes = 0;
8997 if (const auto *FromFn =
8998 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8999 FromAttributes =
9000 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9001 if (const auto *ToFn =
9002 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9003 ToAttributes =
9004 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9005
9006 return FromAttributes != ToAttributes;
9007}
9008
9009// Check if we have a conversion between incompatible cmse function pointer
9010// types, that is, a conversion between a function pointer with the
9011// cmse_nonsecure_call attribute and one without.
9013 QualType ToType) {
9014 if (const auto *ToFn =
9015 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9016 if (const auto *FromFn =
9017 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9018 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9019 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9020
9021 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9022 }
9023 }
9024 return false;
9025}
9026
9027// checkPointerTypesForAssignment - This is a very tricky routine (despite
9028// being closely modeled after the C99 spec:-). The odd characteristic of this
9029// routine is it effectively iqnores the qualifiers on the top level pointee.
9030// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9031// FIXME: add a couple examples in this comment.
9033 QualType LHSType,
9034 QualType RHSType,
9036 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9037 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9038
9039 // get the "pointed to" type (ignoring qualifiers at the top level)
9040 const Type *lhptee, *rhptee;
9041 Qualifiers lhq, rhq;
9042 std::tie(lhptee, lhq) =
9043 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9044 std::tie(rhptee, rhq) =
9045 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9046
9048
9049 // C99 6.5.16.1p1: This following citation is common to constraints
9050 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9051 // qualifiers of the type *pointed to* by the right;
9052
9053 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9054 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9056 // Ignore lifetime for further calculation.
9057 lhq.removeObjCLifetime();
9058 rhq.removeObjCLifetime();
9059 }
9060
9061 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9062 // Treat address-space mismatches as fatal.
9063 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9065
9066 // It's okay to add or remove GC or lifetime qualifiers when converting to
9067 // and from void*.
9070 S.getASTContext()) &&
9071 (lhptee->isVoidType() || rhptee->isVoidType()))
9072 ; // keep old
9073
9074 // Treat lifetime mismatches as fatal.
9075 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9077
9078 // Treat pointer-auth mismatches as fatal.
9079 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9081
9082 // For GCC/MS compatibility, other qualifier mismatches are treated
9083 // as still compatible in C.
9084 else
9086 }
9087
9088 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9089 // incomplete type and the other is a pointer to a qualified or unqualified
9090 // version of void...
9091 if (lhptee->isVoidType()) {
9092 if (rhptee->isIncompleteOrObjectType())
9093 return ConvTy;
9094
9095 // As an extension, we allow cast to/from void* to function pointer.
9096 assert(rhptee->isFunctionType());
9098 }
9099
9100 if (rhptee->isVoidType()) {
9101 // In C, void * to another pointer type is compatible, but we want to note
9102 // that there will be an implicit conversion happening here.
9103 if (lhptee->isIncompleteOrObjectType())
9104 return ConvTy == AssignConvertType::Compatible &&
9105 !S.getLangOpts().CPlusPlus
9107 : ConvTy;
9108
9109 // As an extension, we allow cast to/from void* to function pointer.
9110 assert(lhptee->isFunctionType());
9112 }
9113
9114 if (!S.Diags.isIgnored(
9115 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9116 Loc) &&
9117 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9118 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9120
9121 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9122 // unqualified versions of compatible types, ...
9123 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9124 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9125 // Check if the pointee types are compatible ignoring the sign.
9126 // We explicitly check for char so that we catch "char" vs
9127 // "unsigned char" on systems where "char" is unsigned.
9128 if (lhptee->isCharType())
9129 ltrans = S.Context.UnsignedCharTy;
9130 else if (lhptee->hasSignedIntegerRepresentation())
9131 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9132
9133 if (rhptee->isCharType())
9134 rtrans = S.Context.UnsignedCharTy;
9135 else if (rhptee->hasSignedIntegerRepresentation())
9136 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9137
9138 if (ltrans == rtrans) {
9139 // Types are compatible ignoring the sign. Qualifier incompatibility
9140 // takes priority over sign incompatibility because the sign
9141 // warning can be disabled.
9142 if (!S.IsAssignConvertCompatible(ConvTy))
9143 return ConvTy;
9144
9146 }
9147
9148 // If we are a multi-level pointer, it's possible that our issue is simply
9149 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9150 // the eventual target type is the same and the pointers have the same
9151 // level of indirection, this must be the issue.
9152 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9153 do {
9154 std::tie(lhptee, lhq) =
9155 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9156 std::tie(rhptee, rhq) =
9157 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9158
9159 // Inconsistent address spaces at this point is invalid, even if the
9160 // address spaces would be compatible.
9161 // FIXME: This doesn't catch address space mismatches for pointers of
9162 // different nesting levels, like:
9163 // __local int *** a;
9164 // int ** b = a;
9165 // It's not clear how to actually determine when such pointers are
9166 // invalidly incompatible.
9167 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9168 return AssignConvertType::
9170
9171 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9172
9173 if (lhptee == rhptee)
9175 }
9176
9177 // General pointer incompatibility takes priority over qualifiers.
9178 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9181 }
9182 bool DiscardingCFIUncheckedCallee, AddingCFIUncheckedCallee;
9183 if (!S.getLangOpts().CPlusPlus &&
9184 S.IsFunctionConversion(ltrans, rtrans, &DiscardingCFIUncheckedCallee,
9185 &AddingCFIUncheckedCallee)) {
9186 // Allow conversions between CFIUncheckedCallee-ness.
9187 if (!DiscardingCFIUncheckedCallee && !AddingCFIUncheckedCallee)
9189 }
9190 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9192 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9194 return ConvTy;
9195}
9196
9197/// checkBlockPointerTypesForAssignment - This routine determines whether two
9198/// block pointer types are compatible or whether a block and normal pointer
9199/// are compatible. It is more restrict than comparing two function pointer
9200// types.
9202 QualType LHSType,
9203 QualType RHSType) {
9204 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9205 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9206
9207 QualType lhptee, rhptee;
9208
9209 // get the "pointed to" type (ignoring qualifiers at the top level)
9210 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9211 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9212
9213 // In C++, the types have to match exactly.
9214 if (S.getLangOpts().CPlusPlus)
9216
9218
9219 // For blocks we enforce that qualifiers are identical.
9220 Qualifiers LQuals = lhptee.getLocalQualifiers();
9221 Qualifiers RQuals = rhptee.getLocalQualifiers();
9222 if (S.getLangOpts().OpenCL) {
9223 LQuals.removeAddressSpace();
9224 RQuals.removeAddressSpace();
9225 }
9226 if (LQuals != RQuals)
9228
9229 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9230 // assignment.
9231 // The current behavior is similar to C++ lambdas. A block might be
9232 // assigned to a variable iff its return type and parameters are compatible
9233 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9234 // an assignment. Presumably it should behave in way that a function pointer
9235 // assignment does in C, so for each parameter and return type:
9236 // * CVR and address space of LHS should be a superset of CVR and address
9237 // space of RHS.
9238 // * unqualified types should be compatible.
9239 if (S.getLangOpts().OpenCL) {
9241 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9242 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9244 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9246
9247 return ConvTy;
9248}
9249
9250/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9251/// for assignment compatibility.
9253 QualType LHSType,
9254 QualType RHSType) {
9255 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9256 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9257
9258 if (LHSType->isObjCBuiltinType()) {
9259 // Class is not compatible with ObjC object pointers.
9260 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9261 !RHSType->isObjCQualifiedClassType())
9264 }
9265 if (RHSType->isObjCBuiltinType()) {
9266 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9267 !LHSType->isObjCQualifiedClassType())
9270 }
9271 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9272 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9273
9274 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9275 // make an exception for id<P>
9276 !LHSType->isObjCQualifiedIdType())
9278
9279 if (S.Context.typesAreCompatible(LHSType, RHSType))
9281 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9284}
9285
9287 QualType LHSType,
9288 QualType RHSType) {
9289 // Fake up an opaque expression. We don't actually care about what
9290 // cast operations are required, so if CheckAssignmentConstraints
9291 // adds casts to this they'll be wasted, but fortunately that doesn't
9292 // usually happen on valid code.
9293 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9294 ExprResult RHSPtr = &RHSExpr;
9295 CastKind K;
9296
9297 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9298}
9299
9300/// This helper function returns true if QT is a vector type that has element
9301/// type ElementType.
9302static bool isVector(QualType QT, QualType ElementType) {
9303 if (const VectorType *VT = QT->getAs<VectorType>())
9304 return VT->getElementType().getCanonicalType() == ElementType;
9305 return false;
9306}
9307
9308/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9309/// has code to accommodate several GCC extensions when type checking
9310/// pointers. Here are some objectionable examples that GCC considers warnings:
9311///
9312/// int a, *pint;
9313/// short *pshort;
9314/// struct foo *pfoo;
9315///
9316/// pint = pshort; // warning: assignment from incompatible pointer type
9317/// a = pint; // warning: assignment makes integer from pointer without a cast
9318/// pint = a; // warning: assignment makes pointer from integer without a cast
9319/// pint = pfoo; // warning: assignment from incompatible pointer type
9320///
9321/// As a result, the code for dealing with pointers is more complex than the
9322/// C99 spec dictates.
9323///
9324/// Sets 'Kind' for any result kind except Incompatible.
9326 ExprResult &RHS,
9327 CastKind &Kind,
9328 bool ConvertRHS) {
9329 QualType RHSType = RHS.get()->getType();
9330 QualType OrigLHSType = LHSType;
9331
9332 // Get canonical types. We're not formatting these types, just comparing
9333 // them.
9334 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9335 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9336
9337 // Common case: no conversion required.
9338 if (LHSType == RHSType) {
9339 Kind = CK_NoOp;
9341 }
9342
9343 // If the LHS has an __auto_type, there are no additional type constraints
9344 // to be worried about.
9345 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9346 if (AT->isGNUAutoType()) {
9347 Kind = CK_NoOp;
9349 }
9350 }
9351
9352 // If we have an atomic type, try a non-atomic assignment, then just add an
9353 // atomic qualification step.
9354 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9356 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9358 return Result;
9359 if (Kind != CK_NoOp && ConvertRHS)
9360 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9361 Kind = CK_NonAtomicToAtomic;
9362 return Result;
9363 }
9364
9365 // If the left-hand side is a reference type, then we are in a
9366 // (rare!) case where we've allowed the use of references in C,
9367 // e.g., as a parameter type in a built-in function. In this case,
9368 // just make sure that the type referenced is compatible with the
9369 // right-hand side type. The caller is responsible for adjusting
9370 // LHSType so that the resulting expression does not have reference
9371 // type.
9372 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9373 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9374 Kind = CK_LValueBitCast;
9376 }
9378 }
9379
9380 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9381 // to the same ExtVector type.
9382 if (LHSType->isExtVectorType()) {
9383 if (RHSType->isExtVectorType())
9385 if (RHSType->isArithmeticType()) {
9386 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9387 if (ConvertRHS)
9388 RHS = prepareVectorSplat(LHSType, RHS.get());
9389 Kind = CK_VectorSplat;
9391 }
9392 }
9393
9394 // Conversions to or from vector type.
9395 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9396 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9397 // Allow assignments of an AltiVec vector type to an equivalent GCC
9398 // vector type and vice versa
9399 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9400 Kind = CK_BitCast;
9402 }
9403
9404 // If we are allowing lax vector conversions, and LHS and RHS are both
9405 // vectors, the total size only needs to be the same. This is a bitcast;
9406 // no bits are changed but the result type is different.
9407 if (isLaxVectorConversion(RHSType, LHSType)) {
9408 // The default for lax vector conversions with Altivec vectors will
9409 // change, so if we are converting between vector types where
9410 // at least one is an Altivec vector, emit a warning.
9411 if (Context.getTargetInfo().getTriple().isPPC() &&
9412 anyAltivecTypes(RHSType, LHSType) &&
9413 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9414 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9415 << RHSType << LHSType;
9416 Kind = CK_BitCast;
9418 }
9419 }
9420
9421 // When the RHS comes from another lax conversion (e.g. binops between
9422 // scalars and vectors) the result is canonicalized as a vector. When the
9423 // LHS is also a vector, the lax is allowed by the condition above. Handle
9424 // the case where LHS is a scalar.
9425 if (LHSType->isScalarType()) {
9426 const VectorType *VecType = RHSType->getAs<VectorType>();
9427 if (VecType && VecType->getNumElements() == 1 &&
9428 isLaxVectorConversion(RHSType, LHSType)) {
9429 if (Context.getTargetInfo().getTriple().isPPC() &&
9431 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9433 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9434 << RHSType << LHSType;
9435 ExprResult *VecExpr = &RHS;
9436 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9437 Kind = CK_BitCast;
9439 }
9440 }
9441
9442 // Allow assignments between fixed-length and sizeless SVE vectors.
9443 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9444 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9445 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9446 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9447 Kind = CK_BitCast;
9449 }
9450
9451 // Allow assignments between fixed-length and sizeless RVV vectors.
9452 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9453 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9454 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9455 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9456 Kind = CK_BitCast;
9458 }
9459 }
9460
9462 }
9463
9464 // Diagnose attempts to convert between __ibm128, __float128 and long double
9465 // where such conversions currently can't be handled.
9466 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9468
9469 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9470 // discards the imaginary part.
9471 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9472 !LHSType->getAs<ComplexType>())
9474
9475 // Arithmetic conversions.
9476 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9477 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9478 if (ConvertRHS)
9479 Kind = PrepareScalarCast(RHS, LHSType);
9481 }
9482
9483 // Conversions to normal pointers.
9484 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9485 // U* -> T*
9486 if (isa<PointerType>(RHSType)) {
9487 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9488 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9489 if (AddrSpaceL != AddrSpaceR)
9490 Kind = CK_AddressSpaceConversion;
9491 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9492 Kind = CK_NoOp;
9493 else
9494 Kind = CK_BitCast;
9495 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9496 RHS.get()->getBeginLoc());
9497 }
9498
9499 // int -> T*
9500 if (RHSType->isIntegerType()) {
9501 Kind = CK_IntegralToPointer; // FIXME: null?
9503 }
9504
9505 // C pointers are not compatible with ObjC object pointers,
9506 // with two exceptions:
9507 if (isa<ObjCObjectPointerType>(RHSType)) {
9508 // - conversions to void*
9509 if (LHSPointer->getPointeeType()->isVoidType()) {
9510 Kind = CK_BitCast;
9512 }
9513
9514 // - conversions from 'Class' to the redefinition type
9515 if (RHSType->isObjCClassType() &&
9516 Context.hasSameType(LHSType,
9518 Kind = CK_BitCast;
9520 }
9521
9522 Kind = CK_BitCast;
9524 }
9525
9526 // U^ -> void*
9527 if (RHSType->getAs<BlockPointerType>()) {
9528 if (LHSPointer->getPointeeType()->isVoidType()) {
9529 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9530 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9531 ->getPointeeType()
9532 .getAddressSpace();
9533 Kind =
9534 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9536 }
9537 }
9538
9540 }
9541
9542 // Conversions to block pointers.
9543 if (isa<BlockPointerType>(LHSType)) {
9544 // U^ -> T^
9545 if (RHSType->isBlockPointerType()) {
9546 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9547 ->getPointeeType()
9548 .getAddressSpace();
9549 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9550 ->getPointeeType()
9551 .getAddressSpace();
9552 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9553 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9554 }
9555
9556 // int or null -> T^
9557 if (RHSType->isIntegerType()) {
9558 Kind = CK_IntegralToPointer; // FIXME: null
9560 }
9561
9562 // id -> T^
9563 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9564 Kind = CK_AnyPointerToBlockPointerCast;
9566 }
9567
9568 // void* -> T^
9569 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9570 if (RHSPT->getPointeeType()->isVoidType()) {
9571 Kind = CK_AnyPointerToBlockPointerCast;
9573 }
9574
9576 }
9577
9578 // Conversions to Objective-C pointers.
9579 if (isa<ObjCObjectPointerType>(LHSType)) {
9580 // A* -> B*
9581 if (RHSType->isObjCObjectPointerType()) {
9582 Kind = CK_BitCast;
9583 AssignConvertType result =
9584 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9585 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9587 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9589 return result;
9590 }
9591
9592 // int or null -> A*
9593 if (RHSType->isIntegerType()) {
9594 Kind = CK_IntegralToPointer; // FIXME: null
9596 }
9597
9598 // In general, C pointers are not compatible with ObjC object pointers,
9599 // with two exceptions:
9600 if (isa<PointerType>(RHSType)) {
9601 Kind = CK_CPointerToObjCPointerCast;
9602
9603 // - conversions from 'void*'
9604 if (RHSType->isVoidPointerType()) {
9606 }
9607
9608 // - conversions to 'Class' from its redefinition type
9609 if (LHSType->isObjCClassType() &&
9610 Context.hasSameType(RHSType,
9613 }
9614
9616 }
9617
9618 // Only under strict condition T^ is compatible with an Objective-C pointer.
9619 if (RHSType->isBlockPointerType() &&
9621 if (ConvertRHS)
9623 Kind = CK_BlockPointerToObjCPointerCast;
9625 }
9626
9628 }
9629
9630 // Conversion to nullptr_t (C23 only)
9631 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9634 // null -> nullptr_t
9635 Kind = CK_NullToPointer;
9637 }
9638
9639 // Conversions from pointers that are not covered by the above.
9640 if (isa<PointerType>(RHSType)) {
9641 // T* -> _Bool
9642 if (LHSType == Context.BoolTy) {
9643 Kind = CK_PointerToBoolean;
9645 }
9646
9647 // T* -> int
9648 if (LHSType->isIntegerType()) {
9649 Kind = CK_PointerToIntegral;
9651 }
9652
9654 }
9655
9656 // Conversions from Objective-C pointers that are not covered by the above.
9657 if (isa<ObjCObjectPointerType>(RHSType)) {
9658 // T* -> _Bool
9659 if (LHSType == Context.BoolTy) {
9660 Kind = CK_PointerToBoolean;
9662 }
9663
9664 // T* -> int
9665 if (LHSType->isIntegerType()) {
9666 Kind = CK_PointerToIntegral;
9668 }
9669
9671 }
9672
9673 // struct A -> struct B
9674 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9675 if (Context.typesAreCompatible(LHSType, RHSType)) {
9676 Kind = CK_NoOp;
9678 }
9679 }
9680
9681 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9682 Kind = CK_IntToOCLSampler;
9684 }
9685
9687}
9688
9689/// Constructs a transparent union from an expression that is
9690/// used to initialize the transparent union.
9692 ExprResult &EResult, QualType UnionType,
9693 FieldDecl *Field) {
9694 // Build an initializer list that designates the appropriate member
9695 // of the transparent union.
9696 Expr *E = EResult.get();
9698 E, SourceLocation());
9699 Initializer->setType(UnionType);
9700 Initializer->setInitializedFieldInUnion(Field);
9701
9702 // Build a compound literal constructing a value of the transparent
9703 // union type from this initializer list.
9704 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9705 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9706 VK_PRValue, Initializer, false);
9707}
9708
9711 ExprResult &RHS) {
9712 QualType RHSType = RHS.get()->getType();
9713
9714 // If the ArgType is a Union type, we want to handle a potential
9715 // transparent_union GCC extension.
9716 const RecordType *UT = ArgType->getAsUnionType();
9717 if (!UT)
9719
9721 if (!UD->hasAttr<TransparentUnionAttr>())
9723
9724 // The field to initialize within the transparent union.
9725 FieldDecl *InitField = nullptr;
9726 // It's compatible if the expression matches any of the fields.
9727 for (auto *it : UD->fields()) {
9728 if (it->getType()->isPointerType()) {
9729 // If the transparent union contains a pointer type, we allow:
9730 // 1) void pointer
9731 // 2) null pointer constant
9732 if (RHSType->isPointerType())
9733 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9734 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9735 InitField = it;
9736 break;
9737 }
9738
9741 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9742 CK_NullToPointer);
9743 InitField = it;
9744 break;
9745 }
9746 }
9747
9748 CastKind Kind;
9749 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
9751 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9752 InitField = it;
9753 break;
9754 }
9755 }
9756
9757 if (!InitField)
9759
9760 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9762}
9763
9765 ExprResult &CallerRHS,
9766 bool Diagnose,
9767 bool DiagnoseCFAudited,
9768 bool ConvertRHS) {
9769 // We need to be able to tell the caller whether we diagnosed a problem, if
9770 // they ask us to issue diagnostics.
9771 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9772
9773 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9774 // we can't avoid *all* modifications at the moment, so we need some somewhere
9775 // to put the updated value.
9776 ExprResult LocalRHS = CallerRHS;
9777 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9778
9779 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9780 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9781 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9782 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9783 Diag(RHS.get()->getExprLoc(),
9784 diag::warn_noderef_to_dereferenceable_pointer)
9785 << RHS.get()->getSourceRange();
9786 }
9787 }
9788 }
9789
9790 if (getLangOpts().CPlusPlus) {
9791 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9792 // C++ 5.17p3: If the left operand is not of class type, the
9793 // expression is implicitly converted (C++ 4) to the
9794 // cv-unqualified type of the left operand.
9795 QualType RHSType = RHS.get()->getType();
9796 if (Diagnose) {
9797 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9799 } else {
9802 /*SuppressUserConversions=*/false,
9803 AllowedExplicit::None,
9804 /*InOverloadResolution=*/false,
9805 /*CStyle=*/false,
9806 /*AllowObjCWritebackConversion=*/false);
9807 if (ICS.isFailure())
9809 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9811 }
9812 if (RHS.isInvalid())
9815 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9816 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9818 return result;
9819 }
9820
9821 // FIXME: Currently, we fall through and treat C++ classes like C
9822 // structures.
9823 // FIXME: We also fall through for atomics; not sure what should
9824 // happen there, though.
9825 } else if (RHS.get()->getType() == Context.OverloadTy) {
9826 // As a set of extensions to C, we support overloading on functions. These
9827 // functions need to be resolved here.
9828 DeclAccessPair DAP;
9830 RHS.get(), LHSType, /*Complain=*/false, DAP))
9831 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9832 else
9834 }
9835
9836 // This check seems unnatural, however it is necessary to ensure the proper
9837 // conversion of functions/arrays. If the conversion were done for all
9838 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9839 // expressions that suppress this implicit conversion (&, sizeof). This needs
9840 // to happen before we check for null pointer conversions because C does not
9841 // undergo the same implicit conversions as C++ does above (by the calls to
9842 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9843 // lvalue to rvalue cast before checking for null pointer constraints. This
9844 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9845 //
9846 // Suppress this for references: C++ 8.5.3p5.
9847 if (!LHSType->isReferenceType()) {
9848 // FIXME: We potentially allocate here even if ConvertRHS is false.
9850 if (RHS.isInvalid())
9852 }
9853
9854 // The constraints are expressed in terms of the atomic, qualified, or
9855 // unqualified type of the LHS.
9856 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9857
9858 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9859 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9860 if ((LHSTypeAfterConversion->isPointerType() ||
9861 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9862 LHSTypeAfterConversion->isBlockPointerType()) &&
9863 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9867 if (Diagnose || ConvertRHS) {
9868 CastKind Kind;
9870 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9871 /*IgnoreBaseAccess=*/false, Diagnose);
9872
9873 // If there is a conversion of some kind, check to see what kind of
9874 // pointer conversion happened so we can diagnose a C++ compatibility
9875 // diagnostic if the conversion is invalid. This only matters if the RHS
9876 // is some kind of void pointer. We have a carve-out when the RHS is from
9877 // a macro expansion because the use of a macro may indicate different
9878 // code between C and C++. Consider: char *s = NULL; where NULL is
9879 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
9880 // C++, which is valid in C++.
9881 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
9882 !RHS.get()->getBeginLoc().isMacroID()) {
9883 QualType CanRHS =
9885 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
9886 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
9887 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
9888 RHS.get()->getExprLoc());
9889 // Anything that's not considered perfectly compatible would be
9890 // incompatible in C++.
9893 }
9894 }
9895
9896 if (ConvertRHS)
9897 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9898 }
9899 return Ret;
9900 }
9901 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9902 // unqualified bool, and the right operand is a pointer or its type is
9903 // nullptr_t.
9904 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9905 RHS.get()->getType()->isNullPtrType()) {
9906 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9907 // only handles nullptr -> _Bool due to needing an extra conversion
9908 // step.
9909 // We model this by converting from nullptr -> void * and then let the
9910 // conversion from void * -> _Bool happen naturally.
9911 if (Diagnose || ConvertRHS) {
9912 CastKind Kind;
9915 /*IgnoreBaseAccess=*/false, Diagnose);
9916 if (ConvertRHS)
9917 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9918 &Path);
9919 }
9920 }
9921
9922 // OpenCL queue_t type assignment.
9923 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9925 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9927 }
9928
9929 CastKind Kind;
9930 AssignConvertType result =
9931 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9932
9933 // If assigning a void * created by an allocation function call to some other
9934 // type, check that the allocated size is sufficient for that type.
9935 if (result != AssignConvertType::Incompatible &&
9936 RHS.get()->getType()->isVoidPointerType())
9937 CheckSufficientAllocSize(*this, LHSType, RHS.get());
9938
9939 // C99 6.5.16.1p2: The value of the right operand is converted to the
9940 // type of the assignment expression.
9941 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9942 // so that we can use references in built-in functions even in C.
9943 // The getNonReferenceType() call makes sure that the resulting expression
9944 // does not have reference type.
9945 if (result != AssignConvertType::Incompatible &&
9946 RHS.get()->getType() != LHSType) {
9948 Expr *E = RHS.get();
9949
9950 // Check for various Objective-C errors. If we are not reporting
9951 // diagnostics and just checking for errors, e.g., during overload
9952 // resolution, return Incompatible to indicate the failure.
9953 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9954 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9956 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9957 if (!Diagnose)
9959 }
9960 if (getLangOpts().ObjC &&
9961 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9962 E->getType(), E, Diagnose) ||
9963 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9964 if (!Diagnose)
9966 // Replace the expression with a corrected version and continue so we
9967 // can find further errors.
9968 RHS = E;
9970 }
9971
9972 if (ConvertRHS)
9973 RHS = ImpCastExprToType(E, Ty, Kind);
9974 }
9975
9976 return result;
9977}
9978
9979namespace {
9980/// The original operand to an operator, prior to the application of the usual
9981/// arithmetic conversions and converting the arguments of a builtin operator
9982/// candidate.
9983struct OriginalOperand {
9984 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9985 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9986 Op = MTE->getSubExpr();
9987 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9988 Op = BTE->getSubExpr();
9989 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9990 Orig = ICE->getSubExprAsWritten();
9991 Conversion = ICE->getConversionFunction();
9992 }
9993 }
9994
9995 QualType getType() const { return Orig->getType(); }
9996
9997 Expr *Orig;
9998 NamedDecl *Conversion;
9999};
10000}
10001
10003 ExprResult &RHS) {
10004 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10005
10006 Diag(Loc, diag::err_typecheck_invalid_operands)
10007 << OrigLHS.getType() << OrigRHS.getType()
10008 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10009
10010 // If a user-defined conversion was applied to either of the operands prior
10011 // to applying the built-in operator rules, tell the user about it.
10012 if (OrigLHS.Conversion) {
10013 Diag(OrigLHS.Conversion->getLocation(),
10014 diag::note_typecheck_invalid_operands_converted)
10015 << 0 << LHS.get()->getType();
10016 }
10017 if (OrigRHS.Conversion) {
10018 Diag(OrigRHS.Conversion->getLocation(),
10019 diag::note_typecheck_invalid_operands_converted)
10020 << 1 << RHS.get()->getType();
10021 }
10022
10023 return QualType();
10024}
10025
10027 ExprResult &RHS) {
10028 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10029 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10030
10031 bool LHSNatVec = LHSType->isVectorType();
10032 bool RHSNatVec = RHSType->isVectorType();
10033
10034 if (!(LHSNatVec && RHSNatVec)) {
10035 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10036 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10037 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10038 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10039 << Vector->getSourceRange();
10040 return QualType();
10041 }
10042
10043 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10044 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10045 << RHS.get()->getSourceRange();
10046
10047 return QualType();
10048}
10049
10050/// Try to convert a value of non-vector type to a vector type by converting
10051/// the type to the element type of the vector and then performing a splat.
10052/// If the language is OpenCL, we only use conversions that promote scalar
10053/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10054/// for float->int.
10055///
10056/// OpenCL V2.0 6.2.6.p2:
10057/// An error shall occur if any scalar operand type has greater rank
10058/// than the type of the vector element.
10059///
10060/// \param scalar - if non-null, actually perform the conversions
10061/// \return true if the operation fails (but without diagnosing the failure)
10063 QualType scalarTy,
10064 QualType vectorEltTy,
10065 QualType vectorTy,
10066 unsigned &DiagID) {
10067 // The conversion to apply to the scalar before splatting it,
10068 // if necessary.
10069 CastKind scalarCast = CK_NoOp;
10070
10071 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10072 scalarCast = CK_IntegralToBoolean;
10073 } else if (vectorEltTy->isIntegralType(S.Context)) {
10074 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10075 (scalarTy->isIntegerType() &&
10076 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10077 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10078 return true;
10079 }
10080 if (!scalarTy->isIntegralType(S.Context))
10081 return true;
10082 scalarCast = CK_IntegralCast;
10083 } else if (vectorEltTy->isRealFloatingType()) {
10084 if (scalarTy->isRealFloatingType()) {
10085 if (S.getLangOpts().OpenCL &&
10086 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10087 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10088 return true;
10089 }
10090 scalarCast = CK_FloatingCast;
10091 }
10092 else if (scalarTy->isIntegralType(S.Context))
10093 scalarCast = CK_IntegralToFloating;
10094 else
10095 return true;
10096 } else {
10097 return true;
10098 }
10099
10100 // Adjust scalar if desired.
10101 if (scalar) {
10102 if (scalarCast != CK_NoOp)
10103 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10104 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10105 }
10106 return false;
10107}
10108
10109/// Convert vector E to a vector with the same number of elements but different
10110/// element type.
10111static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10112 const auto *VecTy = E->getType()->getAs<VectorType>();
10113 assert(VecTy && "Expression E must be a vector");
10114 QualType NewVecTy =
10115 VecTy->isExtVectorType()
10116 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10117 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10118 VecTy->getVectorKind());
10119
10120 // Look through the implicit cast. Return the subexpression if its type is
10121 // NewVecTy.
10122 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10123 if (ICE->getSubExpr()->getType() == NewVecTy)
10124 return ICE->getSubExpr();
10125
10126 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10127 return S.ImpCastExprToType(E, NewVecTy, Cast);
10128}
10129
10130/// Test if a (constant) integer Int can be casted to another integer type
10131/// IntTy without losing precision.
10133 QualType OtherIntTy) {
10134 if (Int->get()->containsErrors())
10135 return false;
10136
10137 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10138
10139 // Reject cases where the value of the Int is unknown as that would
10140 // possibly cause truncation, but accept cases where the scalar can be
10141 // demoted without loss of precision.
10142 Expr::EvalResult EVResult;
10143 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10144 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10145 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10146 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10147
10148 if (CstInt) {
10149 // If the scalar is constant and is of a higher order and has more active
10150 // bits that the vector element type, reject it.
10151 llvm::APSInt Result = EVResult.Val.getInt();
10152 unsigned NumBits = IntSigned
10153 ? (Result.isNegative() ? Result.getSignificantBits()
10154 : Result.getActiveBits())
10155 : Result.getActiveBits();
10156 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10157 return true;
10158
10159 // If the signedness of the scalar type and the vector element type
10160 // differs and the number of bits is greater than that of the vector
10161 // element reject it.
10162 return (IntSigned != OtherIntSigned &&
10163 NumBits > S.Context.getIntWidth(OtherIntTy));
10164 }
10165
10166 // Reject cases where the value of the scalar is not constant and it's
10167 // order is greater than that of the vector element type.
10168 return (Order < 0);
10169}
10170
10171/// Test if a (constant) integer Int can be casted to floating point type
10172/// FloatTy without losing precision.
10174 QualType FloatTy) {
10175 if (Int->get()->containsErrors())
10176 return false;
10177
10178 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10179
10180 // Determine if the integer constant can be expressed as a floating point
10181 // number of the appropriate type.
10182 Expr::EvalResult EVResult;
10183 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10184
10185 uint64_t Bits = 0;
10186 if (CstInt) {
10187 // Reject constants that would be truncated if they were converted to
10188 // the floating point type. Test by simple to/from conversion.
10189 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10190 // could be avoided if there was a convertFromAPInt method
10191 // which could signal back if implicit truncation occurred.
10192 llvm::APSInt Result = EVResult.Val.getInt();
10193 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10194 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10195 llvm::APFloat::rmTowardZero);
10196 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10198 bool Ignored = false;
10199 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10200 &Ignored);
10201 if (Result != ConvertBack)
10202 return true;
10203 } else {
10204 // Reject types that cannot be fully encoded into the mantissa of
10205 // the float.
10206 Bits = S.Context.getTypeSize(IntTy);
10207 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10208 S.Context.getFloatTypeSemantics(FloatTy));
10209 if (Bits > FloatPrec)
10210 return true;
10211 }
10212
10213 return false;
10214}
10215
10216/// Attempt to convert and splat Scalar into a vector whose types matches
10217/// Vector following GCC conversion rules. The rule is that implicit
10218/// conversion can occur when Scalar can be casted to match Vector's element
10219/// type without causing truncation of Scalar.
10221 ExprResult *Vector) {
10222 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10223 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10224 QualType VectorEltTy;
10225
10226 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10227 assert(!isa<ExtVectorType>(VT) &&
10228 "ExtVectorTypes should not be handled here!");
10229 VectorEltTy = VT->getElementType();
10230 } else if (VectorTy->isSveVLSBuiltinType()) {
10231 VectorEltTy =
10232 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10233 } else {
10234 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10235 }
10236
10237 // Reject cases where the vector element type or the scalar element type are
10238 // not integral or floating point types.
10239 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10240 return true;
10241
10242 // The conversion to apply to the scalar before splatting it,
10243 // if necessary.
10244 CastKind ScalarCast = CK_NoOp;
10245
10246 // Accept cases where the vector elements are integers and the scalar is
10247 // an integer.
10248 // FIXME: Notionally if the scalar was a floating point value with a precise
10249 // integral representation, we could cast it to an appropriate integer
10250 // type and then perform the rest of the checks here. GCC will perform
10251 // this conversion in some cases as determined by the input language.
10252 // We should accept it on a language independent basis.
10253 if (VectorEltTy->isIntegralType(S.Context) &&
10254 ScalarTy->isIntegralType(S.Context) &&
10255 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10256
10257 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10258 return true;
10259
10260 ScalarCast = CK_IntegralCast;
10261 } else if (VectorEltTy->isIntegralType(S.Context) &&
10262 ScalarTy->isRealFloatingType()) {
10263 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10264 ScalarCast = CK_FloatingToIntegral;
10265 else
10266 return true;
10267 } else if (VectorEltTy->isRealFloatingType()) {
10268 if (ScalarTy->isRealFloatingType()) {
10269
10270 // Reject cases where the scalar type is not a constant and has a higher
10271 // Order than the vector element type.
10272 llvm::APFloat Result(0.0);
10273
10274 // Determine whether this is a constant scalar. In the event that the
10275 // value is dependent (and thus cannot be evaluated by the constant
10276 // evaluator), skip the evaluation. This will then diagnose once the
10277 // expression is instantiated.
10278 bool CstScalar = Scalar->get()->isValueDependent() ||
10279 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10280 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10281 if (!CstScalar && Order < 0)
10282 return true;
10283
10284 // If the scalar cannot be safely casted to the vector element type,
10285 // reject it.
10286 if (CstScalar) {
10287 bool Truncated = false;
10288 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10289 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10290 if (Truncated)
10291 return true;
10292 }
10293
10294 ScalarCast = CK_FloatingCast;
10295 } else if (ScalarTy->isIntegralType(S.Context)) {
10296 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10297 return true;
10298
10299 ScalarCast = CK_IntegralToFloating;
10300 } else
10301 return true;
10302 } else if (ScalarTy->isEnumeralType())
10303 return true;
10304
10305 // Adjust scalar if desired.
10306 if (ScalarCast != CK_NoOp)
10307 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10308 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10309 return false;
10310}
10311
10313 SourceLocation Loc, bool IsCompAssign,
10314 bool AllowBothBool,
10315 bool AllowBoolConversions,
10316 bool AllowBoolOperation,
10317 bool ReportInvalid) {
10318 if (!IsCompAssign) {
10320 if (LHS.isInvalid())
10321 return QualType();
10322 }
10324 if (RHS.isInvalid())
10325 return QualType();
10326
10327 // For conversion purposes, we ignore any qualifiers.
10328 // For example, "const float" and "float" are equivalent.
10329 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10330 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10331
10332 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10333 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10334 assert(LHSVecType || RHSVecType);
10335
10336 if (getLangOpts().HLSL)
10337 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10338 IsCompAssign);
10339
10340 // Any operation with MFloat8 type is only possible with C intrinsics
10341 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10342 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10343 return InvalidOperands(Loc, LHS, RHS);
10344
10345 // AltiVec-style "vector bool op vector bool" combinations are allowed
10346 // for some operators but not others.
10347 if (!AllowBothBool && LHSVecType &&
10348 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10349 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10350 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10351
10352 // This operation may not be performed on boolean vectors.
10353 if (!AllowBoolOperation &&
10354 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10355 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10356
10357 // If the vector types are identical, return.
10358 if (Context.hasSameType(LHSType, RHSType))
10359 return Context.getCommonSugaredType(LHSType, RHSType);
10360
10361 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10362 if (LHSVecType && RHSVecType &&
10363 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10364 if (isa<ExtVectorType>(LHSVecType)) {
10365 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10366 return LHSType;
10367 }
10368
10369 if (!IsCompAssign)
10370 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10371 return RHSType;
10372 }
10373
10374 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10375 // can be mixed, with the result being the non-bool type. The non-bool
10376 // operand must have integer element type.
10377 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10378 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10379 (Context.getTypeSize(LHSVecType->getElementType()) ==
10380 Context.getTypeSize(RHSVecType->getElementType()))) {
10381 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10382 LHSVecType->getElementType()->isIntegerType() &&
10383 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10384 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10385 return LHSType;
10386 }
10387 if (!IsCompAssign &&
10388 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10389 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10390 RHSVecType->getElementType()->isIntegerType()) {
10391 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10392 return RHSType;
10393 }
10394 }
10395
10396 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10397 // invalid since the ambiguity can affect the ABI.
10398 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10399 unsigned &SVEorRVV) {
10400 const VectorType *VecType = SecondType->getAs<VectorType>();
10401 SVEorRVV = 0;
10402 if (FirstType->isSizelessBuiltinType() && VecType) {
10405 return true;
10411 SVEorRVV = 1;
10412 return true;
10413 }
10414 }
10415
10416 return false;
10417 };
10418
10419 unsigned SVEorRVV;
10420 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10421 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10422 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10423 << SVEorRVV << LHSType << RHSType;
10424 return QualType();
10425 }
10426
10427 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10428 // invalid since the ambiguity can affect the ABI.
10429 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10430 unsigned &SVEorRVV) {
10431 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10432 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10433
10434 SVEorRVV = 0;
10435 if (FirstVecType && SecondVecType) {
10436 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10437 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10438 SecondVecType->getVectorKind() ==
10440 return true;
10441 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10442 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10443 SecondVecType->getVectorKind() ==
10445 SecondVecType->getVectorKind() ==
10447 SecondVecType->getVectorKind() ==
10449 SVEorRVV = 1;
10450 return true;
10451 }
10452 }
10453 return false;
10454 }
10455
10456 if (SecondVecType &&
10457 SecondVecType->getVectorKind() == VectorKind::Generic) {
10458 if (FirstType->isSVESizelessBuiltinType())
10459 return true;
10460 if (FirstType->isRVVSizelessBuiltinType()) {
10461 SVEorRVV = 1;
10462 return true;
10463 }
10464 }
10465
10466 return false;
10467 };
10468
10469 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10470 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10471 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10472 << SVEorRVV << LHSType << RHSType;
10473 return QualType();
10474 }
10475
10476 // If there's a vector type and a scalar, try to convert the scalar to
10477 // the vector element type and splat.
10478 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10479 if (!RHSVecType) {
10480 if (isa<ExtVectorType>(LHSVecType)) {
10481 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10482 LHSVecType->getElementType(), LHSType,
10483 DiagID))
10484 return LHSType;
10485 } else {
10486 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10487 return LHSType;
10488 }
10489 }
10490 if (!LHSVecType) {
10491 if (isa<ExtVectorType>(RHSVecType)) {
10492 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10493 LHSType, RHSVecType->getElementType(),
10494 RHSType, DiagID))
10495 return RHSType;
10496 } else {
10497 if (LHS.get()->isLValue() ||
10498 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10499 return RHSType;
10500 }
10501 }
10502
10503 // FIXME: The code below also handles conversion between vectors and
10504 // non-scalars, we should break this down into fine grained specific checks
10505 // and emit proper diagnostics.
10506 QualType VecType = LHSVecType ? LHSType : RHSType;
10507 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10508 QualType OtherType = LHSVecType ? RHSType : LHSType;
10509 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10510 if (isLaxVectorConversion(OtherType, VecType)) {
10511 if (Context.getTargetInfo().getTriple().isPPC() &&
10512 anyAltivecTypes(RHSType, LHSType) &&
10513 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10514 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10515 // If we're allowing lax vector conversions, only the total (data) size
10516 // needs to be the same. For non compound assignment, if one of the types is
10517 // scalar, the result is always the vector type.
10518 if (!IsCompAssign) {
10519 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10520 return VecType;
10521 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10522 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10523 // type. Note that this is already done by non-compound assignments in
10524 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10525 // <1 x T> -> T. The result is also a vector type.
10526 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10527 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10528 ExprResult *RHSExpr = &RHS;
10529 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10530 return VecType;
10531 }
10532 }
10533
10534 // Okay, the expression is invalid.
10535
10536 // If there's a non-vector, non-real operand, diagnose that.
10537 if ((!RHSVecType && !RHSType->isRealType()) ||
10538 (!LHSVecType && !LHSType->isRealType())) {
10539 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10540 << LHSType << RHSType
10541 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10542 return QualType();
10543 }
10544
10545 // OpenCL V1.1 6.2.6.p1:
10546 // If the operands are of more than one vector type, then an error shall
10547 // occur. Implicit conversions between vector types are not permitted, per
10548 // section 6.2.1.
10549 if (getLangOpts().OpenCL &&
10550 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10551 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10552 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10553 << RHSType;
10554 return QualType();
10555 }
10556
10557
10558 // If there is a vector type that is not a ExtVector and a scalar, we reach
10559 // this point if scalar could not be converted to the vector's element type
10560 // without truncation.
10561 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10562 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10563 QualType Scalar = LHSVecType ? RHSType : LHSType;
10564 QualType Vector = LHSVecType ? LHSType : RHSType;
10565 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10566 Diag(Loc,
10567 diag::err_typecheck_vector_not_convertable_implict_truncation)
10568 << ScalarOrVector << Scalar << Vector;
10569
10570 return QualType();
10571 }
10572
10573 // Otherwise, use the generic diagnostic.
10574 Diag(Loc, DiagID)
10575 << LHSType << RHSType
10576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10577 return QualType();
10578}
10579
10582 bool IsCompAssign,
10583 ArithConvKind OperationKind) {
10584 if (!IsCompAssign) {
10586 if (LHS.isInvalid())
10587 return QualType();
10588 }
10590 if (RHS.isInvalid())
10591 return QualType();
10592
10593 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10594 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10595
10596 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10597 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10598
10599 unsigned DiagID = diag::err_typecheck_invalid_operands;
10600 if ((OperationKind == ArithConvKind::Arithmetic) &&
10601 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10602 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10603 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10604 << RHS.get()->getSourceRange();
10605 return QualType();
10606 }
10607
10608 if (Context.hasSameType(LHSType, RHSType))
10609 return LHSType;
10610
10611 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10612 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10613 return LHSType;
10614 }
10615 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10616 if (LHS.get()->isLValue() ||
10617 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10618 return RHSType;
10619 }
10620
10621 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10622 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10623 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10624 << LHSType << RHSType << LHS.get()->getSourceRange()
10625 << RHS.get()->getSourceRange();
10626 return QualType();
10627 }
10628
10629 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10630 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10631 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10632 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10633 << LHSType << RHSType << LHS.get()->getSourceRange()
10634 << RHS.get()->getSourceRange();
10635 return QualType();
10636 }
10637
10638 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10639 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10640 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10641 bool ScalarOrVector =
10642 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10643
10644 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10645 << ScalarOrVector << Scalar << Vector;
10646
10647 return QualType();
10648 }
10649
10650 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10651 << RHS.get()->getSourceRange();
10652 return QualType();
10653}
10654
10655// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10656// expression. These are mainly cases where the null pointer is used as an
10657// integer instead of a pointer.
10659 SourceLocation Loc, bool IsCompare) {
10660 // The canonical way to check for a GNU null is with isNullPointerConstant,
10661 // but we use a bit of a hack here for speed; this is a relatively
10662 // hot path, and isNullPointerConstant is slow.
10663 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10664 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10665
10666 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10667
10668 // Avoid analyzing cases where the result will either be invalid (and
10669 // diagnosed as such) or entirely valid and not something to warn about.
10670 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10671 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10672 return;
10673
10674 // Comparison operations would not make sense with a null pointer no matter
10675 // what the other expression is.
10676 if (!IsCompare) {
10677 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10678 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10679 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10680 return;
10681 }
10682
10683 // The rest of the operations only make sense with a null pointer
10684 // if the other expression is a pointer.
10685 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10686 NonNullType->canDecayToPointerType())
10687 return;
10688
10689 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10690 << LHSNull /* LHS is NULL */ << NonNullType
10691 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10692}
10693
10695 SourceLocation OpLoc) {
10696 // If the divisor is real, then this is real/real or complex/real division.
10697 // Either way there can be no precision loss.
10698 auto *CT = DivisorTy->getAs<ComplexType>();
10699 if (!CT)
10700 return;
10701
10702 QualType ElementType = CT->getElementType();
10703 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10705 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10706 return;
10707
10708 ASTContext &Ctx = S.getASTContext();
10709 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10710 const llvm::fltSemantics &ElementTypeSemantics =
10711 Ctx.getFloatTypeSemantics(ElementType);
10712 const llvm::fltSemantics &HigherElementTypeSemantics =
10713 Ctx.getFloatTypeSemantics(HigherElementType);
10714
10715 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10716 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10717 (HigherElementType == Ctx.LongDoubleTy &&
10718 !Ctx.getTargetInfo().hasLongDoubleType())) {
10719 // Retain the location of the first use of higher precision type.
10722 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10723 if (Type == HigherElementType) {
10724 Num++;
10725 return;
10726 }
10727 }
10728 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
10729 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
10730 }
10731}
10732
10735 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10736 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10737 if (!LUE || !RUE)
10738 return;
10739 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10740 RUE->getKind() != UETT_SizeOf)
10741 return;
10742
10743 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10744 QualType LHSTy = LHSArg->getType();
10745 QualType RHSTy;
10746
10747 if (RUE->isArgumentType())
10748 RHSTy = RUE->getArgumentType().getNonReferenceType();
10749 else
10750 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10751
10752 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10753 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10754 return;
10755
10756 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10757 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10758 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10759 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10760 << LHSArgDecl;
10761 }
10762 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10763 QualType ArrayElemTy = ArrayTy->getElementType();
10764 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10765 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10766 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10767 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10768 return;
10769 S.Diag(Loc, diag::warn_division_sizeof_array)
10770 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10771 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10772 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10773 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10774 << LHSArgDecl;
10775 }
10776
10777 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10778 }
10779}
10780
10782 ExprResult &RHS,
10783 SourceLocation Loc, bool IsDiv) {
10784 // Check for division/remainder by zero.
10785 Expr::EvalResult RHSValue;
10786 if (!RHS.get()->isValueDependent() &&
10787 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10788 RHSValue.Val.getInt() == 0)
10789 S.DiagRuntimeBehavior(Loc, RHS.get(),
10790 S.PDiag(diag::warn_remainder_division_by_zero)
10791 << IsDiv << RHS.get()->getSourceRange());
10792}
10793
10795 const ExprResult &LHS, const ExprResult &RHS,
10796 BinaryOperatorKind Opc) {
10797 if (!LHS.isUsable() || !RHS.isUsable())
10798 return;
10799 const Expr *LHSExpr = LHS.get();
10800 const Expr *RHSExpr = RHS.get();
10801 const QualType LHSType = LHSExpr->getType();
10802 const QualType RHSType = RHSExpr->getType();
10803 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10804 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10805 if (!LHSIsScoped && !RHSIsScoped)
10806 return;
10807 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10808 return;
10809 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10810 return;
10811 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10812 return;
10813 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10814 SourceLocation BeginLoc = expr->getBeginLoc();
10815 QualType IntType = type->castAs<EnumType>()
10816 ->getOriginalDecl()
10817 ->getDefinitionOrSelf()
10818 ->getIntegerType();
10819 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10820 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
10821 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
10822 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
10823 };
10824 if (LHSIsScoped) {
10825 DiagnosticHelper(LHSExpr, LHSType);
10826 }
10827 if (RHSIsScoped) {
10828 DiagnosticHelper(RHSExpr, RHSType);
10829 }
10830}
10831
10834 BinaryOperatorKind Opc) {
10835 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10836 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10837
10838 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10839
10840 QualType LHSTy = LHS.get()->getType();
10841 QualType RHSTy = RHS.get()->getType();
10842 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10843 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10844 /*AllowBothBool*/ getLangOpts().AltiVec,
10845 /*AllowBoolConversions*/ false,
10846 /*AllowBooleanOperation*/ false,
10847 /*ReportInvalid*/ true);
10848 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10849 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10851 if (!IsDiv &&
10852 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10853 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10854 // For division, only matrix-by-scalar is supported. Other combinations with
10855 // matrix types are invalid.
10856 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10857 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10858
10860 LHS, RHS, Loc,
10862 if (LHS.isInvalid() || RHS.isInvalid())
10863 return QualType();
10864
10865 if (compType.isNull() || !compType->isArithmeticType()) {
10866 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10867 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
10868 return ResultTy;
10869 }
10870 if (IsDiv) {
10872 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10873 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10874 }
10875 return compType;
10876}
10877
10879 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10880 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10881
10882 // Note: This check is here to simplify the double exclusions of
10883 // scalar and vector HLSL checks. No getLangOpts().HLSL
10884 // is needed since all languages exlcude doubles.
10885 if (LHS.get()->getType()->isDoubleType() ||
10886 RHS.get()->getType()->isDoubleType() ||
10887 (LHS.get()->getType()->isVectorType() && LHS.get()
10888 ->getType()
10889 ->getAs<VectorType>()
10890 ->getElementType()
10891 ->isDoubleType()) ||
10892 (RHS.get()->getType()->isVectorType() && RHS.get()
10893 ->getType()
10894 ->getAs<VectorType>()
10895 ->getElementType()
10896 ->isDoubleType()))
10897 return InvalidOperands(Loc, LHS, RHS);
10898
10899 if (LHS.get()->getType()->isVectorType() ||
10900 RHS.get()->getType()->isVectorType()) {
10901 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
10902 RHS.get()->getType()->hasIntegerRepresentation()) ||
10903 (getLangOpts().HLSL &&
10904 (LHS.get()->getType()->hasFloatingRepresentation() ||
10906 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10907 /*AllowBothBool*/ getLangOpts().AltiVec,
10908 /*AllowBoolConversions*/ false,
10909 /*AllowBooleanOperation*/ false,
10910 /*ReportInvalid*/ true);
10911 return InvalidOperands(Loc, LHS, RHS);
10912 }
10913
10914 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10915 RHS.get()->getType()->isSveVLSBuiltinType()) {
10916 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10918 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10920
10921 return InvalidOperands(Loc, LHS, RHS);
10922 }
10923
10925 LHS, RHS, Loc,
10927 if (LHS.isInvalid() || RHS.isInvalid())
10928 return QualType();
10929
10930 if (compType.isNull() ||
10931 (!compType->isIntegerType() &&
10932 !(getLangOpts().HLSL && compType->isFloatingType()))) {
10933 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10934 diagnoseScopedEnums(*this, Loc, LHS, RHS,
10935 IsCompAssign ? BO_RemAssign : BO_Rem);
10936 return ResultTy;
10937 }
10938 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10939 return compType;
10940}
10941
10942/// Diagnose invalid arithmetic on two void pointers.
10944 Expr *LHSExpr, Expr *RHSExpr) {
10945 S.Diag(Loc, S.getLangOpts().CPlusPlus
10946 ? diag::err_typecheck_pointer_arith_void_type
10947 : diag::ext_gnu_void_ptr)
10948 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10949 << RHSExpr->getSourceRange();
10950}
10951
10952/// Diagnose invalid arithmetic on a void pointer.
10954 Expr *Pointer) {
10955 S.Diag(Loc, S.getLangOpts().CPlusPlus
10956 ? diag::err_typecheck_pointer_arith_void_type
10957 : diag::ext_gnu_void_ptr)
10958 << 0 /* one pointer */ << Pointer->getSourceRange();
10959}
10960
10961/// Diagnose invalid arithmetic on a null pointer.
10962///
10963/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10964/// idiom, which we recognize as a GNU extension.
10965///
10967 Expr *Pointer, bool IsGNUIdiom) {
10968 if (IsGNUIdiom)
10969 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10970 << Pointer->getSourceRange();
10971 else
10972 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10973 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10974}
10975
10976/// Diagnose invalid subraction on a null pointer.
10977///
10979 Expr *Pointer, bool BothNull) {
10980 // Null - null is valid in C++ [expr.add]p7
10981 if (BothNull && S.getLangOpts().CPlusPlus)
10982 return;
10983
10984 // Is this s a macro from a system header?
10986 return;
10987
10989 S.PDiag(diag::warn_pointer_sub_null_ptr)
10990 << S.getLangOpts().CPlusPlus
10991 << Pointer->getSourceRange());
10992}
10993
10994/// Diagnose invalid arithmetic on two function pointers.
10996 Expr *LHS, Expr *RHS) {
10997 assert(LHS->getType()->isAnyPointerType());
10998 assert(RHS->getType()->isAnyPointerType());
10999 S.Diag(Loc, S.getLangOpts().CPlusPlus
11000 ? diag::err_typecheck_pointer_arith_function_type
11001 : diag::ext_gnu_ptr_func_arith)
11002 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11003 // We only show the second type if it differs from the first.
11005 RHS->getType())
11006 << RHS->getType()->getPointeeType()
11007 << LHS->getSourceRange() << RHS->getSourceRange();
11008}
11009
11010/// Diagnose invalid arithmetic on a function pointer.
11012 Expr *Pointer) {
11013 assert(Pointer->getType()->isAnyPointerType());
11014 S.Diag(Loc, S.getLangOpts().CPlusPlus
11015 ? diag::err_typecheck_pointer_arith_function_type
11016 : diag::ext_gnu_ptr_func_arith)
11017 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11018 << 0 /* one pointer, so only one type */
11019 << Pointer->getSourceRange();
11020}
11021
11022/// Emit error if Operand is incomplete pointer type
11023///
11024/// \returns True if pointer has incomplete type
11026 Expr *Operand) {
11027 QualType ResType = Operand->getType();
11028 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11029 ResType = ResAtomicType->getValueType();
11030
11031 assert(ResType->isAnyPointerType());
11032 QualType PointeeTy = ResType->getPointeeType();
11033 return S.RequireCompleteSizedType(
11034 Loc, PointeeTy,
11035 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11036 Operand->getSourceRange());
11037}
11038
11039/// Check the validity of an arithmetic pointer operand.
11040///
11041/// If the operand has pointer type, this code will check for pointer types
11042/// which are invalid in arithmetic operations. These will be diagnosed
11043/// appropriately, including whether or not the use is supported as an
11044/// extension.
11045///
11046/// \returns True when the operand is valid to use (even if as an extension).
11048 Expr *Operand) {
11049 QualType ResType = Operand->getType();
11050 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11051 ResType = ResAtomicType->getValueType();
11052
11053 if (!ResType->isAnyPointerType()) return true;
11054
11055 QualType PointeeTy = ResType->getPointeeType();
11056 if (PointeeTy->isVoidType()) {
11058 return !S.getLangOpts().CPlusPlus;
11059 }
11060 if (PointeeTy->isFunctionType()) {
11062 return !S.getLangOpts().CPlusPlus;
11063 }
11064
11065 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11066
11067 return true;
11068}
11069
11070/// Check the validity of a binary arithmetic operation w.r.t. pointer
11071/// operands.
11072///
11073/// This routine will diagnose any invalid arithmetic on pointer operands much
11074/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11075/// for emitting a single diagnostic even for operations where both LHS and RHS
11076/// are (potentially problematic) pointers.
11077///
11078/// \returns True when the operand is valid to use (even if as an extension).
11080 Expr *LHSExpr, Expr *RHSExpr) {
11081 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11082 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11083 if (!isLHSPointer && !isRHSPointer) return true;
11084
11085 QualType LHSPointeeTy, RHSPointeeTy;
11086 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11087 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11088
11089 // if both are pointers check if operation is valid wrt address spaces
11090 if (isLHSPointer && isRHSPointer) {
11091 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11092 S.getASTContext())) {
11093 S.Diag(Loc,
11094 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11095 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11096 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11097 return false;
11098 }
11099 }
11100
11101 // Check for arithmetic on pointers to incomplete types.
11102 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11103 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11104 if (isLHSVoidPtr || isRHSVoidPtr) {
11105 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11106 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11107 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11108
11109 return !S.getLangOpts().CPlusPlus;
11110 }
11111
11112 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11113 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11114 if (isLHSFuncPtr || isRHSFuncPtr) {
11115 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11116 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11117 RHSExpr);
11118 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11119
11120 return !S.getLangOpts().CPlusPlus;
11121 }
11122
11123 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11124 return false;
11125 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11126 return false;
11127
11128 return true;
11129}
11130
11131/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11132/// literal.
11134 Expr *LHSExpr, Expr *RHSExpr) {
11135 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11136 Expr* IndexExpr = RHSExpr;
11137 if (!StrExpr) {
11138 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11139 IndexExpr = LHSExpr;
11140 }
11141
11142 bool IsStringPlusInt = StrExpr &&
11144 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11145 return;
11146
11147 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11148 Self.Diag(OpLoc, diag::warn_string_plus_int)
11149 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11150
11151 // Only print a fixit for "str" + int, not for int + "str".
11152 if (IndexExpr == RHSExpr) {
11153 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11154 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11155 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11157 << FixItHint::CreateInsertion(EndLoc, "]");
11158 } else
11159 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11160}
11161
11162/// Emit a warning when adding a char literal to a string.
11164 Expr *LHSExpr, Expr *RHSExpr) {
11165 const Expr *StringRefExpr = LHSExpr;
11166 const CharacterLiteral *CharExpr =
11167 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11168
11169 if (!CharExpr) {
11170 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11171 StringRefExpr = RHSExpr;
11172 }
11173
11174 if (!CharExpr || !StringRefExpr)
11175 return;
11176
11177 const QualType StringType = StringRefExpr->getType();
11178
11179 // Return if not a PointerType.
11180 if (!StringType->isAnyPointerType())
11181 return;
11182
11183 // Return if not a CharacterType.
11184 if (!StringType->getPointeeType()->isAnyCharacterType())
11185 return;
11186
11187 ASTContext &Ctx = Self.getASTContext();
11188 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11189
11190 const QualType CharType = CharExpr->getType();
11191 if (!CharType->isAnyCharacterType() &&
11192 CharType->isIntegerType() &&
11193 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11194 Self.Diag(OpLoc, diag::warn_string_plus_char)
11195 << DiagRange << Ctx.CharTy;
11196 } else {
11197 Self.Diag(OpLoc, diag::warn_string_plus_char)
11198 << DiagRange << CharExpr->getType();
11199 }
11200
11201 // Only print a fixit for str + char, not for char + str.
11202 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11203 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11204 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11205 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11207 << FixItHint::CreateInsertion(EndLoc, "]");
11208 } else {
11209 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11210 }
11211}
11212
11213/// Emit error when two pointers are incompatible.
11215 Expr *LHSExpr, Expr *RHSExpr) {
11216 assert(LHSExpr->getType()->isAnyPointerType());
11217 assert(RHSExpr->getType()->isAnyPointerType());
11218 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11219 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11220 << RHSExpr->getSourceRange();
11221}
11222
11223// C99 6.5.6
11226 QualType* CompLHSTy) {
11227 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11228
11229 if (LHS.get()->getType()->isVectorType() ||
11230 RHS.get()->getType()->isVectorType()) {
11231 QualType compType =
11232 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11233 /*AllowBothBool*/ getLangOpts().AltiVec,
11234 /*AllowBoolConversions*/ getLangOpts().ZVector,
11235 /*AllowBooleanOperation*/ false,
11236 /*ReportInvalid*/ true);
11237 if (CompLHSTy) *CompLHSTy = compType;
11238 return compType;
11239 }
11240
11241 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11242 RHS.get()->getType()->isSveVLSBuiltinType()) {
11243 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11245 if (CompLHSTy)
11246 *CompLHSTy = compType;
11247 return compType;
11248 }
11249
11250 if (LHS.get()->getType()->isConstantMatrixType() ||
11251 RHS.get()->getType()->isConstantMatrixType()) {
11252 QualType compType =
11253 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11254 if (CompLHSTy)
11255 *CompLHSTy = compType;
11256 return compType;
11257 }
11258
11260 LHS, RHS, Loc,
11262 if (LHS.isInvalid() || RHS.isInvalid())
11263 return QualType();
11264
11265 // Diagnose "string literal" '+' int and string '+' "char literal".
11266 if (Opc == BO_Add) {
11267 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11268 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11269 }
11270
11271 // handle the common case first (both operands are arithmetic).
11272 if (!compType.isNull() && compType->isArithmeticType()) {
11273 if (CompLHSTy) *CompLHSTy = compType;
11274 return compType;
11275 }
11276
11277 // Type-checking. Ultimately the pointer's going to be in PExp;
11278 // note that we bias towards the LHS being the pointer.
11279 Expr *PExp = LHS.get(), *IExp = RHS.get();
11280
11281 bool isObjCPointer;
11282 if (PExp->getType()->isPointerType()) {
11283 isObjCPointer = false;
11284 } else if (PExp->getType()->isObjCObjectPointerType()) {
11285 isObjCPointer = true;
11286 } else {
11287 std::swap(PExp, IExp);
11288 if (PExp->getType()->isPointerType()) {
11289 isObjCPointer = false;
11290 } else if (PExp->getType()->isObjCObjectPointerType()) {
11291 isObjCPointer = true;
11292 } else {
11293 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11294 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11295 return ResultTy;
11296 }
11297 }
11298 assert(PExp->getType()->isAnyPointerType());
11299
11300 if (!IExp->getType()->isIntegerType())
11301 return InvalidOperands(Loc, LHS, RHS);
11302
11303 // Adding to a null pointer results in undefined behavior.
11306 // In C++ adding zero to a null pointer is defined.
11307 Expr::EvalResult KnownVal;
11308 if (!getLangOpts().CPlusPlus ||
11309 (!IExp->isValueDependent() &&
11310 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11311 KnownVal.Val.getInt() != 0))) {
11312 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11314 Context, BO_Add, PExp, IExp);
11315 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11316 }
11317 }
11318
11319 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11320 return QualType();
11321
11322 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11323 return QualType();
11324
11325 // Arithmetic on label addresses is normally allowed, except when we add
11326 // a ptrauth signature to the addresses.
11327 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11328 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11329 << /*addition*/ 1;
11330 return QualType();
11331 }
11332
11333 // Check array bounds for pointer arithemtic
11334 CheckArrayAccess(PExp, IExp);
11335
11336 if (CompLHSTy) {
11338 if (LHSTy.isNull()) {
11339 LHSTy = LHS.get()->getType();
11341 LHSTy = Context.getPromotedIntegerType(LHSTy);
11342 }
11343 *CompLHSTy = LHSTy;
11344 }
11345
11346 return PExp->getType();
11347}
11348
11349// C99 6.5.6
11353 QualType *CompLHSTy) {
11354 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11355
11356 if (LHS.get()->getType()->isVectorType() ||
11357 RHS.get()->getType()->isVectorType()) {
11358 QualType compType =
11359 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11360 /*AllowBothBool*/ getLangOpts().AltiVec,
11361 /*AllowBoolConversions*/ getLangOpts().ZVector,
11362 /*AllowBooleanOperation*/ false,
11363 /*ReportInvalid*/ true);
11364 if (CompLHSTy) *CompLHSTy = compType;
11365 return compType;
11366 }
11367
11368 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11369 RHS.get()->getType()->isSveVLSBuiltinType()) {
11370 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11372 if (CompLHSTy)
11373 *CompLHSTy = compType;
11374 return compType;
11375 }
11376
11377 if (LHS.get()->getType()->isConstantMatrixType() ||
11378 RHS.get()->getType()->isConstantMatrixType()) {
11379 QualType compType =
11380 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11381 if (CompLHSTy)
11382 *CompLHSTy = compType;
11383 return compType;
11384 }
11385
11387 LHS, RHS, Loc,
11389 if (LHS.isInvalid() || RHS.isInvalid())
11390 return QualType();
11391
11392 // Enforce type constraints: C99 6.5.6p3.
11393
11394 // Handle the common case first (both operands are arithmetic).
11395 if (!compType.isNull() && compType->isArithmeticType()) {
11396 if (CompLHSTy) *CompLHSTy = compType;
11397 return compType;
11398 }
11399
11400 // Either ptr - int or ptr - ptr.
11401 if (LHS.get()->getType()->isAnyPointerType()) {
11402 QualType lpointee = LHS.get()->getType()->getPointeeType();
11403
11404 // Diagnose bad cases where we step over interface counts.
11405 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11406 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11407 return QualType();
11408
11409 // Arithmetic on label addresses is normally allowed, except when we add
11410 // a ptrauth signature to the addresses.
11411 if (isa<AddrLabelExpr>(LHS.get()) &&
11412 getLangOpts().PointerAuthIndirectGotos) {
11413 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11414 << /*subtraction*/ 0;
11415 return QualType();
11416 }
11417
11418 // The result type of a pointer-int computation is the pointer type.
11419 if (RHS.get()->getType()->isIntegerType()) {
11420 // Subtracting from a null pointer should produce a warning.
11421 // The last argument to the diagnose call says this doesn't match the
11422 // GNU int-to-pointer idiom.
11425 // In C++ adding zero to a null pointer is defined.
11426 Expr::EvalResult KnownVal;
11427 if (!getLangOpts().CPlusPlus ||
11428 (!RHS.get()->isValueDependent() &&
11429 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11430 KnownVal.Val.getInt() != 0))) {
11431 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11432 }
11433 }
11434
11435 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11436 return QualType();
11437
11438 // Check array bounds for pointer arithemtic
11439 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11440 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11441
11442 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11443 return LHS.get()->getType();
11444 }
11445
11446 // Handle pointer-pointer subtractions.
11447 if (const PointerType *RHSPTy
11448 = RHS.get()->getType()->getAs<PointerType>()) {
11449 QualType rpointee = RHSPTy->getPointeeType();
11450
11451 if (getLangOpts().CPlusPlus) {
11452 // Pointee types must be the same: C++ [expr.add]
11453 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11454 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11455 }
11456 } else {
11457 // Pointee types must be compatible C99 6.5.6p3
11461 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11462 return QualType();
11463 }
11464 }
11465
11467 LHS.get(), RHS.get()))
11468 return QualType();
11469
11470 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11472 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11474
11475 // Subtracting nullptr or from nullptr is suspect
11476 if (LHSIsNullPtr)
11477 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11478 if (RHSIsNullPtr)
11479 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11480
11481 // The pointee type may have zero size. As an extension, a structure or
11482 // union may have zero size or an array may have zero length. In this
11483 // case subtraction does not make sense.
11484 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11485 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11486 if (ElementSize.isZero()) {
11487 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11488 << rpointee.getUnqualifiedType()
11489 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11490 }
11491 }
11492
11493 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11494 return Context.getPointerDiffType();
11495 }
11496 }
11497
11498 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11499 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11500 return ResultTy;
11501}
11502
11504 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11505 return ET->getOriginalDecl()->isScoped();
11506 return false;
11507}
11508
11511 QualType LHSType) {
11512 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11513 // so skip remaining warnings as we don't want to modify values within Sema.
11514 if (S.getLangOpts().OpenCL)
11515 return;
11516
11517 if (Opc == BO_Shr &&
11519 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11520
11521 // Check right/shifter operand
11522 Expr::EvalResult RHSResult;
11523 if (RHS.get()->isValueDependent() ||
11524 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11525 return;
11526 llvm::APSInt Right = RHSResult.Val.getInt();
11527
11528 if (Right.isNegative()) {
11529 S.DiagRuntimeBehavior(Loc, RHS.get(),
11530 S.PDiag(diag::warn_shift_negative)
11531 << RHS.get()->getSourceRange());
11532 return;
11533 }
11534
11535 QualType LHSExprType = LHS.get()->getType();
11536 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11537 if (LHSExprType->isBitIntType())
11538 LeftSize = S.Context.getIntWidth(LHSExprType);
11539 else if (LHSExprType->isFixedPointType()) {
11540 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11541 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11542 }
11543 if (Right.uge(LeftSize)) {
11544 S.DiagRuntimeBehavior(Loc, RHS.get(),
11545 S.PDiag(diag::warn_shift_gt_typewidth)
11546 << RHS.get()->getSourceRange());
11547 return;
11548 }
11549
11550 // FIXME: We probably need to handle fixed point types specially here.
11551 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11552 return;
11553
11554 // When left shifting an ICE which is signed, we can check for overflow which
11555 // according to C++ standards prior to C++2a has undefined behavior
11556 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11557 // more than the maximum value representable in the result type, so never
11558 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11559 // expression is still probably a bug.)
11560 Expr::EvalResult LHSResult;
11561 if (LHS.get()->isValueDependent() ||
11563 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11564 return;
11565 llvm::APSInt Left = LHSResult.Val.getInt();
11566
11567 // Don't warn if signed overflow is defined, then all the rest of the
11568 // diagnostics will not be triggered because the behavior is defined.
11569 // Also don't warn in C++20 mode (and newer), as signed left shifts
11570 // always wrap and never overflow.
11571 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11572 return;
11573
11574 // If LHS does not have a non-negative value then, the
11575 // behavior is undefined before C++2a. Warn about it.
11576 if (Left.isNegative()) {
11577 S.DiagRuntimeBehavior(Loc, LHS.get(),
11578 S.PDiag(diag::warn_shift_lhs_negative)
11579 << LHS.get()->getSourceRange());
11580 return;
11581 }
11582
11583 llvm::APInt ResultBits =
11584 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11585 if (ResultBits.ule(LeftSize))
11586 return;
11587 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11588 Result = Result.shl(Right);
11589
11590 // Print the bit representation of the signed integer as an unsigned
11591 // hexadecimal number.
11592 SmallString<40> HexResult;
11593 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11594
11595 // If we are only missing a sign bit, this is less likely to result in actual
11596 // bugs -- if the result is cast back to an unsigned type, it will have the
11597 // expected value. Thus we place this behind a different warning that can be
11598 // turned off separately if needed.
11599 if (ResultBits - 1 == LeftSize) {
11600 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11601 << HexResult << LHSType
11602 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11603 return;
11604 }
11605
11606 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11607 << HexResult.str() << Result.getSignificantBits() << LHSType
11608 << Left.getBitWidth() << LHS.get()->getSourceRange()
11609 << RHS.get()->getSourceRange();
11610}
11611
11612/// Return the resulting type when a vector is shifted
11613/// by a scalar or vector shift amount.
11615 SourceLocation Loc, bool IsCompAssign) {
11616 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11617 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11618 !LHS.get()->getType()->isVectorType()) {
11619 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11620 << RHS.get()->getType() << LHS.get()->getType()
11621 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11622 return QualType();
11623 }
11624
11625 if (!IsCompAssign) {
11626 LHS = S.UsualUnaryConversions(LHS.get());
11627 if (LHS.isInvalid()) return QualType();
11628 }
11629
11630 RHS = S.UsualUnaryConversions(RHS.get());
11631 if (RHS.isInvalid()) return QualType();
11632
11633 QualType LHSType = LHS.get()->getType();
11634 // Note that LHS might be a scalar because the routine calls not only in
11635 // OpenCL case.
11636 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11637 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11638
11639 // Note that RHS might not be a vector.
11640 QualType RHSType = RHS.get()->getType();
11641 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11642 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11643
11644 // Do not allow shifts for boolean vectors.
11645 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11646 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11647 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11648 << LHS.get()->getType() << RHS.get()->getType()
11649 << LHS.get()->getSourceRange();
11650 return QualType();
11651 }
11652
11653 // The operands need to be integers.
11654 if (!LHSEleType->isIntegerType()) {
11655 S.Diag(Loc, diag::err_typecheck_expect_int)
11656 << LHS.get()->getType() << LHS.get()->getSourceRange();
11657 return QualType();
11658 }
11659
11660 if (!RHSEleType->isIntegerType()) {
11661 S.Diag(Loc, diag::err_typecheck_expect_int)
11662 << RHS.get()->getType() << RHS.get()->getSourceRange();
11663 return QualType();
11664 }
11665
11666 if (!LHSVecTy) {
11667 assert(RHSVecTy);
11668 if (IsCompAssign)
11669 return RHSType;
11670 if (LHSEleType != RHSEleType) {
11671 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11672 LHSEleType = RHSEleType;
11673 }
11674 QualType VecTy =
11675 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11676 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11677 LHSType = VecTy;
11678 } else if (RHSVecTy) {
11679 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11680 // are applied component-wise. So if RHS is a vector, then ensure
11681 // that the number of elements is the same as LHS...
11682 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11683 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11684 << LHS.get()->getType() << RHS.get()->getType()
11685 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11686 return QualType();
11687 }
11688 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11689 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11690 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11691 if (LHSBT != RHSBT &&
11692 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11693 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11694 << LHS.get()->getType() << RHS.get()->getType()
11695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11696 }
11697 }
11698 } else {
11699 // ...else expand RHS to match the number of elements in LHS.
11700 QualType VecTy =
11701 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11702 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11703 }
11704
11705 return LHSType;
11706}
11707
11710 bool IsCompAssign) {
11711 if (!IsCompAssign) {
11712 LHS = S.UsualUnaryConversions(LHS.get());
11713 if (LHS.isInvalid())
11714 return QualType();
11715 }
11716
11717 RHS = S.UsualUnaryConversions(RHS.get());
11718 if (RHS.isInvalid())
11719 return QualType();
11720
11721 QualType LHSType = LHS.get()->getType();
11722 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11723 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11724 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11725 : LHSType;
11726
11727 // Note that RHS might not be a vector
11728 QualType RHSType = RHS.get()->getType();
11729 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11730 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11731 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11732 : RHSType;
11733
11734 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11735 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11736 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11737 << LHSType << RHSType << LHS.get()->getSourceRange();
11738 return QualType();
11739 }
11740
11741 if (!LHSEleType->isIntegerType()) {
11742 S.Diag(Loc, diag::err_typecheck_expect_int)
11743 << LHS.get()->getType() << LHS.get()->getSourceRange();
11744 return QualType();
11745 }
11746
11747 if (!RHSEleType->isIntegerType()) {
11748 S.Diag(Loc, diag::err_typecheck_expect_int)
11749 << RHS.get()->getType() << RHS.get()->getSourceRange();
11750 return QualType();
11751 }
11752
11753 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11754 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11755 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11756 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11757 << LHSType << RHSType << LHS.get()->getSourceRange()
11758 << RHS.get()->getSourceRange();
11759 return QualType();
11760 }
11761
11762 if (!LHSType->isSveVLSBuiltinType()) {
11763 assert(RHSType->isSveVLSBuiltinType());
11764 if (IsCompAssign)
11765 return RHSType;
11766 if (LHSEleType != RHSEleType) {
11767 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11768 LHSEleType = RHSEleType;
11769 }
11770 const llvm::ElementCount VecSize =
11771 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11772 QualType VecTy =
11773 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11774 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11775 LHSType = VecTy;
11776 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11777 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11778 S.Context.getTypeSize(LHSBuiltinTy)) {
11779 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11780 << LHSType << RHSType << LHS.get()->getSourceRange()
11781 << RHS.get()->getSourceRange();
11782 return QualType();
11783 }
11784 } else {
11785 const llvm::ElementCount VecSize =
11786 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11787 if (LHSEleType != RHSEleType) {
11788 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11789 RHSEleType = LHSEleType;
11790 }
11791 QualType VecTy =
11792 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11793 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11794 }
11795
11796 return LHSType;
11797}
11798
11799// C99 6.5.7
11802 bool IsCompAssign) {
11803 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11804
11805 // Vector shifts promote their scalar inputs to vector type.
11806 if (LHS.get()->getType()->isVectorType() ||
11807 RHS.get()->getType()->isVectorType()) {
11808 if (LangOpts.ZVector) {
11809 // The shift operators for the z vector extensions work basically
11810 // like general shifts, except that neither the LHS nor the RHS is
11811 // allowed to be a "vector bool".
11812 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11813 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11814 return InvalidOperands(Loc, LHS, RHS);
11815 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11816 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11817 return InvalidOperands(Loc, LHS, RHS);
11818 }
11819 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11820 }
11821
11822 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11823 RHS.get()->getType()->isSveVLSBuiltinType())
11824 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11825
11826 // Shifts don't perform usual arithmetic conversions, they just do integer
11827 // promotions on each operand. C99 6.5.7p3
11828
11829 // For the LHS, do usual unary conversions, but then reset them away
11830 // if this is a compound assignment.
11831 ExprResult OldLHS = LHS;
11832 LHS = UsualUnaryConversions(LHS.get());
11833 if (LHS.isInvalid())
11834 return QualType();
11835 QualType LHSType = LHS.get()->getType();
11836 if (IsCompAssign) LHS = OldLHS;
11837
11838 // The RHS is simpler.
11839 RHS = UsualUnaryConversions(RHS.get());
11840 if (RHS.isInvalid())
11841 return QualType();
11842 QualType RHSType = RHS.get()->getType();
11843
11844 // C99 6.5.7p2: Each of the operands shall have integer type.
11845 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11846 if ((!LHSType->isFixedPointOrIntegerType() &&
11847 !LHSType->hasIntegerRepresentation()) ||
11848 !RHSType->hasIntegerRepresentation()) {
11849 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11850 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11851 return ResultTy;
11852 }
11853
11854 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11855
11856 // "The type of the result is that of the promoted left operand."
11857 return LHSType;
11858}
11859
11860/// Diagnose bad pointer comparisons.
11862 ExprResult &LHS, ExprResult &RHS,
11863 bool IsError) {
11864 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11865 : diag::ext_typecheck_comparison_of_distinct_pointers)
11866 << LHS.get()->getType() << RHS.get()->getType()
11867 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11868}
11869
11870/// Returns false if the pointers are converted to a composite type,
11871/// true otherwise.
11873 ExprResult &LHS, ExprResult &RHS) {
11874 // C++ [expr.rel]p2:
11875 // [...] Pointer conversions (4.10) and qualification
11876 // conversions (4.4) are performed on pointer operands (or on
11877 // a pointer operand and a null pointer constant) to bring
11878 // them to their composite pointer type. [...]
11879 //
11880 // C++ [expr.eq]p1 uses the same notion for (in)equality
11881 // comparisons of pointers.
11882
11883 QualType LHSType = LHS.get()->getType();
11884 QualType RHSType = RHS.get()->getType();
11885 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11886 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11887
11888 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11889 if (T.isNull()) {
11890 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11891 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11892 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11893 else
11894 S.InvalidOperands(Loc, LHS, RHS);
11895 return true;
11896 }
11897
11898 return false;
11899}
11900
11902 ExprResult &LHS,
11903 ExprResult &RHS,
11904 bool IsError) {
11905 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11906 : diag::ext_typecheck_comparison_of_fptr_to_void)
11907 << LHS.get()->getType() << RHS.get()->getType()
11908 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11909}
11910
11912 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11913 case Stmt::ObjCArrayLiteralClass:
11914 case Stmt::ObjCDictionaryLiteralClass:
11915 case Stmt::ObjCStringLiteralClass:
11916 case Stmt::ObjCBoxedExprClass:
11917 return true;
11918 default:
11919 // Note that ObjCBoolLiteral is NOT an object literal!
11920 return false;
11921 }
11922}
11923
11924static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11927
11928 // If this is not actually an Objective-C object, bail out.
11929 if (!Type)
11930 return false;
11931
11932 // Get the LHS object's interface type.
11933 QualType InterfaceType = Type->getPointeeType();
11934
11935 // If the RHS isn't an Objective-C object, bail out.
11936 if (!RHS->getType()->isObjCObjectPointerType())
11937 return false;
11938
11939 // Try to find the -isEqual: method.
11940 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11942 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11943 /*IsInstance=*/true);
11944 if (!Method) {
11945 if (Type->isObjCIdType()) {
11946 // For 'id', just check the global pool.
11947 Method =
11949 /*receiverId=*/true);
11950 } else {
11951 // Check protocols.
11952 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11953 /*IsInstance=*/true);
11954 }
11955 }
11956
11957 if (!Method)
11958 return false;
11959
11960 QualType T = Method->parameters()[0]->getType();
11961 if (!T->isObjCObjectPointerType())
11962 return false;
11963
11964 QualType R = Method->getReturnType();
11965 if (!R->isScalarType())
11966 return false;
11967
11968 return true;
11969}
11970
11972 ExprResult &LHS, ExprResult &RHS,
11974 Expr *Literal;
11975 Expr *Other;
11976 if (isObjCObjectLiteral(LHS)) {
11977 Literal = LHS.get();
11978 Other = RHS.get();
11979 } else {
11980 Literal = RHS.get();
11981 Other = LHS.get();
11982 }
11983
11984 // Don't warn on comparisons against nil.
11985 Other = Other->IgnoreParenCasts();
11986 if (Other->isNullPointerConstant(S.getASTContext(),
11988 return;
11989
11990 // This should be kept in sync with warn_objc_literal_comparison.
11991 // LK_String should always be after the other literals, since it has its own
11992 // warning flag.
11993 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11994 assert(LiteralKind != SemaObjC::LK_Block);
11995 if (LiteralKind == SemaObjC::LK_None) {
11996 llvm_unreachable("Unknown Objective-C object literal kind");
11997 }
11998
11999 if (LiteralKind == SemaObjC::LK_String)
12000 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12001 << Literal->getSourceRange();
12002 else
12003 S.Diag(Loc, diag::warn_objc_literal_comparison)
12004 << LiteralKind << Literal->getSourceRange();
12005
12007 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12008 SourceLocation Start = LHS.get()->getBeginLoc();
12010 CharSourceRange OpRange =
12012
12013 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12014 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12015 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12016 << FixItHint::CreateInsertion(End, "]");
12017 }
12018}
12019
12020/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12023 BinaryOperatorKind Opc) {
12024 // Check that left hand side is !something.
12025 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12026 if (!UO || UO->getOpcode() != UO_LNot) return;
12027
12028 // Only check if the right hand side is non-bool arithmetic type.
12029 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12030
12031 // Make sure that the something in !something is not bool.
12032 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12033 if (SubExpr->isKnownToHaveBooleanValue()) return;
12034
12035 // Emit warning.
12036 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12037 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12038 << Loc << IsBitwiseOp;
12039
12040 // First note suggest !(x < y)
12041 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12042 SourceLocation FirstClose = RHS.get()->getEndLoc();
12043 FirstClose = S.getLocForEndOfToken(FirstClose);
12044 if (FirstClose.isInvalid())
12045 FirstOpen = SourceLocation();
12046 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12047 << IsBitwiseOp
12048 << FixItHint::CreateInsertion(FirstOpen, "(")
12049 << FixItHint::CreateInsertion(FirstClose, ")");
12050
12051 // Second note suggests (!x) < y
12052 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12053 SourceLocation SecondClose = LHS.get()->getEndLoc();
12054 SecondClose = S.getLocForEndOfToken(SecondClose);
12055 if (SecondClose.isInvalid())
12056 SecondOpen = SourceLocation();
12057 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12058 << FixItHint::CreateInsertion(SecondOpen, "(")
12059 << FixItHint::CreateInsertion(SecondClose, ")");
12060}
12061
12062// Returns true if E refers to a non-weak array.
12063static bool checkForArray(const Expr *E) {
12064 const ValueDecl *D = nullptr;
12065 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12066 D = DR->getDecl();
12067 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12068 if (Mem->isImplicitAccess())
12069 D = Mem->getMemberDecl();
12070 }
12071 if (!D)
12072 return false;
12073 return D->getType()->isArrayType() && !D->isWeak();
12074}
12075
12076/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12077/// pointer and size is an unsigned integer. Return whether the result is
12078/// always true/false.
12079static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12080 const Expr *RHS,
12081 BinaryOperatorKind Opc) {
12082 if (!LHS->getType()->isPointerType() ||
12083 S.getLangOpts().PointerOverflowDefined)
12084 return std::nullopt;
12085
12086 // Canonicalize to >= or < predicate.
12087 switch (Opc) {
12088 case BO_GE:
12089 case BO_LT:
12090 break;
12091 case BO_GT:
12092 std::swap(LHS, RHS);
12093 Opc = BO_LT;
12094 break;
12095 case BO_LE:
12096 std::swap(LHS, RHS);
12097 Opc = BO_GE;
12098 break;
12099 default:
12100 return std::nullopt;
12101 }
12102
12103 auto *BO = dyn_cast<BinaryOperator>(LHS);
12104 if (!BO || BO->getOpcode() != BO_Add)
12105 return std::nullopt;
12106
12107 Expr *Other;
12108 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12109 Other = BO->getRHS();
12110 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12111 Other = BO->getLHS();
12112 else
12113 return std::nullopt;
12114
12115 if (!Other->getType()->isUnsignedIntegerType())
12116 return std::nullopt;
12117
12118 return Opc == BO_GE;
12119}
12120
12121/// Diagnose some forms of syntactically-obvious tautological comparison.
12123 Expr *LHS, Expr *RHS,
12124 BinaryOperatorKind Opc) {
12125 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12126 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12127
12128 QualType LHSType = LHS->getType();
12129 QualType RHSType = RHS->getType();
12130 if (LHSType->hasFloatingRepresentation() ||
12131 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12133 return;
12134
12135 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12136 // Tautological diagnostics.
12137 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12138 return;
12139
12140 // Comparisons between two array types are ill-formed for operator<=>, so
12141 // we shouldn't emit any additional warnings about it.
12142 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12143 return;
12144
12145 // For non-floating point types, check for self-comparisons of the form
12146 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12147 // often indicate logic errors in the program.
12148 //
12149 // NOTE: Don't warn about comparison expressions resulting from macro
12150 // expansion. Also don't warn about comparisons which are only self
12151 // comparisons within a template instantiation. The warnings should catch
12152 // obvious cases in the definition of the template anyways. The idea is to
12153 // warn when the typed comparison operator will always evaluate to the same
12154 // result.
12155
12156 // Used for indexing into %select in warn_comparison_always
12157 enum {
12158 AlwaysConstant,
12159 AlwaysTrue,
12160 AlwaysFalse,
12161 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12162 };
12163
12164 // C++1a [array.comp]:
12165 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12166 // operands of array type.
12167 // C++2a [depr.array.comp]:
12168 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12169 // operands of array type are deprecated.
12170 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12171 RHSStripped->getType()->isArrayType()) {
12172 auto IsDeprArrayComparionIgnored =
12173 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12174 auto DiagID = S.getLangOpts().CPlusPlus26
12175 ? diag::warn_array_comparison_cxx26
12176 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12177 ? diag::warn_array_comparison
12178 : diag::warn_depr_array_comparison;
12179 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12180 << LHSStripped->getType() << RHSStripped->getType();
12181 // Carry on to produce the tautological comparison warning, if this
12182 // expression is potentially-evaluated, we can resolve the array to a
12183 // non-weak declaration, and so on.
12184 }
12185
12186 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12187 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12188 unsigned Result;
12189 switch (Opc) {
12190 case BO_EQ:
12191 case BO_LE:
12192 case BO_GE:
12193 Result = AlwaysTrue;
12194 break;
12195 case BO_NE:
12196 case BO_LT:
12197 case BO_GT:
12198 Result = AlwaysFalse;
12199 break;
12200 case BO_Cmp:
12201 Result = AlwaysEqual;
12202 break;
12203 default:
12204 Result = AlwaysConstant;
12205 break;
12206 }
12207 S.DiagRuntimeBehavior(Loc, nullptr,
12208 S.PDiag(diag::warn_comparison_always)
12209 << 0 /*self-comparison*/
12210 << Result);
12211 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12212 // What is it always going to evaluate to?
12213 unsigned Result;
12214 switch (Opc) {
12215 case BO_EQ: // e.g. array1 == array2
12216 Result = AlwaysFalse;
12217 break;
12218 case BO_NE: // e.g. array1 != array2
12219 Result = AlwaysTrue;
12220 break;
12221 default: // e.g. array1 <= array2
12222 // The best we can say is 'a constant'
12223 Result = AlwaysConstant;
12224 break;
12225 }
12226 S.DiagRuntimeBehavior(Loc, nullptr,
12227 S.PDiag(diag::warn_comparison_always)
12228 << 1 /*array comparison*/
12229 << Result);
12230 } else if (std::optional<bool> Res =
12231 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12232 S.DiagRuntimeBehavior(Loc, nullptr,
12233 S.PDiag(diag::warn_comparison_always)
12234 << 2 /*pointer comparison*/
12235 << (*Res ? AlwaysTrue : AlwaysFalse));
12236 }
12237 }
12238
12239 if (isa<CastExpr>(LHSStripped))
12240 LHSStripped = LHSStripped->IgnoreParenCasts();
12241 if (isa<CastExpr>(RHSStripped))
12242 RHSStripped = RHSStripped->IgnoreParenCasts();
12243
12244 // Warn about comparisons against a string constant (unless the other
12245 // operand is null); the user probably wants string comparison function.
12246 Expr *LiteralString = nullptr;
12247 Expr *LiteralStringStripped = nullptr;
12248 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12249 !RHSStripped->isNullPointerConstant(S.Context,
12251 LiteralString = LHS;
12252 LiteralStringStripped = LHSStripped;
12253 } else if ((isa<StringLiteral>(RHSStripped) ||
12254 isa<ObjCEncodeExpr>(RHSStripped)) &&
12255 !LHSStripped->isNullPointerConstant(S.Context,
12257 LiteralString = RHS;
12258 LiteralStringStripped = RHSStripped;
12259 }
12260
12261 if (LiteralString) {
12262 S.DiagRuntimeBehavior(Loc, nullptr,
12263 S.PDiag(diag::warn_stringcompare)
12264 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12265 << LiteralString->getSourceRange());
12266 }
12267}
12268
12270 switch (CK) {
12271 default: {
12272#ifndef NDEBUG
12273 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12274 << "\n";
12275#endif
12276 llvm_unreachable("unhandled cast kind");
12277 }
12278 case CK_UserDefinedConversion:
12279 return ICK_Identity;
12280 case CK_LValueToRValue:
12281 return ICK_Lvalue_To_Rvalue;
12282 case CK_ArrayToPointerDecay:
12283 return ICK_Array_To_Pointer;
12284 case CK_FunctionToPointerDecay:
12286 case CK_IntegralCast:
12288 case CK_FloatingCast:
12290 case CK_IntegralToFloating:
12291 case CK_FloatingToIntegral:
12292 return ICK_Floating_Integral;
12293 case CK_IntegralComplexCast:
12294 case CK_FloatingComplexCast:
12295 case CK_FloatingComplexToIntegralComplex:
12296 case CK_IntegralComplexToFloatingComplex:
12298 case CK_FloatingComplexToReal:
12299 case CK_FloatingRealToComplex:
12300 case CK_IntegralComplexToReal:
12301 case CK_IntegralRealToComplex:
12302 return ICK_Complex_Real;
12303 case CK_HLSLArrayRValue:
12304 return ICK_HLSL_Array_RValue;
12305 }
12306}
12307
12309 QualType FromType,
12311 // Check for a narrowing implicit conversion.
12314 SCS.setToType(0, FromType);
12315 SCS.setToType(1, ToType);
12316 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12317 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12318
12319 APValue PreNarrowingValue;
12320 QualType PreNarrowingType;
12321 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12322 PreNarrowingType,
12323 /*IgnoreFloatToIntegralConversion*/ true)) {
12325 // Implicit conversion to a narrower type, but the expression is
12326 // value-dependent so we can't tell whether it's actually narrowing.
12327 case NK_Not_Narrowing:
12328 return false;
12329
12331 // Implicit conversion to a narrower type, and the value is not a constant
12332 // expression.
12333 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12334 << /*Constant*/ 1
12335 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12336 return true;
12337
12339 // Implicit conversion to a narrower type, and the value is not a constant
12340 // expression.
12341 case NK_Type_Narrowing:
12342 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12343 << /*Constant*/ 0 << FromType << ToType;
12344 // TODO: It's not a constant expression, but what if the user intended it
12345 // to be? Can we produce notes to help them figure out why it isn't?
12346 return true;
12347 }
12348 llvm_unreachable("unhandled case in switch");
12349}
12350
12352 ExprResult &LHS,
12353 ExprResult &RHS,
12355 QualType LHSType = LHS.get()->getType();
12356 QualType RHSType = RHS.get()->getType();
12357 // Dig out the original argument type and expression before implicit casts
12358 // were applied. These are the types/expressions we need to check the
12359 // [expr.spaceship] requirements against.
12360 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12361 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12362 QualType LHSStrippedType = LHSStripped.get()->getType();
12363 QualType RHSStrippedType = RHSStripped.get()->getType();
12364
12365 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12366 // other is not, the program is ill-formed.
12367 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12368 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12369 return QualType();
12370 }
12371
12372 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12373 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12374 RHSStrippedType->isEnumeralType();
12375 if (NumEnumArgs == 1) {
12376 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12377 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12378 if (OtherTy->hasFloatingRepresentation()) {
12379 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12380 return QualType();
12381 }
12382 }
12383 if (NumEnumArgs == 2) {
12384 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12385 // type E, the operator yields the result of converting the operands
12386 // to the underlying type of E and applying <=> to the converted operands.
12387 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12388 S.InvalidOperands(Loc, LHS, RHS);
12389 return QualType();
12390 }
12391 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12392 assert(IntType->isArithmeticType());
12393
12394 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12395 // promote the boolean type, and all other promotable integer types, to
12396 // avoid this.
12397 if (S.Context.isPromotableIntegerType(IntType))
12398 IntType = S.Context.getPromotedIntegerType(IntType);
12399
12400 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12401 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12402 LHSType = RHSType = IntType;
12403 }
12404
12405 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12406 // usual arithmetic conversions are applied to the operands.
12407 QualType Type =
12409 if (LHS.isInvalid() || RHS.isInvalid())
12410 return QualType();
12411 if (Type.isNull()) {
12412 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12413 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12414 return ResultTy;
12415 }
12416
12417 std::optional<ComparisonCategoryType> CCT =
12419 if (!CCT)
12420 return S.InvalidOperands(Loc, LHS, RHS);
12421
12422 bool HasNarrowing = checkThreeWayNarrowingConversion(
12423 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12424 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12425 RHS.get()->getBeginLoc());
12426 if (HasNarrowing)
12427 return QualType();
12428
12429 assert(!Type.isNull() && "composite type for <=> has not been set");
12430
12433}
12434
12436 ExprResult &RHS,
12438 BinaryOperatorKind Opc) {
12439 if (Opc == BO_Cmp)
12440 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12441
12442 // C99 6.5.8p3 / C99 6.5.9p4
12443 QualType Type =
12445 if (LHS.isInvalid() || RHS.isInvalid())
12446 return QualType();
12447 if (Type.isNull()) {
12448 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12449 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12450 return ResultTy;
12451 }
12452 assert(Type->isArithmeticType() || Type->isEnumeralType());
12453
12455 return S.InvalidOperands(Loc, LHS, RHS);
12456
12457 // Check for comparisons of floating point operands using != and ==.
12459 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12460
12461 // The result of comparisons is 'bool' in C++, 'int' in C.
12463}
12464
12466 if (!NullE.get()->getType()->isAnyPointerType())
12467 return;
12468 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12469 if (!E.get()->getType()->isAnyPointerType() &&
12473 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12474 if (CL->getValue() == 0)
12475 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12476 << NullValue
12478 NullValue ? "NULL" : "(void *)0");
12479 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12480 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12482 if (T == Context.CharTy)
12483 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12484 << NullValue
12486 NullValue ? "NULL" : "(void *)0");
12487 }
12488 }
12489}
12490
12491// C99 6.5.8, C++ [expr.rel]
12494 BinaryOperatorKind Opc) {
12495 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12496 bool IsThreeWay = Opc == BO_Cmp;
12497 bool IsOrdered = IsRelational || IsThreeWay;
12498 auto IsAnyPointerType = [](ExprResult E) {
12499 QualType Ty = E.get()->getType();
12500 return Ty->isPointerType() || Ty->isMemberPointerType();
12501 };
12502
12503 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12504 // type, array-to-pointer, ..., conversions are performed on both operands to
12505 // bring them to their composite type.
12506 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12507 // any type-related checks.
12508 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12510 if (LHS.isInvalid())
12511 return QualType();
12513 if (RHS.isInvalid())
12514 return QualType();
12515 } else {
12516 LHS = DefaultLvalueConversion(LHS.get());
12517 if (LHS.isInvalid())
12518 return QualType();
12519 RHS = DefaultLvalueConversion(RHS.get());
12520 if (RHS.isInvalid())
12521 return QualType();
12522 }
12523
12524 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12528 }
12529
12530 // Handle vector comparisons separately.
12531 if (LHS.get()->getType()->isVectorType() ||
12532 RHS.get()->getType()->isVectorType())
12533 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12534
12535 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12536 RHS.get()->getType()->isSveVLSBuiltinType())
12537 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12538
12539 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12540 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12541
12542 QualType LHSType = LHS.get()->getType();
12543 QualType RHSType = RHS.get()->getType();
12544 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12545 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12546 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12547
12548 if ((LHSType->isPointerType() &&
12550 (RHSType->isPointerType() &&
12552 return InvalidOperands(Loc, LHS, RHS);
12553
12554 const Expr::NullPointerConstantKind LHSNullKind =
12556 const Expr::NullPointerConstantKind RHSNullKind =
12558 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12559 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12560
12561 auto computeResultTy = [&]() {
12562 if (Opc != BO_Cmp)
12564 assert(getLangOpts().CPlusPlus);
12565 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12566
12567 QualType CompositeTy = LHS.get()->getType();
12568 assert(!CompositeTy->isReferenceType());
12569
12570 std::optional<ComparisonCategoryType> CCT =
12572 if (!CCT)
12573 return InvalidOperands(Loc, LHS, RHS);
12574
12575 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12576 // P0946R0: Comparisons between a null pointer constant and an object
12577 // pointer result in std::strong_equality, which is ill-formed under
12578 // P1959R0.
12579 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12580 << (LHSIsNull ? LHS.get()->getSourceRange()
12581 : RHS.get()->getSourceRange());
12582 return QualType();
12583 }
12584
12587 };
12588
12589 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12590 bool IsEquality = Opc == BO_EQ;
12591 if (RHSIsNull)
12592 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12593 RHS.get()->getSourceRange());
12594 else
12595 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12596 LHS.get()->getSourceRange());
12597 }
12598
12599 if (IsOrdered && LHSType->isFunctionPointerType() &&
12600 RHSType->isFunctionPointerType()) {
12601 // Valid unless a relational comparison of function pointers
12602 bool IsError = Opc == BO_Cmp;
12603 auto DiagID =
12604 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12605 : getLangOpts().CPlusPlus
12606 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12607 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12608 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12609 << RHS.get()->getSourceRange();
12610 if (IsError)
12611 return QualType();
12612 }
12613
12614 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12615 (RHSType->isIntegerType() && !RHSIsNull)) {
12616 // Skip normal pointer conversion checks in this case; we have better
12617 // diagnostics for this below.
12618 } else if (getLangOpts().CPlusPlus) {
12619 // Equality comparison of a function pointer to a void pointer is invalid,
12620 // but we allow it as an extension.
12621 // FIXME: If we really want to allow this, should it be part of composite
12622 // pointer type computation so it works in conditionals too?
12623 if (!IsOrdered &&
12624 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12625 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12626 // This is a gcc extension compatibility comparison.
12627 // In a SFINAE context, we treat this as a hard error to maintain
12628 // conformance with the C++ standard.
12630 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12631
12632 if (isSFINAEContext())
12633 return QualType();
12634
12635 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12636 return computeResultTy();
12637 }
12638
12639 // C++ [expr.eq]p2:
12640 // If at least one operand is a pointer [...] bring them to their
12641 // composite pointer type.
12642 // C++ [expr.spaceship]p6
12643 // If at least one of the operands is of pointer type, [...] bring them
12644 // to their composite pointer type.
12645 // C++ [expr.rel]p2:
12646 // If both operands are pointers, [...] bring them to their composite
12647 // pointer type.
12648 // For <=>, the only valid non-pointer types are arrays and functions, and
12649 // we already decayed those, so this is really the same as the relational
12650 // comparison rule.
12651 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12652 (IsOrdered ? 2 : 1) &&
12653 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12654 RHSType->isObjCObjectPointerType()))) {
12655 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12656 return QualType();
12657 return computeResultTy();
12658 }
12659 } else if (LHSType->isPointerType() &&
12660 RHSType->isPointerType()) { // C99 6.5.8p2
12661 // All of the following pointer-related warnings are GCC extensions, except
12662 // when handling null pointer constants.
12663 QualType LCanPointeeTy =
12665 QualType RCanPointeeTy =
12667
12668 // C99 6.5.9p2 and C99 6.5.8p2
12669 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12670 RCanPointeeTy.getUnqualifiedType())) {
12671 if (IsRelational) {
12672 // Pointers both need to point to complete or incomplete types
12673 if ((LCanPointeeTy->isIncompleteType() !=
12674 RCanPointeeTy->isIncompleteType()) &&
12675 !getLangOpts().C11) {
12676 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12678 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12679 << RCanPointeeTy->isIncompleteType();
12680 }
12681 }
12682 } else if (!IsRelational &&
12683 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12684 // Valid unless comparison between non-null pointer and function pointer
12685 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12686 && !LHSIsNull && !RHSIsNull)
12688 /*isError*/false);
12689 } else {
12690 // Invalid
12691 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12692 }
12693 if (LCanPointeeTy != RCanPointeeTy) {
12694 // Treat NULL constant as a special case in OpenCL.
12695 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12696 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12697 getASTContext())) {
12698 Diag(Loc,
12699 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12700 << LHSType << RHSType << 0 /* comparison */
12701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12702 }
12703 }
12704 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12705 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12706 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12707 : CK_BitCast;
12708
12709 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12710 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12711 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12712 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12713 bool ChangingCFIUncheckedCallee =
12714 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12715
12716 if (LHSIsNull && !RHSIsNull)
12717 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12718 else if (!ChangingCFIUncheckedCallee)
12719 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12720 }
12721 return computeResultTy();
12722 }
12723
12724
12725 // C++ [expr.eq]p4:
12726 // Two operands of type std::nullptr_t or one operand of type
12727 // std::nullptr_t and the other a null pointer constant compare
12728 // equal.
12729 // C23 6.5.9p5:
12730 // If both operands have type nullptr_t or one operand has type nullptr_t
12731 // and the other is a null pointer constant, they compare equal if the
12732 // former is a null pointer.
12733 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12734 if (LHSType->isNullPtrType()) {
12735 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12736 return computeResultTy();
12737 }
12738 if (RHSType->isNullPtrType()) {
12739 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12740 return computeResultTy();
12741 }
12742 }
12743
12744 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12745 // C23 6.5.9p6:
12746 // Otherwise, at least one operand is a pointer. If one is a pointer and
12747 // the other is a null pointer constant or has type nullptr_t, they
12748 // compare equal
12749 if (LHSIsNull && RHSType->isPointerType()) {
12750 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12751 return computeResultTy();
12752 }
12753 if (RHSIsNull && LHSType->isPointerType()) {
12754 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12755 return computeResultTy();
12756 }
12757 }
12758
12759 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12760 // These aren't covered by the composite pointer type rules.
12761 if (!IsOrdered && RHSType->isNullPtrType() &&
12762 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12763 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12764 return computeResultTy();
12765 }
12766 if (!IsOrdered && LHSType->isNullPtrType() &&
12767 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12768 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12769 return computeResultTy();
12770 }
12771
12772 if (getLangOpts().CPlusPlus) {
12773 if (IsRelational &&
12774 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12775 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12776 // HACK: Relational comparison of nullptr_t against a pointer type is
12777 // invalid per DR583, but we allow it within std::less<> and friends,
12778 // since otherwise common uses of it break.
12779 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12780 // friends to have std::nullptr_t overload candidates.
12781 DeclContext *DC = CurContext;
12782 if (isa<FunctionDecl>(DC))
12783 DC = DC->getParent();
12784 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12785 if (CTSD->isInStdNamespace() &&
12786 llvm::StringSwitch<bool>(CTSD->getName())
12787 .Cases("less", "less_equal", "greater", "greater_equal", true)
12788 .Default(false)) {
12789 if (RHSType->isNullPtrType())
12790 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12791 else
12792 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12793 return computeResultTy();
12794 }
12795 }
12796 }
12797
12798 // C++ [expr.eq]p2:
12799 // If at least one operand is a pointer to member, [...] bring them to
12800 // their composite pointer type.
12801 if (!IsOrdered &&
12802 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12803 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12804 return QualType();
12805 else
12806 return computeResultTy();
12807 }
12808 }
12809
12810 // Handle block pointer types.
12811 if (!IsOrdered && LHSType->isBlockPointerType() &&
12812 RHSType->isBlockPointerType()) {
12813 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12814 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12815
12816 if (!LHSIsNull && !RHSIsNull &&
12817 !Context.typesAreCompatible(lpointee, rpointee)) {
12818 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12819 << LHSType << RHSType << LHS.get()->getSourceRange()
12820 << RHS.get()->getSourceRange();
12821 }
12822 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12823 return computeResultTy();
12824 }
12825
12826 // Allow block pointers to be compared with null pointer constants.
12827 if (!IsOrdered
12828 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12829 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12830 if (!LHSIsNull && !RHSIsNull) {
12831 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12833 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12834 ->getPointeeType()->isVoidType())))
12835 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12836 << LHSType << RHSType << LHS.get()->getSourceRange()
12837 << RHS.get()->getSourceRange();
12838 }
12839 if (LHSIsNull && !RHSIsNull)
12840 LHS = ImpCastExprToType(LHS.get(), RHSType,
12841 RHSType->isPointerType() ? CK_BitCast
12842 : CK_AnyPointerToBlockPointerCast);
12843 else
12844 RHS = ImpCastExprToType(RHS.get(), LHSType,
12845 LHSType->isPointerType() ? CK_BitCast
12846 : CK_AnyPointerToBlockPointerCast);
12847 return computeResultTy();
12848 }
12849
12850 if (LHSType->isObjCObjectPointerType() ||
12851 RHSType->isObjCObjectPointerType()) {
12852 const PointerType *LPT = LHSType->getAs<PointerType>();
12853 const PointerType *RPT = RHSType->getAs<PointerType>();
12854 if (LPT || RPT) {
12855 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12856 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12857
12858 if (!LPtrToVoid && !RPtrToVoid &&
12859 !Context.typesAreCompatible(LHSType, RHSType)) {
12860 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12861 /*isError*/false);
12862 }
12863 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12864 // the RHS, but we have test coverage for this behavior.
12865 // FIXME: Consider using convertPointersToCompositeType in C++.
12866 if (LHSIsNull && !RHSIsNull) {
12867 Expr *E = LHS.get();
12868 if (getLangOpts().ObjCAutoRefCount)
12869 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12871 LHS = ImpCastExprToType(E, RHSType,
12872 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12873 }
12874 else {
12875 Expr *E = RHS.get();
12876 if (getLangOpts().ObjCAutoRefCount)
12877 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12879 /*Diagnose=*/true,
12880 /*DiagnoseCFAudited=*/false, Opc);
12881 RHS = ImpCastExprToType(E, LHSType,
12882 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12883 }
12884 return computeResultTy();
12885 }
12886 if (LHSType->isObjCObjectPointerType() &&
12887 RHSType->isObjCObjectPointerType()) {
12888 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12889 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12890 /*isError*/false);
12892 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12893
12894 if (LHSIsNull && !RHSIsNull)
12895 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12896 else
12897 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12898 return computeResultTy();
12899 }
12900
12901 if (!IsOrdered && LHSType->isBlockPointerType() &&
12903 LHS = ImpCastExprToType(LHS.get(), RHSType,
12904 CK_BlockPointerToObjCPointerCast);
12905 return computeResultTy();
12906 } else if (!IsOrdered &&
12908 RHSType->isBlockPointerType()) {
12909 RHS = ImpCastExprToType(RHS.get(), LHSType,
12910 CK_BlockPointerToObjCPointerCast);
12911 return computeResultTy();
12912 }
12913 }
12914 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12915 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12916 unsigned DiagID = 0;
12917 bool isError = false;
12918 if (LangOpts.DebuggerSupport) {
12919 // Under a debugger, allow the comparison of pointers to integers,
12920 // since users tend to want to compare addresses.
12921 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12922 (RHSIsNull && RHSType->isIntegerType())) {
12923 if (IsOrdered) {
12924 isError = getLangOpts().CPlusPlus;
12925 DiagID =
12926 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12927 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12928 }
12929 } else if (getLangOpts().CPlusPlus) {
12930 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12931 isError = true;
12932 } else if (IsOrdered)
12933 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12934 else
12935 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12936
12937 if (DiagID) {
12938 Diag(Loc, DiagID)
12939 << LHSType << RHSType << LHS.get()->getSourceRange()
12940 << RHS.get()->getSourceRange();
12941 if (isError)
12942 return QualType();
12943 }
12944
12945 if (LHSType->isIntegerType())
12946 LHS = ImpCastExprToType(LHS.get(), RHSType,
12947 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12948 else
12949 RHS = ImpCastExprToType(RHS.get(), LHSType,
12950 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12951 return computeResultTy();
12952 }
12953
12954 // Handle block pointers.
12955 if (!IsOrdered && RHSIsNull
12956 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12957 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12958 return computeResultTy();
12959 }
12960 if (!IsOrdered && LHSIsNull
12961 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12962 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12963 return computeResultTy();
12964 }
12965
12966 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12967 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12968 return computeResultTy();
12969 }
12970
12971 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12972 return computeResultTy();
12973 }
12974
12975 if (LHSIsNull && RHSType->isQueueT()) {
12976 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12977 return computeResultTy();
12978 }
12979
12980 if (LHSType->isQueueT() && RHSIsNull) {
12981 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12982 return computeResultTy();
12983 }
12984 }
12985
12986 return InvalidOperands(Loc, LHS, RHS);
12987}
12988
12990 const VectorType *VTy = V->castAs<VectorType>();
12991 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12992
12993 if (isa<ExtVectorType>(VTy)) {
12994 if (VTy->isExtVectorBoolType())
12996 if (TypeSize == Context.getTypeSize(Context.CharTy))
12998 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13000 if (TypeSize == Context.getTypeSize(Context.IntTy))
13002 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13004 if (TypeSize == Context.getTypeSize(Context.LongTy))
13006 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13007 "Unhandled vector element size in vector compare");
13009 }
13010
13011 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13014 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13017 if (TypeSize == Context.getTypeSize(Context.LongTy))
13020 if (TypeSize == Context.getTypeSize(Context.IntTy))
13023 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13026 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13027 "Unhandled vector element size in vector compare");
13030}
13031
13033 const BuiltinType *VTy = V->castAs<BuiltinType>();
13034 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13035
13036 const QualType ETy = V->getSveEltType(Context);
13037 const auto TypeSize = Context.getTypeSize(ETy);
13038
13039 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13040 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13041 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13042}
13043
13046 BinaryOperatorKind Opc) {
13047 if (Opc == BO_Cmp) {
13048 Diag(Loc, diag::err_three_way_vector_comparison);
13049 return QualType();
13050 }
13051
13052 // Check to make sure we're operating on vectors of the same type and width,
13053 // Allowing one side to be a scalar of element type.
13054 QualType vType =
13055 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13056 /*AllowBothBool*/ true,
13057 /*AllowBoolConversions*/ getLangOpts().ZVector,
13058 /*AllowBooleanOperation*/ true,
13059 /*ReportInvalid*/ true);
13060 if (vType.isNull())
13061 return vType;
13062
13063 QualType LHSType = LHS.get()->getType();
13064
13065 // Determine the return type of a vector compare. By default clang will return
13066 // a scalar for all vector compares except vector bool and vector pixel.
13067 // With the gcc compiler we will always return a vector type and with the xl
13068 // compiler we will always return a scalar type. This switch allows choosing
13069 // which behavior is prefered.
13070 if (getLangOpts().AltiVec) {
13071 switch (getLangOpts().getAltivecSrcCompat()) {
13073 // If AltiVec, the comparison results in a numeric type, i.e.
13074 // bool for C++, int for C
13075 if (vType->castAs<VectorType>()->getVectorKind() ==
13078 else
13079 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13080 break;
13082 // For GCC we always return the vector type.
13083 break;
13086 break;
13087 }
13088 }
13089
13090 // For non-floating point types, check for self-comparisons of the form
13091 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13092 // often indicate logic errors in the program.
13093 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13094
13095 // Check for comparisons of floating point operands using != and ==.
13096 if (LHSType->hasFloatingRepresentation()) {
13097 assert(RHS.get()->getType()->hasFloatingRepresentation());
13098 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13099 }
13100
13101 // Return a signed type for the vector.
13102 return GetSignedVectorType(vType);
13103}
13104
13106 ExprResult &RHS,
13108 BinaryOperatorKind Opc) {
13109 if (Opc == BO_Cmp) {
13110 Diag(Loc, diag::err_three_way_vector_comparison);
13111 return QualType();
13112 }
13113
13114 // Check to make sure we're operating on vectors of the same type and width,
13115 // Allowing one side to be a scalar of element type.
13117 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13118
13119 if (vType.isNull())
13120 return vType;
13121
13122 QualType LHSType = LHS.get()->getType();
13123
13124 // For non-floating point types, check for self-comparisons of the form
13125 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13126 // often indicate logic errors in the program.
13127 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13128
13129 // Check for comparisons of floating point operands using != and ==.
13130 if (LHSType->hasFloatingRepresentation()) {
13131 assert(RHS.get()->getType()->hasFloatingRepresentation());
13132 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13133 }
13134
13135 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13136 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13137
13138 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13139 RHSBuiltinTy->isSVEBool())
13140 return LHSType;
13141
13142 // Return a signed type for the vector.
13143 return GetSignedSizelessVectorType(vType);
13144}
13145
13146static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13147 const ExprResult &XorRHS,
13148 const SourceLocation Loc) {
13149 // Do not diagnose macros.
13150 if (Loc.isMacroID())
13151 return;
13152
13153 // Do not diagnose if both LHS and RHS are macros.
13154 if (XorLHS.get()->getExprLoc().isMacroID() &&
13155 XorRHS.get()->getExprLoc().isMacroID())
13156 return;
13157
13158 bool Negative = false;
13159 bool ExplicitPlus = false;
13160 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13161 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13162
13163 if (!LHSInt)
13164 return;
13165 if (!RHSInt) {
13166 // Check negative literals.
13167 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13168 UnaryOperatorKind Opc = UO->getOpcode();
13169 if (Opc != UO_Minus && Opc != UO_Plus)
13170 return;
13171 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13172 if (!RHSInt)
13173 return;
13174 Negative = (Opc == UO_Minus);
13175 ExplicitPlus = !Negative;
13176 } else {
13177 return;
13178 }
13179 }
13180
13181 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13182 llvm::APInt RightSideValue = RHSInt->getValue();
13183 if (LeftSideValue != 2 && LeftSideValue != 10)
13184 return;
13185
13186 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13187 return;
13188
13190 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13191 llvm::StringRef ExprStr =
13193
13194 CharSourceRange XorRange =
13196 llvm::StringRef XorStr =
13198 // Do not diagnose if xor keyword/macro is used.
13199 if (XorStr == "xor")
13200 return;
13201
13202 std::string LHSStr = std::string(Lexer::getSourceText(
13203 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13204 S.getSourceManager(), S.getLangOpts()));
13205 std::string RHSStr = std::string(Lexer::getSourceText(
13206 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13207 S.getSourceManager(), S.getLangOpts()));
13208
13209 if (Negative) {
13210 RightSideValue = -RightSideValue;
13211 RHSStr = "-" + RHSStr;
13212 } else if (ExplicitPlus) {
13213 RHSStr = "+" + RHSStr;
13214 }
13215
13216 StringRef LHSStrRef = LHSStr;
13217 StringRef RHSStrRef = RHSStr;
13218 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13219 // literals.
13220 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13221 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13222 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13223 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13224 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13225 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13226 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13227 return;
13228
13229 bool SuggestXor =
13230 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13231 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13232 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13233 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13234 std::string SuggestedExpr = "1 << " + RHSStr;
13235 bool Overflow = false;
13236 llvm::APInt One = (LeftSideValue - 1);
13237 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13238 if (Overflow) {
13239 if (RightSideIntValue < 64)
13240 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13241 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13242 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13243 else if (RightSideIntValue == 64)
13244 S.Diag(Loc, diag::warn_xor_used_as_pow)
13245 << ExprStr << toString(XorValue, 10, true);
13246 else
13247 return;
13248 } else {
13249 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13250 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13251 << toString(PowValue, 10, true)
13253 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13254 }
13255
13256 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13257 << ("0x2 ^ " + RHSStr) << SuggestXor;
13258 } else if (LeftSideValue == 10) {
13259 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13260 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13261 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13262 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13263 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13264 << ("0xA ^ " + RHSStr) << SuggestXor;
13265 }
13266}
13267
13270 BinaryOperatorKind Opc) {
13271 // Ensure that either both operands are of the same vector type, or
13272 // one operand is of a vector type and the other is of its element type.
13273 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13274 /*AllowBothBool*/ true,
13275 /*AllowBoolConversions*/ false,
13276 /*AllowBooleanOperation*/ false,
13277 /*ReportInvalid*/ false);
13278 if (vType.isNull())
13279 return InvalidOperands(Loc, LHS, RHS);
13280 if (getLangOpts().OpenCL &&
13281 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13283 return InvalidOperands(Loc, LHS, RHS);
13284 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13285 // usage of the logical operators && and || with vectors in C. This
13286 // check could be notionally dropped.
13287 if (!getLangOpts().CPlusPlus &&
13288 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13289 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13290 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13291 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13292 // `select` functions.
13293 if (getLangOpts().HLSL &&
13294 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13295 (void)InvalidOperands(Loc, LHS, RHS);
13296 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13297 return QualType();
13298 }
13299
13300 return GetSignedVectorType(LHS.get()->getType());
13301}
13302
13305 bool IsCompAssign) {
13306 if (!IsCompAssign) {
13308 if (LHS.isInvalid())
13309 return QualType();
13310 }
13312 if (RHS.isInvalid())
13313 return QualType();
13314
13315 // For conversion purposes, we ignore any qualifiers.
13316 // For example, "const float" and "float" are equivalent.
13317 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13318 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13319
13320 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13321 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13322 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13323
13324 if (Context.hasSameType(LHSType, RHSType))
13325 return Context.getCommonSugaredType(LHSType, RHSType);
13326
13327 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13328 // case we have to return InvalidOperands.
13329 ExprResult OriginalLHS = LHS;
13330 ExprResult OriginalRHS = RHS;
13331 if (LHSMatType && !RHSMatType) {
13332 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13333 if (!RHS.isInvalid())
13334 return LHSType;
13335
13336 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13337 }
13338
13339 if (!LHSMatType && RHSMatType) {
13340 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13341 if (!LHS.isInvalid())
13342 return RHSType;
13343 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13344 }
13345
13346 return InvalidOperands(Loc, LHS, RHS);
13347}
13348
13351 bool IsCompAssign) {
13352 if (!IsCompAssign) {
13354 if (LHS.isInvalid())
13355 return QualType();
13356 }
13358 if (RHS.isInvalid())
13359 return QualType();
13360
13361 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13362 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13363 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13364
13365 if (LHSMatType && RHSMatType) {
13366 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13367 return InvalidOperands(Loc, LHS, RHS);
13368
13369 if (Context.hasSameType(LHSMatType, RHSMatType))
13371 LHS.get()->getType().getUnqualifiedType(),
13372 RHS.get()->getType().getUnqualifiedType());
13373
13374 QualType LHSELTy = LHSMatType->getElementType(),
13375 RHSELTy = RHSMatType->getElementType();
13376 if (!Context.hasSameType(LHSELTy, RHSELTy))
13377 return InvalidOperands(Loc, LHS, RHS);
13378
13380 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13381 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13382 }
13383 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13384}
13385
13387 switch (Opc) {
13388 default:
13389 return false;
13390 case BO_And:
13391 case BO_AndAssign:
13392 case BO_Or:
13393 case BO_OrAssign:
13394 case BO_Xor:
13395 case BO_XorAssign:
13396 return true;
13397 }
13398}
13399
13402 BinaryOperatorKind Opc) {
13403 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13404
13405 bool IsCompAssign =
13406 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13407
13408 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13409
13410 if (LHS.get()->getType()->isVectorType() ||
13411 RHS.get()->getType()->isVectorType()) {
13412 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13414 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13415 /*AllowBothBool*/ true,
13416 /*AllowBoolConversions*/ getLangOpts().ZVector,
13417 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13418 /*ReportInvalid*/ true);
13419 return InvalidOperands(Loc, LHS, RHS);
13420 }
13421
13422 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13423 RHS.get()->getType()->isSveVLSBuiltinType()) {
13424 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13426 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13428 return InvalidOperands(Loc, LHS, RHS);
13429 }
13430
13431 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13432 RHS.get()->getType()->isSveVLSBuiltinType()) {
13433 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13435 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13437 return InvalidOperands(Loc, LHS, RHS);
13438 }
13439
13440 if (Opc == BO_And)
13441 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13442
13443 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13445 return InvalidOperands(Loc, LHS, RHS);
13446
13447 ExprResult LHSResult = LHS, RHSResult = RHS;
13449 LHSResult, RHSResult, Loc,
13451 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13452 return QualType();
13453 LHS = LHSResult.get();
13454 RHS = RHSResult.get();
13455
13456 if (Opc == BO_Xor)
13457 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13458
13459 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13460 return compType;
13461 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13462 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13463 return ResultTy;
13464}
13465
13466// C99 6.5.[13,14]
13469 BinaryOperatorKind Opc) {
13470 // Check vector operands differently.
13471 if (LHS.get()->getType()->isVectorType() ||
13472 RHS.get()->getType()->isVectorType())
13473 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13474
13475 bool EnumConstantInBoolContext = false;
13476 for (const ExprResult &HS : {LHS, RHS}) {
13477 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13478 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13479 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13480 EnumConstantInBoolContext = true;
13481 }
13482 }
13483
13484 if (EnumConstantInBoolContext)
13485 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13486
13487 // WebAssembly tables can't be used with logical operators.
13488 QualType LHSTy = LHS.get()->getType();
13489 QualType RHSTy = RHS.get()->getType();
13490 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13491 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13492 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13493 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13494 return InvalidOperands(Loc, LHS, RHS);
13495 }
13496
13497 // Diagnose cases where the user write a logical and/or but probably meant a
13498 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13499 // is a constant.
13500 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13501 !LHS.get()->getType()->isBooleanType() &&
13502 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13503 // Don't warn in macros or template instantiations.
13505 // If the RHS can be constant folded, and if it constant folds to something
13506 // that isn't 0 or 1 (which indicate a potential logical operation that
13507 // happened to fold to true/false) then warn.
13508 // Parens on the RHS are ignored.
13509 Expr::EvalResult EVResult;
13510 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13511 llvm::APSInt Result = EVResult.Val.getInt();
13512 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13513 !RHS.get()->getExprLoc().isMacroID()) ||
13514 (Result != 0 && Result != 1)) {
13515 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13516 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13517 // Suggest replacing the logical operator with the bitwise version
13518 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13519 << (Opc == BO_LAnd ? "&" : "|")
13522 Opc == BO_LAnd ? "&" : "|");
13523 if (Opc == BO_LAnd)
13524 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13525 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13528 RHS.get()->getEndLoc()));
13529 }
13530 }
13531 }
13532
13533 if (!Context.getLangOpts().CPlusPlus) {
13534 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13535 // not operate on the built-in scalar and vector float types.
13536 if (Context.getLangOpts().OpenCL &&
13537 Context.getLangOpts().OpenCLVersion < 120) {
13538 if (LHS.get()->getType()->isFloatingType() ||
13539 RHS.get()->getType()->isFloatingType())
13540 return InvalidOperands(Loc, LHS, RHS);
13541 }
13542
13543 LHS = UsualUnaryConversions(LHS.get());
13544 if (LHS.isInvalid())
13545 return QualType();
13546
13547 RHS = UsualUnaryConversions(RHS.get());
13548 if (RHS.isInvalid())
13549 return QualType();
13550
13551 if (!LHS.get()->getType()->isScalarType() ||
13552 !RHS.get()->getType()->isScalarType())
13553 return InvalidOperands(Loc, LHS, RHS);
13554
13555 return Context.IntTy;
13556 }
13557
13558 // The following is safe because we only use this method for
13559 // non-overloadable operands.
13560
13561 // C++ [expr.log.and]p1
13562 // C++ [expr.log.or]p1
13563 // The operands are both contextually converted to type bool.
13565 if (LHSRes.isInvalid()) {
13566 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13567 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13568 return ResultTy;
13569 }
13570 LHS = LHSRes;
13571
13573 if (RHSRes.isInvalid()) {
13574 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13575 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13576 return ResultTy;
13577 }
13578 RHS = RHSRes;
13579
13580 // C++ [expr.log.and]p2
13581 // C++ [expr.log.or]p2
13582 // The result is a bool.
13583 return Context.BoolTy;
13584}
13585
13586static bool IsReadonlyMessage(Expr *E, Sema &S) {
13587 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13588 if (!ME) return false;
13589 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13590 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13592 if (!Base) return false;
13593 return Base->getMethodDecl() != nullptr;
13594}
13595
13596/// Is the given expression (which must be 'const') a reference to a
13597/// variable which was originally non-const, but which has become
13598/// 'const' due to being captured within a block?
13601 assert(E->isLValue() && E->getType().isConstQualified());
13602 E = E->IgnoreParens();
13603
13604 // Must be a reference to a declaration from an enclosing scope.
13605 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13606 if (!DRE) return NCCK_None;
13608
13609 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13610
13611 // The declaration must be a value which is not declared 'const'.
13612 if (!Value || Value->getType().isConstQualified())
13613 return NCCK_None;
13614
13615 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13616 if (Binding) {
13617 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13618 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13619 return NCCK_Lambda;
13620 }
13621
13622 VarDecl *Var = dyn_cast<VarDecl>(Value);
13623 if (!Var)
13624 return NCCK_None;
13625 if (Var->getType()->isReferenceType())
13626 return NCCK_None;
13627
13628 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13629
13630 // Decide whether the first capture was for a block or a lambda.
13631 DeclContext *DC = S.CurContext, *Prev = nullptr;
13632 // Decide whether the first capture was for a block or a lambda.
13633 while (DC) {
13634 // For init-capture, it is possible that the variable belongs to the
13635 // template pattern of the current context.
13636 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13637 if (Var->isInitCapture() &&
13638 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13639 break;
13640 if (DC == Var->getDeclContext())
13641 break;
13642 Prev = DC;
13643 DC = DC->getParent();
13644 }
13645 // Unless we have an init-capture, we've gone one step too far.
13646 if (!Var->isInitCapture())
13647 DC = Prev;
13648 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13649}
13650
13651static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13652 Ty = Ty.getNonReferenceType();
13653 if (IsDereference && Ty->isPointerType())
13654 Ty = Ty->getPointeeType();
13655 return !Ty.isConstQualified();
13656}
13657
13658// Update err_typecheck_assign_const and note_typecheck_assign_const
13659// when this enum is changed.
13660enum {
13666 ConstUnknown, // Keep as last element
13667};
13668
13669/// Emit the "read-only variable not assignable" error and print notes to give
13670/// more information about why the variable is not assignable, such as pointing
13671/// to the declaration of a const variable, showing that a method is const, or
13672/// that the function is returning a const reference.
13673static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13675 SourceRange ExprRange = E->getSourceRange();
13676
13677 // Only emit one error on the first const found. All other consts will emit
13678 // a note to the error.
13679 bool DiagnosticEmitted = false;
13680
13681 // Track if the current expression is the result of a dereference, and if the
13682 // next checked expression is the result of a dereference.
13683 bool IsDereference = false;
13684 bool NextIsDereference = false;
13685
13686 // Loop to process MemberExpr chains.
13687 while (true) {
13688 IsDereference = NextIsDereference;
13689
13691 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13692 NextIsDereference = ME->isArrow();
13693 const ValueDecl *VD = ME->getMemberDecl();
13694 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13695 // Mutable fields can be modified even if the class is const.
13696 if (Field->isMutable()) {
13697 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13698 break;
13699 }
13700
13701 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13702 if (!DiagnosticEmitted) {
13703 S.Diag(Loc, diag::err_typecheck_assign_const)
13704 << ExprRange << ConstMember << false /*static*/ << Field
13705 << Field->getType();
13706 DiagnosticEmitted = true;
13707 }
13708 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13709 << ConstMember << false /*static*/ << Field << Field->getType()
13710 << Field->getSourceRange();
13711 }
13712 E = ME->getBase();
13713 continue;
13714 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13715 if (VDecl->getType().isConstQualified()) {
13716 if (!DiagnosticEmitted) {
13717 S.Diag(Loc, diag::err_typecheck_assign_const)
13718 << ExprRange << ConstMember << true /*static*/ << VDecl
13719 << VDecl->getType();
13720 DiagnosticEmitted = true;
13721 }
13722 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13723 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13724 << VDecl->getSourceRange();
13725 }
13726 // Static fields do not inherit constness from parents.
13727 break;
13728 }
13729 break; // End MemberExpr
13730 } else if (const ArraySubscriptExpr *ASE =
13731 dyn_cast<ArraySubscriptExpr>(E)) {
13732 E = ASE->getBase()->IgnoreParenImpCasts();
13733 continue;
13734 } else if (const ExtVectorElementExpr *EVE =
13735 dyn_cast<ExtVectorElementExpr>(E)) {
13736 E = EVE->getBase()->IgnoreParenImpCasts();
13737 continue;
13738 }
13739 break;
13740 }
13741
13742 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13743 // Function calls
13744 const FunctionDecl *FD = CE->getDirectCallee();
13745 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13746 if (!DiagnosticEmitted) {
13747 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13748 << ConstFunction << FD;
13749 DiagnosticEmitted = true;
13750 }
13752 diag::note_typecheck_assign_const)
13753 << ConstFunction << FD << FD->getReturnType()
13754 << FD->getReturnTypeSourceRange();
13755 }
13756 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13757 // Point to variable declaration.
13758 if (const ValueDecl *VD = DRE->getDecl()) {
13759 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13760 if (!DiagnosticEmitted) {
13761 S.Diag(Loc, diag::err_typecheck_assign_const)
13762 << ExprRange << ConstVariable << VD << VD->getType();
13763 DiagnosticEmitted = true;
13764 }
13765 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13766 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13767 }
13768 }
13769 } else if (isa<CXXThisExpr>(E)) {
13770 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13771 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13772 if (MD->isConst()) {
13773 if (!DiagnosticEmitted) {
13774 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13775 << ConstMethod << MD;
13776 DiagnosticEmitted = true;
13777 }
13778 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13779 << ConstMethod << MD << MD->getSourceRange();
13780 }
13781 }
13782 }
13783 }
13784
13785 if (DiagnosticEmitted)
13786 return;
13787
13788 // Can't determine a more specific message, so display the generic error.
13789 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13790}
13791
13797
13799 const RecordType *Ty,
13801 OriginalExprKind OEK,
13802 bool &DiagnosticEmitted) {
13803 std::vector<const RecordType *> RecordTypeList;
13804 RecordTypeList.push_back(Ty);
13805 unsigned NextToCheckIndex = 0;
13806 // We walk the record hierarchy breadth-first to ensure that we print
13807 // diagnostics in field nesting order.
13808 while (RecordTypeList.size() > NextToCheckIndex) {
13809 bool IsNested = NextToCheckIndex > 0;
13810 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13811 ->getOriginalDecl()
13813 ->fields()) {
13814 // First, check every field for constness.
13815 QualType FieldTy = Field->getType();
13816 if (FieldTy.isConstQualified()) {
13817 if (!DiagnosticEmitted) {
13818 S.Diag(Loc, diag::err_typecheck_assign_const)
13819 << Range << NestedConstMember << OEK << VD
13820 << IsNested << Field;
13821 DiagnosticEmitted = true;
13822 }
13823 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13824 << NestedConstMember << IsNested << Field
13825 << FieldTy << Field->getSourceRange();
13826 }
13827
13828 // Then we append it to the list to check next in order.
13829 FieldTy = FieldTy.getCanonicalType();
13830 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
13831 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13832 RecordTypeList.push_back(FieldRecTy);
13833 }
13834 }
13835 ++NextToCheckIndex;
13836 }
13837}
13838
13839/// Emit an error for the case where a record we are trying to assign to has a
13840/// const-qualified field somewhere in its hierarchy.
13843 QualType Ty = E->getType();
13844 assert(Ty->isRecordType() && "lvalue was not record?");
13846 const auto *RTy = Ty->getAsCanonical<RecordType>();
13847 bool DiagEmitted = false;
13848
13849 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13850 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13851 Range, OEK_Member, DiagEmitted);
13852 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13853 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13854 Range, OEK_Variable, DiagEmitted);
13855 else
13856 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13857 Range, OEK_LValue, DiagEmitted);
13858 if (!DiagEmitted)
13860}
13861
13862/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13863/// emit an error and return true. If so, return false.
13865 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13866
13868
13869 SourceLocation OrigLoc = Loc;
13871 &Loc);
13872 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13874 if (IsLV == Expr::MLV_Valid)
13875 return false;
13876
13877 unsigned DiagID = 0;
13878 bool NeedType = false;
13879 switch (IsLV) { // C99 6.5.16p2
13881 // Use a specialized diagnostic when we're assigning to an object
13882 // from an enclosing function or block.
13884 if (NCCK == NCCK_Block)
13885 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13886 else
13887 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13888 break;
13889 }
13890
13891 // In ARC, use some specialized diagnostics for occasions where we
13892 // infer 'const'. These are always pseudo-strong variables.
13893 if (S.getLangOpts().ObjCAutoRefCount) {
13894 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13895 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13896 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13897
13898 // Use the normal diagnostic if it's pseudo-__strong but the
13899 // user actually wrote 'const'.
13900 if (var->isARCPseudoStrong() &&
13901 (!var->getTypeSourceInfo() ||
13902 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13903 // There are three pseudo-strong cases:
13904 // - self
13905 ObjCMethodDecl *method = S.getCurMethodDecl();
13906 if (method && var == method->getSelfDecl()) {
13907 DiagID = method->isClassMethod()
13908 ? diag::err_typecheck_arc_assign_self_class_method
13909 : diag::err_typecheck_arc_assign_self;
13910
13911 // - Objective-C externally_retained attribute.
13912 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13913 isa<ParmVarDecl>(var)) {
13914 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13915
13916 // - fast enumeration variables
13917 } else {
13918 DiagID = diag::err_typecheck_arr_assign_enumeration;
13919 }
13920
13921 SourceRange Assign;
13922 if (Loc != OrigLoc)
13923 Assign = SourceRange(OrigLoc, OrigLoc);
13924 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13925 // We need to preserve the AST regardless, so migration tool
13926 // can do its job.
13927 return false;
13928 }
13929 }
13930 }
13931
13932 // If none of the special cases above are triggered, then this is a
13933 // simple const assignment.
13934 if (DiagID == 0) {
13936 return true;
13937 }
13938
13939 break;
13942 return true;
13945 return true;
13948 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13949 NeedType = true;
13950 break;
13952 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13953 NeedType = true;
13954 break;
13956 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13957 break;
13958 case Expr::MLV_Valid:
13959 llvm_unreachable("did not take early return for MLV_Valid");
13963 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13964 break;
13967 return S.RequireCompleteType(Loc, E->getType(),
13968 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13970 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13971 break;
13973 llvm_unreachable("readonly properties should be processed differently");
13975 DiagID = diag::err_readonly_message_assignment;
13976 break;
13978 DiagID = diag::err_no_subobject_property_setting;
13979 break;
13980 }
13981
13982 SourceRange Assign;
13983 if (Loc != OrigLoc)
13984 Assign = SourceRange(OrigLoc, OrigLoc);
13985 if (NeedType)
13986 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13987 else
13988 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13989 return true;
13990}
13991
13992static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13994 Sema &Sema) {
13996 return;
13998 return;
13999 if (Loc.isInvalid() || Loc.isMacroID())
14000 return;
14001 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14002 return;
14003
14004 // C / C++ fields
14005 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14006 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14007 if (ML && MR) {
14008 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14009 return;
14010 const ValueDecl *LHSDecl =
14011 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14012 const ValueDecl *RHSDecl =
14013 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14014 if (LHSDecl != RHSDecl)
14015 return;
14016 if (LHSDecl->getType().isVolatileQualified())
14017 return;
14018 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14019 if (RefTy->getPointeeType().isVolatileQualified())
14020 return;
14021
14022 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14023 }
14024
14025 // Objective-C instance variables
14026 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14027 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14028 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14029 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14030 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14031 if (RL && RR && RL->getDecl() == RR->getDecl())
14032 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14033 }
14034}
14035
14036// C99 6.5.16.1
14039 QualType CompoundType,
14040 BinaryOperatorKind Opc) {
14041 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14042
14043 // Verify that LHS is a modifiable lvalue, and emit error if not.
14044 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14045 return QualType();
14046
14047 QualType LHSType = LHSExpr->getType();
14048 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14049 CompoundType;
14050
14051 if (RHS.isUsable()) {
14052 // Even if this check fails don't return early to allow the best
14053 // possible error recovery and to allow any subsequent diagnostics to
14054 // work.
14055 const ValueDecl *Assignee = nullptr;
14056 bool ShowFullyQualifiedAssigneeName = false;
14057 // In simple cases describe what is being assigned to
14058 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14059 Assignee = DR->getDecl();
14060 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14061 Assignee = ME->getMemberDecl();
14062 ShowFullyQualifiedAssigneeName = true;
14063 }
14064
14066 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14067 ShowFullyQualifiedAssigneeName);
14068 }
14069
14070 // OpenCL v1.2 s6.1.1.1 p2:
14071 // The half data type can only be used to declare a pointer to a buffer that
14072 // contains half values
14073 if (getLangOpts().OpenCL &&
14074 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14075 LHSType->isHalfType()) {
14076 Diag(Loc, diag::err_opencl_half_load_store) << 1
14077 << LHSType.getUnqualifiedType();
14078 return QualType();
14079 }
14080
14081 // WebAssembly tables can't be used on RHS of an assignment expression.
14082 if (RHSType->isWebAssemblyTableType()) {
14083 Diag(Loc, diag::err_wasm_table_art) << 0;
14084 return QualType();
14085 }
14086
14087 AssignConvertType ConvTy;
14088 if (CompoundType.isNull()) {
14089 Expr *RHSCheck = RHS.get();
14090
14091 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14092
14093 QualType LHSTy(LHSType);
14094 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14095 if (RHS.isInvalid())
14096 return QualType();
14097 // Special case of NSObject attributes on c-style pointer types.
14099 ((Context.isObjCNSObjectType(LHSType) &&
14100 RHSType->isObjCObjectPointerType()) ||
14101 (Context.isObjCNSObjectType(RHSType) &&
14102 LHSType->isObjCObjectPointerType())))
14104
14105 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14106 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14107
14108 // If the RHS is a unary plus or minus, check to see if they = and + are
14109 // right next to each other. If so, the user may have typo'd "x =+ 4"
14110 // instead of "x += 4".
14111 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14112 RHSCheck = ICE->getSubExpr();
14113 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14114 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14115 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14116 // Only if the two operators are exactly adjacent.
14117 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14118 // And there is a space or other character before the subexpr of the
14119 // unary +/-. We don't want to warn on "x=-1".
14120 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14121 UO->getSubExpr()->getBeginLoc().isFileID()) {
14122 Diag(Loc, diag::warn_not_compound_assign)
14123 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14124 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14125 }
14126 }
14127
14128 if (IsAssignConvertCompatible(ConvTy)) {
14129 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14130 // Warn about retain cycles where a block captures the LHS, but
14131 // not if the LHS is a simple variable into which the block is
14132 // being stored...unless that variable can be captured by reference!
14133 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14134 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14135 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14136 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14137 }
14138
14139 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14141 // It is safe to assign a weak reference into a strong variable.
14142 // Although this code can still have problems:
14143 // id x = self.weakProp;
14144 // id y = self.weakProp;
14145 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14146 // paths through the function. This should be revisited if
14147 // -Wrepeated-use-of-weak is made flow-sensitive.
14148 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14149 // variable, which will be valid for the current autorelease scope.
14150 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14151 RHS.get()->getBeginLoc()))
14153
14154 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14155 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14156 }
14157 }
14158 } else {
14159 // Compound assignment "x += y"
14160 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14161 }
14162
14163 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14165 return QualType();
14166
14167 CheckForNullPointerDereference(*this, LHSExpr);
14168
14169 AssignedEntity AE{LHSExpr};
14170 checkAssignmentLifetime(*this, AE, RHS.get());
14171
14172 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14173 if (CompoundType.isNull()) {
14174 // C++2a [expr.ass]p5:
14175 // A simple-assignment whose left operand is of a volatile-qualified
14176 // type is deprecated unless the assignment is either a discarded-value
14177 // expression or an unevaluated operand
14178 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14179 }
14180 }
14181
14182 // C11 6.5.16p3: The type of an assignment expression is the type of the
14183 // left operand would have after lvalue conversion.
14184 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14185 // qualified type, the value has the unqualified version of the type of the
14186 // lvalue; additionally, if the lvalue has atomic type, the value has the
14187 // non-atomic version of the type of the lvalue.
14188 // C++ 5.17p1: the type of the assignment expression is that of its left
14189 // operand.
14190 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14191}
14192
14193// Scenarios to ignore if expression E is:
14194// 1. an explicit cast expression into void
14195// 2. a function call expression that returns void
14196static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14197 E = E->IgnoreParens();
14198
14199 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14200 if (CE->getCastKind() == CK_ToVoid) {
14201 return true;
14202 }
14203
14204 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14205 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14206 CE->getSubExpr()->getType()->isDependentType()) {
14207 return true;
14208 }
14209 }
14210
14211 if (const auto *CE = dyn_cast<CallExpr>(E))
14212 return CE->getCallReturnType(Context)->isVoidType();
14213 return false;
14214}
14215
14217 // No warnings in macros
14218 if (Loc.isMacroID())
14219 return;
14220
14221 // Don't warn in template instantiations.
14223 return;
14224
14225 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14226 // instead, skip more than needed, then call back into here with the
14227 // CommaVisitor in SemaStmt.cpp.
14228 // The listed locations are the initialization and increment portions
14229 // of a for loop. The additional checks are on the condition of
14230 // if statements, do/while loops, and for loops.
14231 // Differences in scope flags for C89 mode requires the extra logic.
14232 const unsigned ForIncrementFlags =
14233 getLangOpts().C99 || getLangOpts().CPlusPlus
14236 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14237 const unsigned ScopeFlags = getCurScope()->getFlags();
14238 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14239 (ScopeFlags & ForInitFlags) == ForInitFlags)
14240 return;
14241
14242 // If there are multiple comma operators used together, get the RHS of the
14243 // of the comma operator as the LHS.
14244 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14245 if (BO->getOpcode() != BO_Comma)
14246 break;
14247 LHS = BO->getRHS();
14248 }
14249
14250 // Only allow some expressions on LHS to not warn.
14251 if (IgnoreCommaOperand(LHS, Context))
14252 return;
14253
14254 Diag(Loc, diag::warn_comma_operator);
14255 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14256 << LHS->getSourceRange()
14258 LangOpts.CPlusPlus ? "static_cast<void>("
14259 : "(void)(")
14261 ")");
14262}
14263
14264// C99 6.5.17
14267 LHS = S.CheckPlaceholderExpr(LHS.get());
14268 RHS = S.CheckPlaceholderExpr(RHS.get());
14269 if (LHS.isInvalid() || RHS.isInvalid())
14270 return QualType();
14271
14272 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14273 // operands, but not unary promotions.
14274 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14275
14276 // So we treat the LHS as a ignored value, and in C++ we allow the
14277 // containing site to determine what should be done with the RHS.
14278 LHS = S.IgnoredValueConversions(LHS.get());
14279 if (LHS.isInvalid())
14280 return QualType();
14281
14282 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14283
14284 if (!S.getLangOpts().CPlusPlus) {
14286 if (RHS.isInvalid())
14287 return QualType();
14288 if (!RHS.get()->getType()->isVoidType())
14289 S.RequireCompleteType(Loc, RHS.get()->getType(),
14290 diag::err_incomplete_type);
14291 }
14292
14293 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14294 S.DiagnoseCommaOperator(LHS.get(), Loc);
14295
14296 return RHS.get()->getType();
14297}
14298
14299/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14300/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14303 ExprObjectKind &OK,
14304 SourceLocation OpLoc, bool IsInc,
14305 bool IsPrefix) {
14306 QualType ResType = Op->getType();
14307 // Atomic types can be used for increment / decrement where the non-atomic
14308 // versions can, so ignore the _Atomic() specifier for the purpose of
14309 // checking.
14310 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14311 ResType = ResAtomicType->getValueType();
14312
14313 assert(!ResType.isNull() && "no type for increment/decrement expression");
14314
14315 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14316 // Decrement of bool is not allowed.
14317 if (!IsInc) {
14318 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14319 return QualType();
14320 }
14321 // Increment of bool sets it to true, but is deprecated.
14322 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14323 : diag::warn_increment_bool)
14324 << Op->getSourceRange();
14325 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14326 // Error on enum increments and decrements in C++ mode
14327 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14328 return QualType();
14329 } else if (ResType->isRealType()) {
14330 // OK!
14331 } else if (ResType->isPointerType()) {
14332 // C99 6.5.2.4p2, 6.5.6p2
14333 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14334 return QualType();
14335 } else if (ResType->isObjCObjectPointerType()) {
14336 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14337 // Otherwise, we just need a complete type.
14338 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14339 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14340 return QualType();
14341 } else if (ResType->isAnyComplexType()) {
14342 // C99 does not support ++/-- on complex types, we allow as an extension.
14343 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14344 : diag::ext_c2y_increment_complex)
14345 << IsInc << Op->getSourceRange();
14346 } else if (ResType->isPlaceholderType()) {
14348 if (PR.isInvalid()) return QualType();
14349 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14350 IsInc, IsPrefix);
14351 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14352 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14353 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14354 (ResType->castAs<VectorType>()->getVectorKind() !=
14356 // The z vector extensions allow ++ and -- for non-bool vectors.
14357 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14358 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14359 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14360 } else {
14361 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14362 << ResType << int(IsInc) << Op->getSourceRange();
14363 return QualType();
14364 }
14365 // At this point, we know we have a real, complex or pointer type.
14366 // Now make sure the operand is a modifiable lvalue.
14367 if (CheckForModifiableLvalue(Op, OpLoc, S))
14368 return QualType();
14369 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14370 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14371 // An operand with volatile-qualified type is deprecated
14372 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14373 << IsInc << ResType;
14374 }
14375 // In C++, a prefix increment is the same type as the operand. Otherwise
14376 // (in C or with postfix), the increment is the unqualified type of the
14377 // operand.
14378 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14379 VK = VK_LValue;
14380 OK = Op->getObjectKind();
14381 return ResType;
14382 } else {
14383 VK = VK_PRValue;
14384 return ResType.getUnqualifiedType();
14385 }
14386}
14387
14388/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14389/// This routine allows us to typecheck complex/recursive expressions
14390/// where the declaration is needed for type checking. We only need to
14391/// handle cases when the expression references a function designator
14392/// or is an lvalue. Here are some examples:
14393/// - &(x) => x
14394/// - &*****f => f for f a function designator.
14395/// - &s.xx => s
14396/// - &s.zz[1].yy -> s, if zz is an array
14397/// - *(x + 1) -> x, if x is an array
14398/// - &"123"[2] -> 0
14399/// - & __real__ x -> x
14400///
14401/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14402/// members.
14404 switch (E->getStmtClass()) {
14405 case Stmt::DeclRefExprClass:
14406 return cast<DeclRefExpr>(E)->getDecl();
14407 case Stmt::MemberExprClass:
14408 // If this is an arrow operator, the address is an offset from
14409 // the base's value, so the object the base refers to is
14410 // irrelevant.
14411 if (cast<MemberExpr>(E)->isArrow())
14412 return nullptr;
14413 // Otherwise, the expression refers to a part of the base
14414 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14415 case Stmt::ArraySubscriptExprClass: {
14416 // FIXME: This code shouldn't be necessary! We should catch the implicit
14417 // promotion of register arrays earlier.
14418 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14419 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14420 if (ICE->getSubExpr()->getType()->isArrayType())
14421 return getPrimaryDecl(ICE->getSubExpr());
14422 }
14423 return nullptr;
14424 }
14425 case Stmt::UnaryOperatorClass: {
14426 UnaryOperator *UO = cast<UnaryOperator>(E);
14427
14428 switch(UO->getOpcode()) {
14429 case UO_Real:
14430 case UO_Imag:
14431 case UO_Extension:
14432 return getPrimaryDecl(UO->getSubExpr());
14433 default:
14434 return nullptr;
14435 }
14436 }
14437 case Stmt::ParenExprClass:
14438 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14439 case Stmt::ImplicitCastExprClass:
14440 // If the result of an implicit cast is an l-value, we care about
14441 // the sub-expression; otherwise, the result here doesn't matter.
14442 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14443 case Stmt::CXXUuidofExprClass:
14444 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14445 default:
14446 return nullptr;
14447 }
14448}
14449
14450namespace {
14451enum {
14452 AO_Bit_Field = 0,
14453 AO_Vector_Element = 1,
14454 AO_Property_Expansion = 2,
14455 AO_Register_Variable = 3,
14456 AO_Matrix_Element = 4,
14457 AO_No_Error = 5
14458};
14459}
14460/// Diagnose invalid operand for address of operations.
14461///
14462/// \param Type The type of operand which cannot have its address taken.
14464 Expr *E, unsigned Type) {
14465 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14466}
14467
14469 const Expr *Op,
14470 const CXXMethodDecl *MD) {
14471 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14472
14473 if (Op != DRE)
14474 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14475 << Op->getSourceRange();
14476
14477 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14478 if (isa<CXXDestructorDecl>(MD))
14479 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14480 << DRE->getSourceRange();
14481
14482 if (DRE->getQualifier())
14483 return false;
14484
14485 if (MD->getParent()->getName().empty())
14486 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14487 << DRE->getSourceRange();
14488
14489 SmallString<32> Str;
14490 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14491 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14492 << DRE->getSourceRange()
14493 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14494}
14495
14497 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14498 if (PTy->getKind() == BuiltinType::Overload) {
14499 Expr *E = OrigOp.get()->IgnoreParens();
14500 if (!isa<OverloadExpr>(E)) {
14501 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14502 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14503 << OrigOp.get()->getSourceRange();
14504 return QualType();
14505 }
14506
14507 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14508 if (isa<UnresolvedMemberExpr>(Ovl))
14510 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14511 << OrigOp.get()->getSourceRange();
14512 return QualType();
14513 }
14514
14515 return Context.OverloadTy;
14516 }
14517
14518 if (PTy->getKind() == BuiltinType::UnknownAny)
14519 return Context.UnknownAnyTy;
14520
14521 if (PTy->getKind() == BuiltinType::BoundMember) {
14522 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14523 << OrigOp.get()->getSourceRange();
14524 return QualType();
14525 }
14526
14527 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14528 if (OrigOp.isInvalid()) return QualType();
14529 }
14530
14531 if (OrigOp.get()->isTypeDependent())
14532 return Context.DependentTy;
14533
14534 assert(!OrigOp.get()->hasPlaceholderType());
14535
14536 // Make sure to ignore parentheses in subsequent checks
14537 Expr *op = OrigOp.get()->IgnoreParens();
14538
14539 // In OpenCL captures for blocks called as lambda functions
14540 // are located in the private address space. Blocks used in
14541 // enqueue_kernel can be located in a different address space
14542 // depending on a vendor implementation. Thus preventing
14543 // taking an address of the capture to avoid invalid AS casts.
14544 if (LangOpts.OpenCL) {
14545 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14546 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14547 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14548 return QualType();
14549 }
14550 }
14551
14552 if (getLangOpts().C99) {
14553 // Implement C99-only parts of addressof rules.
14554 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14555 if (uOp->getOpcode() == UO_Deref)
14556 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14557 // (assuming the deref expression is valid).
14558 return uOp->getSubExpr()->getType();
14559 }
14560 // Technically, there should be a check for array subscript
14561 // expressions here, but the result of one is always an lvalue anyway.
14562 }
14563 ValueDecl *dcl = getPrimaryDecl(op);
14564
14565 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14566 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14567 op->getBeginLoc()))
14568 return QualType();
14569
14571 unsigned AddressOfError = AO_No_Error;
14572
14573 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14574 bool sfinae = (bool)isSFINAEContext();
14575 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14576 : diag::ext_typecheck_addrof_temporary)
14577 << op->getType() << op->getSourceRange();
14578 if (sfinae)
14579 return QualType();
14580 // Materialize the temporary as an lvalue so that we can take its address.
14581 OrigOp = op =
14582 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14583 } else if (isa<ObjCSelectorExpr>(op)) {
14584 return Context.getPointerType(op->getType());
14585 } else if (lval == Expr::LV_MemberFunction) {
14586 // If it's an instance method, make a member pointer.
14587 // The expression must have exactly the form &A::foo.
14588
14589 // If the underlying expression isn't a decl ref, give up.
14590 if (!isa<DeclRefExpr>(op)) {
14591 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14592 << OrigOp.get()->getSourceRange();
14593 return QualType();
14594 }
14595 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14596 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14597
14598 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14600 op->getType(), DRE->getQualifier(), MD->getParent());
14601
14602 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14603 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14604 // When pointer authentication is enabled, argument and return types of
14605 // vitual member functions must be complete. This is because vitrual
14606 // member function pointers are implemented using virtual dispatch
14607 // thunks and the thunks cannot be emitted if the argument or return
14608 // types are incomplete.
14609 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14610 SourceLocation DeclRefLoc,
14611 SourceLocation RetArgTypeLoc) {
14612 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14613 Diag(DeclRefLoc,
14614 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14615 Diag(RetArgTypeLoc,
14616 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14617 << T;
14618 return true;
14619 }
14620 return false;
14621 };
14622 QualType RetTy = MD->getReturnType();
14623 bool IsIncomplete =
14624 !RetTy->isVoidType() &&
14625 ReturnOrParamTypeIsIncomplete(
14626 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14627 for (auto *PVD : MD->parameters())
14628 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14629 PVD->getBeginLoc());
14630 if (IsIncomplete)
14631 return QualType();
14632 }
14633
14634 // Under the MS ABI, lock down the inheritance model now.
14636 (void)isCompleteType(OpLoc, MPTy);
14637 return MPTy;
14638 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14639 // C99 6.5.3.2p1
14640 // The operand must be either an l-value or a function designator
14641 if (!op->getType()->isFunctionType()) {
14642 // Use a special diagnostic for loads from property references.
14643 if (isa<PseudoObjectExpr>(op)) {
14644 AddressOfError = AO_Property_Expansion;
14645 } else {
14646 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14647 << op->getType() << op->getSourceRange();
14648 return QualType();
14649 }
14650 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14651 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14652 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14653 }
14654
14655 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14656 // The operand cannot be a bit-field
14657 AddressOfError = AO_Bit_Field;
14658 } else if (op->getObjectKind() == OK_VectorComponent) {
14659 // The operand cannot be an element of a vector
14660 AddressOfError = AO_Vector_Element;
14661 } else if (op->getObjectKind() == OK_MatrixComponent) {
14662 // The operand cannot be an element of a matrix.
14663 AddressOfError = AO_Matrix_Element;
14664 } else if (dcl) { // C99 6.5.3.2p1
14665 // We have an lvalue with a decl. Make sure the decl is not declared
14666 // with the register storage-class specifier.
14667 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14668 // in C++ it is not error to take address of a register
14669 // variable (c++03 7.1.1P3)
14670 if (vd->getStorageClass() == SC_Register &&
14672 AddressOfError = AO_Register_Variable;
14673 }
14674 } else if (isa<MSPropertyDecl>(dcl)) {
14675 AddressOfError = AO_Property_Expansion;
14676 } else if (isa<FunctionTemplateDecl>(dcl)) {
14677 return Context.OverloadTy;
14678 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14679 // Okay: we can take the address of a field.
14680 // Could be a pointer to member, though, if there is an explicit
14681 // scope qualifier for the class.
14682
14683 // [C++26] [expr.prim.id.general]
14684 // If an id-expression E denotes a non-static non-type member
14685 // of some class C [...] and if E is a qualified-id, E is
14686 // not the un-parenthesized operand of the unary & operator [...]
14687 // the id-expression is transformed into a class member access expression.
14688 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
14689 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
14690 DeclContext *Ctx = dcl->getDeclContext();
14691 if (Ctx && Ctx->isRecord()) {
14692 if (dcl->getType()->isReferenceType()) {
14693 Diag(OpLoc,
14694 diag::err_cannot_form_pointer_to_member_of_reference_type)
14695 << dcl->getDeclName() << dcl->getType();
14696 return QualType();
14697 }
14698
14699 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14700 Ctx = Ctx->getParent();
14701
14703 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
14704 // Under the MS ABI, lock down the inheritance model now.
14706 (void)isCompleteType(OpLoc, MPTy);
14707 return MPTy;
14708 }
14709 }
14712 llvm_unreachable("Unknown/unexpected decl type");
14713 }
14714
14715 if (AddressOfError != AO_No_Error) {
14716 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14717 return QualType();
14718 }
14719
14720 if (lval == Expr::LV_IncompleteVoidType) {
14721 // Taking the address of a void variable is technically illegal, but we
14722 // allow it in cases which are otherwise valid.
14723 // Example: "extern void x; void* y = &x;".
14724 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14725 }
14726
14727 // If the operand has type "type", the result has type "pointer to type".
14728 if (op->getType()->isObjCObjectType())
14730
14731 // Cannot take the address of WebAssembly references or tables.
14732 if (Context.getTargetInfo().getTriple().isWasm()) {
14733 QualType OpTy = op->getType();
14734 if (OpTy.isWebAssemblyReferenceType()) {
14735 Diag(OpLoc, diag::err_wasm_ca_reference)
14736 << 1 << OrigOp.get()->getSourceRange();
14737 return QualType();
14738 }
14739 if (OpTy->isWebAssemblyTableType()) {
14740 Diag(OpLoc, diag::err_wasm_table_pr)
14741 << 1 << OrigOp.get()->getSourceRange();
14742 return QualType();
14743 }
14744 }
14745
14746 CheckAddressOfPackedMember(op);
14747
14748 return Context.getPointerType(op->getType());
14749}
14750
14751static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14752 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14753 if (!DRE)
14754 return;
14755 const Decl *D = DRE->getDecl();
14756 if (!D)
14757 return;
14758 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14759 if (!Param)
14760 return;
14761 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14762 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14763 return;
14764 if (FunctionScopeInfo *FD = S.getCurFunction())
14765 FD->ModifiedNonNullParams.insert(Param);
14766}
14767
14768/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14770 SourceLocation OpLoc,
14771 bool IsAfterAmp = false) {
14772 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14773 if (ConvResult.isInvalid())
14774 return QualType();
14775 Op = ConvResult.get();
14776 QualType OpTy = Op->getType();
14778
14779 if (isa<CXXReinterpretCastExpr>(Op)) {
14780 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14781 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14782 Op->getSourceRange());
14783 }
14784
14785 if (const PointerType *PT = OpTy->getAs<PointerType>())
14786 {
14787 Result = PT->getPointeeType();
14788 }
14789 else if (const ObjCObjectPointerType *OPT =
14791 Result = OPT->getPointeeType();
14792 else {
14794 if (PR.isInvalid()) return QualType();
14795 if (PR.get() != Op)
14796 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14797 }
14798
14799 if (Result.isNull()) {
14800 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14801 << OpTy << Op->getSourceRange();
14802 return QualType();
14803 }
14804
14805 if (Result->isVoidType()) {
14806 // C++ [expr.unary.op]p1:
14807 // [...] the expression to which [the unary * operator] is applied shall
14808 // be a pointer to an object type, or a pointer to a function type
14809 LangOptions LO = S.getLangOpts();
14810 if (LO.CPlusPlus)
14811 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14812 << OpTy << Op->getSourceRange();
14813 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14814 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14815 << OpTy << Op->getSourceRange();
14816 }
14817
14818 // Dereferences are usually l-values...
14819 VK = VK_LValue;
14820
14821 // ...except that certain expressions are never l-values in C.
14822 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14823 VK = VK_PRValue;
14824
14825 return Result;
14826}
14827
14828BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14830 switch (Kind) {
14831 default: llvm_unreachable("Unknown binop!");
14832 case tok::periodstar: Opc = BO_PtrMemD; break;
14833 case tok::arrowstar: Opc = BO_PtrMemI; break;
14834 case tok::star: Opc = BO_Mul; break;
14835 case tok::slash: Opc = BO_Div; break;
14836 case tok::percent: Opc = BO_Rem; break;
14837 case tok::plus: Opc = BO_Add; break;
14838 case tok::minus: Opc = BO_Sub; break;
14839 case tok::lessless: Opc = BO_Shl; break;
14840 case tok::greatergreater: Opc = BO_Shr; break;
14841 case tok::lessequal: Opc = BO_LE; break;
14842 case tok::less: Opc = BO_LT; break;
14843 case tok::greaterequal: Opc = BO_GE; break;
14844 case tok::greater: Opc = BO_GT; break;
14845 case tok::exclaimequal: Opc = BO_NE; break;
14846 case tok::equalequal: Opc = BO_EQ; break;
14847 case tok::spaceship: Opc = BO_Cmp; break;
14848 case tok::amp: Opc = BO_And; break;
14849 case tok::caret: Opc = BO_Xor; break;
14850 case tok::pipe: Opc = BO_Or; break;
14851 case tok::ampamp: Opc = BO_LAnd; break;
14852 case tok::pipepipe: Opc = BO_LOr; break;
14853 case tok::equal: Opc = BO_Assign; break;
14854 case tok::starequal: Opc = BO_MulAssign; break;
14855 case tok::slashequal: Opc = BO_DivAssign; break;
14856 case tok::percentequal: Opc = BO_RemAssign; break;
14857 case tok::plusequal: Opc = BO_AddAssign; break;
14858 case tok::minusequal: Opc = BO_SubAssign; break;
14859 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14860 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14861 case tok::ampequal: Opc = BO_AndAssign; break;
14862 case tok::caretequal: Opc = BO_XorAssign; break;
14863 case tok::pipeequal: Opc = BO_OrAssign; break;
14864 case tok::comma: Opc = BO_Comma; break;
14865 }
14866 return Opc;
14867}
14868
14870 tok::TokenKind Kind) {
14872 switch (Kind) {
14873 default: llvm_unreachable("Unknown unary op!");
14874 case tok::plusplus: Opc = UO_PreInc; break;
14875 case tok::minusminus: Opc = UO_PreDec; break;
14876 case tok::amp: Opc = UO_AddrOf; break;
14877 case tok::star: Opc = UO_Deref; break;
14878 case tok::plus: Opc = UO_Plus; break;
14879 case tok::minus: Opc = UO_Minus; break;
14880 case tok::tilde: Opc = UO_Not; break;
14881 case tok::exclaim: Opc = UO_LNot; break;
14882 case tok::kw___real: Opc = UO_Real; break;
14883 case tok::kw___imag: Opc = UO_Imag; break;
14884 case tok::kw___extension__: Opc = UO_Extension; break;
14885 }
14886 return Opc;
14887}
14888
14889const FieldDecl *
14891 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14892 // common for setters.
14893 // struct A {
14894 // int X;
14895 // -void setX(int X) { X = X; }
14896 // +void setX(int X) { this->X = X; }
14897 // };
14898
14899 // Only consider parameters for self assignment fixes.
14900 if (!isa<ParmVarDecl>(SelfAssigned))
14901 return nullptr;
14902 const auto *Method =
14903 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14904 if (!Method)
14905 return nullptr;
14906
14907 const CXXRecordDecl *Parent = Method->getParent();
14908 // In theory this is fixable if the lambda explicitly captures this, but
14909 // that's added complexity that's rarely going to be used.
14910 if (Parent->isLambda())
14911 return nullptr;
14912
14913 // FIXME: Use an actual Lookup operation instead of just traversing fields
14914 // in order to get base class fields.
14915 auto Field =
14916 llvm::find_if(Parent->fields(),
14917 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14918 return F->getDeclName() == Name;
14919 });
14920 return (Field != Parent->field_end()) ? *Field : nullptr;
14921}
14922
14923/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14924/// This warning suppressed in the event of macro expansions.
14925static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14926 SourceLocation OpLoc, bool IsBuiltin) {
14928 return;
14929 if (S.isUnevaluatedContext())
14930 return;
14931 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14932 return;
14933 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14934 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14935 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14936 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14937 if (!LHSDeclRef || !RHSDeclRef ||
14938 LHSDeclRef->getLocation().isMacroID() ||
14939 RHSDeclRef->getLocation().isMacroID())
14940 return;
14941 const ValueDecl *LHSDecl =
14942 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14943 const ValueDecl *RHSDecl =
14944 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14945 if (LHSDecl != RHSDecl)
14946 return;
14947 if (LHSDecl->getType().isVolatileQualified())
14948 return;
14949 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14950 if (RefTy->getPointeeType().isVolatileQualified())
14951 return;
14952
14953 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14954 : diag::warn_self_assignment_overloaded)
14955 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14956 << RHSExpr->getSourceRange();
14957 if (const FieldDecl *SelfAssignField =
14959 Diag << 1 << SelfAssignField
14960 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14961 else
14962 Diag << 0;
14963}
14964
14965/// Check if a bitwise-& is performed on an Objective-C pointer. This
14966/// is usually indicative of introspection within the Objective-C pointer.
14968 SourceLocation OpLoc) {
14969 if (!S.getLangOpts().ObjC)
14970 return;
14971
14972 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14973 const Expr *LHS = L.get();
14974 const Expr *RHS = R.get();
14975
14977 ObjCPointerExpr = LHS;
14978 OtherExpr = RHS;
14979 }
14980 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14981 ObjCPointerExpr = RHS;
14982 OtherExpr = LHS;
14983 }
14984
14985 // This warning is deliberately made very specific to reduce false
14986 // positives with logic that uses '&' for hashing. This logic mainly
14987 // looks for code trying to introspect into tagged pointers, which
14988 // code should generally never do.
14989 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14990 unsigned Diag = diag::warn_objc_pointer_masking;
14991 // Determine if we are introspecting the result of performSelectorXXX.
14992 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14993 // Special case messages to -performSelector and friends, which
14994 // can return non-pointer values boxed in a pointer value.
14995 // Some clients may wish to silence warnings in this subcase.
14996 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14997 Selector S = ME->getSelector();
14998 StringRef SelArg0 = S.getNameForSlot(0);
14999 if (SelArg0.starts_with("performSelector"))
15000 Diag = diag::warn_objc_pointer_masking_performSelector;
15001 }
15002
15003 S.Diag(OpLoc, Diag)
15004 << ObjCPointerExpr->getSourceRange();
15005 }
15006}
15007
15008// This helper function promotes a binary operator's operands (which are of a
15009// half vector type) to a vector of floats and then truncates the result to
15010// a vector of either half or short.
15012 BinaryOperatorKind Opc, QualType ResultTy,
15014 bool IsCompAssign, SourceLocation OpLoc,
15015 FPOptionsOverride FPFeatures) {
15016 auto &Context = S.getASTContext();
15017 assert((isVector(ResultTy, Context.HalfTy) ||
15018 isVector(ResultTy, Context.ShortTy)) &&
15019 "Result must be a vector of half or short");
15020 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15021 isVector(RHS.get()->getType(), Context.HalfTy) &&
15022 "both operands expected to be a half vector");
15023
15024 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15025 QualType BinOpResTy = RHS.get()->getType();
15026
15027 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15028 // change BinOpResTy to a vector of ints.
15029 if (isVector(ResultTy, Context.ShortTy))
15030 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15031
15032 if (IsCompAssign)
15033 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15034 ResultTy, VK, OK, OpLoc, FPFeatures,
15035 BinOpResTy, BinOpResTy);
15036
15037 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15038 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15039 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15040 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15041}
15042
15043/// Returns true if conversion between vectors of halfs and vectors of floats
15044/// is needed.
15045static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15046 Expr *E0, Expr *E1 = nullptr) {
15047 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15049 return false;
15050
15051 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15052 QualType Ty = E->IgnoreImplicit()->getType();
15053
15054 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15055 // to vectors of floats. Although the element type of the vectors is __fp16,
15056 // the vectors shouldn't be treated as storage-only types. See the
15057 // discussion here: https://reviews.llvm.org/rG825235c140e7
15058 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15059 if (VT->getVectorKind() == VectorKind::Neon)
15060 return false;
15061 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15062 }
15063 return false;
15064 };
15065
15066 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15067}
15068
15070 BinaryOperatorKind Opc, Expr *LHSExpr,
15071 Expr *RHSExpr, bool ForFoldExpression) {
15072 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15073 // The syntax only allows initializer lists on the RHS of assignment,
15074 // so we don't need to worry about accepting invalid code for
15075 // non-assignment operators.
15076 // C++11 5.17p9:
15077 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15078 // of x = {} is x = T().
15080 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15081 InitializedEntity Entity =
15083 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15084 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15085 if (Init.isInvalid())
15086 return Init;
15087 RHSExpr = Init.get();
15088 }
15089
15090 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15091 QualType ResultTy; // Result type of the binary operator.
15092 // The following two variables are used for compound assignment operators
15093 QualType CompLHSTy; // Type of LHS after promotions for computation
15094 QualType CompResultTy; // Type of computation result
15097 bool ConvertHalfVec = false;
15098
15099 if (!LHS.isUsable() || !RHS.isUsable())
15100 return ExprError();
15101
15102 if (getLangOpts().OpenCL) {
15103 QualType LHSTy = LHSExpr->getType();
15104 QualType RHSTy = RHSExpr->getType();
15105 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15106 // the ATOMIC_VAR_INIT macro.
15107 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15108 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15109 if (BO_Assign == Opc)
15110 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15111 else
15112 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15113 return ExprError();
15114 }
15115
15116 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15117 // only with a builtin functions and therefore should be disallowed here.
15118 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15119 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15120 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15121 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15122 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15123 return ExprError();
15124 }
15125 }
15126
15127 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15128 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15129
15130 switch (Opc) {
15131 case BO_Assign:
15132 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15133 if (getLangOpts().CPlusPlus &&
15134 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15135 VK = LHS.get()->getValueKind();
15136 OK = LHS.get()->getObjectKind();
15137 }
15138 if (!ResultTy.isNull()) {
15139 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15140 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15141
15142 // Avoid copying a block to the heap if the block is assigned to a local
15143 // auto variable that is declared in the same scope as the block. This
15144 // optimization is unsafe if the local variable is declared in an outer
15145 // scope. For example:
15146 //
15147 // BlockTy b;
15148 // {
15149 // b = ^{...};
15150 // }
15151 // // It is unsafe to invoke the block here if it wasn't copied to the
15152 // // heap.
15153 // b();
15154
15155 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15156 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15157 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15158 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15159 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15160
15162 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15164 }
15165 RecordModifiableNonNullParam(*this, LHS.get());
15166 break;
15167 case BO_PtrMemD:
15168 case BO_PtrMemI:
15169 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15170 Opc == BO_PtrMemI);
15171 break;
15172 case BO_Mul:
15173 case BO_Div:
15174 ConvertHalfVec = true;
15175 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15176 break;
15177 case BO_Rem:
15178 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15179 break;
15180 case BO_Add:
15181 ConvertHalfVec = true;
15182 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15183 break;
15184 case BO_Sub:
15185 ConvertHalfVec = true;
15186 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15187 break;
15188 case BO_Shl:
15189 case BO_Shr:
15190 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15191 break;
15192 case BO_LE:
15193 case BO_LT:
15194 case BO_GE:
15195 case BO_GT:
15196 ConvertHalfVec = true;
15197 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15198
15199 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15200 !ForFoldExpression && BI && BI->isComparisonOp())
15201 Diag(OpLoc, diag::warn_consecutive_comparison)
15202 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15203
15204 break;
15205 case BO_EQ:
15206 case BO_NE:
15207 ConvertHalfVec = true;
15208 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15209 break;
15210 case BO_Cmp:
15211 ConvertHalfVec = true;
15212 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15213 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15214 break;
15215 case BO_And:
15216 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15217 [[fallthrough]];
15218 case BO_Xor:
15219 case BO_Or:
15220 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15221 break;
15222 case BO_LAnd:
15223 case BO_LOr:
15224 ConvertHalfVec = true;
15225 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15226 break;
15227 case BO_MulAssign:
15228 case BO_DivAssign:
15229 ConvertHalfVec = true;
15230 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15231 CompLHSTy = CompResultTy;
15232 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15233 ResultTy =
15234 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15235 break;
15236 case BO_RemAssign:
15237 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15238 CompLHSTy = CompResultTy;
15239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15240 ResultTy =
15241 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15242 break;
15243 case BO_AddAssign:
15244 ConvertHalfVec = true;
15245 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15246 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15247 ResultTy =
15248 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15249 break;
15250 case BO_SubAssign:
15251 ConvertHalfVec = true;
15252 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15253 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15254 ResultTy =
15255 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15256 break;
15257 case BO_ShlAssign:
15258 case BO_ShrAssign:
15259 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15260 CompLHSTy = CompResultTy;
15261 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15262 ResultTy =
15263 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15264 break;
15265 case BO_AndAssign:
15266 case BO_OrAssign: // fallthrough
15267 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15268 [[fallthrough]];
15269 case BO_XorAssign:
15270 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15271 CompLHSTy = CompResultTy;
15272 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15273 ResultTy =
15274 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15275 break;
15276 case BO_Comma:
15277 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15278 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15279 VK = RHS.get()->getValueKind();
15280 OK = RHS.get()->getObjectKind();
15281 }
15282 break;
15283 }
15284 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15285 return ExprError();
15286
15287 // Some of the binary operations require promoting operands of half vector to
15288 // float vectors and truncating the result back to half vector. For now, we do
15289 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15290 // arm64).
15291 assert(
15292 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15293 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15294 "both sides are half vectors or neither sides are");
15295 ConvertHalfVec =
15296 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15297
15298 // Check for array bounds violations for both sides of the BinaryOperator
15299 CheckArrayAccess(LHS.get());
15300 CheckArrayAccess(RHS.get());
15301
15302 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15303 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15304 &Context.Idents.get("object_setClass"),
15306 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15307 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15308 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15310 "object_setClass(")
15311 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15312 ",")
15313 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15314 }
15315 else
15316 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15317 }
15318 else if (const ObjCIvarRefExpr *OIRE =
15319 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15320 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15321
15322 // Opc is not a compound assignment if CompResultTy is null.
15323 if (CompResultTy.isNull()) {
15324 if (ConvertHalfVec)
15325 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15326 OpLoc, CurFPFeatureOverrides());
15327 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15328 VK, OK, OpLoc, CurFPFeatureOverrides());
15329 }
15330
15331 // Handle compound assignments.
15332 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15334 VK = VK_LValue;
15335 OK = LHS.get()->getObjectKind();
15336 }
15337
15338 // The LHS is not converted to the result type for fixed-point compound
15339 // assignment as the common type is computed on demand. Reset the CompLHSTy
15340 // to the LHS type we would have gotten after unary conversions.
15341 if (CompResultTy->isFixedPointType())
15342 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15343
15344 if (ConvertHalfVec)
15345 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15346 OpLoc, CurFPFeatureOverrides());
15347
15349 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15350 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15351}
15352
15353/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15354/// operators are mixed in a way that suggests that the programmer forgot that
15355/// comparison operators have higher precedence. The most typical example of
15356/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15358 SourceLocation OpLoc, Expr *LHSExpr,
15359 Expr *RHSExpr) {
15360 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15361 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15362
15363 // Check that one of the sides is a comparison operator and the other isn't.
15364 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15365 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15366 if (isLeftComp == isRightComp)
15367 return;
15368
15369 // Bitwise operations are sometimes used as eager logical ops.
15370 // Don't diagnose this.
15371 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15372 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15373 if (isLeftBitwise || isRightBitwise)
15374 return;
15375
15376 SourceRange DiagRange = isLeftComp
15377 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15378 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15379 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15380 SourceRange ParensRange =
15381 isLeftComp
15382 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15383 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15384
15385 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15386 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15387 SuggestParentheses(Self, OpLoc,
15388 Self.PDiag(diag::note_precedence_silence) << OpStr,
15389 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15390 SuggestParentheses(Self, OpLoc,
15391 Self.PDiag(diag::note_precedence_bitwise_first)
15393 ParensRange);
15394}
15395
15396/// It accepts a '&&' expr that is inside a '||' one.
15397/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15398/// in parentheses.
15399static void
15401 BinaryOperator *Bop) {
15402 assert(Bop->getOpcode() == BO_LAnd);
15403 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15404 << Bop->getSourceRange() << OpLoc;
15406 Self.PDiag(diag::note_precedence_silence)
15407 << Bop->getOpcodeStr(),
15408 Bop->getSourceRange());
15409}
15410
15411/// Look for '&&' in the left hand of a '||' expr.
15413 Expr *LHSExpr, Expr *RHSExpr) {
15414 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15415 if (Bop->getOpcode() == BO_LAnd) {
15416 // If it's "string_literal && a || b" don't warn since the precedence
15417 // doesn't matter.
15418 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15419 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15420 } else if (Bop->getOpcode() == BO_LOr) {
15421 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15422 // If it's "a || b && string_literal || c" we didn't warn earlier for
15423 // "a || b && string_literal", but warn now.
15424 if (RBop->getOpcode() == BO_LAnd &&
15425 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15426 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15427 }
15428 }
15429 }
15430}
15431
15432/// Look for '&&' in the right hand of a '||' expr.
15434 Expr *LHSExpr, Expr *RHSExpr) {
15435 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15436 if (Bop->getOpcode() == BO_LAnd) {
15437 // If it's "a || b && string_literal" don't warn since the precedence
15438 // doesn't matter.
15439 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15440 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15441 }
15442 }
15443}
15444
15445/// Look for bitwise op in the left or right hand of a bitwise op with
15446/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15447/// the '&' expression in parentheses.
15449 SourceLocation OpLoc, Expr *SubExpr) {
15450 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15451 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15452 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15453 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15454 << Bop->getSourceRange() << OpLoc;
15455 SuggestParentheses(S, Bop->getOperatorLoc(),
15456 S.PDiag(diag::note_precedence_silence)
15457 << Bop->getOpcodeStr(),
15458 Bop->getSourceRange());
15459 }
15460 }
15461}
15462
15464 Expr *SubExpr, StringRef Shift) {
15465 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15466 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15467 StringRef Op = Bop->getOpcodeStr();
15468 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15469 << Bop->getSourceRange() << OpLoc << Shift << Op;
15470 SuggestParentheses(S, Bop->getOperatorLoc(),
15471 S.PDiag(diag::note_precedence_silence) << Op,
15472 Bop->getSourceRange());
15473 }
15474 }
15475}
15476
15478 Expr *LHSExpr, Expr *RHSExpr) {
15479 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15480 if (!OCE)
15481 return;
15482
15483 FunctionDecl *FD = OCE->getDirectCallee();
15484 if (!FD || !FD->isOverloadedOperator())
15485 return;
15486
15488 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15489 return;
15490
15491 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15492 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15493 << (Kind == OO_LessLess);
15495 S.PDiag(diag::note_precedence_silence)
15496 << (Kind == OO_LessLess ? "<<" : ">>"),
15497 OCE->getSourceRange());
15499 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15500 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15501}
15502
15503/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15504/// precedence.
15506 SourceLocation OpLoc, Expr *LHSExpr,
15507 Expr *RHSExpr){
15508 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15510 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15511
15512 // Diagnose "arg1 & arg2 | arg3"
15513 if ((Opc == BO_Or || Opc == BO_Xor) &&
15514 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15515 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15516 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15517 }
15518
15519 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15520 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15521 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15522 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15523 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15524 }
15525
15526 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15527 || Opc == BO_Shr) {
15528 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15529 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15530 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15531 }
15532
15533 // Warn on overloaded shift operators and comparisons, such as:
15534 // cout << 5 == 4;
15536 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15537}
15538
15540 tok::TokenKind Kind,
15541 Expr *LHSExpr, Expr *RHSExpr) {
15542 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15543 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15544 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15545
15546 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15547 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15548
15552
15553 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15554 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15555
15556 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15557}
15558
15560 UnresolvedSetImpl &Functions) {
15562 if (OverOp != OO_None && OverOp != OO_Equal)
15563 LookupOverloadedOperatorName(OverOp, S, Functions);
15564
15565 // In C++20 onwards, we may have a second operator to look up.
15566 if (getLangOpts().CPlusPlus20) {
15568 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15569 }
15570}
15571
15572/// Build an overloaded binary operator expression in the given scope.
15575 Expr *LHS, Expr *RHS) {
15576 switch (Opc) {
15577 case BO_Assign:
15578 // In the non-overloaded case, we warn about self-assignment (x = x) for
15579 // both simple assignment and certain compound assignments where algebra
15580 // tells us the operation yields a constant result. When the operator is
15581 // overloaded, we can't do the latter because we don't want to assume that
15582 // those algebraic identities still apply; for example, a path-building
15583 // library might use operator/= to append paths. But it's still reasonable
15584 // to assume that simple assignment is just moving/copying values around
15585 // and so self-assignment is likely a bug.
15586 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15587 [[fallthrough]];
15588 case BO_DivAssign:
15589 case BO_RemAssign:
15590 case BO_SubAssign:
15591 case BO_AndAssign:
15592 case BO_OrAssign:
15593 case BO_XorAssign:
15594 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15595 break;
15596 default:
15597 break;
15598 }
15599
15600 // Find all of the overloaded operators visible from this point.
15601 UnresolvedSet<16> Functions;
15602 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15603
15604 // Build the (potentially-overloaded, potentially-dependent)
15605 // binary operation.
15606 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15607}
15608
15610 BinaryOperatorKind Opc, Expr *LHSExpr,
15611 Expr *RHSExpr, bool ForFoldExpression) {
15612 if (!LHSExpr || !RHSExpr)
15613 return ExprError();
15614
15615 // We want to end up calling one of SemaPseudoObject::checkAssignment
15616 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15617 // both expressions are overloadable or either is type-dependent),
15618 // or CreateBuiltinBinOp (in any other case). We also want to get
15619 // any placeholder types out of the way.
15620
15621 // Handle pseudo-objects in the LHS.
15622 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15623 // Assignments with a pseudo-object l-value need special analysis.
15624 if (pty->getKind() == BuiltinType::PseudoObject &&
15626 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15627
15628 // Don't resolve overloads if the other type is overloadable.
15629 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15630 // We can't actually test that if we still have a placeholder,
15631 // though. Fortunately, none of the exceptions we see in that
15632 // code below are valid when the LHS is an overload set. Note
15633 // that an overload set can be dependently-typed, but it never
15634 // instantiates to having an overloadable type.
15635 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15636 if (resolvedRHS.isInvalid()) return ExprError();
15637 RHSExpr = resolvedRHS.get();
15638
15639 if (RHSExpr->isTypeDependent() ||
15640 RHSExpr->getType()->isOverloadableType())
15641 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15642 }
15643
15644 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15645 // template, diagnose the missing 'template' keyword instead of diagnosing
15646 // an invalid use of a bound member function.
15647 //
15648 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15649 // to C++1z [over.over]/1.4, but we already checked for that case above.
15650 if (Opc == BO_LT && inTemplateInstantiation() &&
15651 (pty->getKind() == BuiltinType::BoundMember ||
15652 pty->getKind() == BuiltinType::Overload)) {
15653 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15654 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15655 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15656 return isa<FunctionTemplateDecl>(ND);
15657 })) {
15658 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15659 : OE->getNameLoc(),
15660 diag::err_template_kw_missing)
15661 << OE->getName().getAsIdentifierInfo();
15662 return ExprError();
15663 }
15664 }
15665
15666 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15667 if (LHS.isInvalid()) return ExprError();
15668 LHSExpr = LHS.get();
15669 }
15670
15671 // Handle pseudo-objects in the RHS.
15672 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15673 // An overload in the RHS can potentially be resolved by the type
15674 // being assigned to.
15675 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15676 if (getLangOpts().CPlusPlus &&
15677 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15678 LHSExpr->getType()->isOverloadableType()))
15679 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15680
15681 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15682 ForFoldExpression);
15683 }
15684
15685 // Don't resolve overloads if the other type is overloadable.
15686 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15687 LHSExpr->getType()->isOverloadableType())
15688 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15689
15690 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15691 if (!resolvedRHS.isUsable()) return ExprError();
15692 RHSExpr = resolvedRHS.get();
15693 }
15694
15695 if (getLangOpts().CPlusPlus) {
15696 // Otherwise, build an overloaded op if either expression is type-dependent
15697 // or has an overloadable type.
15698 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15699 LHSExpr->getType()->isOverloadableType() ||
15700 RHSExpr->getType()->isOverloadableType())
15701 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15702 }
15703
15704 if (getLangOpts().RecoveryAST &&
15705 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15706 assert(!getLangOpts().CPlusPlus);
15707 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15708 "Should only occur in error-recovery path.");
15710 // C [6.15.16] p3:
15711 // An assignment expression has the value of the left operand after the
15712 // assignment, but is not an lvalue.
15714 Context, LHSExpr, RHSExpr, Opc,
15716 OpLoc, CurFPFeatureOverrides());
15717 QualType ResultType;
15718 switch (Opc) {
15719 case BO_Assign:
15720 ResultType = LHSExpr->getType().getUnqualifiedType();
15721 break;
15722 case BO_LT:
15723 case BO_GT:
15724 case BO_LE:
15725 case BO_GE:
15726 case BO_EQ:
15727 case BO_NE:
15728 case BO_LAnd:
15729 case BO_LOr:
15730 // These operators have a fixed result type regardless of operands.
15731 ResultType = Context.IntTy;
15732 break;
15733 case BO_Comma:
15734 ResultType = RHSExpr->getType();
15735 break;
15736 default:
15737 ResultType = Context.DependentTy;
15738 break;
15739 }
15740 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15741 VK_PRValue, OK_Ordinary, OpLoc,
15743 }
15744
15745 // Build a built-in binary operation.
15746 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15747}
15748
15750 if (T.isNull() || T->isDependentType())
15751 return false;
15752
15753 if (!Ctx.isPromotableIntegerType(T))
15754 return true;
15755
15756 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15757}
15758
15760 UnaryOperatorKind Opc, Expr *InputExpr,
15761 bool IsAfterAmp) {
15762 ExprResult Input = InputExpr;
15765 QualType resultType;
15766 bool CanOverflow = false;
15767
15768 bool ConvertHalfVec = false;
15769 if (getLangOpts().OpenCL) {
15770 QualType Ty = InputExpr->getType();
15771 // The only legal unary operation for atomics is '&'.
15772 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15773 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15774 // only with a builtin functions and therefore should be disallowed here.
15775 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15776 || Ty->isBlockPointerType())) {
15777 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15778 << InputExpr->getType()
15779 << Input.get()->getSourceRange());
15780 }
15781 }
15782
15783 if (getLangOpts().HLSL && OpLoc.isValid()) {
15784 if (Opc == UO_AddrOf)
15785 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15786 if (Opc == UO_Deref)
15787 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15788 }
15789
15790 if (InputExpr->isTypeDependent() &&
15791 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15792 resultType = Context.DependentTy;
15793 } else {
15794 switch (Opc) {
15795 case UO_PreInc:
15796 case UO_PreDec:
15797 case UO_PostInc:
15798 case UO_PostDec:
15799 resultType =
15800 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15801 Opc == UO_PreInc || Opc == UO_PostInc,
15802 Opc == UO_PreInc || Opc == UO_PreDec);
15803 CanOverflow = isOverflowingIntegerType(Context, resultType);
15804 break;
15805 case UO_AddrOf:
15806 resultType = CheckAddressOfOperand(Input, OpLoc);
15807 CheckAddressOfNoDeref(InputExpr);
15808 RecordModifiableNonNullParam(*this, InputExpr);
15809 break;
15810 case UO_Deref: {
15812 if (Input.isInvalid())
15813 return ExprError();
15814 resultType =
15815 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15816 break;
15817 }
15818 case UO_Plus:
15819 case UO_Minus:
15820 CanOverflow = Opc == UO_Minus &&
15822 Input = UsualUnaryConversions(Input.get());
15823 if (Input.isInvalid())
15824 return ExprError();
15825 // Unary plus and minus require promoting an operand of half vector to a
15826 // float vector and truncating the result back to a half vector. For now,
15827 // we do this only when HalfArgsAndReturns is set (that is, when the
15828 // target is arm or arm64).
15829 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15830
15831 // If the operand is a half vector, promote it to a float vector.
15832 if (ConvertHalfVec)
15833 Input = convertVector(Input.get(), Context.FloatTy, *this);
15834 resultType = Input.get()->getType();
15835 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15836 break;
15837 else if (resultType->isVectorType() &&
15838 // The z vector extensions don't allow + or - with bool vectors.
15839 (!Context.getLangOpts().ZVector ||
15840 resultType->castAs<VectorType>()->getVectorKind() !=
15842 break;
15843 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15844 break;
15845 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15846 Opc == UO_Plus && resultType->isPointerType())
15847 break;
15848
15849 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15850 << resultType << Input.get()->getSourceRange());
15851
15852 case UO_Not: // bitwise complement
15853 Input = UsualUnaryConversions(Input.get());
15854 if (Input.isInvalid())
15855 return ExprError();
15856 resultType = Input.get()->getType();
15857 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15858 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15859 // C99 does not support '~' for complex conjugation.
15860 Diag(OpLoc, diag::ext_integer_complement_complex)
15861 << resultType << Input.get()->getSourceRange();
15862 else if (resultType->hasIntegerRepresentation())
15863 break;
15864 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15865 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15866 // on vector float types.
15867 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15868 if (!T->isIntegerType())
15869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15870 << resultType << Input.get()->getSourceRange());
15871 } else {
15872 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15873 << resultType << Input.get()->getSourceRange());
15874 }
15875 break;
15876
15877 case UO_LNot: // logical negation
15878 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15880 if (Input.isInvalid())
15881 return ExprError();
15882 resultType = Input.get()->getType();
15883
15884 // Though we still have to promote half FP to float...
15885 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15886 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15887 .get();
15888 resultType = Context.FloatTy;
15889 }
15890
15891 // WebAsembly tables can't be used in unary expressions.
15892 if (resultType->isPointerType() &&
15894 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15895 << resultType << Input.get()->getSourceRange());
15896 }
15897
15898 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15899 // C99 6.5.3.3p1: ok, fallthrough;
15900 if (Context.getLangOpts().CPlusPlus) {
15901 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15902 // operand contextually converted to bool.
15903 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15904 ScalarTypeToBooleanCastKind(resultType));
15905 } else if (Context.getLangOpts().OpenCL &&
15906 Context.getLangOpts().OpenCLVersion < 120) {
15907 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15908 // operate on scalar float types.
15909 if (!resultType->isIntegerType() && !resultType->isPointerType())
15910 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15911 << resultType << Input.get()->getSourceRange());
15912 }
15913 } else if (resultType->isExtVectorType()) {
15914 if (Context.getLangOpts().OpenCL &&
15916 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15917 // operate on vector float types.
15918 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15919 if (!T->isIntegerType())
15920 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15921 << resultType << Input.get()->getSourceRange());
15922 }
15923 // Vector logical not returns the signed variant of the operand type.
15924 resultType = GetSignedVectorType(resultType);
15925 break;
15926 } else if (Context.getLangOpts().CPlusPlus &&
15927 resultType->isVectorType()) {
15928 const VectorType *VTy = resultType->castAs<VectorType>();
15929 if (VTy->getVectorKind() != VectorKind::Generic)
15930 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15931 << resultType << Input.get()->getSourceRange());
15932
15933 // Vector logical not returns the signed variant of the operand type.
15934 resultType = GetSignedVectorType(resultType);
15935 break;
15936 } else {
15937 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15938 << resultType << Input.get()->getSourceRange());
15939 }
15940
15941 // LNot always has type int. C99 6.5.3.3p5.
15942 // In C++, it's bool. C++ 5.3.1p8
15943 resultType = Context.getLogicalOperationType();
15944 break;
15945 case UO_Real:
15946 case UO_Imag:
15947 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15948 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15949 // ordinary complex l-values to ordinary l-values and all other values to
15950 // r-values.
15951 if (Input.isInvalid())
15952 return ExprError();
15953 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15954 if (Input.get()->isGLValue() &&
15955 Input.get()->getObjectKind() == OK_Ordinary)
15956 VK = Input.get()->getValueKind();
15957 } else if (!getLangOpts().CPlusPlus) {
15958 // In C, a volatile scalar is read by __imag. In C++, it is not.
15959 Input = DefaultLvalueConversion(Input.get());
15960 }
15961 break;
15962 case UO_Extension:
15963 resultType = Input.get()->getType();
15964 VK = Input.get()->getValueKind();
15965 OK = Input.get()->getObjectKind();
15966 break;
15967 case UO_Coawait:
15968 // It's unnecessary to represent the pass-through operator co_await in the
15969 // AST; just return the input expression instead.
15970 assert(!Input.get()->getType()->isDependentType() &&
15971 "the co_await expression must be non-dependant before "
15972 "building operator co_await");
15973 return Input;
15974 }
15975 }
15976 if (resultType.isNull() || Input.isInvalid())
15977 return ExprError();
15978
15979 // Check for array bounds violations in the operand of the UnaryOperator,
15980 // except for the '*' and '&' operators that have to be handled specially
15981 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15982 // that are explicitly defined as valid by the standard).
15983 if (Opc != UO_AddrOf && Opc != UO_Deref)
15984 CheckArrayAccess(Input.get());
15985
15986 auto *UO =
15987 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15988 OpLoc, CanOverflow, CurFPFeatureOverrides());
15989
15990 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15991 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15993 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15994
15995 // Convert the result back to a half vector.
15996 if (ConvertHalfVec)
15997 return convertVector(UO, Context.HalfTy, *this);
15998 return UO;
15999}
16000
16002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16003 if (!DRE->getQualifier())
16004 return false;
16005
16006 ValueDecl *VD = DRE->getDecl();
16007 if (!VD->isCXXClassMember())
16008 return false;
16009
16010 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16011 return true;
16012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16013 return Method->isImplicitObjectMemberFunction();
16014
16015 return false;
16016 }
16017
16018 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16019 if (!ULE->getQualifier())
16020 return false;
16021
16022 for (NamedDecl *D : ULE->decls()) {
16023 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16024 if (Method->isImplicitObjectMemberFunction())
16025 return true;
16026 } else {
16027 // Overload set does not contain methods.
16028 break;
16029 }
16030 }
16031
16032 return false;
16033 }
16034
16035 return false;
16036}
16037
16039 UnaryOperatorKind Opc, Expr *Input,
16040 bool IsAfterAmp) {
16041 // First things first: handle placeholders so that the
16042 // overloaded-operator check considers the right type.
16043 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16044 // Increment and decrement of pseudo-object references.
16045 if (pty->getKind() == BuiltinType::PseudoObject &&
16047 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16048
16049 // extension is always a builtin operator.
16050 if (Opc == UO_Extension)
16051 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16052
16053 // & gets special logic for several kinds of placeholder.
16054 // The builtin code knows what to do.
16055 if (Opc == UO_AddrOf &&
16056 (pty->getKind() == BuiltinType::Overload ||
16057 pty->getKind() == BuiltinType::UnknownAny ||
16058 pty->getKind() == BuiltinType::BoundMember))
16059 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16060
16061 // Anything else needs to be handled now.
16063 if (Result.isInvalid()) return ExprError();
16064 Input = Result.get();
16065 }
16066
16067 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16069 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16070 // Find all of the overloaded operators visible from this point.
16071 UnresolvedSet<16> Functions;
16073 if (S && OverOp != OO_None)
16074 LookupOverloadedOperatorName(OverOp, S, Functions);
16075
16076 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16077 }
16078
16079 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16080}
16081
16083 Expr *Input, bool IsAfterAmp) {
16084 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16085 IsAfterAmp);
16086}
16087
16089 LabelDecl *TheDecl) {
16090 TheDecl->markUsed(Context);
16091 // Create the AST node. The address of a label always has type 'void*'.
16092 auto *Res = new (Context) AddrLabelExpr(
16093 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16094
16095 if (getCurFunction())
16096 getCurFunction()->AddrLabels.push_back(Res);
16097
16098 return Res;
16099}
16100
16103 // Make sure we diagnose jumping into a statement expression.
16105}
16106
16108 // Note that function is also called by TreeTransform when leaving a
16109 // StmtExpr scope without rebuilding anything.
16110
16113}
16114
16116 SourceLocation RPLoc) {
16117 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16118}
16119
16121 SourceLocation RPLoc, unsigned TemplateDepth) {
16122 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16123 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16124
16127 assert(!Cleanup.exprNeedsCleanups() &&
16128 "cleanups within StmtExpr not correctly bound!");
16130
16131 // FIXME: there are a variety of strange constraints to enforce here, for
16132 // example, it is not possible to goto into a stmt expression apparently.
16133 // More semantic analysis is needed.
16134
16135 // If there are sub-stmts in the compound stmt, take the type of the last one
16136 // as the type of the stmtexpr.
16137 QualType Ty = Context.VoidTy;
16138 bool StmtExprMayBindToTemp = false;
16139 if (!Compound->body_empty()) {
16140 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16141 if (const auto *LastStmt =
16142 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16143 if (const Expr *Value = LastStmt->getExprStmt()) {
16144 StmtExprMayBindToTemp = true;
16145 Ty = Value->getType();
16146 }
16147 }
16148 }
16149
16150 // FIXME: Check that expression type is complete/non-abstract; statement
16151 // expressions are not lvalues.
16152 Expr *ResStmtExpr =
16153 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16154 if (StmtExprMayBindToTemp)
16155 return MaybeBindToTemporary(ResStmtExpr);
16156 return ResStmtExpr;
16157}
16158
16160 if (ER.isInvalid())
16161 return ExprError();
16162
16163 // Do function/array conversion on the last expression, but not
16164 // lvalue-to-rvalue. However, initialize an unqualified type.
16166 if (ER.isInvalid())
16167 return ExprError();
16168 Expr *E = ER.get();
16169
16170 if (E->isTypeDependent())
16171 return E;
16172
16173 // In ARC, if the final expression ends in a consume, splice
16174 // the consume out and bind it later. In the alternate case
16175 // (when dealing with a retainable type), the result
16176 // initialization will create a produce. In both cases the
16177 // result will be +1, and we'll need to balance that out with
16178 // a bind.
16179 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16180 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16181 return Cast->getSubExpr();
16182
16183 // FIXME: Provide a better location for the initialization.
16187 SourceLocation(), E);
16188}
16189
16191 TypeSourceInfo *TInfo,
16192 ArrayRef<OffsetOfComponent> Components,
16193 SourceLocation RParenLoc) {
16194 QualType ArgTy = TInfo->getType();
16195 bool Dependent = ArgTy->isDependentType();
16196 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16197
16198 // We must have at least one component that refers to the type, and the first
16199 // one is known to be a field designator. Verify that the ArgTy represents
16200 // a struct/union/class.
16201 if (!Dependent && !ArgTy->isRecordType())
16202 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16203 << ArgTy << TypeRange);
16204
16205 // Type must be complete per C99 7.17p3 because a declaring a variable
16206 // with an incomplete type would be ill-formed.
16207 if (!Dependent
16208 && RequireCompleteType(BuiltinLoc, ArgTy,
16209 diag::err_offsetof_incomplete_type, TypeRange))
16210 return ExprError();
16211
16212 bool DidWarnAboutNonPOD = false;
16213 QualType CurrentType = ArgTy;
16216 for (const OffsetOfComponent &OC : Components) {
16217 if (OC.isBrackets) {
16218 // Offset of an array sub-field. TODO: Should we allow vector elements?
16219 if (!CurrentType->isDependentType()) {
16220 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16221 if(!AT)
16222 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16223 << CurrentType);
16224 CurrentType = AT->getElementType();
16225 } else
16226 CurrentType = Context.DependentTy;
16227
16228 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16229 if (IdxRval.isInvalid())
16230 return ExprError();
16231 Expr *Idx = IdxRval.get();
16232
16233 // The expression must be an integral expression.
16234 // FIXME: An integral constant expression?
16235 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16236 !Idx->getType()->isIntegerType())
16237 return ExprError(
16238 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16239 << Idx->getSourceRange());
16240
16241 // Record this array index.
16242 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16243 Exprs.push_back(Idx);
16244 continue;
16245 }
16246
16247 // Offset of a field.
16248 if (CurrentType->isDependentType()) {
16249 // We have the offset of a field, but we can't look into the dependent
16250 // type. Just record the identifier of the field.
16251 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16252 CurrentType = Context.DependentTy;
16253 continue;
16254 }
16255
16256 // We need to have a complete type to look into.
16257 if (RequireCompleteType(OC.LocStart, CurrentType,
16258 diag::err_offsetof_incomplete_type))
16259 return ExprError();
16260
16261 // Look for the designated field.
16262 auto *RD = CurrentType->getAsRecordDecl();
16263 if (!RD)
16264 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16265 << CurrentType);
16266
16267 // C++ [lib.support.types]p5:
16268 // The macro offsetof accepts a restricted set of type arguments in this
16269 // International Standard. type shall be a POD structure or a POD union
16270 // (clause 9).
16271 // C++11 [support.types]p4:
16272 // If type is not a standard-layout class (Clause 9), the results are
16273 // undefined.
16274 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16275 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16276 unsigned DiagID =
16277 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16278 : diag::ext_offsetof_non_pod_type;
16279
16280 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16281 Diag(BuiltinLoc, DiagID)
16282 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16283 DidWarnAboutNonPOD = true;
16284 }
16285 }
16286
16287 // Look for the field.
16288 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16289 LookupQualifiedName(R, RD);
16290 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16291 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16292 if (!MemberDecl) {
16293 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16294 MemberDecl = IndirectMemberDecl->getAnonField();
16295 }
16296
16297 if (!MemberDecl) {
16298 // Lookup could be ambiguous when looking up a placeholder variable
16299 // __builtin_offsetof(S, _).
16300 // In that case we would already have emitted a diagnostic
16301 if (!R.isAmbiguous())
16302 Diag(BuiltinLoc, diag::err_no_member)
16303 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16304 return ExprError();
16305 }
16306
16307 // C99 7.17p3:
16308 // (If the specified member is a bit-field, the behavior is undefined.)
16309 //
16310 // We diagnose this as an error.
16311 if (MemberDecl->isBitField()) {
16312 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16313 << MemberDecl->getDeclName()
16314 << SourceRange(BuiltinLoc, RParenLoc);
16315 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16316 return ExprError();
16317 }
16318
16319 RecordDecl *Parent = MemberDecl->getParent();
16320 if (IndirectMemberDecl)
16321 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16322
16323 // If the member was found in a base class, introduce OffsetOfNodes for
16324 // the base class indirections.
16325 CXXBasePaths Paths;
16326 if (IsDerivedFrom(OC.LocStart, CurrentType,
16328 if (Paths.getDetectedVirtual()) {
16329 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16330 << MemberDecl->getDeclName()
16331 << SourceRange(BuiltinLoc, RParenLoc);
16332 return ExprError();
16333 }
16334
16335 CXXBasePath &Path = Paths.front();
16336 for (const CXXBasePathElement &B : Path)
16337 Comps.push_back(OffsetOfNode(B.Base));
16338 }
16339
16340 if (IndirectMemberDecl) {
16341 for (auto *FI : IndirectMemberDecl->chain()) {
16342 assert(isa<FieldDecl>(FI));
16343 Comps.push_back(OffsetOfNode(OC.LocStart,
16344 cast<FieldDecl>(FI), OC.LocEnd));
16345 }
16346 } else
16347 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16348
16349 CurrentType = MemberDecl->getType().getNonReferenceType();
16350 }
16351
16352 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16353 Comps, Exprs, RParenLoc);
16354}
16355
16357 SourceLocation BuiltinLoc,
16359 ParsedType ParsedArgTy,
16360 ArrayRef<OffsetOfComponent> Components,
16361 SourceLocation RParenLoc) {
16362
16363 TypeSourceInfo *ArgTInfo;
16364 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16365 if (ArgTy.isNull())
16366 return ExprError();
16367
16368 if (!ArgTInfo)
16369 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16370
16371 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16372}
16373
16374
16376 Expr *CondExpr,
16377 Expr *LHSExpr, Expr *RHSExpr,
16378 SourceLocation RPLoc) {
16379 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16380
16383 QualType resType;
16384 bool CondIsTrue = false;
16385 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16386 resType = Context.DependentTy;
16387 } else {
16388 // The conditional expression is required to be a constant expression.
16389 llvm::APSInt condEval(32);
16391 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16392 if (CondICE.isInvalid())
16393 return ExprError();
16394 CondExpr = CondICE.get();
16395 CondIsTrue = condEval.getZExtValue();
16396
16397 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16398 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16399
16400 resType = ActiveExpr->getType();
16401 VK = ActiveExpr->getValueKind();
16402 OK = ActiveExpr->getObjectKind();
16403 }
16404
16405 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16406 resType, VK, OK, RPLoc, CondIsTrue);
16407}
16408
16409//===----------------------------------------------------------------------===//
16410// Clang Extensions.
16411//===----------------------------------------------------------------------===//
16412
16413void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16415
16416 if (LangOpts.CPlusPlus) {
16418 Decl *ManglingContextDecl;
16419 std::tie(MCtx, ManglingContextDecl) =
16420 getCurrentMangleNumberContext(Block->getDeclContext());
16421 if (MCtx) {
16422 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16423 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16424 }
16425 }
16426
16427 PushBlockScope(CurScope, Block);
16429 if (CurScope)
16430 PushDeclContext(CurScope, Block);
16431 else
16432 CurContext = Block;
16433
16435
16436 // Enter a new evaluation context to insulate the block from any
16437 // cleanups from the enclosing full-expression.
16440}
16441
16443 Scope *CurScope) {
16444 assert(ParamInfo.getIdentifier() == nullptr &&
16445 "block-id should have no identifier!");
16446 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16447 BlockScopeInfo *CurBlock = getCurBlock();
16448
16449 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16450 QualType T = Sig->getType();
16452
16453 // GetTypeForDeclarator always produces a function type for a block
16454 // literal signature. Furthermore, it is always a FunctionProtoType
16455 // unless the function was written with a typedef.
16456 assert(T->isFunctionType() &&
16457 "GetTypeForDeclarator made a non-function block signature");
16458
16459 // Look for an explicit signature in that function type.
16460 FunctionProtoTypeLoc ExplicitSignature;
16461
16462 if ((ExplicitSignature = Sig->getTypeLoc()
16464
16465 // Check whether that explicit signature was synthesized by
16466 // GetTypeForDeclarator. If so, don't save that as part of the
16467 // written signature.
16468 if (ExplicitSignature.getLocalRangeBegin() ==
16469 ExplicitSignature.getLocalRangeEnd()) {
16470 // This would be much cheaper if we stored TypeLocs instead of
16471 // TypeSourceInfos.
16472 TypeLoc Result = ExplicitSignature.getReturnLoc();
16473 unsigned Size = Result.getFullDataSize();
16474 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16475 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16476
16477 ExplicitSignature = FunctionProtoTypeLoc();
16478 }
16479 }
16480
16481 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16482 CurBlock->FunctionType = T;
16483
16484 const auto *Fn = T->castAs<FunctionType>();
16485 QualType RetTy = Fn->getReturnType();
16486 bool isVariadic =
16487 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16488
16489 CurBlock->TheDecl->setIsVariadic(isVariadic);
16490
16491 // Context.DependentTy is used as a placeholder for a missing block
16492 // return type. TODO: what should we do with declarators like:
16493 // ^ * { ... }
16494 // If the answer is "apply template argument deduction"....
16495 if (RetTy != Context.DependentTy) {
16496 CurBlock->ReturnType = RetTy;
16497 CurBlock->TheDecl->setBlockMissingReturnType(false);
16498 CurBlock->HasImplicitReturnType = false;
16499 }
16500
16501 // Push block parameters from the declarator if we had them.
16503 if (ExplicitSignature) {
16504 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16505 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16506 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16507 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16508 // Diagnose this as an extension in C17 and earlier.
16509 if (!getLangOpts().C23)
16510 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16511 }
16512 Params.push_back(Param);
16513 }
16514
16515 // Fake up parameter variables if we have a typedef, like
16516 // ^ fntype { ... }
16517 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16518 for (const auto &I : Fn->param_types()) {
16520 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16521 Params.push_back(Param);
16522 }
16523 }
16524
16525 // Set the parameters on the block decl.
16526 if (!Params.empty()) {
16527 CurBlock->TheDecl->setParams(Params);
16529 /*CheckParameterNames=*/false);
16530 }
16531
16532 // Finally we can process decl attributes.
16533 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16534
16535 // Put the parameter variables in scope.
16536 for (auto *AI : CurBlock->TheDecl->parameters()) {
16537 AI->setOwningFunction(CurBlock->TheDecl);
16538
16539 // If this has an identifier, add it to the scope stack.
16540 if (AI->getIdentifier()) {
16541 CheckShadow(CurBlock->TheScope, AI);
16542
16543 PushOnScopeChains(AI, CurBlock->TheScope);
16544 }
16545
16546 if (AI->isInvalidDecl())
16547 CurBlock->TheDecl->setInvalidDecl();
16548 }
16549}
16550
16551void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16552 // Leave the expression-evaluation context.
16555
16556 // Pop off CurBlock, handle nested blocks.
16559}
16560
16562 Stmt *Body, Scope *CurScope) {
16563 // If blocks are disabled, emit an error.
16564 if (!LangOpts.Blocks)
16565 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16566
16567 // Leave the expression-evaluation context.
16570 assert(!Cleanup.exprNeedsCleanups() &&
16571 "cleanups within block not correctly bound!");
16573
16574 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16575 BlockDecl *BD = BSI->TheDecl;
16576
16578
16579 if (BSI->HasImplicitReturnType)
16581
16582 QualType RetTy = Context.VoidTy;
16583 if (!BSI->ReturnType.isNull())
16584 RetTy = BSI->ReturnType;
16585
16586 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16587 QualType BlockTy;
16588
16589 // If the user wrote a function type in some form, try to use that.
16590 if (!BSI->FunctionType.isNull()) {
16591 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16592
16593 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16594 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16595
16596 // Turn protoless block types into nullary block types.
16597 if (isa<FunctionNoProtoType>(FTy)) {
16599 EPI.ExtInfo = Ext;
16600 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16601
16602 // Otherwise, if we don't need to change anything about the function type,
16603 // preserve its sugar structure.
16604 } else if (FTy->getReturnType() == RetTy &&
16605 (!NoReturn || FTy->getNoReturnAttr())) {
16606 BlockTy = BSI->FunctionType;
16607
16608 // Otherwise, make the minimal modifications to the function type.
16609 } else {
16610 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16612 EPI.TypeQuals = Qualifiers();
16613 EPI.ExtInfo = Ext;
16614 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16615 }
16616
16617 // If we don't have a function type, just build one from nothing.
16618 } else {
16620 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16621 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16622 }
16623
16625 BlockTy = Context.getBlockPointerType(BlockTy);
16626
16627 // If needed, diagnose invalid gotos and switches in the block.
16628 if (getCurFunction()->NeedsScopeChecking() &&
16630 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16631
16632 BD->setBody(cast<CompoundStmt>(Body));
16633
16634 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16636
16637 // Try to apply the named return value optimization. We have to check again
16638 // if we can do this, though, because blocks keep return statements around
16639 // to deduce an implicit return type.
16640 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16641 !BD->isDependentContext())
16642 computeNRVO(Body, BSI);
16643
16649
16651
16652 // Set the captured variables on the block.
16654 for (Capture &Cap : BSI->Captures) {
16655 if (Cap.isInvalid() || Cap.isThisCapture())
16656 continue;
16657 // Cap.getVariable() is always a VarDecl because
16658 // blocks cannot capture structured bindings or other ValueDecl kinds.
16659 auto *Var = cast<VarDecl>(Cap.getVariable());
16660 Expr *CopyExpr = nullptr;
16661 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16662 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16663 // The capture logic needs the destructor, so make sure we mark it.
16664 // Usually this is unnecessary because most local variables have
16665 // their destructors marked at declaration time, but parameters are
16666 // an exception because it's technically only the call site that
16667 // actually requires the destructor.
16668 if (isa<ParmVarDecl>(Var))
16670
16671 // Enter a separate potentially-evaluated context while building block
16672 // initializers to isolate their cleanups from those of the block
16673 // itself.
16674 // FIXME: Is this appropriate even when the block itself occurs in an
16675 // unevaluated operand?
16678
16680
16682 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16683
16684 // According to the blocks spec, the capture of a variable from
16685 // the stack requires a const copy constructor. This is not true
16686 // of the copy/move done to move a __block variable to the heap.
16687 if (!Result.isInvalid() &&
16688 !Result.get()->getType().isConstQualified()) {
16690 Result.get()->getType().withConst(),
16691 CK_NoOp, VK_LValue);
16692 }
16693
16694 if (!Result.isInvalid()) {
16696 InitializedEntity::InitializeBlock(Var->getLocation(),
16697 Cap.getCaptureType()),
16698 Loc, Result.get());
16699 }
16700
16701 // Build a full-expression copy expression if initialization
16702 // succeeded and used a non-trivial constructor. Recover from
16703 // errors by pretending that the copy isn't necessary.
16704 if (!Result.isInvalid() &&
16705 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16706 ->isTrivial()) {
16708 CopyExpr = Result.get();
16709 }
16710 }
16711 }
16712
16713 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16714 CopyExpr);
16715 Captures.push_back(NewCap);
16716 }
16717 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16718
16719 // Pop the block scope now but keep it alive to the end of this function.
16722 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16723
16724 BlockExpr *Result = new (Context)
16725 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16726
16727 // If the block isn't obviously global, i.e. it captures anything at
16728 // all, then we need to do a few things in the surrounding context:
16729 if (Result->getBlockDecl()->hasCaptures()) {
16730 // First, this expression has a new cleanup object.
16731 ExprCleanupObjects.push_back(Result->getBlockDecl());
16733
16734 // It also gets a branch-protected scope if any of the captured
16735 // variables needs destruction.
16736 for (const auto &CI : Result->getBlockDecl()->captures()) {
16737 const VarDecl *var = CI.getVariable();
16738 if (var->getType().isDestructedType() != QualType::DK_none) {
16740 break;
16741 }
16742 }
16743 }
16744
16745 if (getCurFunction())
16746 getCurFunction()->addBlock(BD);
16747
16748 // This can happen if the block's return type is deduced, but
16749 // the return expression is invalid.
16750 if (BD->isInvalidDecl())
16751 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16752 {Result}, Result->getType());
16753 return Result;
16754}
16755
16757 SourceLocation RPLoc) {
16758 TypeSourceInfo *TInfo;
16759 GetTypeFromParser(Ty, &TInfo);
16760 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16761}
16762
16764 Expr *E, TypeSourceInfo *TInfo,
16765 SourceLocation RPLoc) {
16766 Expr *OrigExpr = E;
16767 bool IsMS = false;
16768
16769 // CUDA device code does not support varargs.
16770 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16771 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16775 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16776 }
16777 }
16778
16779 // NVPTX does not support va_arg expression.
16780 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16781 Context.getTargetInfo().getTriple().isNVPTX())
16782 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16783
16784 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16785 // as Microsoft ABI on an actual Microsoft platform, where
16786 // __builtin_ms_va_list and __builtin_va_list are the same.)
16789 QualType MSVaListType = Context.getBuiltinMSVaListType();
16790 if (Context.hasSameType(MSVaListType, E->getType())) {
16791 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16792 return ExprError();
16793 IsMS = true;
16794 }
16795 }
16796
16797 // Get the va_list type
16798 QualType VaListType = Context.getBuiltinVaListType();
16799 if (!IsMS) {
16800 if (VaListType->isArrayType()) {
16801 // Deal with implicit array decay; for example, on x86-64,
16802 // va_list is an array, but it's supposed to decay to
16803 // a pointer for va_arg.
16804 VaListType = Context.getArrayDecayedType(VaListType);
16805 // Make sure the input expression also decays appropriately.
16807 if (Result.isInvalid())
16808 return ExprError();
16809 E = Result.get();
16810 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16811 // If va_list is a record type and we are compiling in C++ mode,
16812 // check the argument using reference binding.
16814 Context, Context.getLValueReferenceType(VaListType), false);
16816 if (Init.isInvalid())
16817 return ExprError();
16818 E = Init.getAs<Expr>();
16819 } else {
16820 // Otherwise, the va_list argument must be an l-value because
16821 // it is modified by va_arg.
16822 if (!E->isTypeDependent() &&
16823 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16824 return ExprError();
16825 }
16826 }
16827
16828 if (!IsMS && !E->isTypeDependent() &&
16829 !Context.hasSameType(VaListType, E->getType()))
16830 return ExprError(
16831 Diag(E->getBeginLoc(),
16832 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16833 << OrigExpr->getType() << E->getSourceRange());
16834
16835 if (!TInfo->getType()->isDependentType()) {
16836 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16837 diag::err_second_parameter_to_va_arg_incomplete,
16838 TInfo->getTypeLoc()))
16839 return ExprError();
16840
16842 TInfo->getType(),
16843 diag::err_second_parameter_to_va_arg_abstract,
16844 TInfo->getTypeLoc()))
16845 return ExprError();
16846
16847 if (!TInfo->getType().isPODType(Context)) {
16848 Diag(TInfo->getTypeLoc().getBeginLoc(),
16849 TInfo->getType()->isObjCLifetimeType()
16850 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16851 : diag::warn_second_parameter_to_va_arg_not_pod)
16852 << TInfo->getType()
16853 << TInfo->getTypeLoc().getSourceRange();
16854 }
16855
16856 if (TInfo->getType()->isArrayType()) {
16858 PDiag(diag::warn_second_parameter_to_va_arg_array)
16859 << TInfo->getType()
16860 << TInfo->getTypeLoc().getSourceRange());
16861 }
16862
16863 // Check for va_arg where arguments of the given type will be promoted
16864 // (i.e. this va_arg is guaranteed to have undefined behavior).
16865 QualType PromoteType;
16866 if (Context.isPromotableIntegerType(TInfo->getType())) {
16867 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16868 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16869 // and C23 7.16.1.1p2 says, in part:
16870 // If type is not compatible with the type of the actual next argument
16871 // (as promoted according to the default argument promotions), the
16872 // behavior is undefined, except for the following cases:
16873 // - both types are pointers to qualified or unqualified versions of
16874 // compatible types;
16875 // - one type is compatible with a signed integer type, the other
16876 // type is compatible with the corresponding unsigned integer type,
16877 // and the value is representable in both types;
16878 // - one type is pointer to qualified or unqualified void and the
16879 // other is a pointer to a qualified or unqualified character type;
16880 // - or, the type of the next argument is nullptr_t and type is a
16881 // pointer type that has the same representation and alignment
16882 // requirements as a pointer to a character type.
16883 // Given that type compatibility is the primary requirement (ignoring
16884 // qualifications), you would think we could call typesAreCompatible()
16885 // directly to test this. However, in C++, that checks for *same type*,
16886 // which causes false positives when passing an enumeration type to
16887 // va_arg. Instead, get the underlying type of the enumeration and pass
16888 // that.
16889 QualType UnderlyingType = TInfo->getType();
16890 if (const auto *ED = UnderlyingType->getAsEnumDecl())
16891 UnderlyingType = ED->getIntegerType();
16892 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16893 /*CompareUnqualified*/ true))
16894 PromoteType = QualType();
16895
16896 // If the types are still not compatible, we need to test whether the
16897 // promoted type and the underlying type are the same except for
16898 // signedness. Ask the AST for the correctly corresponding type and see
16899 // if that's compatible.
16900 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16901 PromoteType->isUnsignedIntegerType() !=
16902 UnderlyingType->isUnsignedIntegerType()) {
16903 UnderlyingType =
16904 UnderlyingType->isUnsignedIntegerType()
16905 ? Context.getCorrespondingSignedType(UnderlyingType)
16906 : Context.getCorrespondingUnsignedType(UnderlyingType);
16907 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16908 /*CompareUnqualified*/ true))
16909 PromoteType = QualType();
16910 }
16911 }
16912 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16913 PromoteType = Context.DoubleTy;
16914 if (!PromoteType.isNull())
16916 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16917 << TInfo->getType()
16918 << PromoteType
16919 << TInfo->getTypeLoc().getSourceRange());
16920 }
16921
16923 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16924}
16925
16927 // The type of __null will be int or long, depending on the size of
16928 // pointers on the target.
16929 QualType Ty;
16931 if (pw == Context.getTargetInfo().getIntWidth())
16932 Ty = Context.IntTy;
16933 else if (pw == Context.getTargetInfo().getLongWidth())
16934 Ty = Context.LongTy;
16935 else if (pw == Context.getTargetInfo().getLongLongWidth())
16936 Ty = Context.LongLongTy;
16937 else {
16938 llvm_unreachable("I don't know size of pointer!");
16939 }
16940
16941 return new (Context) GNUNullExpr(Ty, TokenLoc);
16942}
16943
16945 CXXRecordDecl *ImplDecl = nullptr;
16946
16947 // Fetch the std::source_location::__impl decl.
16948 if (NamespaceDecl *Std = S.getStdNamespace()) {
16949 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16951 if (S.LookupQualifiedName(ResultSL, Std)) {
16952 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16953 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16955 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16956 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16957 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16958 }
16959 }
16960 }
16961 }
16962
16963 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16964 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16965 return nullptr;
16966 }
16967
16968 // Verify that __impl is a trivial struct type, with no base classes, and with
16969 // only the four expected fields.
16970 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16971 ImplDecl->getNumBases() != 0) {
16972 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16973 return nullptr;
16974 }
16975
16976 unsigned Count = 0;
16977 for (FieldDecl *F : ImplDecl->fields()) {
16978 StringRef Name = F->getName();
16979
16980 if (Name == "_M_file_name") {
16981 if (F->getType() !=
16983 break;
16984 Count++;
16985 } else if (Name == "_M_function_name") {
16986 if (F->getType() !=
16988 break;
16989 Count++;
16990 } else if (Name == "_M_line") {
16991 if (!F->getType()->isIntegerType())
16992 break;
16993 Count++;
16994 } else if (Name == "_M_column") {
16995 if (!F->getType()->isIntegerType())
16996 break;
16997 Count++;
16998 } else {
16999 Count = 100; // invalid
17000 break;
17001 }
17002 }
17003 if (Count != 4) {
17004 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17005 return nullptr;
17006 }
17007
17008 return ImplDecl;
17009}
17010
17012 SourceLocation BuiltinLoc,
17013 SourceLocation RPLoc) {
17014 QualType ResultTy;
17015 switch (Kind) {
17021 ResultTy =
17023 break;
17024 }
17027 ResultTy = Context.UnsignedIntTy;
17028 break;
17032 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17034 return ExprError();
17035 }
17036 ResultTy = Context.getPointerType(
17038 break;
17039 }
17040
17041 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17042}
17043
17045 SourceLocation BuiltinLoc,
17046 SourceLocation RPLoc,
17047 DeclContext *ParentContext) {
17048 return new (Context)
17049 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17050}
17051
17053 StringLiteral *BinaryData, StringRef FileName) {
17055 Data->BinaryData = BinaryData;
17056 Data->FileName = FileName;
17057 return new (Context)
17058 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17059 Data->getDataElementCount());
17060}
17061
17063 const Expr *SrcExpr) {
17064 if (!DstType->isFunctionPointerType() ||
17065 !SrcExpr->getType()->isFunctionType())
17066 return false;
17067
17068 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17069 if (!DRE)
17070 return false;
17071
17072 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17073 if (!FD)
17074 return false;
17075
17077 /*Complain=*/true,
17078 SrcExpr->getBeginLoc());
17079}
17080
17083 QualType DstType, QualType SrcType,
17084 Expr *SrcExpr, AssignmentAction Action,
17085 bool *Complained) {
17086 if (Complained)
17087 *Complained = false;
17088
17089 // Decode the result (notice that AST's are still created for extensions).
17090 bool CheckInferredResultType = false;
17091 bool isInvalid = false;
17092 unsigned DiagKind = 0;
17093 ConversionFixItGenerator ConvHints;
17094 bool MayHaveConvFixit = false;
17095 bool MayHaveFunctionDiff = false;
17096 const ObjCInterfaceDecl *IFace = nullptr;
17097 const ObjCProtocolDecl *PDecl = nullptr;
17098
17099 switch (ConvTy) {
17101 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17102 return false;
17104 // Still a valid conversion, but we may want to diagnose for C++
17105 // compatibility reasons.
17106 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17107 break;
17109 if (getLangOpts().CPlusPlus) {
17110 DiagKind = diag::err_typecheck_convert_pointer_int;
17111 isInvalid = true;
17112 } else {
17113 DiagKind = diag::ext_typecheck_convert_pointer_int;
17114 }
17115 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17116 MayHaveConvFixit = true;
17117 break;
17119 if (getLangOpts().CPlusPlus) {
17120 DiagKind = diag::err_typecheck_convert_int_pointer;
17121 isInvalid = true;
17122 } else {
17123 DiagKind = diag::ext_typecheck_convert_int_pointer;
17124 }
17125 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17126 MayHaveConvFixit = true;
17127 break;
17129 DiagKind =
17130 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17131 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17132 MayHaveConvFixit = true;
17133 break;
17135 if (getLangOpts().CPlusPlus) {
17136 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17137 isInvalid = true;
17138 } else {
17139 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17140 }
17141 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17142 MayHaveConvFixit = true;
17143 break;
17146 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17147 } else if (getLangOpts().CPlusPlus) {
17148 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17149 isInvalid = true;
17150 } else {
17151 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17152 }
17153 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17154 SrcType->isObjCObjectPointerType();
17155 if (CheckInferredResultType) {
17156 SrcType = SrcType.getUnqualifiedType();
17157 DstType = DstType.getUnqualifiedType();
17158 } else {
17159 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17160 }
17161 MayHaveConvFixit = true;
17162 break;
17164 if (getLangOpts().CPlusPlus) {
17165 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17166 isInvalid = true;
17167 } else {
17168 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17169 }
17170 break;
17172 if (getLangOpts().CPlusPlus) {
17173 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17174 isInvalid = true;
17175 } else {
17176 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17177 }
17178 break;
17180 // Perform array-to-pointer decay if necessary.
17181 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17182
17183 isInvalid = true;
17184
17185 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17186 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17187 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17188 DiagKind = diag::err_typecheck_incompatible_address_space;
17189 break;
17190 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17191 DiagKind = diag::err_typecheck_incompatible_ownership;
17192 break;
17193 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17194 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17195 break;
17196 }
17197
17198 llvm_unreachable("unknown error case for discarding qualifiers!");
17199 // fallthrough
17200 }
17202 // If the qualifiers lost were because we were applying the
17203 // (deprecated) C++ conversion from a string literal to a char*
17204 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17205 // Ideally, this check would be performed in
17206 // checkPointerTypesForAssignment. However, that would require a
17207 // bit of refactoring (so that the second argument is an
17208 // expression, rather than a type), which should be done as part
17209 // of a larger effort to fix checkPointerTypesForAssignment for
17210 // C++ semantics.
17211 if (getLangOpts().CPlusPlus &&
17213 return false;
17214 if (getLangOpts().CPlusPlus) {
17215 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17216 isInvalid = true;
17217 } else {
17218 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17219 }
17220
17221 break;
17223 if (getLangOpts().CPlusPlus) {
17224 isInvalid = true;
17225 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17226 } else {
17227 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17228 }
17229 break;
17231 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17232 isInvalid = true;
17233 break;
17235 DiagKind = diag::err_int_to_block_pointer;
17236 isInvalid = true;
17237 break;
17239 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17240 isInvalid = true;
17241 break;
17243 if (SrcType->isObjCQualifiedIdType()) {
17244 const ObjCObjectPointerType *srcOPT =
17245 SrcType->castAs<ObjCObjectPointerType>();
17246 for (auto *srcProto : srcOPT->quals()) {
17247 PDecl = srcProto;
17248 break;
17249 }
17250 if (const ObjCInterfaceType *IFaceT =
17252 IFace = IFaceT->getDecl();
17253 }
17254 else if (DstType->isObjCQualifiedIdType()) {
17255 const ObjCObjectPointerType *dstOPT =
17256 DstType->castAs<ObjCObjectPointerType>();
17257 for (auto *dstProto : dstOPT->quals()) {
17258 PDecl = dstProto;
17259 break;
17260 }
17261 if (const ObjCInterfaceType *IFaceT =
17263 IFace = IFaceT->getDecl();
17264 }
17265 if (getLangOpts().CPlusPlus) {
17266 DiagKind = diag::err_incompatible_qualified_id;
17267 isInvalid = true;
17268 } else {
17269 DiagKind = diag::warn_incompatible_qualified_id;
17270 }
17271 break;
17272 }
17274 if (getLangOpts().CPlusPlus) {
17275 DiagKind = diag::err_incompatible_vectors;
17276 isInvalid = true;
17277 } else {
17278 DiagKind = diag::warn_incompatible_vectors;
17279 }
17280 break;
17282 DiagKind = diag::err_arc_weak_unavailable_assign;
17283 isInvalid = true;
17284 break;
17286 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17287 if (Complained)
17288 *Complained = true;
17289 return true;
17290 }
17291
17292 DiagKind = diag::err_typecheck_convert_incompatible;
17293 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17294 MayHaveConvFixit = true;
17295 isInvalid = true;
17296 MayHaveFunctionDiff = true;
17297 break;
17298 }
17299
17300 QualType FirstType, SecondType;
17301 switch (Action) {
17304 // The destination type comes first.
17305 FirstType = DstType;
17306 SecondType = SrcType;
17307 break;
17308
17315 // The source type comes first.
17316 FirstType = SrcType;
17317 SecondType = DstType;
17318 break;
17319 }
17320
17321 PartialDiagnostic FDiag = PDiag(DiagKind);
17322 AssignmentAction ActionForDiag = Action;
17324 ActionForDiag = AssignmentAction::Passing;
17325
17326 FDiag << FirstType << SecondType << ActionForDiag
17327 << SrcExpr->getSourceRange();
17328
17329 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17330 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17331 auto isPlainChar = [](const clang::Type *Type) {
17332 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17333 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17334 };
17335 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17336 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17337 }
17338
17339 // If we can fix the conversion, suggest the FixIts.
17340 if (!ConvHints.isNull()) {
17341 for (FixItHint &H : ConvHints.Hints)
17342 FDiag << H;
17343 }
17344
17345 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17346
17347 if (MayHaveFunctionDiff)
17348 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17349
17350 Diag(Loc, FDiag);
17351 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17352 DiagKind == diag::err_incompatible_qualified_id) &&
17353 PDecl && IFace && !IFace->hasDefinition())
17354 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17355 << IFace << PDecl;
17356
17357 if (SecondType == Context.OverloadTy)
17359 FirstType, /*TakingAddress=*/true);
17360
17361 if (CheckInferredResultType)
17363
17364 if (Action == AssignmentAction::Returning &&
17367
17368 if (Complained)
17369 *Complained = true;
17370 return isInvalid;
17371}
17372
17374 llvm::APSInt *Result,
17375 AllowFoldKind CanFold) {
17376 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17377 public:
17378 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17379 QualType T) override {
17380 return S.Diag(Loc, diag::err_ice_not_integral)
17381 << T << S.LangOpts.CPlusPlus;
17382 }
17383 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17384 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17385 }
17386 } Diagnoser;
17387
17388 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17389}
17390
17392 llvm::APSInt *Result,
17393 unsigned DiagID,
17394 AllowFoldKind CanFold) {
17395 class IDDiagnoser : public VerifyICEDiagnoser {
17396 unsigned DiagID;
17397
17398 public:
17399 IDDiagnoser(unsigned DiagID)
17400 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17401
17402 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17403 return S.Diag(Loc, DiagID);
17404 }
17405 } Diagnoser(DiagID);
17406
17407 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17408}
17409
17412 QualType T) {
17413 return diagnoseNotICE(S, Loc);
17414}
17415
17418 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17419}
17420
17423 VerifyICEDiagnoser &Diagnoser,
17424 AllowFoldKind CanFold) {
17425 SourceLocation DiagLoc = E->getBeginLoc();
17426
17427 if (getLangOpts().CPlusPlus11) {
17428 // C++11 [expr.const]p5:
17429 // If an expression of literal class type is used in a context where an
17430 // integral constant expression is required, then that class type shall
17431 // have a single non-explicit conversion function to an integral or
17432 // unscoped enumeration type
17433 ExprResult Converted;
17434 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17435 VerifyICEDiagnoser &BaseDiagnoser;
17436 public:
17437 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17438 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17439 BaseDiagnoser.Suppress, true),
17440 BaseDiagnoser(BaseDiagnoser) {}
17441
17442 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17443 QualType T) override {
17444 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17445 }
17446
17447 SemaDiagnosticBuilder diagnoseIncomplete(
17448 Sema &S, SourceLocation Loc, QualType T) override {
17449 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17450 }
17451
17452 SemaDiagnosticBuilder diagnoseExplicitConv(
17453 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17454 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17455 }
17456
17457 SemaDiagnosticBuilder noteExplicitConv(
17458 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17459 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17460 << ConvTy->isEnumeralType() << ConvTy;
17461 }
17462
17463 SemaDiagnosticBuilder diagnoseAmbiguous(
17464 Sema &S, SourceLocation Loc, QualType T) override {
17465 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17466 }
17467
17468 SemaDiagnosticBuilder noteAmbiguous(
17469 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17470 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17471 << ConvTy->isEnumeralType() << ConvTy;
17472 }
17473
17474 SemaDiagnosticBuilder diagnoseConversion(
17475 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17476 llvm_unreachable("conversion functions are permitted");
17477 }
17478 } ConvertDiagnoser(Diagnoser);
17479
17480 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17481 ConvertDiagnoser);
17482 if (Converted.isInvalid())
17483 return Converted;
17484 E = Converted.get();
17485 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17486 // don't try to evaluate it later. We also don't want to return the
17487 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17488 // this function will attempt to use 'Value'.
17489 if (isa<RecoveryExpr>(E))
17490 return ExprError();
17492 return ExprError();
17493 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17494 // An ICE must be of integral or unscoped enumeration type.
17495 if (!Diagnoser.Suppress)
17496 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17497 << E->getSourceRange();
17498 return ExprError();
17499 }
17500
17501 ExprResult RValueExpr = DefaultLvalueConversion(E);
17502 if (RValueExpr.isInvalid())
17503 return ExprError();
17504
17505 E = RValueExpr.get();
17506
17507 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17508 // in the non-ICE case.
17511 if (Result)
17513 if (!isa<ConstantExpr>(E))
17516
17517 if (Notes.empty())
17518 return E;
17519
17520 // If our only note is the usual "invalid subexpression" note, just point
17521 // the caret at its location rather than producing an essentially
17522 // redundant note.
17523 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17524 diag::note_invalid_subexpr_in_const_expr) {
17525 DiagLoc = Notes[0].first;
17526 Notes.clear();
17527 }
17528
17529 if (getLangOpts().CPlusPlus) {
17530 if (!Diagnoser.Suppress) {
17531 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17532 for (const PartialDiagnosticAt &Note : Notes)
17533 Diag(Note.first, Note.second);
17534 }
17535 return ExprError();
17536 }
17537
17538 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17539 for (const PartialDiagnosticAt &Note : Notes)
17540 Diag(Note.first, Note.second);
17541
17542 return E;
17543 }
17544
17545 Expr::EvalResult EvalResult;
17547 EvalResult.Diag = &Notes;
17548
17549 // Try to evaluate the expression, and produce diagnostics explaining why it's
17550 // not a constant expression as a side-effect.
17551 bool Folded =
17552 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17553 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17554 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17555
17556 if (!isa<ConstantExpr>(E))
17557 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17558
17559 // In C++11, we can rely on diagnostics being produced for any expression
17560 // which is not a constant expression. If no diagnostics were produced, then
17561 // this is a constant expression.
17562 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17563 if (Result)
17564 *Result = EvalResult.Val.getInt();
17565 return E;
17566 }
17567
17568 // If our only note is the usual "invalid subexpression" note, just point
17569 // the caret at its location rather than producing an essentially
17570 // redundant note.
17571 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17572 diag::note_invalid_subexpr_in_const_expr) {
17573 DiagLoc = Notes[0].first;
17574 Notes.clear();
17575 }
17576
17577 if (!Folded || CanFold == AllowFoldKind::No) {
17578 if (!Diagnoser.Suppress) {
17579 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17580 for (const PartialDiagnosticAt &Note : Notes)
17581 Diag(Note.first, Note.second);
17582 }
17583
17584 return ExprError();
17585 }
17586
17587 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17588 for (const PartialDiagnosticAt &Note : Notes)
17589 Diag(Note.first, Note.second);
17590
17591 if (Result)
17592 *Result = EvalResult.Val.getInt();
17593 return E;
17594}
17595
17596namespace {
17597 // Handle the case where we conclude a expression which we speculatively
17598 // considered to be unevaluated is actually evaluated.
17599 class TransformToPE : public TreeTransform<TransformToPE> {
17600 typedef TreeTransform<TransformToPE> BaseTransform;
17601
17602 public:
17603 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17604
17605 // Make sure we redo semantic analysis
17606 bool AlwaysRebuild() { return true; }
17607 bool ReplacingOriginal() { return true; }
17608
17609 // We need to special-case DeclRefExprs referring to FieldDecls which
17610 // are not part of a member pointer formation; normal TreeTransforming
17611 // doesn't catch this case because of the way we represent them in the AST.
17612 // FIXME: This is a bit ugly; is it really the best way to handle this
17613 // case?
17614 //
17615 // Error on DeclRefExprs referring to FieldDecls.
17616 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17617 if (isa<FieldDecl>(E->getDecl()) &&
17618 !SemaRef.isUnevaluatedContext())
17619 return SemaRef.Diag(E->getLocation(),
17620 diag::err_invalid_non_static_member_use)
17621 << E->getDecl() << E->getSourceRange();
17622
17623 return BaseTransform::TransformDeclRefExpr(E);
17624 }
17625
17626 // Exception: filter out member pointer formation
17627 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17628 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17629 return E;
17630
17631 return BaseTransform::TransformUnaryOperator(E);
17632 }
17633
17634 // The body of a lambda-expression is in a separate expression evaluation
17635 // context so never needs to be transformed.
17636 // FIXME: Ideally we wouldn't transform the closure type either, and would
17637 // just recreate the capture expressions and lambda expression.
17638 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17639 return SkipLambdaBody(E, Body);
17640 }
17641 };
17642}
17643
17645 assert(isUnevaluatedContext() &&
17646 "Should only transform unevaluated expressions");
17647 ExprEvalContexts.back().Context =
17648 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17650 return E;
17651 return TransformToPE(*this).TransformExpr(E);
17652}
17653
17655 assert(isUnevaluatedContext() &&
17656 "Should only transform unevaluated expressions");
17659 return TInfo;
17660 return TransformToPE(*this).TransformType(TInfo);
17661}
17662
17663void
17665 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17667 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17668 LambdaContextDecl, ExprContext);
17669
17670 // Discarded statements and immediate contexts nested in other
17671 // discarded statements or immediate context are themselves
17672 // a discarded statement or an immediate context, respectively.
17673 ExprEvalContexts.back().InDiscardedStatement =
17675
17676 // C++23 [expr.const]/p15
17677 // An expression or conversion is in an immediate function context if [...]
17678 // it is a subexpression of a manifestly constant-evaluated expression or
17679 // conversion.
17680 const auto &Prev = parentEvaluationContext();
17681 ExprEvalContexts.back().InImmediateFunctionContext =
17682 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17683
17684 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17685 Prev.InImmediateEscalatingFunctionContext;
17686
17687 Cleanup.reset();
17688 if (!MaybeODRUseExprs.empty())
17689 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17690}
17691
17692void
17696 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17697 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17698}
17699
17701 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17702 // [expr.const]/p14.1
17703 // An expression or conversion is in an immediate function context if it is
17704 // potentially evaluated and either: its innermost enclosing non-block scope
17705 // is a function parameter scope of an immediate function.
17707 FD && FD->isConsteval()
17709 : NewContext);
17713
17714 Current.InDiscardedStatement = false;
17715
17716 if (FD) {
17717
17718 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17719 // context is nested in an immediate function context, so smaller contexts
17720 // that appear inside immediate functions (like variable initializers) are
17721 // considered to be inside an immediate function context even though by
17722 // themselves they are not immediate function contexts. But when a new
17723 // function is entered, we need to reset this tracking, since the entered
17724 // function might be not an immediate function.
17725
17726 Current.InImmediateEscalatingFunctionContext =
17727 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17728
17729 if (isLambdaMethod(FD))
17730 Current.InImmediateFunctionContext =
17731 FD->isConsteval() ||
17732 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
17733 Parent.isImmediateFunctionContext()));
17734 else
17735 Current.InImmediateFunctionContext = FD->isConsteval();
17736 }
17737}
17738
17739namespace {
17740
17741const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17742 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17743 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17744 if (E->getOpcode() == UO_Deref)
17745 return CheckPossibleDeref(S, E->getSubExpr());
17746 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17747 return CheckPossibleDeref(S, E->getBase());
17748 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17749 return CheckPossibleDeref(S, E->getBase());
17750 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17751 QualType Inner;
17752 QualType Ty = E->getType();
17753 if (const auto *Ptr = Ty->getAs<PointerType>())
17754 Inner = Ptr->getPointeeType();
17755 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17756 Inner = Arr->getElementType();
17757 else
17758 return nullptr;
17759
17760 if (Inner->hasAttr(attr::NoDeref))
17761 return E;
17762 }
17763 return nullptr;
17764}
17765
17766} // namespace
17767
17769 for (const Expr *E : Rec.PossibleDerefs) {
17770 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17771 if (DeclRef) {
17772 const ValueDecl *Decl = DeclRef->getDecl();
17773 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17774 << Decl->getName() << E->getSourceRange();
17775 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17776 } else {
17777 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17778 << E->getSourceRange();
17779 }
17780 }
17781 Rec.PossibleDerefs.clear();
17782}
17783
17786 return;
17787
17788 // Note: ignoring parens here is not justified by the standard rules, but
17789 // ignoring parentheses seems like a more reasonable approach, and this only
17790 // drives a deprecation warning so doesn't affect conformance.
17791 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17792 if (BO->getOpcode() == BO_Assign) {
17793 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17794 llvm::erase(LHSs, BO->getLHS());
17795 }
17796 }
17797}
17798
17800 assert(getLangOpts().CPlusPlus20 &&
17801 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17802 "Cannot mark an immediate escalating expression outside of an "
17803 "immediate escalating context");
17804 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17805 Call && Call->getCallee()) {
17806 if (auto *DeclRef =
17807 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17808 DeclRef->setIsImmediateEscalating(true);
17809 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17810 Ctr->setIsImmediateEscalating(true);
17811 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17812 DeclRef->setIsImmediateEscalating(true);
17813 } else {
17814 assert(false && "expected an immediately escalating expression");
17815 }
17817 FI->FoundImmediateEscalatingExpression = true;
17818}
17819
17821 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17822 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17825 return E;
17826
17827 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17828 /// It's OK if this fails; we'll also remove this in
17829 /// HandleImmediateInvocations, but catching it here allows us to avoid
17830 /// walking the AST looking for it in simple cases.
17831 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17832 if (auto *DeclRef =
17833 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17834 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17835
17836 // C++23 [expr.const]/p16
17837 // An expression or conversion is immediate-escalating if it is not initially
17838 // in an immediate function context and it is [...] an immediate invocation
17839 // that is not a constant expression and is not a subexpression of an
17840 // immediate invocation.
17841 APValue Cached;
17842 auto CheckConstantExpressionAndKeepResult = [&]() {
17844 Expr::EvalResult Eval;
17845 Eval.Diag = &Notes;
17846 bool Res = E.get()->EvaluateAsConstantExpr(
17847 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17848 if (Res && Notes.empty()) {
17849 Cached = std::move(Eval.Val);
17850 return true;
17851 }
17852 return false;
17853 };
17854
17855 if (!E.get()->isValueDependent() &&
17856 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17857 !CheckConstantExpressionAndKeepResult()) {
17859 return E;
17860 }
17861
17862 if (Cleanup.exprNeedsCleanups()) {
17863 // Since an immediate invocation is a full expression itself - it requires
17864 // an additional ExprWithCleanups node, but it can participate to a bigger
17865 // full expression which actually requires cleanups to be run after so
17866 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17867 // may discard cleanups for outer expression too early.
17868
17869 // Note that ExprWithCleanups created here must always have empty cleanup
17870 // objects:
17871 // - compound literals do not create cleanup objects in C++ and immediate
17872 // invocations are C++-only.
17873 // - blocks are not allowed inside constant expressions and compiler will
17874 // issue an error if they appear there.
17875 //
17876 // Hence, in correct code any cleanup objects created inside current
17877 // evaluation context must be outside the immediate invocation.
17880 }
17881
17883 getASTContext(), E.get(),
17884 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17885 getASTContext()),
17886 /*IsImmediateInvocation*/ true);
17887 if (Cached.hasValue())
17888 Res->MoveIntoResult(Cached, getASTContext());
17889 /// Value-dependent constant expressions should not be immediately
17890 /// evaluated until they are instantiated.
17891 if (!Res->isValueDependent())
17892 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17893 return Res;
17894}
17895
17899 Expr::EvalResult Eval;
17900 Eval.Diag = &Notes;
17901 ConstantExpr *CE = Candidate.getPointer();
17902 bool Result = CE->EvaluateAsConstantExpr(
17903 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17904 if (!Result || !Notes.empty()) {
17906 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17907 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17908 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17909 FunctionDecl *FD = nullptr;
17910 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17911 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17912 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17913 FD = Call->getConstructor();
17914 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17915 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17916
17917 assert(FD && FD->isImmediateFunction() &&
17918 "could not find an immediate function in this expression");
17919 if (FD->isInvalidDecl())
17920 return;
17921 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17922 << FD << FD->isConsteval();
17923 if (auto Context =
17925 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17926 << Context->Decl;
17927 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17928 }
17929 if (!FD->isConsteval())
17931 for (auto &Note : Notes)
17932 SemaRef.Diag(Note.first, Note.second);
17933 return;
17934 }
17936}
17937
17941 struct ComplexRemove : TreeTransform<ComplexRemove> {
17943 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17946 CurrentII;
17947 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17950 4>::reverse_iterator Current)
17951 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17952 void RemoveImmediateInvocation(ConstantExpr* E) {
17953 auto It = std::find_if(CurrentII, IISet.rend(),
17955 return Elem.getPointer() == E;
17956 });
17957 // It is possible that some subexpression of the current immediate
17958 // invocation was handled from another expression evaluation context. Do
17959 // not handle the current immediate invocation if some of its
17960 // subexpressions failed before.
17961 if (It == IISet.rend()) {
17962 if (SemaRef.FailedImmediateInvocations.contains(E))
17963 CurrentII->setInt(1);
17964 } else {
17965 It->setInt(1); // Mark as deleted
17966 }
17967 }
17968 ExprResult TransformConstantExpr(ConstantExpr *E) {
17969 if (!E->isImmediateInvocation())
17970 return Base::TransformConstantExpr(E);
17971 RemoveImmediateInvocation(E);
17972 return Base::TransformExpr(E->getSubExpr());
17973 }
17974 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17975 /// we need to remove its DeclRefExpr from the DRSet.
17976 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17977 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17978 return Base::TransformCXXOperatorCallExpr(E);
17979 }
17980 /// Base::TransformUserDefinedLiteral doesn't preserve the
17981 /// UserDefinedLiteral node.
17982 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17983 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17984 /// here.
17985 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17986 if (!Init)
17987 return Init;
17988
17989 // We cannot use IgnoreImpCasts because we need to preserve
17990 // full expressions.
17991 while (true) {
17992 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
17993 Init = ICE->getSubExpr();
17994 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
17995 Init = ICE->getSubExpr();
17996 else
17997 break;
17998 }
17999 /// ConstantExprs are the first layer of implicit node to be removed so if
18000 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18001 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18002 CE && CE->isImmediateInvocation())
18003 RemoveImmediateInvocation(CE);
18004 return Base::TransformInitializer(Init, NotCopyInit);
18005 }
18006 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18007 DRSet.erase(E);
18008 return E;
18009 }
18010 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18011 // Do not rebuild lambdas to avoid creating a new type.
18012 // Lambdas have already been processed inside their eval contexts.
18013 return E;
18014 }
18015 bool AlwaysRebuild() { return false; }
18016 bool ReplacingOriginal() { return true; }
18017 bool AllowSkippingCXXConstructExpr() {
18018 bool Res = AllowSkippingFirstCXXConstructExpr;
18019 AllowSkippingFirstCXXConstructExpr = true;
18020 return Res;
18021 }
18022 bool AllowSkippingFirstCXXConstructExpr = true;
18023 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18025
18026 /// CXXConstructExpr with a single argument are getting skipped by
18027 /// TreeTransform in some situtation because they could be implicit. This
18028 /// can only occur for the top-level CXXConstructExpr because it is used
18029 /// nowhere in the expression being transformed therefore will not be rebuilt.
18030 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18031 /// skipping the first CXXConstructExpr.
18032 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18033 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18034
18035 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18036 // The result may not be usable in case of previous compilation errors.
18037 // In this case evaluation of the expression may result in crash so just
18038 // don't do anything further with the result.
18039 if (Res.isUsable()) {
18041 It->getPointer()->setSubExpr(Res.get());
18042 }
18043}
18044
18045static void
18048 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18049 Rec.ReferenceToConsteval.size() == 0) ||
18051 return;
18052
18053 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18054 // [...]
18055 // - the initializer of a variable that is usable in constant expressions or
18056 // has constant initialization.
18057 if (SemaRef.getLangOpts().CPlusPlus23 &&
18058 Rec.ExprContext ==
18060 auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);
18061 if (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18062 VD->hasConstantInitialization()) {
18063 // An expression or conversion is in an 'immediate function context' if it
18064 // is potentially evaluated and either:
18065 // [...]
18066 // - it is a subexpression of a manifestly constant-evaluated expression
18067 // or conversion.
18068 return;
18069 }
18070 }
18071
18072 /// When we have more than 1 ImmediateInvocationCandidates or previously
18073 /// failed immediate invocations, we need to check for nested
18074 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18075 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18076 /// invocation.
18077 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18079
18080 /// Prevent sema calls during the tree transform from adding pointers that
18081 /// are already in the sets.
18082 llvm::SaveAndRestore DisableIITracking(
18084
18085 /// Prevent diagnostic during tree transfrom as they are duplicates
18087
18088 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18089 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18090 if (!It->getInt())
18092 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18093 Rec.ReferenceToConsteval.size()) {
18094 struct SimpleRemove : DynamicRecursiveASTVisitor {
18095 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18096 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18097 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18098 DRSet.erase(E);
18099 return DRSet.size();
18100 }
18101 } Visitor(Rec.ReferenceToConsteval);
18102 Visitor.TraverseStmt(
18103 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18104 }
18105 for (auto CE : Rec.ImmediateInvocationCandidates)
18106 if (!CE.getInt())
18108 for (auto *DR : Rec.ReferenceToConsteval) {
18109 // If the expression is immediate escalating, it is not an error;
18110 // The outer context itself becomes immediate and further errors,
18111 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18112 if (DR->isImmediateEscalating())
18113 continue;
18114 auto *FD = cast<FunctionDecl>(DR->getDecl());
18115 const NamedDecl *ND = FD;
18116 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18117 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18118 ND = MD->getParent();
18119
18120 // C++23 [expr.const]/p16
18121 // An expression or conversion is immediate-escalating if it is not
18122 // initially in an immediate function context and it is [...] a
18123 // potentially-evaluated id-expression that denotes an immediate function
18124 // that is not a subexpression of an immediate invocation.
18125 bool ImmediateEscalating = false;
18126 bool IsPotentiallyEvaluated =
18127 Rec.Context ==
18129 Rec.Context ==
18131 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18132 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18133
18135 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18136 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18137 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18138 if (!FD->getBuiltinID())
18139 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18140 if (auto Context =
18142 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18143 << Context->Decl;
18144 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18145 }
18146 if (FD->isImmediateEscalating() && !FD->isConsteval())
18148
18149 } else {
18151 }
18152 }
18153}
18154
18157 if (!Rec.Lambdas.empty()) {
18159 if (!getLangOpts().CPlusPlus20 &&
18160 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18161 Rec.isUnevaluated() ||
18163 unsigned D;
18164 if (Rec.isUnevaluated()) {
18165 // C++11 [expr.prim.lambda]p2:
18166 // A lambda-expression shall not appear in an unevaluated operand
18167 // (Clause 5).
18168 D = diag::err_lambda_unevaluated_operand;
18169 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18170 // C++1y [expr.const]p2:
18171 // A conditional-expression e is a core constant expression unless the
18172 // evaluation of e, following the rules of the abstract machine, would
18173 // evaluate [...] a lambda-expression.
18174 D = diag::err_lambda_in_constant_expression;
18175 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18176 // C++17 [expr.prim.lamda]p2:
18177 // A lambda-expression shall not appear [...] in a template-argument.
18178 D = diag::err_lambda_in_invalid_context;
18179 } else
18180 llvm_unreachable("Couldn't infer lambda error message.");
18181
18182 for (const auto *L : Rec.Lambdas)
18183 Diag(L->getBeginLoc(), D);
18184 }
18185 }
18186
18187 // Append the collected materialized temporaries into previous context before
18188 // exit if the previous also is a lifetime extending context.
18190 parentEvaluationContext().InLifetimeExtendingContext &&
18191 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18194 }
18195
18197 HandleImmediateInvocations(*this, Rec);
18198
18199 // Warn on any volatile-qualified simple-assignments that are not discarded-
18200 // value expressions nor unevaluated operands (those cases get removed from
18201 // this list by CheckUnusedVolatileAssignment).
18202 for (auto *BO : Rec.VolatileAssignmentLHSs)
18203 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18204 << BO->getType();
18205
18206 // When are coming out of an unevaluated context, clear out any
18207 // temporaries that we may have created as part of the evaluation of
18208 // the expression in that context: they aren't relevant because they
18209 // will never be constructed.
18210 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18212 ExprCleanupObjects.end());
18213 Cleanup = Rec.ParentCleanup;
18216 // Otherwise, merge the contexts together.
18217 } else {
18219 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18220 }
18221
18223
18224 // Pop the current expression evaluation context off the stack.
18225 ExprEvalContexts.pop_back();
18226}
18227
18229 ExprCleanupObjects.erase(
18230 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18231 ExprCleanupObjects.end());
18232 Cleanup.reset();
18233 MaybeODRUseExprs.clear();
18234}
18235
18238 if (Result.isInvalid())
18239 return ExprError();
18240 E = Result.get();
18241 if (!E->getType()->isVariablyModifiedType())
18242 return E;
18244}
18245
18246/// Are we in a context that is potentially constant evaluated per C++20
18247/// [expr.const]p12?
18249 /// C++2a [expr.const]p12:
18250 // An expression or conversion is potentially constant evaluated if it is
18251 switch (SemaRef.ExprEvalContexts.back().Context) {
18254
18255 // -- a manifestly constant-evaluated expression,
18259 // -- a potentially-evaluated expression,
18261 // -- an immediate subexpression of a braced-init-list,
18262
18263 // -- [FIXME] an expression of the form & cast-expression that occurs
18264 // within a templated entity
18265 // -- a subexpression of one of the above that is not a subexpression of
18266 // a nested unevaluated operand.
18267 return true;
18268
18271 // Expressions in this context are never evaluated.
18272 return false;
18273 }
18274 llvm_unreachable("Invalid context");
18275}
18276
18277/// Return true if this function has a calling convention that requires mangling
18278/// in the size of the parameter pack.
18280 // These manglings are only applicable for targets whcih use Microsoft
18281 // mangling scheme for C.
18283 return false;
18284
18285 // If this is C++ and this isn't an extern "C" function, parameters do not
18286 // need to be complete. In this case, C++ mangling will apply, which doesn't
18287 // use the size of the parameters.
18288 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18289 return false;
18290
18291 // Stdcall, fastcall, and vectorcall need this special treatment.
18292 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18293 switch (CC) {
18294 case CC_X86StdCall:
18295 case CC_X86FastCall:
18296 case CC_X86VectorCall:
18297 return true;
18298 default:
18299 break;
18300 }
18301 return false;
18302}
18303
18304/// Require that all of the parameter types of function be complete. Normally,
18305/// parameter types are only required to be complete when a function is called
18306/// or defined, but to mangle functions with certain calling conventions, the
18307/// mangler needs to know the size of the parameter list. In this situation,
18308/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18309/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18310/// result in a linker error. Clang doesn't implement this behavior, and instead
18311/// attempts to error at compile time.
18314 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18315 FunctionDecl *FD;
18316 ParmVarDecl *Param;
18317
18318 public:
18319 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18320 : FD(FD), Param(Param) {}
18321
18322 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18323 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18324 StringRef CCName;
18325 switch (CC) {
18326 case CC_X86StdCall:
18327 CCName = "stdcall";
18328 break;
18329 case CC_X86FastCall:
18330 CCName = "fastcall";
18331 break;
18332 case CC_X86VectorCall:
18333 CCName = "vectorcall";
18334 break;
18335 default:
18336 llvm_unreachable("CC does not need mangling");
18337 }
18338
18339 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18340 << Param->getDeclName() << FD->getDeclName() << CCName;
18341 }
18342 };
18343
18344 for (ParmVarDecl *Param : FD->parameters()) {
18345 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18346 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18347 }
18348}
18349
18350namespace {
18351enum class OdrUseContext {
18352 /// Declarations in this context are not odr-used.
18353 None,
18354 /// Declarations in this context are formally odr-used, but this is a
18355 /// dependent context.
18356 Dependent,
18357 /// Declarations in this context are odr-used but not actually used (yet).
18358 FormallyOdrUsed,
18359 /// Declarations in this context are used.
18360 Used
18361};
18362}
18363
18364/// Are we within a context in which references to resolved functions or to
18365/// variables result in odr-use?
18366static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18369
18370 if (Context.isUnevaluated())
18371 return OdrUseContext::None;
18372
18374 return OdrUseContext::Dependent;
18375
18376 if (Context.isDiscardedStatementContext())
18377 return OdrUseContext::FormallyOdrUsed;
18378
18379 else if (Context.Context ==
18381 return OdrUseContext::FormallyOdrUsed;
18382
18383 return OdrUseContext::Used;
18384}
18385
18387 if (!Func->isConstexpr())
18388 return false;
18389
18390 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18391 return true;
18392
18393 // Lambda conversion operators are never user provided.
18394 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18395 return isLambdaConversionOperator(Conv);
18396
18397 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18398 return CCD && CCD->getInheritedConstructor();
18399}
18400
18402 bool MightBeOdrUse) {
18403 assert(Func && "No function?");
18404
18405 Func->setReferenced();
18406
18407 // Recursive functions aren't really used until they're used from some other
18408 // context.
18409 bool IsRecursiveCall = CurContext == Func;
18410
18411 // C++11 [basic.def.odr]p3:
18412 // A function whose name appears as a potentially-evaluated expression is
18413 // odr-used if it is the unique lookup result or the selected member of a
18414 // set of overloaded functions [...].
18415 //
18416 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18417 // can just check that here.
18418 OdrUseContext OdrUse =
18419 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18420 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18421 OdrUse = OdrUseContext::FormallyOdrUsed;
18422
18423 // Trivial default constructors and destructors are never actually used.
18424 // FIXME: What about other special members?
18425 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18426 OdrUse == OdrUseContext::Used) {
18427 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18428 if (Constructor->isDefaultConstructor())
18429 OdrUse = OdrUseContext::FormallyOdrUsed;
18430 if (isa<CXXDestructorDecl>(Func))
18431 OdrUse = OdrUseContext::FormallyOdrUsed;
18432 }
18433
18434 // C++20 [expr.const]p12:
18435 // A function [...] is needed for constant evaluation if it is [...] a
18436 // constexpr function that is named by an expression that is potentially
18437 // constant evaluated
18438 bool NeededForConstantEvaluation =
18441
18442 // Determine whether we require a function definition to exist, per
18443 // C++11 [temp.inst]p3:
18444 // Unless a function template specialization has been explicitly
18445 // instantiated or explicitly specialized, the function template
18446 // specialization is implicitly instantiated when the specialization is
18447 // referenced in a context that requires a function definition to exist.
18448 // C++20 [temp.inst]p7:
18449 // The existence of a definition of a [...] function is considered to
18450 // affect the semantics of the program if the [...] function is needed for
18451 // constant evaluation by an expression
18452 // C++20 [basic.def.odr]p10:
18453 // Every program shall contain exactly one definition of every non-inline
18454 // function or variable that is odr-used in that program outside of a
18455 // discarded statement
18456 // C++20 [special]p1:
18457 // The implementation will implicitly define [defaulted special members]
18458 // if they are odr-used or needed for constant evaluation.
18459 //
18460 // Note that we skip the implicit instantiation of templates that are only
18461 // used in unused default arguments or by recursive calls to themselves.
18462 // This is formally non-conforming, but seems reasonable in practice.
18463 bool NeedDefinition =
18464 !IsRecursiveCall &&
18465 (OdrUse == OdrUseContext::Used ||
18466 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18467
18468 // C++14 [temp.expl.spec]p6:
18469 // If a template [...] is explicitly specialized then that specialization
18470 // shall be declared before the first use of that specialization that would
18471 // cause an implicit instantiation to take place, in every translation unit
18472 // in which such a use occurs
18473 if (NeedDefinition &&
18474 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18475 Func->getMemberSpecializationInfo()))
18477
18478 if (getLangOpts().CUDA)
18479 CUDA().CheckCall(Loc, Func);
18480
18481 // If we need a definition, try to create one.
18482 if (NeedDefinition && !Func->getBody()) {
18485 dyn_cast<CXXConstructorDecl>(Func)) {
18486 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18487 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18488 if (Constructor->isDefaultConstructor()) {
18489 if (Constructor->isTrivial() &&
18490 !Constructor->hasAttr<DLLExportAttr>())
18491 return;
18493 } else if (Constructor->isCopyConstructor()) {
18495 } else if (Constructor->isMoveConstructor()) {
18497 }
18498 } else if (Constructor->getInheritedConstructor()) {
18500 }
18501 } else if (CXXDestructorDecl *Destructor =
18502 dyn_cast<CXXDestructorDecl>(Func)) {
18503 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18504 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18505 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18506 return;
18508 }
18509 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18510 MarkVTableUsed(Loc, Destructor->getParent());
18511 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18512 if (MethodDecl->isOverloadedOperator() &&
18513 MethodDecl->getOverloadedOperator() == OO_Equal) {
18514 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18515 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18516 if (MethodDecl->isCopyAssignmentOperator())
18517 DefineImplicitCopyAssignment(Loc, MethodDecl);
18518 else if (MethodDecl->isMoveAssignmentOperator())
18519 DefineImplicitMoveAssignment(Loc, MethodDecl);
18520 }
18521 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18522 MethodDecl->getParent()->isLambda()) {
18523 CXXConversionDecl *Conversion =
18524 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18525 if (Conversion->isLambdaToBlockPointerConversion())
18527 else
18529 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18530 MarkVTableUsed(Loc, MethodDecl->getParent());
18531 }
18532
18533 if (Func->isDefaulted() && !Func->isDeleted()) {
18537 }
18538
18539 // Implicit instantiation of function templates and member functions of
18540 // class templates.
18541 if (Func->isImplicitlyInstantiable()) {
18543 Func->getTemplateSpecializationKindForInstantiation();
18544 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18545 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18546 if (FirstInstantiation) {
18547 PointOfInstantiation = Loc;
18548 if (auto *MSI = Func->getMemberSpecializationInfo())
18549 MSI->setPointOfInstantiation(Loc);
18550 // FIXME: Notify listener.
18551 else
18552 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18553 } else if (TSK != TSK_ImplicitInstantiation) {
18554 // Use the point of use as the point of instantiation, instead of the
18555 // point of explicit instantiation (which we track as the actual point
18556 // of instantiation). This gives better backtraces in diagnostics.
18557 PointOfInstantiation = Loc;
18558 }
18559
18560 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18561 Func->isConstexpr()) {
18562 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18563 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18564 CodeSynthesisContexts.size())
18566 std::make_pair(Func, PointOfInstantiation));
18567 else if (Func->isConstexpr())
18568 // Do not defer instantiations of constexpr functions, to avoid the
18569 // expression evaluator needing to call back into Sema if it sees a
18570 // call to such a function.
18571 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18572 else {
18573 Func->setInstantiationIsPending(true);
18574 PendingInstantiations.push_back(
18575 std::make_pair(Func, PointOfInstantiation));
18576 if (llvm::isTimeTraceVerbose()) {
18577 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18578 std::string Name;
18579 llvm::raw_string_ostream OS(Name);
18580 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18581 /*Qualified=*/true);
18582 return Name;
18583 });
18584 }
18585 // Notify the consumer that a function was implicitly instantiated.
18587 }
18588 }
18589 } else {
18590 // Walk redefinitions, as some of them may be instantiable.
18591 for (auto *i : Func->redecls()) {
18592 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18593 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18594 }
18595 }
18596 });
18597 }
18598
18599 // If a constructor was defined in the context of a default parameter
18600 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18601 // context), its initializers may not be referenced yet.
18602 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18604 *this,
18605 Constructor->isImmediateFunction()
18608 Constructor);
18609 for (CXXCtorInitializer *Init : Constructor->inits()) {
18610 if (Init->isInClassMemberInitializer())
18611 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18612 MarkDeclarationsReferencedInExpr(Init->getInit());
18613 });
18614 }
18615 }
18616
18617 // C++14 [except.spec]p17:
18618 // An exception-specification is considered to be needed when:
18619 // - the function is odr-used or, if it appears in an unevaluated operand,
18620 // would be odr-used if the expression were potentially-evaluated;
18621 //
18622 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18623 // function is a pure virtual function we're calling, and in that case the
18624 // function was selected by overload resolution and we need to resolve its
18625 // exception specification for a different reason.
18626 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18629
18630 // A callee could be called by a host function then by a device function.
18631 // If we only try recording once, we will miss recording the use on device
18632 // side. Therefore keep trying until it is recorded.
18633 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18636
18637 // If this is the first "real" use, act on that.
18638 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18639 // Keep track of used but undefined functions.
18640 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18641 if (mightHaveNonExternalLinkage(Func))
18642 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18643 else if (Func->getMostRecentDecl()->isInlined() &&
18644 !LangOpts.GNUInline &&
18645 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18646 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18648 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18649 }
18650
18651 // Some x86 Windows calling conventions mangle the size of the parameter
18652 // pack into the name. Computing the size of the parameters requires the
18653 // parameter types to be complete. Check that now.
18656
18657 // In the MS C++ ABI, the compiler emits destructor variants where they are
18658 // used. If the destructor is used here but defined elsewhere, mark the
18659 // virtual base destructors referenced. If those virtual base destructors
18660 // are inline, this will ensure they are defined when emitting the complete
18661 // destructor variant. This checking may be redundant if the destructor is
18662 // provided later in this TU.
18664 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18665 CXXRecordDecl *Parent = Dtor->getParent();
18666 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18668 }
18669 }
18670
18671 Func->markUsed(Context);
18672 }
18673}
18674
18675/// Directly mark a variable odr-used. Given a choice, prefer to use
18676/// MarkVariableReferenced since it does additional checks and then
18677/// calls MarkVarDeclODRUsed.
18678/// If the variable must be captured:
18679/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18680/// - else capture it in the DeclContext that maps to the
18681/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18682static void
18684 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18685 // Keep track of used but undefined variables.
18686 // FIXME: We shouldn't suppress this warning for static data members.
18687 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18688 assert(Var && "expected a capturable variable");
18689
18691 (!Var->isExternallyVisible() || Var->isInline() ||
18693 !(Var->isStaticDataMember() && Var->hasInit())) {
18695 if (old.isInvalid())
18696 old = Loc;
18697 }
18698 QualType CaptureType, DeclRefType;
18699 if (SemaRef.LangOpts.OpenMP)
18702 /*EllipsisLoc*/ SourceLocation(),
18703 /*BuildAndDiagnose*/ true, CaptureType,
18704 DeclRefType, FunctionScopeIndexToStopAt);
18705
18706 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18707 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18708 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18709 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18710 if (VarTarget == SemaCUDA::CVT_Host &&
18711 (UserTarget == CUDAFunctionTarget::Device ||
18712 UserTarget == CUDAFunctionTarget::HostDevice ||
18713 UserTarget == CUDAFunctionTarget::Global)) {
18714 // Diagnose ODR-use of host global variables in device functions.
18715 // Reference of device global variables in host functions is allowed
18716 // through shadow variables therefore it is not diagnosed.
18717 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18718 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18719 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18721 Var->getType().isConstQualified()
18722 ? diag::note_cuda_const_var_unpromoted
18723 : diag::note_cuda_host_var);
18724 }
18725 } else if (VarTarget == SemaCUDA::CVT_Device &&
18726 !Var->hasAttr<CUDASharedAttr>() &&
18727 (UserTarget == CUDAFunctionTarget::Host ||
18728 UserTarget == CUDAFunctionTarget::HostDevice)) {
18729 // Record a CUDA/HIP device side variable if it is ODR-used
18730 // by host code. This is done conservatively, when the variable is
18731 // referenced in any of the following contexts:
18732 // - a non-function context
18733 // - a host function
18734 // - a host device function
18735 // This makes the ODR-use of the device side variable by host code to
18736 // be visible in the device compilation for the compiler to be able to
18737 // emit template variables instantiated by host code only and to
18738 // externalize the static device side variable ODR-used by host code.
18739 if (!Var->hasExternalStorage())
18741 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18742 (!FD || (!FD->getDescribedFunctionTemplate() &&
18746 }
18747 }
18748
18749 V->markUsed(SemaRef.Context);
18750}
18751
18754 unsigned CapturingScopeIndex) {
18755 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18756}
18757
18759 SourceLocation loc,
18760 ValueDecl *var) {
18761 DeclContext *VarDC = var->getDeclContext();
18762
18763 // If the parameter still belongs to the translation unit, then
18764 // we're actually just using one parameter in the declaration of
18765 // the next.
18766 if (isa<ParmVarDecl>(var) &&
18767 isa<TranslationUnitDecl>(VarDC))
18768 return;
18769
18770 // For C code, don't diagnose about capture if we're not actually in code
18771 // right now; it's impossible to write a non-constant expression outside of
18772 // function context, so we'll get other (more useful) diagnostics later.
18773 //
18774 // For C++, things get a bit more nasty... it would be nice to suppress this
18775 // diagnostic for certain cases like using a local variable in an array bound
18776 // for a member of a local class, but the correct predicate is not obvious.
18777 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18778 return;
18779
18780 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18781 unsigned ContextKind = 3; // unknown
18782 if (isa<CXXMethodDecl>(VarDC) &&
18783 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18784 ContextKind = 2;
18785 } else if (isa<FunctionDecl>(VarDC)) {
18786 ContextKind = 0;
18787 } else if (isa<BlockDecl>(VarDC)) {
18788 ContextKind = 1;
18789 }
18790
18791 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18792 << var << ValueKind << ContextKind << VarDC;
18793 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18794 << var;
18795
18796 // FIXME: Add additional diagnostic info about class etc. which prevents
18797 // capture.
18798}
18799
18801 ValueDecl *Var,
18802 bool &SubCapturesAreNested,
18803 QualType &CaptureType,
18804 QualType &DeclRefType) {
18805 // Check whether we've already captured it.
18806 if (CSI->CaptureMap.count(Var)) {
18807 // If we found a capture, any subcaptures are nested.
18808 SubCapturesAreNested = true;
18809
18810 // Retrieve the capture type for this variable.
18811 CaptureType = CSI->getCapture(Var).getCaptureType();
18812
18813 // Compute the type of an expression that refers to this variable.
18814 DeclRefType = CaptureType.getNonReferenceType();
18815
18816 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18817 // are mutable in the sense that user can change their value - they are
18818 // private instances of the captured declarations.
18819 const Capture &Cap = CSI->getCapture(Var);
18820 // C++ [expr.prim.lambda]p10:
18821 // The type of such a data member is [...] an lvalue reference to the
18822 // referenced function type if the entity is a reference to a function.
18823 // [...]
18824 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18825 !(isa<LambdaScopeInfo>(CSI) &&
18826 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18827 !(isa<CapturedRegionScopeInfo>(CSI) &&
18828 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18829 DeclRefType.addConst();
18830 return true;
18831 }
18832 return false;
18833}
18834
18835// Only block literals, captured statements, and lambda expressions can
18836// capture; other scopes don't work.
18838 ValueDecl *Var,
18840 const bool Diagnose,
18841 Sema &S) {
18842 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18844
18845 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18846 if (Underlying) {
18847 if (Underlying->hasLocalStorage() && Diagnose)
18849 }
18850 return nullptr;
18851}
18852
18853// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18854// certain types of variables (unnamed, variably modified types etc.)
18855// so check for eligibility.
18857 SourceLocation Loc, const bool Diagnose,
18858 Sema &S) {
18859
18860 assert((isa<VarDecl, BindingDecl>(Var)) &&
18861 "Only variables and structured bindings can be captured");
18862
18863 bool IsBlock = isa<BlockScopeInfo>(CSI);
18864 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18865
18866 // Lambdas are not allowed to capture unnamed variables
18867 // (e.g. anonymous unions).
18868 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18869 // assuming that's the intent.
18870 if (IsLambda && !Var->getDeclName()) {
18871 if (Diagnose) {
18872 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18873 S.Diag(Var->getLocation(), diag::note_declared_at);
18874 }
18875 return false;
18876 }
18877
18878 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18879 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18880 if (Diagnose) {
18881 S.Diag(Loc, diag::err_ref_vm_type);
18882 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18883 }
18884 return false;
18885 }
18886 // Prohibit structs with flexible array members too.
18887 // We cannot capture what is in the tail end of the struct.
18888 if (const auto *VTD = Var->getType()->getAsRecordDecl();
18889 VTD && VTD->hasFlexibleArrayMember()) {
18890 if (Diagnose) {
18891 if (IsBlock)
18892 S.Diag(Loc, diag::err_ref_flexarray_type);
18893 else
18894 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18895 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18896 }
18897 return false;
18898 }
18899 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18900 // Lambdas and captured statements are not allowed to capture __block
18901 // variables; they don't support the expected semantics.
18902 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18903 if (Diagnose) {
18904 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18905 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18906 }
18907 return false;
18908 }
18909 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18910 if (S.getLangOpts().OpenCL && IsBlock &&
18911 Var->getType()->isBlockPointerType()) {
18912 if (Diagnose)
18913 S.Diag(Loc, diag::err_opencl_block_ref_block);
18914 return false;
18915 }
18916
18917 if (isa<BindingDecl>(Var)) {
18918 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18919 if (Diagnose)
18921 return false;
18922 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18923 S.Diag(Loc, S.LangOpts.CPlusPlus20
18924 ? diag::warn_cxx17_compat_capture_binding
18925 : diag::ext_capture_binding)
18926 << Var;
18927 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18928 }
18929 }
18930
18931 return true;
18932}
18933
18934// Returns true if the capture by block was successful.
18936 SourceLocation Loc, const bool BuildAndDiagnose,
18937 QualType &CaptureType, QualType &DeclRefType,
18938 const bool Nested, Sema &S, bool Invalid) {
18939 bool ByRef = false;
18940
18941 // Blocks are not allowed to capture arrays, excepting OpenCL.
18942 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18943 // (decayed to pointers).
18944 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18945 if (BuildAndDiagnose) {
18946 S.Diag(Loc, diag::err_ref_array_type);
18947 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18948 Invalid = true;
18949 } else {
18950 return false;
18951 }
18952 }
18953
18954 // Forbid the block-capture of autoreleasing variables.
18955 if (!Invalid &&
18957 if (BuildAndDiagnose) {
18958 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18959 << /*block*/ 0;
18960 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18961 Invalid = true;
18962 } else {
18963 return false;
18964 }
18965 }
18966
18967 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18968 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18969 QualType PointeeTy = PT->getPointeeType();
18970
18971 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18973 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18974 if (BuildAndDiagnose) {
18975 SourceLocation VarLoc = Var->getLocation();
18976 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18977 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18978 }
18979 }
18980 }
18981
18982 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18983 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18984 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18985 // Block capture by reference does not change the capture or
18986 // declaration reference types.
18987 ByRef = true;
18988 } else {
18989 // Block capture by copy introduces 'const'.
18990 CaptureType = CaptureType.getNonReferenceType().withConst();
18991 DeclRefType = CaptureType;
18992 }
18993
18994 // Actually capture the variable.
18995 if (BuildAndDiagnose)
18996 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18997 CaptureType, Invalid);
18998
18999 return !Invalid;
19000}
19001
19002/// Capture the given variable in the captured region.
19005 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19006 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19007 Sema &S, bool Invalid) {
19008 // By default, capture variables by reference.
19009 bool ByRef = true;
19010 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19011 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19012 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19013 // Using an LValue reference type is consistent with Lambdas (see below).
19014 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19015 bool HasConst = DeclRefType.isConstQualified();
19016 DeclRefType = DeclRefType.getUnqualifiedType();
19017 // Don't lose diagnostics about assignments to const.
19018 if (HasConst)
19019 DeclRefType.addConst();
19020 }
19021 // Do not capture firstprivates in tasks.
19022 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19023 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19024 return true;
19025 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19026 RSI->OpenMPCaptureLevel);
19027 }
19028
19029 if (ByRef)
19030 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19031 else
19032 CaptureType = DeclRefType;
19033
19034 // Actually capture the variable.
19035 if (BuildAndDiagnose)
19036 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19037 Loc, SourceLocation(), CaptureType, Invalid);
19038
19039 return !Invalid;
19040}
19041
19042/// Capture the given variable in the lambda.
19044 SourceLocation Loc, const bool BuildAndDiagnose,
19045 QualType &CaptureType, QualType &DeclRefType,
19046 const bool RefersToCapturedVariable,
19047 const TryCaptureKind Kind,
19048 SourceLocation EllipsisLoc, const bool IsTopScope,
19049 Sema &S, bool Invalid) {
19050 // Determine whether we are capturing by reference or by value.
19051 bool ByRef = false;
19052 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19053 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19054 } else {
19055 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19056 }
19057
19058 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19060 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19061 Invalid = true;
19062 }
19063
19064 // Compute the type of the field that will capture this variable.
19065 if (ByRef) {
19066 // C++11 [expr.prim.lambda]p15:
19067 // An entity is captured by reference if it is implicitly or
19068 // explicitly captured but not captured by copy. It is
19069 // unspecified whether additional unnamed non-static data
19070 // members are declared in the closure type for entities
19071 // captured by reference.
19072 //
19073 // FIXME: It is not clear whether we want to build an lvalue reference
19074 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19075 // to do the former, while EDG does the latter. Core issue 1249 will
19076 // clarify, but for now we follow GCC because it's a more permissive and
19077 // easily defensible position.
19078 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19079 } else {
19080 // C++11 [expr.prim.lambda]p14:
19081 // For each entity captured by copy, an unnamed non-static
19082 // data member is declared in the closure type. The
19083 // declaration order of these members is unspecified. The type
19084 // of such a data member is the type of the corresponding
19085 // captured entity if the entity is not a reference to an
19086 // object, or the referenced type otherwise. [Note: If the
19087 // captured entity is a reference to a function, the
19088 // corresponding data member is also a reference to a
19089 // function. - end note ]
19090 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19091 if (!RefType->getPointeeType()->isFunctionType())
19092 CaptureType = RefType->getPointeeType();
19093 }
19094
19095 // Forbid the lambda copy-capture of autoreleasing variables.
19096 if (!Invalid &&
19098 if (BuildAndDiagnose) {
19099 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19100 S.Diag(Var->getLocation(), diag::note_previous_decl)
19101 << Var->getDeclName();
19102 Invalid = true;
19103 } else {
19104 return false;
19105 }
19106 }
19107
19108 // Make sure that by-copy captures are of a complete and non-abstract type.
19109 if (!Invalid && BuildAndDiagnose) {
19110 if (!CaptureType->isDependentType() &&
19112 Loc, CaptureType,
19113 diag::err_capture_of_incomplete_or_sizeless_type,
19114 Var->getDeclName()))
19115 Invalid = true;
19116 else if (S.RequireNonAbstractType(Loc, CaptureType,
19117 diag::err_capture_of_abstract_type))
19118 Invalid = true;
19119 }
19120 }
19121
19122 // Compute the type of a reference to this captured variable.
19123 if (ByRef)
19124 DeclRefType = CaptureType.getNonReferenceType();
19125 else {
19126 // C++ [expr.prim.lambda]p5:
19127 // The closure type for a lambda-expression has a public inline
19128 // function call operator [...]. This function call operator is
19129 // declared const (9.3.1) if and only if the lambda-expression's
19130 // parameter-declaration-clause is not followed by mutable.
19131 DeclRefType = CaptureType.getNonReferenceType();
19132 bool Const = LSI->lambdaCaptureShouldBeConst();
19133 // C++ [expr.prim.lambda]p10:
19134 // The type of such a data member is [...] an lvalue reference to the
19135 // referenced function type if the entity is a reference to a function.
19136 // [...]
19137 if (Const && !CaptureType->isReferenceType() &&
19138 !DeclRefType->isFunctionType())
19139 DeclRefType.addConst();
19140 }
19141
19142 // Add the capture.
19143 if (BuildAndDiagnose)
19144 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19145 Loc, EllipsisLoc, CaptureType, Invalid);
19146
19147 return !Invalid;
19148}
19149
19151 const ASTContext &Context) {
19152 // Offer a Copy fix even if the type is dependent.
19153 if (Var->getType()->isDependentType())
19154 return true;
19156 if (T.isTriviallyCopyableType(Context))
19157 return true;
19158 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19159
19160 if (!(RD = RD->getDefinition()))
19161 return false;
19162 if (RD->hasSimpleCopyConstructor())
19163 return true;
19164 if (RD->hasUserDeclaredCopyConstructor())
19165 for (CXXConstructorDecl *Ctor : RD->ctors())
19166 if (Ctor->isCopyConstructor())
19167 return !Ctor->isDeleted();
19168 }
19169 return false;
19170}
19171
19172/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19173/// default capture. Fixes may be omitted if they aren't allowed by the
19174/// standard, for example we can't emit a default copy capture fix-it if we
19175/// already explicitly copy capture capture another variable.
19177 ValueDecl *Var) {
19179 // Don't offer Capture by copy of default capture by copy fixes if Var is
19180 // known not to be copy constructible.
19181 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19182
19183 SmallString<32> FixBuffer;
19184 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19185 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19186 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19187 if (ShouldOfferCopyFix) {
19188 // Offer fixes to insert an explicit capture for the variable.
19189 // [] -> [VarName]
19190 // [OtherCapture] -> [OtherCapture, VarName]
19191 FixBuffer.assign({Separator, Var->getName()});
19192 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19193 << Var << /*value*/ 0
19194 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19195 }
19196 // As above but capture by reference.
19197 FixBuffer.assign({Separator, "&", Var->getName()});
19198 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19199 << Var << /*reference*/ 1
19200 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19201 }
19202
19203 // Only try to offer default capture if there are no captures excluding this
19204 // and init captures.
19205 // [this]: OK.
19206 // [X = Y]: OK.
19207 // [&A, &B]: Don't offer.
19208 // [A, B]: Don't offer.
19209 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19210 return !C.isThisCapture() && !C.isInitCapture();
19211 }))
19212 return;
19213
19214 // The default capture specifiers, '=' or '&', must appear first in the
19215 // capture body.
19216 SourceLocation DefaultInsertLoc =
19218
19219 if (ShouldOfferCopyFix) {
19220 bool CanDefaultCopyCapture = true;
19221 // [=, *this] OK since c++17
19222 // [=, this] OK since c++20
19223 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19224 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19226 : false;
19227 // We can't use default capture by copy if any captures already specified
19228 // capture by copy.
19229 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19230 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19231 })) {
19232 FixBuffer.assign({"=", Separator});
19233 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19234 << /*value*/ 0
19235 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19236 }
19237 }
19238
19239 // We can't use default capture by reference if any captures already specified
19240 // capture by reference.
19241 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19242 return !C.isInitCapture() && C.isReferenceCapture() &&
19243 !C.isThisCapture();
19244 })) {
19245 FixBuffer.assign({"&", Separator});
19246 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19247 << /*reference*/ 1
19248 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19249 }
19250}
19251
19253 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19254 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19255 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19256 // An init-capture is notionally from the context surrounding its
19257 // declaration, but its parent DC is the lambda class.
19258 DeclContext *VarDC = Var->getDeclContext();
19259 DeclContext *DC = CurContext;
19260
19261 // Skip past RequiresExprBodys because they don't constitute function scopes.
19262 while (DC->isRequiresExprBody())
19263 DC = DC->getParent();
19264
19265 // tryCaptureVariable is called every time a DeclRef is formed,
19266 // it can therefore have non-negigible impact on performances.
19267 // For local variables and when there is no capturing scope,
19268 // we can bailout early.
19269 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19270 return true;
19271
19272 // Exception: Function parameters are not tied to the function's DeclContext
19273 // until we enter the function definition. Capturing them anyway would result
19274 // in an out-of-bounds error while traversing DC and its parents.
19275 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19276 return true;
19277
19278 const auto *VD = dyn_cast<VarDecl>(Var);
19279 if (VD) {
19280 if (VD->isInitCapture())
19281 VarDC = VarDC->getParent();
19282 } else {
19284 }
19285 assert(VD && "Cannot capture a null variable");
19286
19287 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19288 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19289 // We need to sync up the Declaration Context with the
19290 // FunctionScopeIndexToStopAt
19291 if (FunctionScopeIndexToStopAt) {
19292 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19293 unsigned FSIndex = FunctionScopes.size() - 1;
19294 // When we're parsing the lambda parameter list, the current DeclContext is
19295 // NOT the lambda but its parent. So move away the current LSI before
19296 // aligning DC and FunctionScopeIndexToStopAt.
19297 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19298 FSIndex && LSI && !LSI->AfterParameterList)
19299 --FSIndex;
19300 assert(MaxFunctionScopesIndex <= FSIndex &&
19301 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19302 "FunctionScopes.");
19303 while (FSIndex != MaxFunctionScopesIndex) {
19305 --FSIndex;
19306 }
19307 }
19308
19309 // Capture global variables if it is required to use private copy of this
19310 // variable.
19311 bool IsGlobal = !VD->hasLocalStorage();
19312 if (IsGlobal && !(LangOpts.OpenMP &&
19313 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19314 MaxFunctionScopesIndex)))
19315 return true;
19316
19317 if (isa<VarDecl>(Var))
19318 Var = cast<VarDecl>(Var->getCanonicalDecl());
19319
19320 // Walk up the stack to determine whether we can capture the variable,
19321 // performing the "simple" checks that don't depend on type. We stop when
19322 // we've either hit the declared scope of the variable or find an existing
19323 // capture of that variable. We start from the innermost capturing-entity
19324 // (the DC) and ensure that all intervening capturing-entities
19325 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19326 // declcontext can either capture the variable or have already captured
19327 // the variable.
19328 CaptureType = Var->getType();
19329 DeclRefType = CaptureType.getNonReferenceType();
19330 bool Nested = false;
19331 bool Explicit = (Kind != TryCaptureKind::Implicit);
19332 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19333 do {
19334
19335 LambdaScopeInfo *LSI = nullptr;
19336 if (!FunctionScopes.empty())
19337 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19338 FunctionScopes[FunctionScopesIndex]);
19339
19340 bool IsInScopeDeclarationContext =
19341 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19342
19343 if (LSI && !LSI->AfterParameterList) {
19344 // This allows capturing parameters from a default value which does not
19345 // seems correct
19346 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19347 return true;
19348 }
19349 // If the variable is declared in the current context, there is no need to
19350 // capture it.
19351 if (IsInScopeDeclarationContext &&
19352 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19353 return true;
19354
19355 // Only block literals, captured statements, and lambda expressions can
19356 // capture; other scopes don't work.
19357 DeclContext *ParentDC =
19358 !IsInScopeDeclarationContext
19359 ? DC->getParent()
19360 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19361 BuildAndDiagnose, *this);
19362 // We need to check for the parent *first* because, if we *have*
19363 // private-captured a global variable, we need to recursively capture it in
19364 // intermediate blocks, lambdas, etc.
19365 if (!ParentDC) {
19366 if (IsGlobal) {
19367 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19368 break;
19369 }
19370 return true;
19371 }
19372
19373 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19374 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19375
19376 // Check whether we've already captured it.
19377 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19378 DeclRefType)) {
19379 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19380 break;
19381 }
19382
19383 // When evaluating some attributes (like enable_if) we might refer to a
19384 // function parameter appertaining to the same declaration as that
19385 // attribute.
19386 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19387 Parm && Parm->getDeclContext() == DC)
19388 return true;
19389
19390 // If we are instantiating a generic lambda call operator body,
19391 // we do not want to capture new variables. What was captured
19392 // during either a lambdas transformation or initial parsing
19393 // should be used.
19395 if (BuildAndDiagnose) {
19396 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19398 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19399 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19400 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19401 buildLambdaCaptureFixit(*this, LSI, Var);
19402 } else
19404 }
19405 return true;
19406 }
19407
19408 // Try to capture variable-length arrays types.
19409 if (Var->getType()->isVariablyModifiedType()) {
19410 // We're going to walk down into the type and look for VLA
19411 // expressions.
19412 QualType QTy = Var->getType();
19413 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19414 QTy = PVD->getOriginalType();
19416 }
19417
19418 if (getLangOpts().OpenMP) {
19419 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19420 // OpenMP private variables should not be captured in outer scope, so
19421 // just break here. Similarly, global variables that are captured in a
19422 // target region should not be captured outside the scope of the region.
19423 if (RSI->CapRegionKind == CR_OpenMP) {
19424 // FIXME: We should support capturing structured bindings in OpenMP.
19425 if (isa<BindingDecl>(Var)) {
19426 if (BuildAndDiagnose) {
19427 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19428 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19429 }
19430 return true;
19431 }
19432 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19433 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19434 // If the variable is private (i.e. not captured) and has variably
19435 // modified type, we still need to capture the type for correct
19436 // codegen in all regions, associated with the construct. Currently,
19437 // it is captured in the innermost captured region only.
19438 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19439 Var->getType()->isVariablyModifiedType()) {
19440 QualType QTy = Var->getType();
19441 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19442 QTy = PVD->getOriginalType();
19443 for (int I = 1,
19444 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19445 I < E; ++I) {
19446 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19447 FunctionScopes[FunctionScopesIndex - I]);
19448 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19449 "Wrong number of captured regions associated with the "
19450 "OpenMP construct.");
19451 captureVariablyModifiedType(Context, QTy, OuterRSI);
19452 }
19453 }
19454 bool IsTargetCap =
19455 IsOpenMPPrivateDecl != OMPC_private &&
19456 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19457 RSI->OpenMPCaptureLevel);
19458 // Do not capture global if it is not privatized in outer regions.
19459 bool IsGlobalCap =
19460 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19461 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19462
19463 // When we detect target captures we are looking from inside the
19464 // target region, therefore we need to propagate the capture from the
19465 // enclosing region. Therefore, the capture is not initially nested.
19466 if (IsTargetCap)
19467 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19468 RSI->OpenMPLevel);
19469
19470 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19471 (IsGlobal && !IsGlobalCap)) {
19472 Nested = !IsTargetCap;
19473 bool HasConst = DeclRefType.isConstQualified();
19474 DeclRefType = DeclRefType.getUnqualifiedType();
19475 // Don't lose diagnostics about assignments to const.
19476 if (HasConst)
19477 DeclRefType.addConst();
19478 CaptureType = Context.getLValueReferenceType(DeclRefType);
19479 break;
19480 }
19481 }
19482 }
19483 }
19485 // No capture-default, and this is not an explicit capture
19486 // so cannot capture this variable.
19487 if (BuildAndDiagnose) {
19488 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19489 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19490 auto *LSI = cast<LambdaScopeInfo>(CSI);
19491 if (LSI->Lambda) {
19492 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19493 buildLambdaCaptureFixit(*this, LSI, Var);
19494 }
19495 // FIXME: If we error out because an outer lambda can not implicitly
19496 // capture a variable that an inner lambda explicitly captures, we
19497 // should have the inner lambda do the explicit capture - because
19498 // it makes for cleaner diagnostics later. This would purely be done
19499 // so that the diagnostic does not misleadingly claim that a variable
19500 // can not be captured by a lambda implicitly even though it is captured
19501 // explicitly. Suggestion:
19502 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19503 // at the function head
19504 // - cache the StartingDeclContext - this must be a lambda
19505 // - captureInLambda in the innermost lambda the variable.
19506 }
19507 return true;
19508 }
19509 Explicit = false;
19510 FunctionScopesIndex--;
19511 if (IsInScopeDeclarationContext)
19512 DC = ParentDC;
19513 } while (!VarDC->Equals(DC));
19514
19515 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19516 // computing the type of the capture at each step, checking type-specific
19517 // requirements, and adding captures if requested.
19518 // If the variable had already been captured previously, we start capturing
19519 // at the lambda nested within that one.
19520 bool Invalid = false;
19521 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19522 ++I) {
19523 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19524
19525 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19526 // certain types of variables (unnamed, variably modified types etc.)
19527 // so check for eligibility.
19528 if (!Invalid)
19529 Invalid =
19530 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19531
19532 // After encountering an error, if we're actually supposed to capture, keep
19533 // capturing in nested contexts to suppress any follow-on diagnostics.
19534 if (Invalid && !BuildAndDiagnose)
19535 return true;
19536
19537 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19538 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19539 DeclRefType, Nested, *this, Invalid);
19540 Nested = true;
19541 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19543 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19544 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19545 Nested = true;
19546 } else {
19547 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19548 Invalid =
19549 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19550 DeclRefType, Nested, Kind, EllipsisLoc,
19551 /*IsTopScope*/ I == N - 1, *this, Invalid);
19552 Nested = true;
19553 }
19554
19555 if (Invalid && !BuildAndDiagnose)
19556 return true;
19557 }
19558 return Invalid;
19559}
19560
19562 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19563 QualType CaptureType;
19564 QualType DeclRefType;
19565 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19566 /*BuildAndDiagnose=*/true, CaptureType,
19567 DeclRefType, nullptr);
19568}
19569
19571 QualType CaptureType;
19572 QualType DeclRefType;
19573 return !tryCaptureVariable(
19575 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19576}
19577
19579 assert(Var && "Null value cannot be captured");
19580
19581 QualType CaptureType;
19582 QualType DeclRefType;
19583
19584 // Determine whether we can capture this variable.
19586 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19587 nullptr))
19588 return QualType();
19589
19590 return DeclRefType;
19591}
19592
19593namespace {
19594// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19595// The produced TemplateArgumentListInfo* points to data stored within this
19596// object, so should only be used in contexts where the pointer will not be
19597// used after the CopiedTemplateArgs object is destroyed.
19598class CopiedTemplateArgs {
19599 bool HasArgs;
19600 TemplateArgumentListInfo TemplateArgStorage;
19601public:
19602 template<typename RefExpr>
19603 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19604 if (HasArgs)
19605 E->copyTemplateArgumentsInto(TemplateArgStorage);
19606 }
19607 operator TemplateArgumentListInfo*()
19608#ifdef __has_cpp_attribute
19609#if __has_cpp_attribute(clang::lifetimebound)
19610 [[clang::lifetimebound]]
19611#endif
19612#endif
19613 {
19614 return HasArgs ? &TemplateArgStorage : nullptr;
19615 }
19616};
19617}
19618
19619/// Walk the set of potential results of an expression and mark them all as
19620/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19621///
19622/// \return A new expression if we found any potential results, ExprEmpty() if
19623/// not, and ExprError() if we diagnosed an error.
19625 NonOdrUseReason NOUR) {
19626 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19627 // an object that satisfies the requirements for appearing in a
19628 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19629 // is immediately applied." This function handles the lvalue-to-rvalue
19630 // conversion part.
19631 //
19632 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19633 // transform it into the relevant kind of non-odr-use node and rebuild the
19634 // tree of nodes leading to it.
19635 //
19636 // This is a mini-TreeTransform that only transforms a restricted subset of
19637 // nodes (and only certain operands of them).
19638
19639 // Rebuild a subexpression.
19640 auto Rebuild = [&](Expr *Sub) {
19641 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19642 };
19643
19644 // Check whether a potential result satisfies the requirements of NOUR.
19645 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19646 // Any entity other than a VarDecl is always odr-used whenever it's named
19647 // in a potentially-evaluated expression.
19648 auto *VD = dyn_cast<VarDecl>(D);
19649 if (!VD)
19650 return true;
19651
19652 // C++2a [basic.def.odr]p4:
19653 // A variable x whose name appears as a potentially-evalauted expression
19654 // e is odr-used by e unless
19655 // -- x is a reference that is usable in constant expressions, or
19656 // -- x is a variable of non-reference type that is usable in constant
19657 // expressions and has no mutable subobjects, and e is an element of
19658 // the set of potential results of an expression of
19659 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19660 // conversion is applied, or
19661 // -- x is a variable of non-reference type, and e is an element of the
19662 // set of potential results of a discarded-value expression to which
19663 // the lvalue-to-rvalue conversion is not applied
19664 //
19665 // We check the first bullet and the "potentially-evaluated" condition in
19666 // BuildDeclRefExpr. We check the type requirements in the second bullet
19667 // in CheckLValueToRValueConversionOperand below.
19668 switch (NOUR) {
19669 case NOUR_None:
19670 case NOUR_Unevaluated:
19671 llvm_unreachable("unexpected non-odr-use-reason");
19672
19673 case NOUR_Constant:
19674 // Constant references were handled when they were built.
19675 if (VD->getType()->isReferenceType())
19676 return true;
19677 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19678 if (RD->hasDefinition() && RD->hasMutableFields())
19679 return true;
19680 if (!VD->isUsableInConstantExpressions(S.Context))
19681 return true;
19682 break;
19683
19684 case NOUR_Discarded:
19685 if (VD->getType()->isReferenceType())
19686 return true;
19687 break;
19688 }
19689 return false;
19690 };
19691
19692 // Check whether this expression may be odr-used in CUDA/HIP.
19693 auto MaybeCUDAODRUsed = [&]() -> bool {
19694 if (!S.LangOpts.CUDA)
19695 return false;
19696 LambdaScopeInfo *LSI = S.getCurLambda();
19697 if (!LSI)
19698 return false;
19699 auto *DRE = dyn_cast<DeclRefExpr>(E);
19700 if (!DRE)
19701 return false;
19702 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
19703 if (!VD)
19704 return false;
19705 return LSI->CUDAPotentialODRUsedVars.count(VD);
19706 };
19707
19708 // Mark that this expression does not constitute an odr-use.
19709 auto MarkNotOdrUsed = [&] {
19710 if (!MaybeCUDAODRUsed()) {
19711 S.MaybeODRUseExprs.remove(E);
19712 if (LambdaScopeInfo *LSI = S.getCurLambda())
19713 LSI->markVariableExprAsNonODRUsed(E);
19714 }
19715 };
19716
19717 // C++2a [basic.def.odr]p2:
19718 // The set of potential results of an expression e is defined as follows:
19719 switch (E->getStmtClass()) {
19720 // -- If e is an id-expression, ...
19721 case Expr::DeclRefExprClass: {
19722 auto *DRE = cast<DeclRefExpr>(E);
19723 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19724 break;
19725
19726 // Rebuild as a non-odr-use DeclRefExpr.
19727 MarkNotOdrUsed();
19728 return DeclRefExpr::Create(
19729 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19730 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19731 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19732 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19733 }
19734
19735 case Expr::FunctionParmPackExprClass: {
19736 auto *FPPE = cast<FunctionParmPackExpr>(E);
19737 // If any of the declarations in the pack is odr-used, then the expression
19738 // as a whole constitutes an odr-use.
19739 for (ValueDecl *D : *FPPE)
19740 if (IsPotentialResultOdrUsed(D))
19741 return ExprEmpty();
19742
19743 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19744 // nothing cares about whether we marked this as an odr-use, but it might
19745 // be useful for non-compiler tools.
19746 MarkNotOdrUsed();
19747 break;
19748 }
19749
19750 // -- If e is a subscripting operation with an array operand...
19751 case Expr::ArraySubscriptExprClass: {
19752 auto *ASE = cast<ArraySubscriptExpr>(E);
19753 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19754 if (!OldBase->getType()->isArrayType())
19755 break;
19756 ExprResult Base = Rebuild(OldBase);
19757 if (!Base.isUsable())
19758 return Base;
19759 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19760 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19761 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19762 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19763 ASE->getRBracketLoc());
19764 }
19765
19766 case Expr::MemberExprClass: {
19767 auto *ME = cast<MemberExpr>(E);
19768 // -- If e is a class member access expression [...] naming a non-static
19769 // data member...
19770 if (isa<FieldDecl>(ME->getMemberDecl())) {
19771 ExprResult Base = Rebuild(ME->getBase());
19772 if (!Base.isUsable())
19773 return Base;
19774 return MemberExpr::Create(
19775 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19776 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19777 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19778 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19779 ME->getObjectKind(), ME->isNonOdrUse());
19780 }
19781
19782 if (ME->getMemberDecl()->isCXXInstanceMember())
19783 break;
19784
19785 // -- If e is a class member access expression naming a static data member,
19786 // ...
19787 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19788 break;
19789
19790 // Rebuild as a non-odr-use MemberExpr.
19791 MarkNotOdrUsed();
19792 return MemberExpr::Create(
19793 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19794 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19795 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19796 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19797 }
19798
19799 case Expr::BinaryOperatorClass: {
19800 auto *BO = cast<BinaryOperator>(E);
19801 Expr *LHS = BO->getLHS();
19802 Expr *RHS = BO->getRHS();
19803 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19804 if (BO->getOpcode() == BO_PtrMemD) {
19805 ExprResult Sub = Rebuild(LHS);
19806 if (!Sub.isUsable())
19807 return Sub;
19808 BO->setLHS(Sub.get());
19809 // -- If e is a comma expression, ...
19810 } else if (BO->getOpcode() == BO_Comma) {
19811 ExprResult Sub = Rebuild(RHS);
19812 if (!Sub.isUsable())
19813 return Sub;
19814 BO->setRHS(Sub.get());
19815 } else {
19816 break;
19817 }
19818 return ExprResult(BO);
19819 }
19820
19821 // -- If e has the form (e1)...
19822 case Expr::ParenExprClass: {
19823 auto *PE = cast<ParenExpr>(E);
19824 ExprResult Sub = Rebuild(PE->getSubExpr());
19825 if (!Sub.isUsable())
19826 return Sub;
19827 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19828 }
19829
19830 // -- If e is a glvalue conditional expression, ...
19831 // We don't apply this to a binary conditional operator. FIXME: Should we?
19832 case Expr::ConditionalOperatorClass: {
19833 auto *CO = cast<ConditionalOperator>(E);
19834 ExprResult LHS = Rebuild(CO->getLHS());
19835 if (LHS.isInvalid())
19836 return ExprError();
19837 ExprResult RHS = Rebuild(CO->getRHS());
19838 if (RHS.isInvalid())
19839 return ExprError();
19840 if (!LHS.isUsable() && !RHS.isUsable())
19841 return ExprEmpty();
19842 if (!LHS.isUsable())
19843 LHS = CO->getLHS();
19844 if (!RHS.isUsable())
19845 RHS = CO->getRHS();
19846 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19847 CO->getCond(), LHS.get(), RHS.get());
19848 }
19849
19850 // [Clang extension]
19851 // -- If e has the form __extension__ e1...
19852 case Expr::UnaryOperatorClass: {
19853 auto *UO = cast<UnaryOperator>(E);
19854 if (UO->getOpcode() != UO_Extension)
19855 break;
19856 ExprResult Sub = Rebuild(UO->getSubExpr());
19857 if (!Sub.isUsable())
19858 return Sub;
19859 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19860 Sub.get());
19861 }
19862
19863 // [Clang extension]
19864 // -- If e has the form _Generic(...), the set of potential results is the
19865 // union of the sets of potential results of the associated expressions.
19866 case Expr::GenericSelectionExprClass: {
19867 auto *GSE = cast<GenericSelectionExpr>(E);
19868
19869 SmallVector<Expr *, 4> AssocExprs;
19870 bool AnyChanged = false;
19871 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19872 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19873 if (AssocExpr.isInvalid())
19874 return ExprError();
19875 if (AssocExpr.isUsable()) {
19876 AssocExprs.push_back(AssocExpr.get());
19877 AnyChanged = true;
19878 } else {
19879 AssocExprs.push_back(OrigAssocExpr);
19880 }
19881 }
19882
19883 void *ExOrTy = nullptr;
19884 bool IsExpr = GSE->isExprPredicate();
19885 if (IsExpr)
19886 ExOrTy = GSE->getControllingExpr();
19887 else
19888 ExOrTy = GSE->getControllingType();
19889 return AnyChanged ? S.CreateGenericSelectionExpr(
19890 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19891 GSE->getRParenLoc(), IsExpr, ExOrTy,
19892 GSE->getAssocTypeSourceInfos(), AssocExprs)
19893 : ExprEmpty();
19894 }
19895
19896 // [Clang extension]
19897 // -- If e has the form __builtin_choose_expr(...), the set of potential
19898 // results is the union of the sets of potential results of the
19899 // second and third subexpressions.
19900 case Expr::ChooseExprClass: {
19901 auto *CE = cast<ChooseExpr>(E);
19902
19903 ExprResult LHS = Rebuild(CE->getLHS());
19904 if (LHS.isInvalid())
19905 return ExprError();
19906
19907 ExprResult RHS = Rebuild(CE->getLHS());
19908 if (RHS.isInvalid())
19909 return ExprError();
19910
19911 if (!LHS.get() && !RHS.get())
19912 return ExprEmpty();
19913 if (!LHS.isUsable())
19914 LHS = CE->getLHS();
19915 if (!RHS.isUsable())
19916 RHS = CE->getRHS();
19917
19918 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19919 RHS.get(), CE->getRParenLoc());
19920 }
19921
19922 // Step through non-syntactic nodes.
19923 case Expr::ConstantExprClass: {
19924 auto *CE = cast<ConstantExpr>(E);
19925 ExprResult Sub = Rebuild(CE->getSubExpr());
19926 if (!Sub.isUsable())
19927 return Sub;
19928 return ConstantExpr::Create(S.Context, Sub.get());
19929 }
19930
19931 // We could mostly rely on the recursive rebuilding to rebuild implicit
19932 // casts, but not at the top level, so rebuild them here.
19933 case Expr::ImplicitCastExprClass: {
19934 auto *ICE = cast<ImplicitCastExpr>(E);
19935 // Only step through the narrow set of cast kinds we expect to encounter.
19936 // Anything else suggests we've left the region in which potential results
19937 // can be found.
19938 switch (ICE->getCastKind()) {
19939 case CK_NoOp:
19940 case CK_DerivedToBase:
19941 case CK_UncheckedDerivedToBase: {
19942 ExprResult Sub = Rebuild(ICE->getSubExpr());
19943 if (!Sub.isUsable())
19944 return Sub;
19945 CXXCastPath Path(ICE->path());
19946 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19947 ICE->getValueKind(), &Path);
19948 }
19949
19950 default:
19951 break;
19952 }
19953 break;
19954 }
19955
19956 default:
19957 break;
19958 }
19959
19960 // Can't traverse through this node. Nothing to do.
19961 return ExprEmpty();
19962}
19963
19965 // Check whether the operand is or contains an object of non-trivial C union
19966 // type.
19967 if (E->getType().isVolatileQualified() &&
19973
19974 // C++2a [basic.def.odr]p4:
19975 // [...] an expression of non-volatile-qualified non-class type to which
19976 // the lvalue-to-rvalue conversion is applied [...]
19978 return E;
19979
19982 if (Result.isInvalid())
19983 return ExprError();
19984 return Result.get() ? Result : E;
19985}
19986
19988 if (!Res.isUsable())
19989 return Res;
19990
19991 // If a constant-expression is a reference to a variable where we delay
19992 // deciding whether it is an odr-use, just assume we will apply the
19993 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19994 // (a non-type template argument), we have special handling anyway.
19996}
19997
19999 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20000 // call.
20001 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20002 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20003
20004 for (Expr *E : LocalMaybeODRUseExprs) {
20005 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20006 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20007 DRE->getLocation(), *this);
20008 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20009 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20010 *this);
20011 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20012 for (ValueDecl *VD : *FP)
20013 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20014 } else {
20015 llvm_unreachable("Unexpected expression");
20016 }
20017 }
20018
20019 assert(MaybeODRUseExprs.empty() &&
20020 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20021}
20022
20024 ValueDecl *Var, Expr *E) {
20026 if (!VD)
20027 return;
20028
20029 const bool RefersToEnclosingScope =
20030 (SemaRef.CurContext != VD->getDeclContext() &&
20032 if (RefersToEnclosingScope) {
20033 LambdaScopeInfo *const LSI =
20034 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20035 if (LSI && (!LSI->CallOperator ||
20036 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20037 // If a variable could potentially be odr-used, defer marking it so
20038 // until we finish analyzing the full expression for any
20039 // lvalue-to-rvalue
20040 // or discarded value conversions that would obviate odr-use.
20041 // Add it to the list of potential captures that will be analyzed
20042 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20043 // unless the variable is a reference that was initialized by a constant
20044 // expression (this will never need to be captured or odr-used).
20045 //
20046 // FIXME: We can simplify this a lot after implementing P0588R1.
20047 assert(E && "Capture variable should be used in an expression.");
20048 if (!Var->getType()->isReferenceType() ||
20051 }
20052 }
20053}
20054
20057 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20058 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20059 isa<FunctionParmPackExpr>(E)) &&
20060 "Invalid Expr argument to DoMarkVarDeclReferenced");
20061 Var->setReferenced();
20062
20063 if (Var->isInvalidDecl())
20064 return;
20065
20066 auto *MSI = Var->getMemberSpecializationInfo();
20069
20070 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20071 bool UsableInConstantExpr =
20073
20074 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20075 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20076 }
20077
20078 // C++20 [expr.const]p12:
20079 // A variable [...] is needed for constant evaluation if it is [...] a
20080 // variable whose name appears as a potentially constant evaluated
20081 // expression that is either a contexpr variable or is of non-volatile
20082 // const-qualified integral type or of reference type
20083 bool NeededForConstantEvaluation =
20084 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20085
20086 bool NeedDefinition =
20087 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20088
20089 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20090 "Can't instantiate a partial template specialization.");
20091
20092 // If this might be a member specialization of a static data member, check
20093 // the specialization is visible. We already did the checks for variable
20094 // template specializations when we created them.
20095 if (NeedDefinition && TSK != TSK_Undeclared &&
20096 !isa<VarTemplateSpecializationDecl>(Var))
20098
20099 // Perform implicit instantiation of static data members, static data member
20100 // templates of class templates, and variable template specializations. Delay
20101 // instantiations of variable templates, except for those that could be used
20102 // in a constant expression.
20103 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20104 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20105 // instantiation declaration if a variable is usable in a constant
20106 // expression (among other cases).
20107 bool TryInstantiating =
20109 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20110
20111 if (TryInstantiating) {
20112 SourceLocation PointOfInstantiation =
20113 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20114 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20115 if (FirstInstantiation) {
20116 PointOfInstantiation = Loc;
20117 if (MSI)
20118 MSI->setPointOfInstantiation(PointOfInstantiation);
20119 // FIXME: Notify listener.
20120 else
20121 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20122 }
20123
20124 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20125 // Do not defer instantiations of variables that could be used in a
20126 // constant expression.
20127 // The type deduction also needs a complete initializer.
20128 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20129 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20130 });
20131
20132 // The size of an incomplete array type can be updated by
20133 // instantiating the initializer. The DeclRefExpr's type should be
20134 // updated accordingly too, or users of it would be confused!
20135 if (E)
20137
20138 // Re-set the member to trigger a recomputation of the dependence bits
20139 // for the expression.
20140 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20141 DRE->setDecl(DRE->getDecl());
20142 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20143 ME->setMemberDecl(ME->getMemberDecl());
20144 } else if (FirstInstantiation) {
20146 .push_back(std::make_pair(Var, PointOfInstantiation));
20147 } else {
20148 bool Inserted = false;
20149 for (auto &I : SemaRef.SavedPendingInstantiations) {
20150 auto Iter = llvm::find_if(
20151 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20152 return P.first == Var;
20153 });
20154 if (Iter != I.end()) {
20156 I.erase(Iter);
20157 Inserted = true;
20158 break;
20159 }
20160 }
20161
20162 // FIXME: For a specialization of a variable template, we don't
20163 // distinguish between "declaration and type implicitly instantiated"
20164 // and "implicit instantiation of definition requested", so we have
20165 // no direct way to avoid enqueueing the pending instantiation
20166 // multiple times.
20167 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20169 .push_back(std::make_pair(Var, PointOfInstantiation));
20170 }
20171 }
20172 }
20173
20174 // C++2a [basic.def.odr]p4:
20175 // A variable x whose name appears as a potentially-evaluated expression e
20176 // is odr-used by e unless
20177 // -- x is a reference that is usable in constant expressions
20178 // -- x is a variable of non-reference type that is usable in constant
20179 // expressions and has no mutable subobjects [FIXME], and e is an
20180 // element of the set of potential results of an expression of
20181 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20182 // conversion is applied
20183 // -- x is a variable of non-reference type, and e is an element of the set
20184 // of potential results of a discarded-value expression to which the
20185 // lvalue-to-rvalue conversion is not applied [FIXME]
20186 //
20187 // We check the first part of the second bullet here, and
20188 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20189 // FIXME: To get the third bullet right, we need to delay this even for
20190 // variables that are not usable in constant expressions.
20191
20192 // If we already know this isn't an odr-use, there's nothing more to do.
20193 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20194 if (DRE->isNonOdrUse())
20195 return;
20196 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20197 if (ME->isNonOdrUse())
20198 return;
20199
20200 switch (OdrUse) {
20201 case OdrUseContext::None:
20202 // In some cases, a variable may not have been marked unevaluated, if it
20203 // appears in a defaukt initializer.
20204 assert((!E || isa<FunctionParmPackExpr>(E) ||
20206 "missing non-odr-use marking for unevaluated decl ref");
20207 break;
20208
20209 case OdrUseContext::FormallyOdrUsed:
20210 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20211 // behavior.
20212 break;
20213
20214 case OdrUseContext::Used:
20215 // If we might later find that this expression isn't actually an odr-use,
20216 // delay the marking.
20218 SemaRef.MaybeODRUseExprs.insert(E);
20219 else
20221 break;
20222
20223 case OdrUseContext::Dependent:
20224 // If this is a dependent context, we don't need to mark variables as
20225 // odr-used, but we may still need to track them for lambda capture.
20226 // FIXME: Do we also need to do this inside dependent typeid expressions
20227 // (which are modeled as unevaluated at this point)?
20229 break;
20230 }
20231}
20232
20234 BindingDecl *BD, Expr *E) {
20235 BD->setReferenced();
20236
20237 if (BD->isInvalidDecl())
20238 return;
20239
20240 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20241 if (OdrUse == OdrUseContext::Used) {
20242 QualType CaptureType, DeclRefType;
20244 /*EllipsisLoc*/ SourceLocation(),
20245 /*BuildAndDiagnose*/ true, CaptureType,
20246 DeclRefType,
20247 /*FunctionScopeIndexToStopAt*/ nullptr);
20248 } else if (OdrUse == OdrUseContext::Dependent) {
20250 }
20251}
20252
20254 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20255}
20256
20257// C++ [temp.dep.expr]p3:
20258// An id-expression is type-dependent if it contains:
20259// - an identifier associated by name lookup with an entity captured by copy
20260// in a lambda-expression that has an explicit object parameter whose type
20261// is dependent ([dcl.fct]),
20263 Sema &SemaRef, ValueDecl *D, Expr *E) {
20264 auto *ID = dyn_cast<DeclRefExpr>(E);
20265 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20266 return;
20267
20268 // If any enclosing lambda with a dependent explicit object parameter either
20269 // explicitly captures the variable by value, or has a capture default of '='
20270 // and does not capture the variable by reference, then the type of the DRE
20271 // is dependent on the type of that lambda's explicit object parameter.
20272 auto IsDependent = [&]() {
20273 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20274 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20275 if (!LSI)
20276 continue;
20277
20278 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20279 LSI->AfterParameterList)
20280 return false;
20281
20282 const auto *MD = LSI->CallOperator;
20283 if (MD->getType().isNull())
20284 continue;
20285
20286 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20287 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20288 !Ty->getParamType(0)->isDependentType())
20289 continue;
20290
20291 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20292 if (C->isCopyCapture())
20293 return true;
20294 continue;
20295 }
20296
20297 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20298 return true;
20299 }
20300 return false;
20301 }();
20302
20303 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20304 IsDependent, SemaRef.getASTContext());
20305}
20306
20307static void
20309 bool MightBeOdrUse,
20310 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20313
20314 if (SemaRef.getLangOpts().OpenACC)
20316
20317 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20319 if (SemaRef.getLangOpts().CPlusPlus)
20321 Var, E);
20322 return;
20323 }
20324
20325 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20327 if (SemaRef.getLangOpts().CPlusPlus)
20329 Decl, E);
20330 return;
20331 }
20332 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20333
20334 // If this is a call to a method via a cast, also mark the method in the
20335 // derived class used in case codegen can devirtualize the call.
20336 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20337 if (!ME)
20338 return;
20339 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20340 if (!MD)
20341 return;
20342 // Only attempt to devirtualize if this is truly a virtual call.
20343 bool IsVirtualCall = MD->isVirtual() &&
20345 if (!IsVirtualCall)
20346 return;
20347
20348 // If it's possible to devirtualize the call, mark the called function
20349 // referenced.
20351 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20352 if (DM)
20353 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20354}
20355
20357 // [basic.def.odr] (CWG 1614)
20358 // A function is named by an expression or conversion [...]
20359 // unless it is a pure virtual function and either the expression is not an
20360 // id-expression naming the function with an explicitly qualified name or
20361 // the expression forms a pointer to member
20362 bool OdrUse = true;
20363 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20364 if (Method->isVirtual() &&
20365 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20366 OdrUse = false;
20367
20368 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20372 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20373 !FD->isDependentContext())
20374 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20375 }
20376 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20378}
20379
20381 // C++11 [basic.def.odr]p2:
20382 // A non-overloaded function whose name appears as a potentially-evaluated
20383 // expression or a member of a set of candidate functions, if selected by
20384 // overload resolution when referred to from a potentially-evaluated
20385 // expression, is odr-used, unless it is a pure virtual function and its
20386 // name is not explicitly qualified.
20387 bool MightBeOdrUse = true;
20388 if (E->performsVirtualDispatch(getLangOpts())) {
20389 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20390 if (Method->isPureVirtual())
20391 MightBeOdrUse = false;
20392 }
20394 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20395 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20397}
20398
20400 for (ValueDecl *VD : *E)
20401 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20403}
20404
20405/// Perform marking for a reference to an arbitrary declaration. It
20406/// marks the declaration referenced, and performs odr-use checking for
20407/// functions and variables. This method should not be used when building a
20408/// normal expression which refers to a variable.
20410 bool MightBeOdrUse) {
20411 if (MightBeOdrUse) {
20412 if (auto *VD = dyn_cast<VarDecl>(D)) {
20414 return;
20415 }
20416 }
20417 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20418 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20419 return;
20420 }
20421 D->setReferenced();
20422}
20423
20424namespace {
20425 // Mark all of the declarations used by a type as referenced.
20426 // FIXME: Not fully implemented yet! We need to have a better understanding
20427 // of when we're entering a context we should not recurse into.
20428 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20429 // TreeTransforms rebuilding the type in a new context. Rather than
20430 // duplicating the TreeTransform logic, we should consider reusing it here.
20431 // Currently that causes problems when rebuilding LambdaExprs.
20432class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20433 Sema &S;
20435
20436public:
20437 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20438
20439 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20440};
20441}
20442
20443bool MarkReferencedDecls::TraverseTemplateArgument(
20444 const TemplateArgument &Arg) {
20445 {
20446 // A non-type template argument is a constant-evaluated context.
20450 if (Decl *D = Arg.getAsDecl())
20451 S.MarkAnyDeclReferenced(Loc, D, true);
20452 } else if (Arg.getKind() == TemplateArgument::Expression) {
20454 }
20455 }
20456
20458}
20459
20461 MarkReferencedDecls Marker(*this, Loc);
20462 Marker.TraverseType(T);
20463}
20464
20465namespace {
20466/// Helper class that marks all of the declarations referenced by
20467/// potentially-evaluated subexpressions as "referenced".
20468class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20469public:
20470 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20471 bool SkipLocalVariables;
20473
20474 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20476 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20477
20478 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20479 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20480 }
20481
20482 void Visit(Expr *E) {
20483 if (llvm::is_contained(StopAt, E))
20484 return;
20485 Inherited::Visit(E);
20486 }
20487
20488 void VisitConstantExpr(ConstantExpr *E) {
20489 // Don't mark declarations within a ConstantExpression, as this expression
20490 // will be evaluated and folded to a value.
20491 }
20492
20493 void VisitDeclRefExpr(DeclRefExpr *E) {
20494 // If we were asked not to visit local variables, don't.
20495 if (SkipLocalVariables) {
20496 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20497 if (VD->hasLocalStorage())
20498 return;
20499 }
20500
20501 // FIXME: This can trigger the instantiation of the initializer of a
20502 // variable, which can cause the expression to become value-dependent
20503 // or error-dependent. Do we need to propagate the new dependence bits?
20505 }
20506
20507 void VisitMemberExpr(MemberExpr *E) {
20509 Visit(E->getBase());
20510 }
20511};
20512} // namespace
20513
20515 bool SkipLocalVariables,
20516 ArrayRef<const Expr*> StopAt) {
20517 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20518}
20519
20520/// Emit a diagnostic when statements are reachable.
20521/// FIXME: check for reachability even in expressions for which we don't build a
20522/// CFG (eg, in the initializer of a global or in a constant expression).
20523/// For example,
20524/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20526 const PartialDiagnostic &PD) {
20527 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20528 if (!FunctionScopes.empty())
20529 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20531 return true;
20532 }
20533
20534 // The initializer of a constexpr variable or of the first declaration of a
20535 // static data member is not syntactically a constant evaluated constant,
20536 // but nonetheless is always required to be a constant expression, so we
20537 // can skip diagnosing.
20538 // FIXME: Using the mangling context here is a hack.
20539 if (auto *VD = dyn_cast_or_null<VarDecl>(
20540 ExprEvalContexts.back().ManglingContextDecl)) {
20541 if (VD->isConstexpr() ||
20542 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20543 return false;
20544 // FIXME: For any other kind of variable, we should build a CFG for its
20545 // initializer and check whether the context in question is reachable.
20546 }
20547
20548 Diag(Loc, PD);
20549 return true;
20550}
20551
20552/// Emit a diagnostic that describes an effect on the run-time behavior
20553/// of the program being compiled.
20554///
20555/// This routine emits the given diagnostic when the code currently being
20556/// type-checked is "potentially evaluated", meaning that there is a
20557/// possibility that the code will actually be executable. Code in sizeof()
20558/// expressions, code used only during overload resolution, etc., are not
20559/// potentially evaluated. This routine will suppress such diagnostics or,
20560/// in the absolutely nutty case of potentially potentially evaluated
20561/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20562/// later.
20563///
20564/// This routine should be used for all diagnostics that describe the run-time
20565/// behavior of a program, such as passing a non-POD value through an ellipsis.
20566/// Failure to do so will likely result in spurious diagnostics or failures
20567/// during overload resolution or within sizeof/alignof/typeof/typeid.
20569 const PartialDiagnostic &PD) {
20570
20571 if (ExprEvalContexts.back().isDiscardedStatementContext())
20572 return false;
20573
20574 switch (ExprEvalContexts.back().Context) {
20579 // The argument will never be evaluated, so don't complain.
20580 break;
20581
20584 // Relevant diagnostics should be produced by constant evaluation.
20585 break;
20586
20589 return DiagIfReachable(Loc, Stmts, PD);
20590 }
20591
20592 return false;
20593}
20594
20596 const PartialDiagnostic &PD) {
20597 return DiagRuntimeBehavior(
20598 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20599 PD);
20600}
20601
20603 CallExpr *CE, FunctionDecl *FD) {
20604 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20605 return false;
20606
20607 // If we're inside a decltype's expression, don't check for a valid return
20608 // type or construct temporaries until we know whether this is the last call.
20609 if (ExprEvalContexts.back().ExprContext ==
20611 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20612 return false;
20613 }
20614
20615 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20616 FunctionDecl *FD;
20617 CallExpr *CE;
20618
20619 public:
20620 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20621 : FD(FD), CE(CE) { }
20622
20623 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20624 if (!FD) {
20625 S.Diag(Loc, diag::err_call_incomplete_return)
20626 << T << CE->getSourceRange();
20627 return;
20628 }
20629
20630 S.Diag(Loc, diag::err_call_function_incomplete_return)
20631 << CE->getSourceRange() << FD << T;
20632 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20633 << FD->getDeclName();
20634 }
20635 } Diagnoser(FD, CE);
20636
20637 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20638 return true;
20639
20640 return false;
20641}
20642
20643// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20644// will prevent this condition from triggering, which is what we want.
20647
20648 unsigned diagnostic = diag::warn_condition_is_assignment;
20649 bool IsOrAssign = false;
20650
20651 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20652 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20653 return;
20654
20655 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20656
20657 // Greylist some idioms by putting them into a warning subcategory.
20658 if (ObjCMessageExpr *ME
20659 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20660 Selector Sel = ME->getSelector();
20661
20662 // self = [<foo> init...]
20663 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20664 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20665
20666 // <foo> = [<bar> nextObject]
20667 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20668 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20669 }
20670
20671 Loc = Op->getOperatorLoc();
20672 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20673 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20674 return;
20675
20676 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20677 Loc = Op->getOperatorLoc();
20678 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20679 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20680 else {
20681 // Not an assignment.
20682 return;
20683 }
20684
20685 Diag(Loc, diagnostic) << E->getSourceRange();
20686
20689 Diag(Loc, diag::note_condition_assign_silence)
20691 << FixItHint::CreateInsertion(Close, ")");
20692
20693 if (IsOrAssign)
20694 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20696 else
20697 Diag(Loc, diag::note_condition_assign_to_comparison)
20699}
20700
20702 // Don't warn if the parens came from a macro.
20703 SourceLocation parenLoc = ParenE->getBeginLoc();
20704 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20705 return;
20706 // Don't warn for dependent expressions.
20707 if (ParenE->isTypeDependent())
20708 return;
20709
20710 Expr *E = ParenE->IgnoreParens();
20711 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20712 return;
20713
20714 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20715 if (opE->getOpcode() == BO_EQ &&
20716 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20717 == Expr::MLV_Valid) {
20718 SourceLocation Loc = opE->getOperatorLoc();
20719
20720 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20721 SourceRange ParenERange = ParenE->getSourceRange();
20722 Diag(Loc, diag::note_equality_comparison_silence)
20723 << FixItHint::CreateRemoval(ParenERange.getBegin())
20724 << FixItHint::CreateRemoval(ParenERange.getEnd());
20725 Diag(Loc, diag::note_equality_comparison_to_assign)
20727 }
20728}
20729
20731 bool IsConstexpr) {
20733 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20735
20737 if (result.isInvalid()) return ExprError();
20738 E = result.get();
20739
20740 if (!E->isTypeDependent()) {
20741 if (getLangOpts().CPlusPlus)
20742 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20743
20745 if (ERes.isInvalid())
20746 return ExprError();
20747 E = ERes.get();
20748
20749 QualType T = E->getType();
20750 if (!T->isScalarType()) { // C99 6.8.4.1p1
20751 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20752 << T << E->getSourceRange();
20753 return ExprError();
20754 }
20755 CheckBoolLikeConversion(E, Loc);
20756 }
20757
20758 return E;
20759}
20760
20762 Expr *SubExpr, ConditionKind CK,
20763 bool MissingOK) {
20764 // MissingOK indicates whether having no condition expression is valid
20765 // (for loop) or invalid (e.g. while loop).
20766 if (!SubExpr)
20767 return MissingOK ? ConditionResult() : ConditionError();
20768
20769 ExprResult Cond;
20770 switch (CK) {
20772 Cond = CheckBooleanCondition(Loc, SubExpr);
20773 break;
20774
20776 // Note: this might produce a FullExpr
20777 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20778 break;
20779
20781 Cond = CheckSwitchCondition(Loc, SubExpr);
20782 break;
20783 }
20784 if (Cond.isInvalid()) {
20785 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20786 {SubExpr}, PreferredConditionType(CK));
20787 if (!Cond.get())
20788 return ConditionError();
20789 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
20790 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
20791
20792 if (!Cond.isUsable())
20793 return ConditionError();
20794
20795 return ConditionResult(*this, nullptr, Cond,
20797}
20798
20799namespace {
20800 /// A visitor for rebuilding a call to an __unknown_any expression
20801 /// to have an appropriate type.
20802 struct RebuildUnknownAnyFunction
20803 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20804
20805 Sema &S;
20806
20807 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20808
20809 ExprResult VisitStmt(Stmt *S) {
20810 llvm_unreachable("unexpected statement!");
20811 }
20812
20813 ExprResult VisitExpr(Expr *E) {
20814 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20815 << E->getSourceRange();
20816 return ExprError();
20817 }
20818
20819 /// Rebuild an expression which simply semantically wraps another
20820 /// expression which it shares the type and value kind of.
20821 template <class T> ExprResult rebuildSugarExpr(T *E) {
20822 ExprResult SubResult = Visit(E->getSubExpr());
20823 if (SubResult.isInvalid()) return ExprError();
20824
20825 Expr *SubExpr = SubResult.get();
20826 E->setSubExpr(SubExpr);
20827 E->setType(SubExpr->getType());
20828 E->setValueKind(SubExpr->getValueKind());
20829 assert(E->getObjectKind() == OK_Ordinary);
20830 return E;
20831 }
20832
20833 ExprResult VisitParenExpr(ParenExpr *E) {
20834 return rebuildSugarExpr(E);
20835 }
20836
20837 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20838 return rebuildSugarExpr(E);
20839 }
20840
20841 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20842 ExprResult SubResult = Visit(E->getSubExpr());
20843 if (SubResult.isInvalid()) return ExprError();
20844
20845 Expr *SubExpr = SubResult.get();
20846 E->setSubExpr(SubExpr);
20847 E->setType(S.Context.getPointerType(SubExpr->getType()));
20848 assert(E->isPRValue());
20849 assert(E->getObjectKind() == OK_Ordinary);
20850 return E;
20851 }
20852
20853 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20854 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20855
20856 E->setType(VD->getType());
20857
20858 assert(E->isPRValue());
20859 if (S.getLangOpts().CPlusPlus &&
20860 !(isa<CXXMethodDecl>(VD) &&
20861 cast<CXXMethodDecl>(VD)->isInstance()))
20863
20864 return E;
20865 }
20866
20867 ExprResult VisitMemberExpr(MemberExpr *E) {
20868 return resolveDecl(E, E->getMemberDecl());
20869 }
20870
20871 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20872 return resolveDecl(E, E->getDecl());
20873 }
20874 };
20875}
20876
20877/// Given a function expression of unknown-any type, try to rebuild it
20878/// to have a function type.
20880 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20881 if (Result.isInvalid()) return ExprError();
20882 return S.DefaultFunctionArrayConversion(Result.get());
20883}
20884
20885namespace {
20886 /// A visitor for rebuilding an expression of type __unknown_anytype
20887 /// into one which resolves the type directly on the referring
20888 /// expression. Strict preservation of the original source
20889 /// structure is not a goal.
20890 struct RebuildUnknownAnyExpr
20891 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20892
20893 Sema &S;
20894
20895 /// The current destination type.
20896 QualType DestType;
20897
20898 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20899 : S(S), DestType(CastType) {}
20900
20901 ExprResult VisitStmt(Stmt *S) {
20902 llvm_unreachable("unexpected statement!");
20903 }
20904
20905 ExprResult VisitExpr(Expr *E) {
20906 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20907 << E->getSourceRange();
20908 return ExprError();
20909 }
20910
20911 ExprResult VisitCallExpr(CallExpr *E);
20912 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20913
20914 /// Rebuild an expression which simply semantically wraps another
20915 /// expression which it shares the type and value kind of.
20916 template <class T> ExprResult rebuildSugarExpr(T *E) {
20917 ExprResult SubResult = Visit(E->getSubExpr());
20918 if (SubResult.isInvalid()) return ExprError();
20919 Expr *SubExpr = SubResult.get();
20920 E->setSubExpr(SubExpr);
20921 E->setType(SubExpr->getType());
20922 E->setValueKind(SubExpr->getValueKind());
20923 assert(E->getObjectKind() == OK_Ordinary);
20924 return E;
20925 }
20926
20927 ExprResult VisitParenExpr(ParenExpr *E) {
20928 return rebuildSugarExpr(E);
20929 }
20930
20931 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20932 return rebuildSugarExpr(E);
20933 }
20934
20935 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20936 const PointerType *Ptr = DestType->getAs<PointerType>();
20937 if (!Ptr) {
20938 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20939 << E->getSourceRange();
20940 return ExprError();
20941 }
20942
20943 if (isa<CallExpr>(E->getSubExpr())) {
20944 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20945 << E->getSourceRange();
20946 return ExprError();
20947 }
20948
20949 assert(E->isPRValue());
20950 assert(E->getObjectKind() == OK_Ordinary);
20951 E->setType(DestType);
20952
20953 // Build the sub-expression as if it were an object of the pointee type.
20954 DestType = Ptr->getPointeeType();
20955 ExprResult SubResult = Visit(E->getSubExpr());
20956 if (SubResult.isInvalid()) return ExprError();
20957 E->setSubExpr(SubResult.get());
20958 return E;
20959 }
20960
20961 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20962
20963 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20964
20965 ExprResult VisitMemberExpr(MemberExpr *E) {
20966 return resolveDecl(E, E->getMemberDecl());
20967 }
20968
20969 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20970 return resolveDecl(E, E->getDecl());
20971 }
20972 };
20973}
20974
20975/// Rebuilds a call expression which yielded __unknown_anytype.
20976ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20977 Expr *CalleeExpr = E->getCallee();
20978
20979 enum FnKind {
20980 FK_MemberFunction,
20981 FK_FunctionPointer,
20982 FK_BlockPointer
20983 };
20984
20985 FnKind Kind;
20986 QualType CalleeType = CalleeExpr->getType();
20987 if (CalleeType == S.Context.BoundMemberTy) {
20988 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20989 Kind = FK_MemberFunction;
20990 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20991 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20992 CalleeType = Ptr->getPointeeType();
20993 Kind = FK_FunctionPointer;
20994 } else {
20995 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20996 Kind = FK_BlockPointer;
20997 }
20998 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20999
21000 // Verify that this is a legal result type of a function.
21001 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21002 DestType->isFunctionType()) {
21003 unsigned diagID = diag::err_func_returning_array_function;
21004 if (Kind == FK_BlockPointer)
21005 diagID = diag::err_block_returning_array_function;
21006
21007 S.Diag(E->getExprLoc(), diagID)
21008 << DestType->isFunctionType() << DestType;
21009 return ExprError();
21010 }
21011
21012 // Otherwise, go ahead and set DestType as the call's result.
21013 E->setType(DestType.getNonLValueExprType(S.Context));
21015 assert(E->getObjectKind() == OK_Ordinary);
21016
21017 // Rebuild the function type, replacing the result type with DestType.
21018 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21019 if (Proto) {
21020 // __unknown_anytype(...) is a special case used by the debugger when
21021 // it has no idea what a function's signature is.
21022 //
21023 // We want to build this call essentially under the K&R
21024 // unprototyped rules, but making a FunctionNoProtoType in C++
21025 // would foul up all sorts of assumptions. However, we cannot
21026 // simply pass all arguments as variadic arguments, nor can we
21027 // portably just call the function under a non-variadic type; see
21028 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21029 // However, it turns out that in practice it is generally safe to
21030 // call a function declared as "A foo(B,C,D);" under the prototype
21031 // "A foo(B,C,D,...);". The only known exception is with the
21032 // Windows ABI, where any variadic function is implicitly cdecl
21033 // regardless of its normal CC. Therefore we change the parameter
21034 // types to match the types of the arguments.
21035 //
21036 // This is a hack, but it is far superior to moving the
21037 // corresponding target-specific code from IR-gen to Sema/AST.
21038
21039 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21040 SmallVector<QualType, 8> ArgTypes;
21041 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21042 ArgTypes.reserve(E->getNumArgs());
21043 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21044 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21045 }
21046 ParamTypes = ArgTypes;
21047 }
21048 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21049 Proto->getExtProtoInfo());
21050 } else {
21051 DestType = S.Context.getFunctionNoProtoType(DestType,
21052 FnType->getExtInfo());
21053 }
21054
21055 // Rebuild the appropriate pointer-to-function type.
21056 switch (Kind) {
21057 case FK_MemberFunction:
21058 // Nothing to do.
21059 break;
21060
21061 case FK_FunctionPointer:
21062 DestType = S.Context.getPointerType(DestType);
21063 break;
21064
21065 case FK_BlockPointer:
21066 DestType = S.Context.getBlockPointerType(DestType);
21067 break;
21068 }
21069
21070 // Finally, we can recurse.
21071 ExprResult CalleeResult = Visit(CalleeExpr);
21072 if (!CalleeResult.isUsable()) return ExprError();
21073 E->setCallee(CalleeResult.get());
21074
21075 // Bind a temporary if necessary.
21076 return S.MaybeBindToTemporary(E);
21077}
21078
21079ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21080 // Verify that this is a legal result type of a call.
21081 if (DestType->isArrayType() || DestType->isFunctionType()) {
21082 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21083 << DestType->isFunctionType() << DestType;
21084 return ExprError();
21085 }
21086
21087 // Rewrite the method result type if available.
21088 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21089 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21090 Method->setReturnType(DestType);
21091 }
21092
21093 // Change the type of the message.
21094 E->setType(DestType.getNonReferenceType());
21096
21097 return S.MaybeBindToTemporary(E);
21098}
21099
21100ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21101 // The only case we should ever see here is a function-to-pointer decay.
21102 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21103 assert(E->isPRValue());
21104 assert(E->getObjectKind() == OK_Ordinary);
21105
21106 E->setType(DestType);
21107
21108 // Rebuild the sub-expression as the pointee (function) type.
21109 DestType = DestType->castAs<PointerType>()->getPointeeType();
21110
21111 ExprResult Result = Visit(E->getSubExpr());
21112 if (!Result.isUsable()) return ExprError();
21113
21114 E->setSubExpr(Result.get());
21115 return E;
21116 } else if (E->getCastKind() == CK_LValueToRValue) {
21117 assert(E->isPRValue());
21118 assert(E->getObjectKind() == OK_Ordinary);
21119
21120 assert(isa<BlockPointerType>(E->getType()));
21121
21122 E->setType(DestType);
21123
21124 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21125 DestType = S.Context.getLValueReferenceType(DestType);
21126
21127 ExprResult Result = Visit(E->getSubExpr());
21128 if (!Result.isUsable()) return ExprError();
21129
21130 E->setSubExpr(Result.get());
21131 return E;
21132 } else {
21133 llvm_unreachable("Unhandled cast type!");
21134 }
21135}
21136
21137ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21138 ExprValueKind ValueKind = VK_LValue;
21139 QualType Type = DestType;
21140
21141 // We know how to make this work for certain kinds of decls:
21142
21143 // - functions
21144 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21145 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21146 DestType = Ptr->getPointeeType();
21147 ExprResult Result = resolveDecl(E, VD);
21148 if (Result.isInvalid()) return ExprError();
21149 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21150 VK_PRValue);
21151 }
21152
21153 if (!Type->isFunctionType()) {
21154 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21155 << VD << E->getSourceRange();
21156 return ExprError();
21157 }
21158 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21159 // We must match the FunctionDecl's type to the hack introduced in
21160 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21161 // type. See the lengthy commentary in that routine.
21162 QualType FDT = FD->getType();
21163 const FunctionType *FnType = FDT->castAs<FunctionType>();
21164 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21165 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21166 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21167 SourceLocation Loc = FD->getLocation();
21169 S.Context, FD->getDeclContext(), Loc, Loc,
21170 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21172 false /*isInlineSpecified*/, FD->hasPrototype(),
21173 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21174
21175 if (FD->getQualifier())
21176 NewFD->setQualifierInfo(FD->getQualifierLoc());
21177
21179 for (const auto &AI : FT->param_types()) {
21180 ParmVarDecl *Param =
21182 Param->setScopeInfo(0, Params.size());
21183 Params.push_back(Param);
21184 }
21185 NewFD->setParams(Params);
21186 DRE->setDecl(NewFD);
21187 VD = DRE->getDecl();
21188 }
21189 }
21190
21191 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21192 if (MD->isInstance()) {
21193 ValueKind = VK_PRValue;
21195 }
21196
21197 // Function references aren't l-values in C.
21198 if (!S.getLangOpts().CPlusPlus)
21199 ValueKind = VK_PRValue;
21200
21201 // - variables
21202 } else if (isa<VarDecl>(VD)) {
21203 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21204 Type = RefTy->getPointeeType();
21205 } else if (Type->isFunctionType()) {
21206 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21207 << VD << E->getSourceRange();
21208 return ExprError();
21209 }
21210
21211 // - nothing else
21212 } else {
21213 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21214 << VD << E->getSourceRange();
21215 return ExprError();
21216 }
21217
21218 // Modifying the declaration like this is friendly to IR-gen but
21219 // also really dangerous.
21220 VD->setType(DestType);
21221 E->setType(Type);
21222 E->setValueKind(ValueKind);
21223 return E;
21224}
21225
21229 // The type we're casting to must be either void or complete.
21230 if (!CastType->isVoidType() &&
21232 diag::err_typecheck_cast_to_incomplete))
21233 return ExprError();
21234
21235 // Rewrite the casted expression from scratch.
21236 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21237 if (!result.isUsable()) return ExprError();
21238
21239 CastExpr = result.get();
21241 CastKind = CK_NoOp;
21242
21243 return CastExpr;
21244}
21245
21247 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21248}
21249
21251 Expr *arg, QualType &paramType) {
21252 // If the syntactic form of the argument is not an explicit cast of
21253 // any sort, just do default argument promotion.
21254 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21255 if (!castArg) {
21257 if (result.isInvalid()) return ExprError();
21258 paramType = result.get()->getType();
21259 return result;
21260 }
21261
21262 // Otherwise, use the type that was written in the explicit cast.
21263 assert(!arg->hasPlaceholderType());
21264 paramType = castArg->getTypeAsWritten();
21265
21266 // Copy-initialize a parameter of that type.
21267 InitializedEntity entity =
21269 /*consumed*/ false);
21270 return PerformCopyInitialization(entity, callLoc, arg);
21271}
21272
21274 Expr *orig = E;
21275 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21276 while (true) {
21277 E = E->IgnoreParenImpCasts();
21278 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21279 E = call->getCallee();
21280 diagID = diag::err_uncasted_call_of_unknown_any;
21281 } else {
21282 break;
21283 }
21284 }
21285
21286 SourceLocation loc;
21287 NamedDecl *d;
21288 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21289 loc = ref->getLocation();
21290 d = ref->getDecl();
21291 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21292 loc = mem->getMemberLoc();
21293 d = mem->getMemberDecl();
21294 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21295 diagID = diag::err_uncasted_call_of_unknown_any;
21296 loc = msg->getSelectorStartLoc();
21297 d = msg->getMethodDecl();
21298 if (!d) {
21299 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21300 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21301 << orig->getSourceRange();
21302 return ExprError();
21303 }
21304 } else {
21305 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21306 << E->getSourceRange();
21307 return ExprError();
21308 }
21309
21310 S.Diag(loc, diagID) << d << orig->getSourceRange();
21311
21312 // Never recoverable.
21313 return ExprError();
21314}
21315
21317 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21318 if (!placeholderType) return E;
21319
21320 switch (placeholderType->getKind()) {
21321 case BuiltinType::UnresolvedTemplate: {
21322 auto *ULE = cast<UnresolvedLookupExpr>(E);
21323 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21324 // There's only one FoundDecl for UnresolvedTemplate type. See
21325 // BuildTemplateIdExpr.
21326 NamedDecl *Temp = *ULE->decls_begin();
21327 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21328
21329 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21330 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21331 // as it models only the unqualified-id case, where this case can clearly be
21332 // qualified. Thus we can't just qualify an assumed template.
21333 TemplateName TN;
21334 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21335 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21336 TemplateName(TD));
21337 else
21338 TN = Context.getAssumedTemplateName(NameInfo.getName());
21339
21340 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21341 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21342 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21343 << IsTypeAliasTemplateDecl;
21344
21345 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21346 bool HasAnyDependentTA = false;
21347 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21348 HasAnyDependentTA |= Arg.getArgument().isDependent();
21349 TAL.addArgument(Arg);
21350 }
21351
21352 QualType TST;
21353 {
21354 SFINAETrap Trap(*this);
21356 NameInfo.getBeginLoc(), TAL);
21357 }
21358 if (TST.isNull())
21360 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21361 /*CanonicalArgs=*/{},
21362 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21363 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21364 TST);
21365 }
21366
21367 // Overloaded expressions.
21368 case BuiltinType::Overload: {
21369 // Try to resolve a single function template specialization.
21370 // This is obligatory.
21373 return Result;
21374
21375 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21376 // leaves Result unchanged on failure.
21377 Result = E;
21379 return Result;
21380
21381 // If that failed, try to recover with a call.
21382 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21383 /*complain*/ true);
21384 return Result;
21385 }
21386
21387 // Bound member functions.
21388 case BuiltinType::BoundMember: {
21389 ExprResult result = E;
21390 const Expr *BME = E->IgnoreParens();
21391 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21392 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21393 if (isa<CXXPseudoDestructorExpr>(BME)) {
21394 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21395 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21396 if (ME->getMemberNameInfo().getName().getNameKind() ==
21398 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21399 }
21400 tryToRecoverWithCall(result, PD,
21401 /*complain*/ true);
21402 return result;
21403 }
21404
21405 // ARC unbridged casts.
21406 case BuiltinType::ARCUnbridgedCast: {
21407 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21408 ObjC().diagnoseARCUnbridgedCast(realCast);
21409 return realCast;
21410 }
21411
21412 // Expressions of unknown type.
21413 case BuiltinType::UnknownAny:
21414 return diagnoseUnknownAnyExpr(*this, E);
21415
21416 // Pseudo-objects.
21417 case BuiltinType::PseudoObject:
21418 return PseudoObject().checkRValue(E);
21419
21420 case BuiltinType::BuiltinFn: {
21421 // Accept __noop without parens by implicitly converting it to a call expr.
21422 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21423 if (DRE) {
21424 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21425 unsigned BuiltinID = FD->getBuiltinID();
21426 if (BuiltinID == Builtin::BI__noop) {
21427 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21428 CK_BuiltinFnToFnPtr)
21429 .get();
21430 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21433 }
21434
21435 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21436 // Any use of these other than a direct call is ill-formed as of C++20,
21437 // because they are not addressable functions. In earlier language
21438 // modes, warn and force an instantiation of the real body.
21439 Diag(E->getBeginLoc(),
21441 ? diag::err_use_of_unaddressable_function
21442 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21443 if (FD->isImplicitlyInstantiable()) {
21444 // Require a definition here because a normal attempt at
21445 // instantiation for a builtin will be ignored, and we won't try
21446 // again later. We assume that the definition of the template
21447 // precedes this use.
21449 /*Recursive=*/false,
21450 /*DefinitionRequired=*/true,
21451 /*AtEndOfTU=*/false);
21452 }
21453 // Produce a properly-typed reference to the function.
21454 CXXScopeSpec SS;
21455 SS.Adopt(DRE->getQualifierLoc());
21456 TemplateArgumentListInfo TemplateArgs;
21457 DRE->copyTemplateArgumentsInto(TemplateArgs);
21458 return BuildDeclRefExpr(
21459 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21460 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21461 DRE->getTemplateKeywordLoc(),
21462 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21463 }
21464 }
21465
21466 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21467 return ExprError();
21468 }
21469
21470 case BuiltinType::IncompleteMatrixIdx:
21471 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21472 ->getRowIdx()
21473 ->getBeginLoc(),
21474 diag::err_matrix_incomplete_index);
21475 return ExprError();
21476
21477 // Expressions of unknown type.
21478 case BuiltinType::ArraySection:
21479 Diag(E->getBeginLoc(), diag::err_array_section_use)
21480 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21481 return ExprError();
21482
21483 // Expressions of unknown type.
21484 case BuiltinType::OMPArrayShaping:
21485 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21486
21487 case BuiltinType::OMPIterator:
21488 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21489
21490 // Everything else should be impossible.
21491#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21492 case BuiltinType::Id:
21493#include "clang/Basic/OpenCLImageTypes.def"
21494#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21495 case BuiltinType::Id:
21496#include "clang/Basic/OpenCLExtensionTypes.def"
21497#define SVE_TYPE(Name, Id, SingletonId) \
21498 case BuiltinType::Id:
21499#include "clang/Basic/AArch64ACLETypes.def"
21500#define PPC_VECTOR_TYPE(Name, Id, Size) \
21501 case BuiltinType::Id:
21502#include "clang/Basic/PPCTypes.def"
21503#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21504#include "clang/Basic/RISCVVTypes.def"
21505#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21506#include "clang/Basic/WebAssemblyReferenceTypes.def"
21507#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21508#include "clang/Basic/AMDGPUTypes.def"
21509#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21510#include "clang/Basic/HLSLIntangibleTypes.def"
21511#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21512#define PLACEHOLDER_TYPE(Id, SingletonId)
21513#include "clang/AST/BuiltinTypes.def"
21514 break;
21515 }
21516
21517 llvm_unreachable("invalid placeholder type!");
21518}
21519
21521 if (E->isTypeDependent())
21522 return true;
21525 return false;
21526}
21527
21529 ArrayRef<Expr *> SubExprs, QualType T) {
21530 if (!Context.getLangOpts().RecoveryAST)
21531 return ExprError();
21532
21533 if (isSFINAEContext())
21534 return ExprError();
21535
21536 if (T.isNull() || T->isUndeducedType() ||
21537 !Context.getLangOpts().RecoveryASTType)
21538 // We don't know the concrete type, fallback to dependent type.
21540
21541 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21542}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ template declaration subclasses.
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition: Decl.cpp:2691
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
LangStandard::Kind Std
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.
uint32_t Id
Definition: SemaARM.cpp:1179
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)
Definition: SemaExpr.cpp:10694
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:18046
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:2036
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.
Definition: SemaExpr.cpp:15573
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...
Definition: SemaExpr.cpp:10173
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:11047
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...
Definition: SemaExpr.cpp:15357
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6209
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10966
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...
Definition: SemaExpr.cpp:8831
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3198
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18758
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8282
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",...
Definition: SemaExpr.cpp:8490
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.
Definition: SemaExpr.cpp:12021
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:11011
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9252
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11971
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5872
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2319
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14869
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18386
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13599
@ NCCK_Block
Definition: SemaExpr.cpp:13599
@ NCCK_None
Definition: SemaExpr.cpp:13599
@ NCCK_Lambda
Definition: SemaExpr.cpp:13599
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...
Definition: SemaExpr.cpp:10062
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9302
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6141
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,...
Definition: SemaExpr.cpp:2680
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9201
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:20262
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18856
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:17062
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.
Definition: SemaExpr.cpp:8735
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:2020
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16944
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:14196
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4795
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12435
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14769
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4394
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8810
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:18248
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14925
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:11133
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8118
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:20055
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3223
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8084
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:12063
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6490
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13798
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:20308
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
Definition: SemaExpr.cpp:6556
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.
Definition: SemaExpr.cpp:10111
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:20023
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14751
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17896
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12308
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...
Definition: SemaExpr.cpp:8765
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:15011
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1320
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6380
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.
Definition: SemaExpr.cpp:9691
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.
Definition: SemaExpr.cpp:8406
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8105
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10978
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4852
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9012
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17938
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Definition: SemaExpr.cpp:1566
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...
Definition: SemaExpr.cpp:15448
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...
Definition: SemaExpr.cpp:14301
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8351
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.
Definition: SemaExpr.cpp:8460
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10733
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:12122
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...
Definition: SemaExpr.cpp:4256
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10781
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3511
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5831
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:147
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11509
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4163
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.
Definition: SemaExpr.cpp:19043
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 ...
Definition: SemaExpr.cpp:1277
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18683
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:11163
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13864
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14403
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:163
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:18279
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:11872
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15505
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14463
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1370
static AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9032
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4866
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...
Definition: SemaExpr.cpp:10220
static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, const ExprResult &LHS, const ExprResult &RHS, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10794
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15412
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:551
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8865
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:18366
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...
Definition: SemaExpr.cpp:13673
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3642
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13651
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18800
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:11025
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4208
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.
Definition: SemaExpr.cpp:7828
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11708
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12351
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:21273
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...
Definition: SemaExpr.cpp:2028
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8528
OriginalExprKind
Definition: SemaExpr.cpp:13792
@ OEK_Variable
Definition: SemaExpr.cpp:13793
@ OEK_LValue
Definition: SemaExpr.cpp:13795
@ OEK_Member
Definition: SemaExpr.cpp:13794
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18935
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1227
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10953
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.
Definition: SemaExpr.cpp:11614
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
Definition: SemaExpr.cpp:5640
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1302
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10658
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13586
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...
Definition: SemaExpr.cpp:12079
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.
Definition: SemaExpr.cpp:19176
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6449
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4193
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4181
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15433
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4885
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11214
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.
Definition: SemaExpr.cpp:19003
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6407
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1416
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4238
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10995
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,...
Definition: SemaExpr.cpp:8321
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:12269
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:13146
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8440
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8750
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...
Definition: SemaExpr.cpp:1121
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14967
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:576
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20879
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1196
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11924
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1149
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...
Definition: SemaExpr.cpp:6301
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:20233
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1996
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:109
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1463
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1172
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14265
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:19150
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10943
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11861
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.
Definition: SemaExpr.cpp:15045
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11911
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13600
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8256
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15477
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15463
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11901
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15400
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4460
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...
Definition: SemaExpr.cpp:10132
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18837
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15749
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13992
@ ConstMethod
Definition: SemaExpr.cpp:13664
@ ConstUnknown
Definition: SemaExpr.cpp:13666
@ ConstVariable
Definition: SemaExpr.cpp:13662
@ NestedConstMember
Definition: SemaExpr.cpp:13665
@ ConstMember
Definition: SemaExpr.cpp:13663
@ ConstFunction
Definition: SemaExpr.cpp:13661
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13386
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 ...
Definition: SemaExpr.cpp:19624
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18312
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11503
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:11079
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7589
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
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.
SourceLocation Begin
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
__device__ int
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
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:83
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType AccumTy
Definition: ASTContext.h:1235
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1253
CanQualType LongTy
Definition: ASTContext.h:1231
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
Definition: ASTContext.h:1231
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
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.
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2394
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
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 getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2409
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1235
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1234
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
CanQualType DoubleTy
Definition: ASTContext.h:1234
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
Definition: ASTContext.h:1234
CanQualType Char16Ty
Definition: ASTContext.h:1229
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1249
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
Definition: ASTContext.h:1250
CanQualType WideCharTy
Definition: ASTContext.h:1226
IdentifierTable & Idents
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2269
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition: ASTContext.h:862
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1306
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1223
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType Float128Ty
Definition: ASTContext.h:1234
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1310
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1238
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
Definition: ASTContext.h:1250
CanQualType CharTy
Definition: ASTContext.h:1224
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1231
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1302
CanQualType PseudoObjectTy
Definition: ASTContext.h:1253
CanQualType Float16Ty
Definition: ASTContext.h:1248
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1250
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2605
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
CanQualType BuiltinFnTy
Definition: ASTContext.h:1252
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1222
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:2146
CanQualType UnknownAnyTy
Definition: ASTContext.h:1251
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
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.
Definition: ASTContext.h:1750
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1231
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
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.
CanQualType FractTy
Definition: ASTContext.h:1238
CanQualType LongAccumTy
Definition: ASTContext.h:1236
CanQualType Char32Ty
Definition: ASTContext.h:1230
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CanQualType LongFractTy
Definition: ASTContext.h:1238
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1261
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2644
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 ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
CanQualType LongLongTy
Definition: ASTContext.h:1231
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:2060
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
unsigned char getFixedPointScale(QualType Ty) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1228
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1246
bool isDependenceAllowed() const
Definition: ASTContext.h:900
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2629
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
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:4486
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2723
Wrapper for source info for arrays.
Definition: TypeLoc.h:1757
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
ArraySizeModifier getSizeModifier() const
Definition: TypeBase.h:3752
QualType getElementType() const
Definition: TypeBase.h:3750
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6621
Attr - This represents one attribute.
Definition: Attr.h:44
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4389
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
Expr * getLHS() const
Definition: Expr.h:4024
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2175
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:4074
bool isComparisonOp() const
Definition: Expr.h:4075
StringRef getOpcodeStr() const
Definition: Expr.h:4040
bool isRelationalOp() const
Definition: Expr.h:4069
SourceLocation getOperatorLoc() const
Definition: Expr.h:4016
bool isCompoundAssignmentOp() const
Definition: Expr.h:4118
bool isMultiplicativeOp() const
Definition: Expr.h:4059
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2128
bool isShiftOp() const
Definition: Expr.h:4063
Expr * getRHS() const
Definition: Expr.h:4026
bool isEqualityOp() const
Definition: Expr.h:4072
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:4938
bool isBitwiseOp() const
Definition: Expr.h:4066
bool isAdditiveOp() const
Definition: Expr.h:4061
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition: Expr.cpp:2200
Opcode getOpcode() const
Definition: Expr.h:4019
bool isAssignmentOp() const
Definition: Expr.h:4113
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2137
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:4065
A binding in a decomposition declaration.
Definition: DeclCXX.h:4179
A class which contains all the information about a particular captured value.
Definition: Decl.h:4640
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4634
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5314
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4716
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4773
void setIsVariadic(bool value)
Definition: Decl.h:4710
SourceLocation getCaretLocation() const
Definition: Decl.h:4707
void setBody(CompoundStmt *B)
Definition: Decl.h:4714
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4720
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5325
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5513
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6560
Pointer to a block type.
Definition: TypeBase.h:3558
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
bool isSVEBool() const
Definition: TypeBase.h:3259
Kind getKind() const
Definition: TypeBase.h:3230
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:362
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:436
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:349
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.cpp:80
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:335
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:341
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...
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2937
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:3168
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2369
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1271
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:1039
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1378
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.cpp:1093
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:2739
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
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
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:180
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:97
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:103
Represents the this expression in C++.
Definition: ExprCXX.h:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3083
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3096
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3062
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3102
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3612
const char * getCastKindName() const
Definition: Expr.h:3660
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
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:1631
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4784
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: TypeBase.h:3293
QualType getElementType() const
Definition: TypeBase.h:3303
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:4960
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3541
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1720
bool body_empty() const
Definition: Stmt.h:1764
Stmt * getStmtExprResult()
Definition: Stmt.h:1842
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4327
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: TypeBase.h:3852
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1084
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:298
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1134
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition: TypeBase.h:4389
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: TypeBase.h:4410
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: TypeBase.h:4407
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4655
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:1454
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1382
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
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1662
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2048
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1309
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Definition: DeclBase.cpp:1428
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1383
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1427
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1373
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1476
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:540
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1431
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1344
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1399
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:484
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1361
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1365
ValueDecl * getDecl()
Definition: Expr.h:1340
SourceLocation getBeginLoc() const
Definition: Expr.h:1351
SourceLocation getLocation() const
Definition: Expr.h:1348
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:573
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
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:753
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:156
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:568
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
void setReferenced(bool R=true)
Definition: DeclBase.h:623
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1049
DeclContext * getDeclContext()
Definition: DeclBase.h:448
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
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...
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:830
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2000
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:844
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
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
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.
Definition: Diagnostic.h:1233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:950
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:722
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool VisitStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Recursively visit a template argument and dispatch to the appropriate method for the argument type.
Represents a reference to #emded data.
Definition: Expr.h:5062
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4168
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EnumDecl * getOriginalDecl() const
Definition: TypeBase.h:6529
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3864
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3891
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:3100
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:3029
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:3078
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:3073
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3061
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3082
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:3069
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:3293
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:833
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:829
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:837
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:3624
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:3053
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:804
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:813
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:816
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:819
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:806
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:4001
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4255
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:464
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:476
isModifiableLvalueResult
Definition: Expr.h:304
@ MLV_DuplicateVectorComponents
Definition: Expr.h:308
@ MLV_LValueCast
Definition: Expr.h:310
@ MLV_InvalidMessageExpression
Definition: Expr.h:319
@ MLV_ConstQualifiedField
Definition: Expr.h:313
@ MLV_InvalidExpression
Definition: Expr.h:309
@ MLV_IncompleteType
Definition: Expr.h:311
@ MLV_Valid
Definition: Expr.h:305
@ MLV_ConstQualified
Definition: Expr.h:312
@ MLV_NoSetterProperty
Definition: Expr.h:316
@ MLV_ArrayTemporary
Definition: Expr.h:321
@ MLV_SubObjCPropertySetting
Definition: Expr.h:318
@ MLV_ConstAddrSpace
Definition: Expr.h:314
@ MLV_MemberFunction
Definition: Expr.h:317
@ MLV_NotObjectType
Definition: Expr.h:306
@ MLV_ArrayType
Definition: Expr.h:315
@ MLV_ClassTemporary
Definition: Expr.h:320
@ MLV_IncompleteVoidType
Definition: Expr.h:307
QualType getType() const
Definition: Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:455
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:434
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:133
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6500
ExtVectorType - Extended vector type.
Definition: TypeBase.h:4283
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
bool isFPConstrained() const
Definition: LangOptions.h:844
RoundingMode getRoundingMode() const
Definition: LangOptions.h:850
Represents a member of a struct/union/class.
Definition: Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3260
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3337
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3393
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:128
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:102
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1072
const Expr * getSubExpr() const
Definition: Expr.h:1064
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:1999
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:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3788
bool isImmediateFunction() const
Definition: Decl.cpp:3328
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3965
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3703
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3806
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2918
QualType getReturnType() const
Definition: Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2771
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2442
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3559
bool isImmediateEscalating() const
Definition: Decl.cpp:3303
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2930
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4071
bool isConsteval() const
Definition: Decl.h:2481
size_t param_size() const
Definition: Decl.h:2787
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3191
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3981
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2878
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition: ExprCXX.h:4835
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
QualType desugar() const
Definition: TypeBase.h:5863
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: TypeBase.h:5786
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: TypeBase.h:5589
bool isParamConsumed(unsigned I) const
Definition: TypeBase.h:5800
unsigned getNumParams() const
Definition: TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
ArrayRef< QualType > param_types() const
Definition: TypeBase.h:5722
Declaration of a template function.
Definition: DeclTemplate.h:952
unsigned getNumParams() const
Definition: TypeLoc.h:1696
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1702
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1648
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1705
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1640
A class which abstracts out some details necessary for making a call.
Definition: TypeBase.h:4589
ExtInfo withNoReturn(bool noReturn) const
Definition: TypeBase.h:4660
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: TypeBase.h:4517
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
ExtInfo getExtInfo() const
Definition: TypeBase.h:4834
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: TypeBase.h:4826
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition: Type.cpp:3607
QualType getReturnType() const
Definition: TypeBase.h:4818
bool getCmseNSCallAttr() const
Definition: TypeBase.h:4832
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: TypeBase.h:4846
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4859
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:4560
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:1733
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:615
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3464
Describes an C or C++ initializer list.
Definition: Expr.h:5235
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.
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7739
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:971
Represents the declaration of a label.
Definition: Decl.h:523
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:239
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:245
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:243
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:250
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:241
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
Definition: LangOptions.h:395
@ 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...
Definition: LangOptions.h:434
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:469
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:614
bool isSignedOverflowDefined() const
Definition: LangOptions.h:610
bool allowArrayReturnTypes() const
Definition: LangOptions.h:739
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:65
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1020
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:309
Represents the results of name lookup.
Definition: Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:607
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:488
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:4392
MS property subscript expression.
Definition: ExprCXX.h:1007
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2801
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: TypeBase.h:4353
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: TypeBase.h:4367
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3489
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3383
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1746
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3518
Expr * getBase() const
Definition: Expr.h:3377
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:636
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1680
bool isExternallyVisible() const
Definition: Decl.h:432
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:396
Represent a C++ namespace.
Definition: Decl.h:591
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.
@ Type
A type, stored as a Type*.
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
Interfaces are the core concept in Objective-C for object oriented design.
Definition: TypeBase.h:7905
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1498
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:548
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:594
SourceLocation getLocation() const
Definition: ExprObjC.h:591
SourceLocation getOpLoc() const
Definition: ExprObjC.h:599
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:578
bool isArrow() const
Definition: ExprObjC.h:586
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:597
const Expr * getBase() const
Definition: ExprObjC.h:582
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
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:7961
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1840
qual_range quals() const
Definition: TypeBase.h:8080
Represents a class type in Objective C.
Definition: TypeBase.h:7707
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:731
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:176
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2084
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1649
Helper class for OffsetOfExpr.
Definition: Expr.h:2423
void * getAsOpaquePtr() const
Definition: Ownership.h:91
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:3122
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3183
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2205
const Expr * getSubExpr() const
Definition: Expr.h:2201
bool isProducedByFoldExpansion() const
Definition: Expr.h:2226
Expr * getExpr(unsigned Init)
Definition: Expr.h:6048
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4810
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:6046
Represents a parameter to a function.
Definition: Decl.h:1789
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1918
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1822
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1922
QualType getOriginalType() const
Definition: Decl.cpp:2955
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2946
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3050
bool isEquivalent(PointerAuthQualifier Other) const
Definition: TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:629
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:669
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6692
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: TypeBase.h:8432
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:87
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3591
@ DK_nontrivial_c_struct
Definition: TypeBase.h:1538
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2925
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:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
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:81
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
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:2707
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:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2944
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:8535
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: TypeBase.h:8464
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: TypeBase.h:1545
bool isCanonical() const
Definition: TypeBase.h:8400
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:2699
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:8508
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: TypeBase.h:8375
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:75
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:4309
bool hasFlexibleArrayMember() const
Definition: Decl.h:4342
field_range fields() const
Definition: Decl.h:4512
RecordDecl * getDefinitionOrSelf() const
Definition: Decl.h:4497
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5265
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:271
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition: SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
Sema & SemaRef
Definition: SemaBase.h:40
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:723
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:899
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:120
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
Definition: SemaHLSL.cpp:3519
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Definition: SemaHLSL.cpp:1060
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Definition: SemaHLSL.cpp:993
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
Definition: SemaObjC.cpp:1256
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1156
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:371
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:8393
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12359
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12401
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7668
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17411
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17417
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
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...
Definition: SemaExpr.cpp:14890
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.
Definition: SemaType.cpp:6383
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:8036
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:8146
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13430
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:1113
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:16082
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:8196
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15759
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:8114
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:6904
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15533
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:8189
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9320
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
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:405
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19987
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13467
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7112
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)
Definition: SemaExpr.cpp:7634
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)
Definition: SemaExpr.cpp:5786
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.
Definition: SemaExpr.cpp:15069
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...
Definition: SemaExpr.cpp:2432
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1498
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:16101
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.
Definition: SemaExpr.cpp:17768
void ActOnStmtExprError()
Definition: SemaExpr.cpp:16107
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20514
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....
Definition: SemaExpr.cpp:1642
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)
Definition: SemaExpr.cpp:12465
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16811
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:1223
SemaCUDA & CUDA()
Definition: Sema.h:1438
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17664
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20730
ConditionKind
Definition: Sema.h:7788
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2720
bool needsRebuildOfDefaultArgOrInit() const
Definition: Sema.h:8134
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.
Definition: SemaExpr.cpp:6030
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition: Sema.h:8276
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:1216
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2442
Preprocessor & getPreprocessor() const
Definition: Sema.h:917
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6882
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2311
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:13032
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:8265
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3575
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:8177
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)
Definition: SemaExpr.cpp:18752
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6788
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10312
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:2042
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7608
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)
Definition: SemaExpr.cpp:16120
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.
Definition: SemaExpr.cpp:9764
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16763
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6894
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:1647
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:827
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1052
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
Definition: SemaExpr.cpp:14216
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5075
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2095
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7718
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14496
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15520
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1108
ASTContext & Context
Definition: Sema.h:1276
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:8101
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2721
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13268
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:10002
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:20525
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11800
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
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...
Definition: SemaExpr.cpp:8014
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)
Definition: SemaExpr.cpp:21520
SemaObjC & ObjC()
Definition: Sema.h:1483
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13303
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:2821
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.
Definition: SemaDecl.cpp:1555
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19998
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:748
bool isImmediateFunctionContext() const
Definition: Sema.h:8126
ASTContext & getASTContext() const
Definition: Sema.h:918
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:758
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)
Definition: SemaExpr.cpp:16038
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.
Definition: SemaExpr.cpp:19252
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:20253
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15559
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()
Definition: SemaExpr.cpp:18155
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:877
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3523
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6276
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3142
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)
Definition: SemaExpr.cpp:7126
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:16088
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11350
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:6034
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8030
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:13349
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1652
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2298
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)
Definition: SemaExpr.cpp:16375
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 *.
Definition: SemaExpr.cpp:1759
AssumedTemplateKind
Definition: Sema.h:11360
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:2065
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:500
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...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1053
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:8161
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:913
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:8259
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20761
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_Block
Block expression.
Definition: Sema.h:14280
const LangOptions & getLangOpts() const
Definition: Sema.h:911
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12492
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7382
SemaOpenACC & OpenACC()
Definition: Sema.h:1488
ReuseLambdaContextDecl_t
Definition: Sema.h:6970
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.
Definition: SemaDecl.cpp:6750
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17799
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2346
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.
Definition: SemaExpr.cpp:20399
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2513
Preprocessor & PP
Definition: Sema.h:1275
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11224
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.
Definition: SemaExpr.cpp:6572
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14468
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:17044
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4787
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:2113
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7623
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,...
Definition: SemaExpr.cpp:9286
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:1274
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
Definition: SemaExpr.cpp:17700
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:16190
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2557
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.
Definition: SemaExpr.cpp:6838
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17820
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7699
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:946
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6460
SemaHLSL & HLSL()
Definition: Sema.h:1448
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17784
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15504
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:207
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:75
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20409
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.
Definition: SemaExpr.cpp:10026
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:6915
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6490
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1659
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10832
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:13841
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:16001
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)
Definition: SemaCast.cpp:3441
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1307
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)
Definition: SemaExpr.cpp:17052
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3675
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10580
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...
Definition: SemaStmt.cpp:1728
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6912
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2294
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:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3230
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:8130
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9710
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7369
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 *.
Definition: SemaExpr.cpp:1727
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16551
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7759
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition: Sema.h:7997
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2512
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7682
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:21226
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:12425
SemaOpenCL & OpenCL()
Definition: Sema.h:1493
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5948
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13850
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16926
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...
Definition: SemaExpr.cpp:8045
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.
Definition: SemaExpr.cpp:20460
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:8122
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1627
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.
Definition: SemaDecl.cpp:8605
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20356
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2918
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4154
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:17011
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6719
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21316
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17644
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:13791
SourceManager & getSourceManager() const
Definition: Sema.h:916
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6816
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4450
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 ?: operation.
Definition: SemaExpr.cpp:8916
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:13044
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19964
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:14037
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)
@ NTCUK_Destruct
Definition: Sema.h:4065
@ NTCUK_Copy
Definition: Sema.h:4066
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition: Sema.h:8275
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20595
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5564
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7653
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7690
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2342
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 ?: under C++ semantics.
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:6717
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:218
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.
Definition: SemaDecl.cpp:8440
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....
Definition: SemaExpr.cpp:2144
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:15279
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15539
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)
Definition: SemaExpr.cpp:7792
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2497
bool isConstantEvaluatedContext() const
Definition: Sema.h:2584
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 ...
Definition: SemaExpr.cpp:17422
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12719
ASTConsumer & Consumer
Definition: Sema.h:1277
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4622
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:6919
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:123
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:1312
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13833
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5197
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3571
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12989
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.
Definition: SemaExpr.cpp:8547
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6661
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2067
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.
Definition: SemaExpr.cpp:6809
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4687
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5693
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.
Definition: SemaExpr.cpp:20602
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4272
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16756
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5805
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9241
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1239
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21246
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.
Definition: SemaExpr.cpp:19578
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7862
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3003
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:8112
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18228
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19570
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:8262
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1366
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7739
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9216
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3184
SourceManager & SourceMgr
Definition: Sema.h:1279
@ TemplateNameIsRequired
Definition: Sema.h:11337
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4779
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7931
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition: SemaExpr.cpp:777
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.
Definition: SemaExpr.cpp:2454
DiagnosticsEngine & Diags
Definition: Sema.h:1278
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:912
FPOptions CurFPFeatures
Definition: Sema.h:1272
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:509
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:710
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:7676
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
Definition: SemaExpr.cpp:15609
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9874
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3635
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5658
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20645
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
Definition: SemaDecl.cpp:1373
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13400
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6494
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16115
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...
Definition: SemaExpr.cpp:1007
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6151
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13105
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8995
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13284
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16561
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:627
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20380
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...
Definition: SemaExpr.cpp:17081
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,...
Definition: SemaExpr.cpp:18401
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:16159
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4832
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:279
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20701
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:2096
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21528
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3709
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7344
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16413
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4905
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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.
Definition: SemaExpr.cpp:6520
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...
Definition: SemaExpr.cpp:4762
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7920
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:9334
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9340
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9332
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9337
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9348
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9344
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16442
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10878
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:13829
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...
Definition: SemaExpr.cpp:1502
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2773
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 ...
Definition: SemaDecl.cpp:16171
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...
Definition: SemaDecl.cpp:13544
static ConditionResult ConditionError()
Definition: Sema.h:7775
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6830
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.
Definition: SemaExpr.cpp:21250
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 ...
Definition: SemaExpr.cpp:5890
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16356
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1508
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2488
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2734
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:18236
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7276
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:8138
SemaARM & ARM()
Definition: Sema.h:1418
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5409
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8599
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5083
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4953
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:390
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4531
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:186
Stmt - This represents one statement.
Definition: Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
StmtClass getStmtClass() const
Definition: Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
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:1801
unsigned getLength() const
Definition: Expr.h:1911
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition: Expr.cpp:1184
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1884
StringRef getString() const
Definition: Expr.h:1869
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3809
bool isUnion() const
Definition: Decl.h:3919
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3941
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:810
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:226
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition: TargetInfo.h:730
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:332
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:690
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:1015
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:293
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:486
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:673
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:527
IntType getSizeType() const
Definition: TargetInfo.h:385
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:537
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1616
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1709
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1062
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
Definition: TargetInfo.h:1365
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:888
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:532
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1526
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:652
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:653
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:669
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:411
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.
Definition: TemplateBase.h:329
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:134
unsigned getLength() const
Definition: Token.h:137
void setKind(tok::TokenKind K)
Definition: Token.h:98
tok::TokenKind getKind() const
Definition: Token.h:97
void startToken()
Reset all flags to cleared.
Definition: Token.h:179
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents a declaration of a type.
Definition: Decl.h:3510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3544
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:222
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:2843
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:556
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:2503
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: TypeBase.h:9000
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isFunctionReferenceType() const
Definition: TypeBase.h:8654
bool isObjCBuiltinType() const
Definition: TypeBase.h:8800
bool isMFloat8Type() const
Definition: TypeBase.h:8961
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:1955
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: TypeBase.h:9116
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:787
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
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:8912
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
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:9096
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:2070
bool isVoidPointerType() const
Definition: Type.cpp:712
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:745
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isArithmeticType() const
Definition: Type.cpp:2341
bool isConstantMatrixType() const
Definition: TypeBase.h:8741
bool isPointerType() const
Definition: TypeBase.h:8580
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2578
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
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:9020
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isScalarType() const
Definition: TypeBase.h:9038
bool isVariableArrayType() const
Definition: TypeBase.h:8691
bool isChar8Type() const
Definition: Type.cpp:2152
bool isSizelessBuiltinType() const
Definition: Type.cpp:2536
bool isClkEventT() const
Definition: TypeBase.h:8822
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2612
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
bool isObjCQualifiedIdType() const
Definition: TypeBase.h:8770
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2295
bool isExtVectorType() const
Definition: TypeBase.h:8723
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2172
bool isExtVectorBoolType() const
Definition: TypeBase.h:8727
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2651
bool isImageType() const
Definition: TypeBase.h:8834
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: TypeBase.h:8930
bool isPipeType() const
Definition: TypeBase.h:8841
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: TypeBase.h:2808
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: TypeBase.h:8905
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isChar16Type() const
Definition: Type.cpp:2158
bool isAnyComplexType() const
Definition: TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
bool isHalfType() const
Definition: TypeBase.h:8940
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:9008
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: TypeBase.h:2423
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2368
const BuiltinType * getAsPlaceholderType() const
Definition: TypeBase.h:8918
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2247
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2562
bool isQueueT() const
Definition: TypeBase.h:8826
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isAtomicType() const
Definition: TypeBase.h:8762
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: TypeBase.h:9079
bool isObjCIdType() const
Definition: TypeBase.h:8782
bool isMatrixType() const
Definition: TypeBase.h:8737
bool isChar32Type() const
Definition: Type.cpp:2164
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:2818
bool isComplexIntegerType() const
Definition: Type.cpp:730
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2129
bool isObjCObjectType() const
Definition: TypeBase.h:8753
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:5266
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9212
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5355
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isDoubleType() const
Definition: TypeBase.h:8953
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2316
bool isMemberFunctionPointerType() const
Definition: TypeBase.h:8665
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:9034
bool isVectorType() const
Definition: TypeBase.h:8719
bool isObjCQualifiedClassType() const
Definition: TypeBase.h:8776
bool isObjCClassType() const
Definition: TypeBase.h:8788
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2599
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
@ STK_FloatingComplex
Definition: TypeBase.h:2782
@ STK_BlockPointer
Definition: TypeBase.h:2775
@ STK_ObjCObjectPointer
Definition: TypeBase.h:2776
@ STK_FixedPoint
Definition: TypeBase.h:2783
@ STK_IntegralComplex
Definition: TypeBase.h:2781
@ STK_MemberPointer
Definition: TypeBase.h:2777
bool isFloatingType() const
Definition: Type.cpp:2308
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:2257
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
bool isAnyPointerType() const
Definition: TypeBase.h:8588
bool isRealType() const
Definition: Type.cpp:2330
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
bool isSubscriptableVectorType() const
Definition: TypeBase.h:8733
bool isSamplerT() const
Definition: TypeBase.h:8814
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:5066
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2574
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition: Type.cpp:735
bool isUnicodeCharacterType() const
Definition: Type.cpp:2192
Wrapper for source info for typedefs.
Definition: TypeLoc.h:782
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.
bool isOverloaded() const
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:2627
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2291
Expr * getSubExpr() const
Definition: Expr.h:2287
Opcode getOpcode() const
Definition: Expr.h:2282
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1426
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:4995
bool isIncrementDecrementOp() const
Definition: Expr.h:2343
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4449
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:998
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3384
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:4120
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.
Definition: UnresolvedSet.h:62
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:4893
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
void setType(QualType newType)
Definition: Decl.h:723
QualType getType() const
Definition: Decl.h:722
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3566
QualType getType() const
Definition: Value.cpp:237
Represents a variable declaration or definition.
Definition: Decl.h:925
bool hasInit() const
Definition: Decl.cpp:2398
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1577
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1225
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2486
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2907
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1550
const Expr * getInit() const
Definition: Decl.h:1367
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1216
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1183
@ TLS_None
Not a TLS variable.
Definition: Decl.h:945
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2375
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2528
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2800
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1261
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2898
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: TypeBase.h:3982
Expr * getSizeExpr() const
Definition: TypeBase.h:3996
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
unsigned getNumElements() const
Definition: TypeBase.h:4206
VectorKind getVectorKind() const
Definition: TypeBase.h:4211
QualType getElementType() const
Definition: TypeBase.h:4205
Policy getPolicyInEffectAt(SourceLocation Loc)
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.
Definition: ScopeInfo.cpp:228
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.
Definition: ScopeInfo.cpp:160
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
Definition: ScopeInfo.cpp:251
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:992
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:998
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition: ScopeInfo.h:953
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
#define bool
Definition: gpuintrin.h:32
Defines the clang::TargetInfo interface.
Definition: SPIR.cpp:35
Definition: SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
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
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ GVA_StrongExternal
Definition: Linkage.h:76
VariadicCallType
Definition: Sema.h:511
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
CUDAFunctionTarget
Definition: Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition: Sema.h:651
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:659
@ BitwiseOp
A bitwise operation.
@ Arithmetic
An arithmetic operation.
@ Conditional
A conditional (?:) operator.
@ CompAssign
A compound assignment expression.
@ Comparison
A comparison.
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:348
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:169
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
BinaryOperatorKind
@ 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.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ AS_none
Definition: Specifiers.h:127
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:28
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_None
Definition: Specifiers.h:250
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:85
ExprResult ExprEmpty()
Definition: Ownership.h:272
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
@ Compatible
Compatible - the types are compatible according to the standard.
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
UnaryOperatorKind
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 ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:249
ExprResult ExprError()
Definition: Ownership.h:265
@ AR_Unavailable
Definition: DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition: Sema.h:653
VarArgKind
Definition: Sema.h:674
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:69
AssignmentAction
Definition: Sema.h:213
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
BuiltinCountedByRefKind
Definition: Sema.h:519
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:95
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.
for(const auto &A :T->param_types())
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
StringLiteralKind
Definition: Expr.h:1765
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
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 ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4940
@ None
No keyword precedes the qualified type name.
bool isLambdaMethod(const DeclContext *DC)
Definition: ASTLambda.h:39
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1991
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1605
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)
Definition: SemaExpr.cpp:5542
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5539
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5524
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5534
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5533
bool VisitSourceLocExpr(SourceLocExpr *E) override
Definition: SemaExpr.cpp:5498
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
Definition: SemaExpr.cpp:5488
bool VisitCallExpr(CallExpr *E) override
Definition: SemaExpr.cpp:5482
const ASTContext & Context
Definition: SemaExpr.cpp:5475
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
Definition: SemaExpr.cpp:5517
bool VisitLambdaExpr(LambdaExpr *E) override
Definition: SemaExpr.cpp:5509
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
Definition: SemaExpr.cpp:5513
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5476
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:5029
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:5367
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12970
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6723
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6753
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6804
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition: Sema.h:6743
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6758
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:6766
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6762
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6772
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:6738
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6780
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6728
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6725
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6732
Abstract class used to diagnose incomplete types.
Definition: Sema.h:8203
Location information for a TemplateArgument.
Definition: TemplateBase.h:480
uint64_t Width
Definition: ASTContext.h:159
Describes an entity that is being assigned.