clang 23.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
64#include "clang/Sema/Template.h"
65#include "llvm/ADT/STLExtras.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/TypeSize.h"
71#include <limits>
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
77bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
78 // See if this is an auto-typed variable whose initializer we are parsing.
79 if (ParsingInitForAutoVars.count(D))
80 return false;
81
82 // See if this is a deleted function.
83 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->isDeleted())
85 return false;
86
87 // If the function has a deduced return type, and we can't deduce it,
88 // then we can't use it either.
89 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
90 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
91 return false;
92
93 // See if this is an aligned allocation/deallocation function that is
94 // unavailable.
95 if (TreatUnavailableAsInvalid &&
97 return false;
98 }
99
100 // See if this function is unavailable.
101 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
102 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
103 return false;
104
106 return false;
107
108 return true;
109}
110
112 // Warn if this is used but marked unused.
113 if (const auto *A = D->getAttr<UnusedAttr>()) {
114 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
115 // should diagnose them.
116 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
117 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
118 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
119 if (DC && !DC->hasAttr<UnusedAttr>())
120 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
121 }
122 }
123}
124
126 assert(Decl && Decl->isDeleted());
127
128 if (Decl->isDefaulted()) {
129 // If the method was explicitly defaulted, point at that declaration.
130 if (!Decl->isImplicit())
131 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
132
133 // Try to diagnose why this special member function was implicitly
134 // deleted. This might fail, if that reason no longer applies.
136 return;
137 }
138
139 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
140 if (Ctor && Ctor->isInheritingConstructor())
142
143 Diag(Decl->getLocation(), diag::note_availability_specified_here)
144 << Decl << 1;
145}
146
147/// Determine whether a FunctionDecl was ever declared with an
148/// explicit storage class.
150 for (auto *I : D->redecls()) {
151 if (I->getStorageClass() != SC_None)
152 return true;
153 }
154 return false;
155}
156
157/// Check whether we're in an extern inline function and referring to a
158/// variable or function with internal linkage (C11 6.7.4p3).
159///
160/// This is only a warning because we used to silently accept this code, but
161/// in many cases it will not behave correctly. This is not enabled in C++ mode
162/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
163/// and so while there may still be user mistakes, most of the time we can't
164/// prove that there are errors.
166 const NamedDecl *D,
167 SourceLocation Loc) {
168 // This is disabled under C++; there are too many ways for this to fire in
169 // contexts where the warning is a false positive, or where it is technically
170 // correct but benign.
171 //
172 // WG14 N3622 which removed the constraint entirely in C2y. It is left
173 // enabled in earlier language modes because this is a constraint in those
174 // language modes. But in C2y mode, we still want to issue the "incompatible
175 // with previous standards" diagnostic, too.
176 if (S.getLangOpts().CPlusPlus)
177 return;
178
179 // Check if this is an inlined function or method.
180 FunctionDecl *Current = S.getCurFunctionDecl();
181 if (!Current)
182 return;
183 if (!Current->isInlined())
184 return;
185 if (!Current->isExternallyVisible())
186 return;
187
188 // Check if the decl has internal linkage.
190 return;
191
192 // Downgrade from ExtWarn to Extension if
193 // (1) the supposedly external inline function is in the main file,
194 // and probably won't be included anywhere else.
195 // (2) the thing we're referencing is a pure function.
196 // (3) the thing we're referencing is another inline function.
197 // This last can give us false negatives, but it's better than warning on
198 // wrappers for simple C library functions.
199 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
200 unsigned DiagID;
201 if (S.getLangOpts().C2y)
202 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
203 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
205 DiagID = diag::ext_internal_in_extern_inline_quiet;
206 else
207 DiagID = diag::ext_internal_in_extern_inline;
208
209 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
211 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
212 << D;
213}
214
216 const FunctionDecl *First = Cur->getFirstDecl();
217
218 // Suggest "static" on the function, if possible.
220 SourceLocation DeclBegin = First->getSourceRange().getBegin();
221 Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224}
225
227 const ObjCInterfaceDecl *UnknownObjCClass,
228 bool ObjCPropertyAccess,
229 bool AvoidPartialAvailabilityChecks,
230 ObjCInterfaceDecl *ClassReceiver,
231 bool SkipTrailingRequiresClause) {
232 SourceLocation Loc = Locs.front();
234 // If there were any diagnostics suppressed by template argument deduction,
235 // emit them now.
236 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
237 if (Pos != SuppressedDiagnostics.end()) {
238 for (const auto &[DiagLoc, PD] : Pos->second) {
239 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
240 PD.Emit(Builder);
241 }
242 // Clear out the list of suppressed diagnostics, so that we don't emit
243 // them again for this specialization. However, we don't obsolete this
244 // entry from the table, because we want to avoid ever emitting these
245 // diagnostics again.
246 Pos->second.clear();
247 }
248
249 // C++ [basic.start.main]p3:
250 // The function 'main' shall not be used within a program.
251 if (cast<FunctionDecl>(D)->isMain())
252 Diag(Loc, diag::ext_main_used);
253
255 }
256
257 // See if this is an auto-typed variable whose initializer we are parsing.
258 if (ParsingInitForAutoVars.count(D)) {
259 if (isa<BindingDecl>(D)) {
260 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << diag::ParsingInitFor::Var << D->getDeclName()
265 << cast<VarDecl>(D)->getType();
266 }
267 return true;
268 }
269
270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271 // See if this is a deleted function.
272 if (FD->isDeleted()) {
273 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
274 if (Ctor && Ctor->isInheritingConstructor())
275 Diag(Loc, diag::err_deleted_inherited_ctor_use)
276 << Ctor->getParent()
277 << Ctor->getInheritedConstructor().getConstructor()->getParent();
278 else {
279 StringLiteral *Msg = FD->getDeletedMessage();
280 Diag(Loc, diag::err_deleted_function_use)
281 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
282 }
284 return true;
285 }
286
287 // [expr.prim.id]p4
288 // A program that refers explicitly or implicitly to a function with a
289 // trailing requires-clause whose constraint-expression is not satisfied,
290 // other than to declare it, is ill-formed. [...]
291 //
292 // See if this is a function with constraints that need to be satisfied.
293 // Check this before deducing the return type, as it might instantiate the
294 // definition.
295 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
296 ConstraintSatisfaction Satisfaction;
297 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
298 /*ForOverloadResolution*/ true))
299 // A diagnostic will have already been generated (non-constant
300 // constraint expression, for example)
301 return true;
302 if (!Satisfaction.IsSatisfied) {
303 Diag(Loc,
304 diag::err_reference_to_function_with_unsatisfied_constraints)
305 << D;
306 DiagnoseUnsatisfiedConstraint(Satisfaction);
307 return true;
308 }
309 }
310
311 // If the function has a deduced return type, and we can't deduce it,
312 // then we can't use it either.
313 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
314 DeduceReturnType(FD, Loc))
315 return true;
316
317 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
318 return true;
319
320 }
321
322 if (auto *Concept = dyn_cast<ConceptDecl>(D);
324 return true;
325
326 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
327 // Lambdas are only default-constructible or assignable in C++2a onwards.
328 if (MD->getParent()->isLambda() &&
330 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
331 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
332 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
334 }
335 }
336
337 auto getReferencedObjCProp = [](const NamedDecl *D) ->
338 const ObjCPropertyDecl * {
339 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
340 return MD->findPropertyDecl();
341 return nullptr;
342 };
343 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
344 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
345 return true;
346 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
347 return true;
348 }
349
350 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
351 // Only the variables omp_in and omp_out are allowed in the combiner.
352 // Only the variables omp_priv and omp_orig are allowed in the
353 // initializer-clause.
354 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
355 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
356 isa<VarDecl>(D)) {
357 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
359 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
360 return true;
361 }
362
363 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
364 // List-items in map clauses on this construct may only refer to the declared
365 // variable var and entities that could be referenced by a procedure defined
366 // at the same location.
367 // [OpenMP 5.2] Also allow iterator declared variables.
368 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
369 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
370 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
372 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
373 return true;
374 }
375
376 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
377 Diag(Loc, diag::err_use_of_empty_using_if_exists);
378 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
379 return true;
380 }
381
382 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
383 AvoidPartialAvailabilityChecks, ClassReceiver);
384
385 DiagnoseUnusedOfDecl(*this, D, Loc);
386
388
389 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
390 if (getLangOpts().getFPEvalMethod() !=
392 PP.getLastFPEvalPragmaLocation().isValid() &&
393 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
394 Diag(D->getLocation(),
395 diag::err_type_available_only_in_default_eval_method)
396 << D->getName();
397 }
398
399 if (auto *VD = dyn_cast<ValueDecl>(D))
400 checkTypeSupport(VD->getType(), Loc, VD);
401
402 if (LangOpts.SYCLIsDevice ||
403 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
404 if (!Context.getTargetInfo().isTLSSupported())
405 if (const auto *VD = dyn_cast<VarDecl>(D))
406 if (VD->getTLSKind() != VarDecl::TLS_None)
407 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
408 }
409
410 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
411 SYCL().CheckDeviceUseOfDecl(D, Loc);
412
413 return false;
414}
415
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
419 if (!Attr)
420 return;
421
422 // The number of formal parameters of the declaration.
423 unsigned NumFormalParams;
424
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
428
429 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
430 NumFormalParams = MD->param_size();
431 CalleeKind = CK_Method;
432 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
433 NumFormalParams = FD->param_size();
434 CalleeKind = CK_Function;
435 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
436 QualType Ty = VD->getType();
437 const FunctionType *Fn = nullptr;
438 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
439 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
440 if (!Fn)
441 return;
442 CalleeKind = CK_Function;
443 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
444 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
445 CalleeKind = CK_Block;
446 } else {
447 return;
448 }
449
450 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
451 NumFormalParams = proto->getNumParams();
452 else
453 NumFormalParams = 0;
454 } else {
455 return;
456 }
457
458 // "NullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned NullPos = Attr->getNullPos();
463 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
464 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
465
466 // The number of arguments which should follow the sentinel.
467 unsigned NumArgsAfterSentinel = Attr->getSentinel();
468
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
474 return;
475 }
476
477 // Otherwise, find the sentinel expression.
478 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
479 if (!SentinelExpr)
480 return;
481 if (SentinelExpr->isValueDependent())
482 return;
483 if (Context.isSentinelNullExpr(SentinelExpr))
484 return;
485
486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
487 // or 'NULL' if those are actually defined in the context. Only use
488 // 'nil' for ObjC methods, where it's much more likely that the
489 // variadic arguments form a list of object pointers.
490 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
491 std::string NullValue;
492 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
493 NullValue = "nil";
494 else if (getLangOpts().CPlusPlus11)
495 NullValue = "nullptr";
496 else if (PP.isMacroDefined("NULL"))
497 NullValue = "NULL";
498 else
499 NullValue = "(void*) 0";
500
501 if (MissingNilLoc.isInvalid())
502 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
503 else
504 Diag(MissingNilLoc, diag::warn_missing_sentinel)
505 << int(CalleeKind)
506 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
507 Diag(D->getLocation(), diag::note_sentinel_here)
508 << int(CalleeKind) << Attr->getRange();
509}
510
512 return E ? E->getSourceRange() : SourceRange();
513}
514
515//===----------------------------------------------------------------------===//
516// Standard Promotions and Conversions
517//===----------------------------------------------------------------------===//
518
519/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521 // Handle any placeholder expressions which made it here.
522 if (E->hasPlaceholderType()) {
524 if (result.isInvalid()) return ExprError();
525 E = result.get();
526 }
527
528 QualType Ty = E->getType();
529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
530
531 if (Ty->isFunctionType()) {
532 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
533 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535 return ExprError();
536
537 E = ImpCastExprToType(E, Context.getPointerType(Ty),
538 CK_FunctionToPointerDecay).get();
539 } else if (Ty->isArrayType()) {
540 // In C90 mode, arrays only promote to pointers if the array expression is
541 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
542 // type 'array of type' is converted to an expression that has type 'pointer
543 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
544 // that has type 'array of type' ...". The relevant change is "an lvalue"
545 // (C90) to "an expression" (C99).
546 //
547 // C++ 4.2p1:
548 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
549 // T" can be converted to an rvalue of type "pointer to T".
550 //
551 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
552 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
553 CK_ArrayToPointerDecay);
554 if (Res.isInvalid())
555 return ExprError();
556 E = Res.get();
557 }
558 }
559 return E;
560}
561
563 // Check to see if we are dereferencing a null pointer. If so,
564 // and if not volatile-qualified, this is undefined behavior that the
565 // optimizer will delete, so warn about it. People sometimes try to use this
566 // to get a deterministic trap and are surprised by clang's behavior. This
567 // only handles the pattern "*null", which is a very syntactic check.
568 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
569 if (UO && UO->getOpcode() == UO_Deref &&
570 UO->getSubExpr()->getType()->isPointerType()) {
571 const LangAS AS =
572 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
573 if ((!isTargetAddressSpace(AS) ||
574 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
575 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 !UO->getType().isVolatileQualified()) {
578 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
579 S.PDiag(diag::warn_indirection_through_null)
580 << UO->getSubExpr()->getSourceRange());
581 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
582 S.PDiag(diag::note_indirection_through_null));
583 }
584 }
585}
586
587static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
588 SourceLocation AssignLoc,
589 const Expr* RHS) {
590 const ObjCIvarDecl *IV = OIRE->getDecl();
591 if (!IV)
592 return;
593
594 DeclarationName MemberName = IV->getDeclName();
596 if (!Member || !Member->isStr("isa"))
597 return;
598
599 const Expr *Base = OIRE->getBase();
600 QualType BaseType = Base->getType();
601 if (OIRE->isArrow())
602 BaseType = BaseType->getPointeeType();
603 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
604 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
605 ObjCInterfaceDecl *ClassDeclared = nullptr;
606 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
607 if (!ClassDeclared->getSuperClass()
608 && (*ClassDeclared->ivar_begin()) == IV) {
609 if (RHS) {
610 NamedDecl *ObjectSetClass =
612 &S.Context.Idents.get("object_setClass"),
614 if (ObjectSetClass) {
615 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618 "object_setClass(")
620 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
621 << FixItHint::CreateInsertion(RHSLocEnd, ")");
622 }
623 else
624 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
625 } else {
626 NamedDecl *ObjectGetClass =
628 &S.Context.Idents.get("object_getClass"),
630 if (ObjectGetClass)
631 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633 "object_getClass(")
635 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
636 else
637 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
638 }
639 S.Diag(IV->getLocation(), diag::note_ivar_decl);
640 }
641 }
642}
643
645 // Handle any placeholder expressions which made it here.
646 if (E->hasPlaceholderType()) {
648 if (result.isInvalid()) return ExprError();
649 E = result.get();
650 }
651
652 // C++ [conv.lval]p1:
653 // A glvalue of a non-function, non-array type T can be
654 // converted to a prvalue.
655 if (!E->isGLValue()) return E;
656
657 QualType T = E->getType();
658 assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660 // lvalue-to-rvalue conversion cannot be applied to types that decay to
661 // pointers (i.e. function or array types).
662 if (T->canDecayToPointerType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus) {
668 if (T == Context.OverloadTy || T->isRecordType() ||
669 (T->isDependentType() && !T->isAnyPointerType() &&
670 !T->isMemberPointerType()))
671 return E;
672 }
673
674 // The C standard is actually really unclear on this point, and
675 // DR106 tells us what the result should be but not why. It's
676 // generally best to say that void types just doesn't undergo
677 // lvalue-to-rvalue at all. Note that expressions of unqualified
678 // 'void' type are never l-values, but qualified void can be.
679 if (T->isVoidType())
680 return E;
681
682 // OpenCL usually rejects direct accesses to values of 'half' type.
683 if (getLangOpts().OpenCL &&
684 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
685 T->isHalfType()) {
686 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
687 << 0 << T;
688 return ExprError();
689 }
690
692 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
693 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
694 &Context.Idents.get("object_getClass"),
696 if (ObjectGetClass)
697 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
698 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
700 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
701 else
702 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
703 }
704 else if (const ObjCIvarRefExpr *OIRE =
705 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
706 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
707
708 // C++ [conv.lval]p1:
709 // [...] If T is a non-class type, the type of the prvalue is the
710 // cv-unqualified version of T. Otherwise, the type of the
711 // rvalue is T.
712 //
713 // C99 6.3.2.1p2:
714 // If the lvalue has qualified type, the value has the unqualified
715 // version of the type of the lvalue; otherwise, the value has the
716 // type of the lvalue.
717 if (T.hasQualifiers())
718 T = T.getUnqualifiedType();
719
720 // Under the MS ABI, lock down the inheritance model now.
721 if (T->isMemberPointerType() &&
722 Context.getTargetInfo().getCXXABI().isMicrosoft())
723 (void)isCompleteType(E->getExprLoc(), T);
724
726 if (Res.isInvalid())
727 return Res;
728 E = Res.get();
729
730 // Loading a __weak object implicitly retains the value, so we need a cleanup to
731 // balance that.
733 Cleanup.setExprNeedsCleanups(true);
734
736 Cleanup.setExprNeedsCleanups(true);
737
739 return ExprError();
740
741 // C++ [conv.lval]p3:
742 // If T is cv std::nullptr_t, the result is a null pointer constant.
743 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
744 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
746
747 // C11 6.3.2.1p2:
748 // ... if the lvalue has atomic type, the value has the non-atomic version
749 // of the type of the lvalue ...
750 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
751 T = Atomic->getValueType().getUnqualifiedType();
752 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
753 nullptr, VK_PRValue, FPOptionsOverride());
754 }
755
756 return Res;
757}
758
761 if (Res.isInvalid())
762 return ExprError();
763 Res = DefaultLvalueConversion(Res.get());
764 if (Res.isInvalid())
765 return ExprError();
766 return Res;
767}
768
770 QualType Ty = E->getType();
771 ExprResult Res = E;
772 // Only do implicit cast for a function type, but not for a pointer
773 // to function type.
774 if (Ty->isFunctionType()) {
775 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
776 CK_FunctionToPointerDecay);
777 if (Res.isInvalid())
778 return ExprError();
779 }
780 Res = DefaultLvalueConversion(Res.get());
781 if (Res.isInvalid())
782 return ExprError();
783 return Res.get();
784}
785
786/// UsualUnaryFPConversions - Promotes floating-point types according to the
787/// current language semantics.
789 QualType Ty = E->getType();
790 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
791
792 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
793 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
794 (getLangOpts().getFPEvalMethod() !=
796 PP.getLastFPEvalPragmaLocation().isValid())) {
797 switch (EvalMethod) {
798 default:
799 llvm_unreachable("Unrecognized float evaluation method");
800 break;
802 llvm_unreachable("Float evaluation method should be set by now");
803 break;
805 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
806 // Widen the expression to double.
807 return Ty->isComplexType()
809 Context.getComplexType(Context.DoubleTy),
810 CK_FloatingComplexCast)
811 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
812 break;
814 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
815 // Widen the expression to long double.
816 return Ty->isComplexType()
818 E, Context.getComplexType(Context.LongDoubleTy),
819 CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Context.LongDoubleTy,
821 CK_FloatingCast);
822 break;
823 }
824 }
825
826 // Half FP have to be promoted to float unless it is natively supported
827 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
828 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
829
830 return E;
831}
832
833/// UsualUnaryConversions - Performs various conversions that are common to most
834/// operators (C99 6.3). The conversions of array and function types are
835/// sometimes suppressed. For example, the array->pointer conversion doesn't
836/// apply if the array is an argument to the sizeof or address (&) operators.
837/// In these instances, this routine should *not* be called.
839 // First, convert to an r-value.
841 if (Res.isInvalid())
842 return ExprError();
843
844 // Promote floating-point types.
845 Res = UsualUnaryFPConversions(Res.get());
846 if (Res.isInvalid())
847 return ExprError();
848 E = Res.get();
849
850 QualType Ty = E->getType();
851 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
852
853 // Try to perform integral promotions if the object has a theoretically
854 // promotable type.
856 // C99 6.3.1.1p2:
857 //
858 // The following may be used in an expression wherever an int or
859 // unsigned int may be used:
860 // - an object or expression with an integer type whose integer
861 // conversion rank is less than or equal to the rank of int
862 // and unsigned int.
863 // - A bit-field of type _Bool, int, signed int, or unsigned int.
864 //
865 // If an int can represent all values of the original type, the
866 // value is converted to an int; otherwise, it is converted to an
867 // unsigned int. These are called the integer promotions. All
868 // other types are unchanged by the integer promotions.
869
870 QualType PTy = Context.isPromotableBitField(E);
871 if (!PTy.isNull()) {
872 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
873 return E;
874 }
875 if (Context.isPromotableIntegerType(Ty)) {
876 QualType PT = Context.getPromotedIntegerType(Ty);
877 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
878 return E;
879 }
880 }
881 return E;
882}
883
884/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
885/// do not have a prototype. Arguments that have type float or __fp16
886/// are promoted to double. All other argument types are converted by
887/// UsualUnaryConversions().
889 QualType Ty = E->getType();
890 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
891
893 if (Res.isInvalid())
894 return ExprError();
895 E = Res.get();
896
897 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
898 // promote to double.
899 // Note that default argument promotion applies only to float (and
900 // half/fp16); it does not apply to _Float16.
901 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
902 if (BTy && (BTy->getKind() == BuiltinType::Half ||
903 BTy->getKind() == BuiltinType::Float)) {
904 if (getLangOpts().OpenCL &&
905 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
906 if (BTy->getKind() == BuiltinType::Half) {
907 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
908 }
909 } else {
910 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
911 }
912 }
913 if (BTy &&
914 getLangOpts().getExtendIntArgs() ==
916 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
917 Context.getTypeSizeInChars(BTy) <
918 Context.getTypeSizeInChars(Context.LongLongTy)) {
919 E = (Ty->isUnsignedIntegerType())
920 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
921 .get()
922 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
923 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
924 "Unexpected typesize for LongLongTy");
925 }
926
927 // C++ performs lvalue-to-rvalue conversion as a default argument
928 // promotion, even on class types, but note:
929 // C++11 [conv.lval]p2:
930 // When an lvalue-to-rvalue conversion occurs in an unevaluated
931 // operand or a subexpression thereof the value contained in the
932 // referenced object is not accessed. Otherwise, if the glvalue
933 // has a class type, the conversion copy-initializes a temporary
934 // of type T from the glvalue and the result of the conversion
935 // is a prvalue for the temporary.
936 // FIXME: add some way to gate this entire thing for correctness in
937 // potentially potentially evaluated contexts.
941 E->getExprLoc(), E);
942 if (Temp.isInvalid())
943 return ExprError();
944 E = Temp.get();
945 }
946
947 // C++ [expr.call]p7, per CWG722:
948 // An argument that has (possibly cv-qualified) type std::nullptr_t is
949 // converted to void* ([conv.ptr]).
950 // (This does not apply to C23 nullptr)
952 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
953
954 return E;
955}
956
958 if (Ty->isIncompleteType()) {
959 // C++11 [expr.call]p7:
960 // After these conversions, if the argument does not have arithmetic,
961 // enumeration, pointer, pointer to member, or class type, the program
962 // is ill-formed.
963 //
964 // Since we've already performed null pointer conversion, array-to-pointer
965 // decay and function-to-pointer decay, the only such type in C++ is cv
966 // void. This also handles initializer lists as variadic arguments.
967 if (Ty->isVoidType())
968 return VarArgKind::Invalid;
969
970 if (Ty->isObjCObjectType())
971 return VarArgKind::Invalid;
972 return VarArgKind::Valid;
973 }
974
976 return VarArgKind::Invalid;
977
978 if (Context.getTargetInfo().getTriple().isWasm() &&
980 return VarArgKind::Invalid;
981 }
982
983 if (Ty.isCXX98PODType(Context))
984 return VarArgKind::Valid;
985
986 // C++11 [expr.call]p7:
987 // Passing a potentially-evaluated argument of class type (Clause 9)
988 // having a non-trivial copy constructor, a non-trivial move constructor,
989 // or a non-trivial destructor, with no corresponding parameter,
990 // is conditionally-supported with implementation-defined semantics.
993 if (!Record->hasNonTrivialCopyConstructor() &&
994 !Record->hasNonTrivialMoveConstructor() &&
995 !Record->hasNonTrivialDestructor())
997
998 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
999 return VarArgKind::Valid;
1000
1001 if (Ty->isObjCObjectType())
1002 return VarArgKind::Invalid;
1003
1004 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1005 return VarArgKind::Valid;
1006
1007 if (getLangOpts().MSVCCompat)
1009
1010 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1011 return VarArgKind::Valid;
1012
1013 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1014 // permitted to reject them. We should consider doing so.
1015 return VarArgKind::Undefined;
1016}
1017
1019 // Don't allow one to pass an Objective-C interface to a vararg.
1020 const QualType &Ty = E->getType();
1021 VarArgKind VAK = isValidVarArgType(Ty);
1022
1023 // Complain about passing non-POD types through varargs.
1024 switch (VAK) {
1027 E->getBeginLoc(), nullptr,
1028 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1029 [[fallthrough]];
1030 case VarArgKind::Valid:
1031 if (Ty->isRecordType()) {
1032 // This is unlikely to be what the user intended. If the class has a
1033 // 'c_str' member function, the user probably meant to call that.
1034 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1035 PDiag(diag::warn_pass_class_arg_to_vararg)
1036 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1037 }
1038 break;
1039
1042 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1043 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1044 << getLangOpts().CPlusPlus11 << Ty << CT);
1045 break;
1046
1049 Diag(E->getBeginLoc(),
1050 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1051 << Ty << CT;
1052 else if (Ty->isObjCObjectType())
1053 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1054 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1055 << Ty << CT);
1056 else
1057 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1058 << isa<InitListExpr>(E) << Ty << CT;
1059 break;
1060 }
1061}
1062
1064 FunctionDecl *FDecl) {
1065 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1066 // Strip the unbridged-cast placeholder expression off, if applicable.
1067 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1068 (CT == VariadicCallType::Method ||
1069 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1070 E = ObjC().stripARCUnbridgedCast(E);
1071
1072 // Otherwise, do normal placeholder checking.
1073 } else {
1074 ExprResult ExprRes = CheckPlaceholderExpr(E);
1075 if (ExprRes.isInvalid())
1076 return ExprError();
1077 E = ExprRes.get();
1078 }
1079 }
1080
1082 if (ExprRes.isInvalid())
1083 return ExprError();
1084
1085 // Copy blocks to the heap.
1086 if (ExprRes.get()->getType()->isBlockPointerType())
1087 maybeExtendBlockObject(ExprRes);
1088
1089 E = ExprRes.get();
1090
1091 // Diagnostics regarding non-POD argument types are
1092 // emitted along with format string checking in Sema::CheckFunctionCall().
1094 // Turn this into a trap.
1095 CXXScopeSpec SS;
1096 SourceLocation TemplateKWLoc;
1097 UnqualifiedId Name;
1098 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1099 E->getBeginLoc());
1100 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1101 /*HasTrailingLParen=*/true,
1102 /*IsAddressOfOperand=*/false);
1103 if (TrapFn.isInvalid())
1104 return ExprError();
1105
1106 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1107 E->getEndLoc());
1108 if (Call.isInvalid())
1109 return ExprError();
1110
1111 ExprResult Comma =
1112 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1113 if (Comma.isInvalid())
1114 return ExprError();
1115 return Comma.get();
1116 }
1117
1118 if (!getLangOpts().CPlusPlus &&
1120 diag::err_call_incomplete_argument))
1121 return ExprError();
1122
1123 return E;
1124}
1125
1126/// Convert complex integers to complex floats and real integers to
1127/// real floats as required for complex arithmetic. Helper function of
1128/// UsualArithmeticConversions()
1129///
1130/// \return false if the integer expression is an integer type and is
1131/// successfully converted to the (complex) float type.
1133 ExprResult &ComplexExpr,
1134 QualType IntTy,
1135 QualType ComplexTy,
1136 bool SkipCast) {
1137 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1138 if (SkipCast) return false;
1139 if (IntTy->isIntegerType()) {
1140 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1141 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1142 } else {
1143 assert(IntTy->isComplexIntegerType());
1144 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1145 CK_IntegralComplexToFloatingComplex);
1146 }
1147 return false;
1148}
1149
1150// This handles complex/complex, complex/float, or float/complex.
1151// When both operands are complex, the shorter operand is converted to the
1152// type of the longer, and that is the type of the result. This corresponds
1153// to what is done when combining two real floating-point operands.
1154// The fun begins when size promotion occur across type domains.
1155// From H&S 6.3.4: When one operand is complex and the other is a real
1156// floating-point type, the less precise type is converted, within it's
1157// real or complex domain, to the precision of the other type. For example,
1158// when combining a "long double" with a "double _Complex", the
1159// "double _Complex" is promoted to "long double _Complex".
1161 QualType ShorterType,
1162 QualType LongerType,
1163 bool PromotePrecision) {
1164 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1165 QualType Result =
1166 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1167
1168 if (PromotePrecision) {
1169 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1170 Shorter =
1171 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1172 } else {
1173 if (LongerIsComplex)
1174 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1175 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1176 }
1177 }
1178 return Result;
1179}
1180
1181/// Handle arithmetic conversion with complex types. Helper function of
1182/// UsualArithmeticConversions()
1184 ExprResult &RHS, QualType LHSType,
1185 QualType RHSType, bool IsCompAssign) {
1186 // Handle (complex) integer types.
1187 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1188 /*SkipCast=*/false))
1189 return LHSType;
1190 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1191 /*SkipCast=*/IsCompAssign))
1192 return RHSType;
1193
1194 // Compute the rank of the two types, regardless of whether they are complex.
1195 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1196 if (Order < 0)
1197 // Promote the precision of the LHS if not an assignment.
1198 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1199 /*PromotePrecision=*/!IsCompAssign);
1200 // Promote the precision of the RHS unless it is already the same as the LHS.
1201 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1202 /*PromotePrecision=*/Order > 0);
1203}
1204
1205/// Handle arithmetic conversion from integer to float. Helper function
1206/// of UsualArithmeticConversions()
1208 ExprResult &IntExpr,
1209 QualType FloatTy, QualType IntTy,
1210 bool ConvertFloat, bool ConvertInt) {
1211 if (IntTy->isIntegerType()) {
1212 if (ConvertInt)
1213 // Convert intExpr to the lhs floating point type.
1214 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1215 CK_IntegralToFloating);
1216 return FloatTy;
1217 }
1218
1219 // Convert both sides to the appropriate complex float.
1220 assert(IntTy->isComplexIntegerType());
1221 QualType result = S.Context.getComplexType(FloatTy);
1222
1223 // _Complex int -> _Complex float
1224 if (ConvertInt)
1225 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1226 CK_IntegralComplexToFloatingComplex);
1227
1228 // float -> _Complex float
1229 if (ConvertFloat)
1230 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1231 CK_FloatingRealToComplex);
1232
1233 return result;
1234}
1235
1236/// Handle arithmethic conversion with floating point types. Helper
1237/// function of UsualArithmeticConversions()
1239 ExprResult &RHS, QualType LHSType,
1240 QualType RHSType, bool IsCompAssign) {
1241 bool LHSFloat = LHSType->isRealFloatingType();
1242 bool RHSFloat = RHSType->isRealFloatingType();
1243
1244 // N1169 4.1.4: If one of the operands has a floating type and the other
1245 // operand has a fixed-point type, the fixed-point operand
1246 // is converted to the floating type [...]
1247 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1248 if (LHSFloat)
1249 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1250 else if (!IsCompAssign)
1251 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1252 return LHSFloat ? LHSType : RHSType;
1253 }
1254
1255 // If we have two real floating types, convert the smaller operand
1256 // to the bigger result.
1257 if (LHSFloat && RHSFloat) {
1258 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1259 if (order > 0) {
1260 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1261 return LHSType;
1262 }
1263
1264 assert(order < 0 && "illegal float comparison");
1265 if (!IsCompAssign)
1266 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1267 return RHSType;
1268 }
1269
1270 if (LHSFloat) {
1271 // Half FP has to be promoted to float unless it is natively supported
1272 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1273 LHSType = S.Context.FloatTy;
1274
1275 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1276 /*ConvertFloat=*/!IsCompAssign,
1277 /*ConvertInt=*/ true);
1278 }
1279 assert(RHSFloat);
1280 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1281 /*ConvertFloat=*/ true,
1282 /*ConvertInt=*/!IsCompAssign);
1283}
1284
1285/// Diagnose attempts to convert between __float128, __ibm128 and
1286/// long double if there is no support for such conversion.
1287/// Helper function of UsualArithmeticConversions().
1288static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1289 QualType RHSType) {
1290 // No issue if either is not a floating point type.
1291 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1292 return false;
1293
1294 // No issue if both have the same 128-bit float semantics.
1295 auto *LHSComplex = LHSType->getAs<ComplexType>();
1296 auto *RHSComplex = RHSType->getAs<ComplexType>();
1297
1298 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1299 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1300
1301 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1302 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1303
1304 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1305 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1306 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1307 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1308 return false;
1309
1310 return true;
1311}
1312
1313typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1314
1315namespace {
1316/// These helper callbacks are placed in an anonymous namespace to
1317/// permit their use as function template parameters.
1318ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1320}
1321
1322ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1323 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1324 CK_IntegralComplexCast);
1325}
1326}
1327
1328/// Handle integer arithmetic conversions. Helper function of
1329/// UsualArithmeticConversions()
1330template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1332 ExprResult &RHS, QualType LHSType,
1333 QualType RHSType, bool IsCompAssign) {
1334 // The rules for this case are in C99 6.3.1.8
1335 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1336 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1337 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1338 if (LHSSigned == RHSSigned) {
1339 // Same signedness; use the higher-ranked type
1340 if (order >= 0) {
1341 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1342 return LHSType;
1343 } else if (!IsCompAssign)
1344 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1345 return RHSType;
1346 } else if (order != (LHSSigned ? 1 : -1)) {
1347 // The unsigned type has greater than or equal rank to the
1348 // signed type, so use the unsigned type
1349 if (RHSSigned) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1356 // The two types are different widths; if we are here, that
1357 // means the signed type is larger than the unsigned type, so
1358 // use the signed type.
1359 if (LHSSigned) {
1360 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1361 return LHSType;
1362 } else if (!IsCompAssign)
1363 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1364 return RHSType;
1365 } else {
1366 // The signed type is higher-ranked than the unsigned type,
1367 // but isn't actually any bigger (like unsigned int and long
1368 // on most 32-bit systems). Use the unsigned type corresponding
1369 // to the signed type.
1370 QualType result =
1371 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1372 RHS = (*doRHSCast)(S, RHS.get(), result);
1373 if (!IsCompAssign)
1374 LHS = (*doLHSCast)(S, LHS.get(), result);
1375 return result;
1376 }
1377}
1378
1379/// Handle conversions with GCC complex int extension. Helper function
1380/// of UsualArithmeticConversions()
1382 ExprResult &RHS, QualType LHSType,
1383 QualType RHSType,
1384 bool IsCompAssign) {
1385 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1386 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1387
1388 if (LHSComplexInt && RHSComplexInt) {
1389 QualType LHSEltType = LHSComplexInt->getElementType();
1390 QualType RHSEltType = RHSComplexInt->getElementType();
1391 QualType ScalarType =
1393 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1394
1395 return S.Context.getComplexType(ScalarType);
1396 }
1397
1398 if (LHSComplexInt) {
1399 QualType LHSEltType = LHSComplexInt->getElementType();
1400 QualType ScalarType =
1402 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1404 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1405 CK_IntegralRealToComplex);
1406
1407 return ComplexType;
1408 }
1409
1410 assert(RHSComplexInt);
1411
1412 QualType RHSEltType = RHSComplexInt->getElementType();
1413 QualType ScalarType =
1415 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1417
1418 if (!IsCompAssign)
1419 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1420 CK_IntegralRealToComplex);
1421 return ComplexType;
1422}
1423
1425 ExprResult &RHS,
1426 QualType LHSType,
1427 QualType RHSType,
1428 bool IsCompAssign) {
1429
1430 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1431 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1432
1433 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1434 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1435
1436 bool LHSHasTrap =
1437 LhsOBT && LhsOBT->getBehaviorKind() ==
1438 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1439 bool RHSHasTrap =
1440 RhsOBT && RhsOBT->getBehaviorKind() ==
1441 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1442 bool LHSHasWrap =
1443 LhsOBT && LhsOBT->getBehaviorKind() ==
1444 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1445 bool RHSHasWrap =
1446 RhsOBT && RhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1448
1449 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1450 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1451
1452 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1453 if (LHSHasTrap || RHSHasTrap)
1454 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1455 else if (LHSHasWrap || RHSHasWrap)
1456 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSConvType = LHSUnderlyingType;
1459 QualType RHSConvType = RHSUnderlyingType;
1460 if (DominantBehavior) {
1461 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1462 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1463 LHSUnderlyingType);
1464 else
1465 LHSConvType = LHSType;
1466
1467 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1468 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1469 RHSUnderlyingType);
1470 else
1471 RHSConvType = RHSType;
1472 }
1473
1475 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1476}
1477
1478/// Return the rank of a given fixed point or integer type. The value itself
1479/// doesn't matter, but the values must be increasing with proper increasing
1480/// rank as described in N1169 4.1.1.
1481static unsigned GetFixedPointRank(QualType Ty) {
1482 const auto *BTy = Ty->getAs<BuiltinType>();
1483 assert(BTy && "Expected a builtin type.");
1484
1485 switch (BTy->getKind()) {
1486 case BuiltinType::ShortFract:
1487 case BuiltinType::UShortFract:
1488 case BuiltinType::SatShortFract:
1489 case BuiltinType::SatUShortFract:
1490 return 1;
1491 case BuiltinType::Fract:
1492 case BuiltinType::UFract:
1493 case BuiltinType::SatFract:
1494 case BuiltinType::SatUFract:
1495 return 2;
1496 case BuiltinType::LongFract:
1497 case BuiltinType::ULongFract:
1498 case BuiltinType::SatLongFract:
1499 case BuiltinType::SatULongFract:
1500 return 3;
1501 case BuiltinType::ShortAccum:
1502 case BuiltinType::UShortAccum:
1503 case BuiltinType::SatShortAccum:
1504 case BuiltinType::SatUShortAccum:
1505 return 4;
1506 case BuiltinType::Accum:
1507 case BuiltinType::UAccum:
1508 case BuiltinType::SatAccum:
1509 case BuiltinType::SatUAccum:
1510 return 5;
1511 case BuiltinType::LongAccum:
1512 case BuiltinType::ULongAccum:
1513 case BuiltinType::SatLongAccum:
1514 case BuiltinType::SatULongAccum:
1515 return 6;
1516 default:
1517 if (BTy->isInteger())
1518 return 0;
1519 llvm_unreachable("Unexpected fixed point or integer type");
1520 }
1521}
1522
1523/// handleFixedPointConversion - Fixed point operations between fixed
1524/// point types and integers or other fixed point types do not fall under
1525/// usual arithmetic conversion since these conversions could result in loss
1526/// of precsision (N1169 4.1.4). These operations should be calculated with
1527/// the full precision of their result type (N1169 4.1.6.2.1).
1529 QualType RHSTy) {
1530 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1531 "Expected at least one of the operands to be a fixed point type");
1532 assert((LHSTy->isFixedPointOrIntegerType() ||
1533 RHSTy->isFixedPointOrIntegerType()) &&
1534 "Special fixed point arithmetic operation conversions are only "
1535 "applied to ints or other fixed point types");
1536
1537 // If one operand has signed fixed-point type and the other operand has
1538 // unsigned fixed-point type, then the unsigned fixed-point operand is
1539 // converted to its corresponding signed fixed-point type and the resulting
1540 // type is the type of the converted operand.
1541 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1543 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1545
1546 // The result type is the type with the highest rank, whereby a fixed-point
1547 // conversion rank is always greater than an integer conversion rank; if the
1548 // type of either of the operands is a saturating fixedpoint type, the result
1549 // type shall be the saturating fixed-point type corresponding to the type
1550 // with the highest rank; the resulting value is converted (taking into
1551 // account rounding and overflow) to the precision of the resulting type.
1552 // Same ranks between signed and unsigned types are resolved earlier, so both
1553 // types are either signed or both unsigned at this point.
1554 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1555 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1556
1557 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1558
1560 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1561
1562 return ResultTy;
1563}
1564
1565/// Check that the usual arithmetic conversions can be performed on this pair of
1566/// expressions that might be of enumeration type.
1568 SourceLocation Loc,
1569 ArithConvKind ACK) {
1570 // C++2a [expr.arith.conv]p1:
1571 // If one operand is of enumeration type and the other operand is of a
1572 // different enumeration type or a floating-point type, this behavior is
1573 // deprecated ([depr.arith.conv.enum]).
1574 //
1575 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1576 // Eventually we will presumably reject these cases (in C++23 onwards?).
1578 R = RHS->getEnumCoercedType(Context);
1579 bool LEnum = L->isUnscopedEnumerationType(),
1580 REnum = R->isUnscopedEnumerationType();
1581 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1582 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1583 (REnum && L->isFloatingType())) {
1584 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1586 ? diag::warn_arith_conv_enum_float_cxx20
1587 : diag::warn_arith_conv_enum_float)
1588 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1589 << L << R;
1590 } else if (!IsCompAssign && LEnum && REnum &&
1591 !Context.hasSameUnqualifiedType(L, R)) {
1592 unsigned DiagID;
1593 // In C++ 26, usual arithmetic conversions between 2 different enum types
1594 // are ill-formed.
1596 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1597 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1598 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1599 // If either enumeration type is unnamed, it's less likely that the
1600 // user cares about this, but this situation is still deprecated in
1601 // C++2a. Use a different warning group.
1602 DiagID = getLangOpts().CPlusPlus20
1603 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1604 : diag::warn_arith_conv_mixed_anon_enum_types;
1605 } else if (ACK == ArithConvKind::Conditional) {
1606 // Conditional expressions are separated out because they have
1607 // historically had a different warning flag.
1608 DiagID = getLangOpts().CPlusPlus20
1609 ? diag::warn_conditional_mixed_enum_types_cxx20
1610 : diag::warn_conditional_mixed_enum_types;
1611 } else if (ACK == ArithConvKind::Comparison) {
1612 // Comparison expressions are separated out because they have
1613 // historically had a different warning flag.
1614 DiagID = getLangOpts().CPlusPlus20
1615 ? diag::warn_comparison_mixed_enum_types_cxx20
1616 : diag::warn_comparison_mixed_enum_types;
1617 } else {
1618 DiagID = getLangOpts().CPlusPlus20
1619 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1620 : diag::warn_arith_conv_mixed_enum_types;
1621 }
1622 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1623 << (int)ACK << L << R;
1624 }
1625}
1626
1628 Expr *RHS, SourceLocation Loc,
1629 ArithConvKind ACK) {
1630 QualType LHSType = LHS->getType().getUnqualifiedType();
1631 QualType RHSType = RHS->getType().getUnqualifiedType();
1632
1633 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1634 !RHSType->isUnicodeCharacterType())
1635 return;
1636
1637 if (ACK == ArithConvKind::Comparison) {
1638 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1639 return;
1640
1641 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1642 if (T->isChar8Type())
1643 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1644 if (T->isChar16Type())
1645 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1646 assert(T->isChar32Type());
1647 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1648 };
1649
1650 Expr::EvalResult LHSRes, RHSRes;
1651 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1653 SemaRef.isConstantEvaluatedContext());
1654 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1656 SemaRef.isConstantEvaluatedContext());
1657
1658 // Don't warn if the one known value is a representable
1659 // in the type of both expressions.
1660 if (LHSSuccess != RHSuccess) {
1661 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1662 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1663 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1664 return;
1665 }
1666
1667 if (!LHSSuccess || !RHSuccess) {
1668 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1669 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1670 << RHSType;
1671 return;
1672 }
1673
1674 llvm::APSInt LHSValue(32);
1675 LHSValue = LHSRes.Val.getInt();
1676 llvm::APSInt RHSValue(32);
1677 RHSValue = RHSRes.Val.getInt();
1678
1679 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1680 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1681 if (LHSSafe && RHSSafe)
1682 return;
1683
1684 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1685 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1686 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1687 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1688 return;
1689 }
1690
1691 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1692 return;
1693
1694 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1695 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1696 << RHSType;
1697}
1698
1699/// UsualArithmeticConversions - Performs various conversions that are common to
1700/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1701/// routine returns the first non-arithmetic type found. The client is
1702/// responsible for emitting appropriate error diagnostics.
1704 SourceLocation Loc,
1705 ArithConvKind ACK) {
1706
1707 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1708
1709 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1710
1711 if (ACK != ArithConvKind::CompAssign) {
1712 LHS = UsualUnaryConversions(LHS.get());
1713 if (LHS.isInvalid())
1714 return QualType();
1715 }
1716
1717 RHS = UsualUnaryConversions(RHS.get());
1718 if (RHS.isInvalid())
1719 return QualType();
1720
1721 // For conversion purposes, we ignore any qualifiers.
1722 // For example, "const float" and "float" are equivalent.
1723 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1724 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1725
1726 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1727 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1728 LHSType = AtomicLHS->getValueType();
1729
1730 // If both types are identical, no conversion is needed.
1731 if (Context.hasSameType(LHSType, RHSType))
1732 return Context.getCommonSugaredType(LHSType, RHSType);
1733
1734 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1735 // The caller can deal with this (e.g. pointer + int).
1736 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1737 return QualType();
1738
1739 // Apply unary and bitfield promotions to the LHS's type.
1740 QualType LHSUnpromotedType = LHSType;
1741 if (Context.isPromotableIntegerType(LHSType))
1742 LHSType = Context.getPromotedIntegerType(LHSType);
1743 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1744 if (!LHSBitfieldPromoteTy.isNull())
1745 LHSType = LHSBitfieldPromoteTy;
1746 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1747 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1748
1749 // If both types are identical, no conversion is needed.
1750 if (Context.hasSameType(LHSType, RHSType))
1751 return Context.getCommonSugaredType(LHSType, RHSType);
1752
1753 // At this point, we have two different arithmetic types.
1754
1755 // Diagnose attempts to convert between __ibm128, __float128 and long double
1756 // where such conversions currently can't be handled.
1757 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1758 return QualType();
1759
1760 // Handle complex types first (C99 6.3.1.8p1).
1761 if (LHSType->isComplexType() || RHSType->isComplexType())
1762 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1764
1765 // Now handle "real" floating types (i.e. float, double, long double).
1766 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1767 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1769
1770 // Handle GCC complex int extension.
1771 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1772 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1774
1775 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1776 return handleFixedPointConversion(*this, LHSType, RHSType);
1777
1778 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1780 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1781
1782 // Finally, we have two differing integer types.
1784 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1785}
1786
1787//===----------------------------------------------------------------------===//
1788// Semantic Analysis for various Expression Types
1789//===----------------------------------------------------------------------===//
1790
1791
1793 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1794 bool PredicateIsExpr, void *ControllingExprOrType,
1795 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1796 unsigned NumAssocs = ArgTypes.size();
1797 assert(NumAssocs == ArgExprs.size());
1798
1799 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1800 for (unsigned i = 0; i < NumAssocs; ++i) {
1801 if (ArgTypes[i])
1802 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1803 else
1804 Types[i] = nullptr;
1805 }
1806
1807 // If we have a controlling type, we need to convert it from a parsed type
1808 // into a semantic type and then pass that along.
1809 if (!PredicateIsExpr) {
1810 TypeSourceInfo *ControllingType;
1811 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1812 &ControllingType);
1813 assert(ControllingType && "couldn't get the type out of the parser");
1814 ControllingExprOrType = ControllingType;
1815 }
1816
1818 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1819 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1820 delete [] Types;
1821 return ER;
1822}
1823
1824// Helper function to determine type compatibility for C _Generic expressions.
1825// Multiple compatible types within the same _Generic expression is ambiguous
1826// and not valid.
1828 QualType U) {
1829 // Try to handle special types like OverflowBehaviorTypes
1830 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1831 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1832
1833 if (TOBT || UOBT) {
1834 if (TOBT && UOBT) {
1835 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1836 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1837 UOBT->getUnderlyingType());
1838 return false;
1839 }
1840 return false;
1841 }
1842
1843 // We're dealing with types that don't require special handling.
1844 return Ctx.typesAreCompatible(T, U);
1845}
1846
1848 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1849 bool PredicateIsExpr, void *ControllingExprOrType,
1851 unsigned NumAssocs = Types.size();
1852 assert(NumAssocs == Exprs.size());
1853 assert(ControllingExprOrType &&
1854 "Must have either a controlling expression or a controlling type");
1855
1856 Expr *ControllingExpr = nullptr;
1857 TypeSourceInfo *ControllingType = nullptr;
1858 if (PredicateIsExpr) {
1859 // Decay and strip qualifiers for the controlling expression type, and
1860 // handle placeholder type replacement. See committee discussion from WG14
1861 // DR423.
1865 reinterpret_cast<Expr *>(ControllingExprOrType));
1866 if (R.isInvalid())
1867 return ExprError();
1868 ControllingExpr = R.get();
1869 } else {
1870 // The extension form uses the type directly rather than converting it.
1871 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1872 if (!ControllingType)
1873 return ExprError();
1874 }
1875
1876 bool TypeErrorFound = false,
1877 IsResultDependent = ControllingExpr
1878 ? ControllingExpr->isTypeDependent()
1879 : ControllingType->getType()->isDependentType(),
1880 ContainsUnexpandedParameterPack =
1881 ControllingExpr
1882 ? ControllingExpr->containsUnexpandedParameterPack()
1883 : ControllingType->getType()->containsUnexpandedParameterPack();
1884
1885 // The controlling expression is an unevaluated operand, so side effects are
1886 // likely unintended.
1887 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1888 ControllingExpr->HasSideEffects(Context, false))
1889 Diag(ControllingExpr->getExprLoc(),
1890 diag::warn_side_effects_unevaluated_context);
1891
1892 for (unsigned i = 0; i < NumAssocs; ++i) {
1893 if (Exprs[i]->containsUnexpandedParameterPack())
1894 ContainsUnexpandedParameterPack = true;
1895
1896 if (Types[i]) {
1897 if (Types[i]->getType()->containsUnexpandedParameterPack())
1898 ContainsUnexpandedParameterPack = true;
1899
1900 if (Types[i]->getType()->isDependentType()) {
1901 IsResultDependent = true;
1902 } else {
1903 // We relax the restriction on use of incomplete types and non-object
1904 // types with the type-based extension of _Generic. Allowing incomplete
1905 // objects means those can be used as "tags" for a type-safe way to map
1906 // to a value. Similarly, matching on function types rather than
1907 // function pointer types can be useful. However, the restriction on VM
1908 // types makes sense to retain as there are open questions about how
1909 // the selection can be made at compile time.
1910 //
1911 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1912 // complete object type other than a variably modified type."
1913 // C2y removed the requirement that an expression form must
1914 // use a complete type, though it's still as-if the type has undergone
1915 // lvalue conversion. We support this as an extension in C23 and
1916 // earlier because GCC does so.
1917 unsigned D = 0;
1918 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1919 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1920 : diag::ext_assoc_type_incomplete;
1921 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1922 D = diag::err_assoc_type_nonobject;
1923 else if (Types[i]->getType()->isVariablyModifiedType())
1924 D = diag::err_assoc_type_variably_modified;
1925 else if (ControllingExpr) {
1926 // Because the controlling expression undergoes lvalue conversion,
1927 // array conversion, and function conversion, an association which is
1928 // of array type, function type, or is qualified can never be
1929 // reached. We will warn about this so users are less surprised by
1930 // the unreachable association. However, we don't have to handle
1931 // function types; that's not an object type, so it's handled above.
1932 //
1933 // The logic is somewhat different for C++ because C++ has different
1934 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1935 // If T is a non-class type, the type of the prvalue is the cv-
1936 // unqualified version of T. Otherwise, the type of the prvalue is T.
1937 // The result of these rules is that all qualified types in an
1938 // association in C are unreachable, and in C++, only qualified non-
1939 // class types are unreachable.
1940 //
1941 // NB: this does not apply when the first operand is a type rather
1942 // than an expression, because the type form does not undergo
1943 // conversion.
1944 unsigned Reason = 0;
1945 QualType QT = Types[i]->getType();
1946 if (QT->isArrayType())
1947 Reason = 1;
1948 else if (QT.hasQualifiers() &&
1949 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1950 Reason = 2;
1951
1952 if (Reason)
1953 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1954 diag::warn_unreachable_association)
1955 << QT << (Reason - 1);
1956 }
1957
1958 if (D != 0) {
1959 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1960 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1961 if (getDiagnostics().getDiagnosticLevel(
1962 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1964 TypeErrorFound = true;
1965 }
1966
1967 // C11 6.5.1.1p2 "No two generic associations in the same generic
1968 // selection shall specify compatible types."
1969 for (unsigned j = i+1; j < NumAssocs; ++j)
1970 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1972 Types[j]->getType())) {
1973 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1974 diag::err_assoc_compatible_types)
1975 << Types[j]->getTypeLoc().getSourceRange()
1976 << Types[j]->getType()
1977 << Types[i]->getType();
1978 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1979 diag::note_compat_assoc)
1980 << Types[i]->getTypeLoc().getSourceRange()
1981 << Types[i]->getType();
1982 TypeErrorFound = true;
1983 }
1984 }
1985 }
1986 }
1987 if (TypeErrorFound)
1988 return ExprError();
1989
1990 // If we determined that the generic selection is result-dependent, don't
1991 // try to compute the result expression.
1992 if (IsResultDependent) {
1993 if (ControllingExpr)
1994 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1995 Types, Exprs, DefaultLoc, RParenLoc,
1996 ContainsUnexpandedParameterPack);
1997 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1998 Exprs, DefaultLoc, RParenLoc,
1999 ContainsUnexpandedParameterPack);
2000 }
2001
2002 SmallVector<unsigned, 1> CompatIndices;
2003 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2004 // Look at the canonical type of the controlling expression in case it was a
2005 // deduced type like __auto_type. However, when issuing diagnostics, use the
2006 // type the user wrote in source rather than the canonical one.
2007 for (unsigned i = 0; i < NumAssocs; ++i) {
2008 if (!Types[i])
2009 DefaultIndex = i;
2010 else {
2011 bool Compatible;
2012 QualType ControllingQT =
2013 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2014 : ControllingType->getType().getCanonicalType();
2015 QualType AssocQT = Types[i]->getType();
2016
2017 Compatible =
2018 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2019
2020 if (Compatible)
2021 CompatIndices.push_back(i);
2022 }
2023 }
2024
2025 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2026 TypeSourceInfo *ControllingType) {
2027 // We strip parens here because the controlling expression is typically
2028 // parenthesized in macro definitions.
2029 if (ControllingExpr)
2030 ControllingExpr = ControllingExpr->IgnoreParens();
2031
2032 SourceRange SR = ControllingExpr
2033 ? ControllingExpr->getSourceRange()
2034 : ControllingType->getTypeLoc().getSourceRange();
2035 QualType QT = ControllingExpr ? ControllingExpr->getType()
2036 : ControllingType->getType();
2037
2038 return std::make_pair(SR, QT);
2039 };
2040
2041 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2042 // type compatible with at most one of the types named in its generic
2043 // association list."
2044 if (CompatIndices.size() > 1) {
2045 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2046 SourceRange SR = P.first;
2047 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2048 << SR << P.second << (unsigned)CompatIndices.size();
2049 for (unsigned I : CompatIndices) {
2050 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2051 diag::note_compat_assoc)
2052 << Types[I]->getTypeLoc().getSourceRange()
2053 << Types[I]->getType();
2054 }
2055 return ExprError();
2056 }
2057
2058 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2059 // its controlling expression shall have type compatible with exactly one of
2060 // the types named in its generic association list."
2061 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2062 CompatIndices.size() == 0) {
2063 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2064 SourceRange SR = P.first;
2065 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2066 return ExprError();
2067 }
2068
2069 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2070 // type name that is compatible with the type of the controlling expression,
2071 // then the result expression of the generic selection is the expression
2072 // in that generic association. Otherwise, the result expression of the
2073 // generic selection is the expression in the default generic association."
2074 unsigned ResultIndex =
2075 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2076
2077 if (ControllingExpr) {
2079 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2080 ContainsUnexpandedParameterPack, ResultIndex);
2081 }
2083 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2084 ContainsUnexpandedParameterPack, ResultIndex);
2085}
2086
2088 switch (Kind) {
2089 default:
2090 llvm_unreachable("unexpected TokenKind");
2091 case tok::kw___func__:
2092 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2093 case tok::kw___FUNCTION__:
2095 case tok::kw___FUNCDNAME__:
2096 return PredefinedIdentKind::FuncDName; // [MS]
2097 case tok::kw___FUNCSIG__:
2098 return PredefinedIdentKind::FuncSig; // [MS]
2099 case tok::kw_L__FUNCTION__:
2100 return PredefinedIdentKind::LFunction; // [MS]
2101 case tok::kw_L__FUNCSIG__:
2102 return PredefinedIdentKind::LFuncSig; // [MS]
2103 case tok::kw___PRETTY_FUNCTION__:
2105 }
2106}
2107
2108/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2109/// to determine the value of a PredefinedExpr. This can be either a
2110/// block, lambda, captured statement, function, otherwise a nullptr.
2113 DC = DC->getParent();
2114 return cast_or_null<Decl>(DC);
2115}
2116
2117/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2118/// location of the token and the offset of the ud-suffix within it.
2120 unsigned Offset) {
2121 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2122 S.getLangOpts());
2123}
2124
2125/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2126/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2128 IdentifierInfo *UDSuffix,
2129 SourceLocation UDSuffixLoc,
2130 ArrayRef<Expr*> Args,
2131 SourceLocation LitEndLoc) {
2132 assert(Args.size() <= 2 && "too many arguments for literal operator");
2133
2134 QualType ArgTy[2];
2135 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2136 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2137 if (ArgTy[ArgIdx]->isArrayType())
2138 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2139 }
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2147 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2148 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2149 /*AllowStringTemplatePack*/ false,
2150 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2151 return ExprError();
2152
2153 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2154}
2155
2157 // StringToks needs backing storage as it doesn't hold array elements itself
2158 std::vector<Token> ExpandedToks;
2159 if (getLangOpts().MicrosoftExt)
2160 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2161
2162 StringLiteralParser Literal(StringToks, PP,
2164 if (Literal.hadError)
2165 return ExprError();
2166
2167 SmallVector<SourceLocation, 4> StringTokLocs;
2168 for (const Token &Tok : StringToks)
2169 StringTokLocs.push_back(Tok.getLocation());
2170
2171 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2173 false, {}, StringTokLocs);
2174
2175 if (!Literal.getUDSuffix().empty()) {
2176 SourceLocation UDSuffixLoc =
2177 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2178 Literal.getUDSuffixOffset());
2179 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2180 }
2181
2182 return Lit;
2183}
2184
2185std::vector<Token>
2187 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2188 // local macros that expand to string literals that may be concatenated.
2189 // These macros are expanded here (in Sema), because StringLiteralParser
2190 // (in Lex) doesn't know the enclosing function (because it hasn't been
2191 // parsed yet).
2192 assert(getLangOpts().MicrosoftExt);
2193
2194 // Note: Although function local macros are defined only inside functions,
2195 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2196 // expansion of macros into empty string literals without additional checks.
2197 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2198 if (!CurrentDecl)
2199 CurrentDecl = Context.getTranslationUnitDecl();
2200
2201 std::vector<Token> ExpandedToks;
2202 ExpandedToks.reserve(Toks.size());
2203 for (const Token &Tok : Toks) {
2205 assert(tok::isStringLiteral(Tok.getKind()));
2206 ExpandedToks.emplace_back(Tok);
2207 continue;
2208 }
2209 if (isa<TranslationUnitDecl>(CurrentDecl))
2210 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2211 // Stringify predefined expression
2212 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2213 << Tok.getKind();
2214 SmallString<64> Str;
2215 llvm::raw_svector_ostream OS(Str);
2216 Token &Exp = ExpandedToks.emplace_back();
2217 Exp.startToken();
2218 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2219 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2220 OS << 'L';
2221 Exp.setKind(tok::wide_string_literal);
2222 } else {
2223 Exp.setKind(tok::string_literal);
2224 }
2225 OS << '"'
2227 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2228 << '"';
2229 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2230 }
2231 return ExpandedToks;
2232}
2233
2236 assert(!StringToks.empty() && "Must have at least one string!");
2237
2238 // StringToks needs backing storage as it doesn't hold array elements itself
2239 std::vector<Token> ExpandedToks;
2240 if (getLangOpts().MicrosoftExt)
2241 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2242
2243 StringLiteralParser Literal(StringToks, PP);
2244 if (Literal.hadError)
2245 return ExprError();
2246
2247 SmallVector<SourceLocation, 4> StringTokLocs;
2248 for (const Token &Tok : StringToks)
2249 StringTokLocs.push_back(Tok.getLocation());
2250
2251 QualType CharTy = Context.CharTy;
2253 if (Literal.isWide()) {
2254 CharTy = Context.getWideCharType();
2256 } else if (Literal.isUTF8()) {
2257 if (getLangOpts().Char8)
2258 CharTy = Context.Char8Ty;
2259 else if (getLangOpts().C23)
2260 CharTy = Context.UnsignedCharTy;
2262 } else if (Literal.isUTF16()) {
2263 CharTy = Context.Char16Ty;
2265 } else if (Literal.isUTF32()) {
2266 CharTy = Context.Char32Ty;
2268 } else if (Literal.isPascal()) {
2269 CharTy = Context.UnsignedCharTy;
2270 }
2271
2272 // Warn on u8 string literals before C++20 and C23, whose type
2273 // was an array of char before but becomes an array of char8_t.
2274 // In C++20, it cannot be used where a pointer to char is expected.
2275 // In C23, it might have an unexpected value if char was signed.
2276 if (Kind == StringLiteralKind::UTF8 &&
2278 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2279 : !getLangOpts().C23)) {
2280 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2281 ? diag::warn_cxx20_compat_utf8_string
2282 : diag::warn_c23_compat_utf8_string);
2283
2284 // Create removals for all 'u8' prefixes in the string literal(s). This
2285 // ensures C++20/C23 compatibility (but may change the program behavior when
2286 // built by non-Clang compilers for which the execution character set is
2287 // not always UTF-8).
2288 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2289 SourceLocation RemovalDiagLoc;
2290 for (const Token &Tok : StringToks) {
2291 if (Tok.getKind() == tok::utf8_string_literal) {
2292 if (RemovalDiagLoc.isInvalid())
2293 RemovalDiagLoc = Tok.getLocation();
2295 Tok.getLocation(),
2296 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2298 }
2299 }
2300 Diag(RemovalDiagLoc, RemovalDiag);
2301 }
2302
2303 QualType StrTy =
2304 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2305
2306 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2308 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2309 if (Literal.getUDSuffix().empty())
2310 return Lit;
2311
2312 // We're building a user-defined literal.
2313 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2314 SourceLocation UDSuffixLoc =
2315 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2316 Literal.getUDSuffixOffset());
2317
2318 // Make sure we're allowed user-defined literals here.
2319 if (!UDLScope)
2320 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2321
2322 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2323 // operator "" X (str, len)
2324 QualType SizeType = Context.getSizeType();
2325
2326 DeclarationName OpName =
2327 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2328 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2329 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2330
2331 QualType ArgTy[] = {
2332 Context.getArrayDecayedType(StrTy), SizeType
2333 };
2334
2335 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2336 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2337 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2338 /*AllowStringTemplatePack*/ true,
2339 /*DiagnoseMissing*/ true, Lit)) {
2340
2341 case LOLR_Cooked: {
2342 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2343 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2344 StringTokLocs[0]);
2345 Expr *Args[] = { Lit, LenArg };
2346
2347 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2348 }
2349
2350 case LOLR_Template: {
2351 TemplateArgumentListInfo ExplicitArgs;
2352 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2353 TemplateArgumentLocInfo ArgInfo(Lit);
2354 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2355 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2356 &ExplicitArgs);
2357 }
2358
2360 TemplateArgumentListInfo ExplicitArgs;
2361
2362 unsigned CharBits = Context.getIntWidth(CharTy);
2363 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2364 llvm::APSInt Value(CharBits, CharIsUnsigned);
2365
2366 TemplateArgument TypeArg(CharTy);
2367 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2368 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2369
2370 SourceLocation Loc = StringTokLocs.back();
2371 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2372 Value = Lit->getCodeUnit(I);
2373 TemplateArgument Arg(Context, Value, CharTy);
2375 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2376 }
2377 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2378 }
2379 case LOLR_Raw:
2381 llvm_unreachable("unexpected literal operator lookup result");
2382 case LOLR_Error:
2383 return ExprError();
2384 }
2385 llvm_unreachable("unexpected literal operator lookup result");
2386}
2387
2390 SourceLocation Loc,
2391 const CXXScopeSpec *SS) {
2392 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2393 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2394}
2395
2398 const DeclarationNameInfo &NameInfo,
2399 const CXXScopeSpec *SS, NamedDecl *FoundD,
2400 SourceLocation TemplateKWLoc,
2401 const TemplateArgumentListInfo *TemplateArgs) {
2404 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2405 TemplateArgs);
2406}
2407
2408// CUDA/HIP: Check whether a captured reference variable is referencing a
2409// host variable in a device or host device lambda.
2411 VarDecl *VD) {
2412 if (!S.getLangOpts().CUDA || !VD->hasInit())
2413 return false;
2414 assert(VD->getType()->isReferenceType());
2415
2416 // Check whether the reference variable is referencing a host variable.
2417 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2418 if (!DRE)
2419 return false;
2420 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2421 if (!Referee || !Referee->hasGlobalStorage() ||
2422 Referee->hasAttr<CUDADeviceAttr>())
2423 return false;
2424
2425 // Check whether the current function is a device or host device lambda.
2426 // Check whether the reference variable is a capture by getDeclContext()
2427 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2428 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2429 if (MD && MD->getParent()->isLambda() &&
2430 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2431 VD->getDeclContext() != MD)
2432 return true;
2433
2434 return false;
2435}
2436
2438 // A declaration named in an unevaluated operand never constitutes an odr-use.
2440 return NOUR_Unevaluated;
2441
2442 // C++2a [basic.def.odr]p4:
2443 // A variable x whose name appears as a potentially-evaluated expression e
2444 // is odr-used by e unless [...] x is a reference that is usable in
2445 // constant expressions.
2446 // CUDA/HIP:
2447 // If a reference variable referencing a host variable is captured in a
2448 // device or host device lambda, the value of the referee must be copied
2449 // to the capture and the reference variable must be treated as odr-use
2450 // since the value of the referee is not known at compile time and must
2451 // be loaded from the captured.
2452 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2453 if (VD->getType()->isReferenceType() &&
2454 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2456 VD->isUsableInConstantExpressions(Context))
2457 return NOUR_Constant;
2458 }
2459
2460 // All remaining non-variable cases constitute an odr-use. For variables, we
2461 // need to wait and see how the expression is used.
2462 return NOUR_None;
2463}
2464
2467 const DeclarationNameInfo &NameInfo,
2468 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2469 SourceLocation TemplateKWLoc,
2470 const TemplateArgumentListInfo *TemplateArgs) {
2471 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2472 NeedToCaptureVariable(D, NameInfo.getLoc());
2473
2475 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2476 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2478
2479 // C++ [except.spec]p17:
2480 // An exception-specification is considered to be needed when:
2481 // - in an expression, the function is the unique lookup result or
2482 // the selected member of a set of overloaded functions.
2483 //
2484 // We delay doing this until after we've built the function reference and
2485 // marked it as used so that:
2486 // a) if the function is defaulted, we get errors from defining it before /
2487 // instead of errors from computing its exception specification, and
2488 // b) if the function is a defaulted comparison, we can use the body we
2489 // build when defining it as input to the exception specification
2490 // computation rather than computing a new body.
2491 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2492 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2493 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2494 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2495 }
2496 }
2497
2498 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2500 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2502
2503 const auto *FD = dyn_cast<FieldDecl>(D);
2504 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2505 FD = IFD->getAnonField();
2506 if (FD) {
2507 UnusedPrivateFields.remove(FD);
2508 // Just in case we're building an illegal pointer-to-member.
2509 if (FD->isBitField())
2511 }
2512
2513 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2514 // designates a bit-field.
2515 if (const auto *BD = dyn_cast<BindingDecl>(D))
2516 if (const auto *BE = BD->getBinding())
2517 E->setObjectKind(BE->getObjectKind());
2518
2519 return E;
2520}
2521
2522void
2525 DeclarationNameInfo &NameInfo,
2526 const TemplateArgumentListInfo *&TemplateArgs) {
2528 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2529 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2530
2531 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2532 Id.TemplateId->NumArgs);
2533 translateTemplateArguments(TemplateArgsPtr, Buffer);
2534
2535 TemplateName TName = Id.TemplateId->Template.get();
2537 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2538 TemplateArgs = &Buffer;
2539 } else {
2540 NameInfo = GetNameFromUnqualifiedId(Id);
2541 TemplateArgs = nullptr;
2542 }
2543}
2544
2546 // During a default argument instantiation the CurContext points
2547 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2548 // function parameter list, hence add an explicit check.
2549 bool isDefaultArgument =
2550 !CodeSynthesisContexts.empty() &&
2551 CodeSynthesisContexts.back().Kind ==
2553 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2554 bool isInstance = CurMethod && CurMethod->isInstance() &&
2555 R.getNamingClass() == CurMethod->getParent() &&
2556 !isDefaultArgument;
2557
2558 // There are two ways we can find a class-scope declaration during template
2559 // instantiation that we did not find in the template definition: if it is a
2560 // member of a dependent base class, or if it is declared after the point of
2561 // use in the same class. Distinguish these by comparing the class in which
2562 // the member was found to the naming class of the lookup.
2563 unsigned DiagID = diag::err_found_in_dependent_base;
2564 unsigned NoteID = diag::note_member_declared_at;
2565 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2566 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2567 : diag::err_found_later_in_class;
2568 } else if (getLangOpts().MSVCCompat) {
2569 DiagID = diag::ext_found_in_dependent_base;
2570 NoteID = diag::note_dependent_member_use;
2571 }
2572
2573 if (isInstance) {
2574 // Give a code modification hint to insert 'this->'.
2575 Diag(R.getNameLoc(), DiagID)
2576 << R.getLookupName()
2577 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2578 CheckCXXThisCapture(R.getNameLoc());
2579 } else {
2580 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2581 // they're not shadowed).
2582 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2583 }
2584
2585 for (const NamedDecl *D : R)
2586 Diag(D->getLocation(), NoteID);
2587
2588 // Return true if we are inside a default argument instantiation
2589 // and the found name refers to an instance member function, otherwise
2590 // the caller will try to create an implicit member call and this is wrong
2591 // for default arguments.
2592 //
2593 // FIXME: Is this special case necessary? We could allow the caller to
2594 // diagnose this.
2595 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2596 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2597 return true;
2598 }
2599
2600 // Tell the callee to try to recover.
2601 return false;
2602}
2603
2606 TemplateArgumentListInfo *ExplicitTemplateArgs,
2607 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2608 DeclarationName Name = R.getLookupName();
2609 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2610
2611 unsigned diagnostic = diag::err_undeclared_var_use;
2612 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2616 diagnostic = diag::err_undeclared_use;
2617 diagnostic_suggest = diag::err_undeclared_use_suggest;
2618 }
2619
2620 // If the original lookup was an unqualified lookup, fake an
2621 // unqualified lookup. This is useful when (for example) the
2622 // original lookup would not have found something because it was a
2623 // dependent name.
2624 DeclContext *DC =
2625 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2626 while (DC) {
2627 if (isa<CXXRecordDecl>(DC)) {
2628 if (ExplicitTemplateArgs) {
2630 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2631 /*EnteringContext*/ false, TemplateNameIsRequired,
2632 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2633 return true;
2634 } else {
2635 LookupQualifiedName(R, DC);
2636 }
2637
2638 if (!R.empty()) {
2639 // Don't give errors about ambiguities in this lookup.
2640 R.suppressDiagnostics();
2641
2642 // If there's a best viable function among the results, only mention
2643 // that one in the notes.
2644 OverloadCandidateSet Candidates(R.getNameLoc(),
2646 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2648 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2649 OR_Success) {
2650 R.clear();
2651 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2652 R.resolveKind();
2653 }
2654
2656 }
2657
2658 R.clear();
2659 }
2660
2661 DC = DC->getLookupParent();
2662 }
2663
2664 // We didn't find anything, so try to correct for a typo.
2665 TypoCorrection Corrected;
2666 if (S && (Corrected =
2667 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2668 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2669 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2670 bool DroppedSpecifier =
2671 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2672 R.setLookupName(Corrected.getCorrection());
2673
2674 bool AcceptableWithRecovery = false;
2675 bool AcceptableWithoutRecovery = false;
2676 NamedDecl *ND = Corrected.getFoundDecl();
2677 if (ND) {
2678 if (Corrected.isOverloaded()) {
2679 OverloadCandidateSet OCS(R.getNameLoc(),
2682 for (NamedDecl *CD : Corrected) {
2683 if (FunctionTemplateDecl *FTD =
2684 dyn_cast<FunctionTemplateDecl>(CD))
2686 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2687 Args, OCS);
2688 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2689 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2691 Args, OCS);
2692 }
2693 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2694 case OR_Success:
2695 ND = Best->FoundDecl;
2696 Corrected.setCorrectionDecl(ND);
2697 break;
2698 default:
2699 // FIXME: Arbitrarily pick the first declaration for the note.
2700 Corrected.setCorrectionDecl(ND);
2701 break;
2702 }
2703 }
2704 R.addDecl(ND);
2705 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2708 if (!Record)
2711 R.setNamingClass(Record);
2712 }
2713
2714 auto *UnderlyingND = ND->getUnderlyingDecl();
2715 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2716 isa<FunctionTemplateDecl>(UnderlyingND);
2717 // FIXME: If we ended up with a typo for a type name or
2718 // Objective-C class name, we're in trouble because the parser
2719 // is in the wrong place to recover. Suggest the typo
2720 // correction, but don't make it a fix-it since we're not going
2721 // to recover well anyway.
2722 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2723 getAsTypeTemplateDecl(UnderlyingND) ||
2724 isa<ObjCInterfaceDecl>(UnderlyingND);
2725 } else {
2726 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2727 // because we aren't able to recover.
2728 AcceptableWithoutRecovery = true;
2729 }
2730
2731 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2732 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2733 ? diag::note_implicit_param_decl
2734 : diag::note_previous_decl;
2735 if (SS.isEmpty())
2736 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2737 PDiag(NoteID), AcceptableWithRecovery);
2738 else
2739 diagnoseTypo(Corrected,
2740 PDiag(diag::err_no_member_suggest)
2741 << Name << computeDeclContext(SS, false)
2742 << DroppedSpecifier << NameRange,
2743 PDiag(NoteID), AcceptableWithRecovery);
2744
2745 if (Corrected.WillReplaceSpecifier()) {
2747 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2748 SS.MakeTrivial(Context, NNS,
2749 NNS ? NameRange.getBegin() : SourceRange());
2750 }
2751
2752 // Tell the callee whether to try to recover.
2753 return !AcceptableWithRecovery;
2754 }
2755 }
2756 R.clear();
2757
2758 // Emit a special diagnostic for failed member lookups.
2759 // FIXME: computing the declaration context might fail here (?)
2760 if (!SS.isEmpty()) {
2761 Diag(R.getNameLoc(), diag::err_no_member)
2762 << Name << computeDeclContext(SS, false) << NameRange;
2763 return true;
2764 }
2765
2766 // Give up, we can't recover.
2767 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2768 return true;
2769}
2770
2771/// In Microsoft mode, if we are inside a template class whose parent class has
2772/// dependent base classes, and we can't resolve an unqualified identifier, then
2773/// assume the identifier is a member of a dependent base class. We can only
2774/// recover successfully in static methods, instance methods, and other contexts
2775/// where 'this' is available. This doesn't precisely match MSVC's
2776/// instantiation model, but it's close enough.
2777static Expr *
2779 DeclarationNameInfo &NameInfo,
2780 SourceLocation TemplateKWLoc,
2781 const TemplateArgumentListInfo *TemplateArgs) {
2782 // Only try to recover from lookup into dependent bases in static methods or
2783 // contexts where 'this' is available.
2784 QualType ThisType = S.getCurrentThisType();
2785 const CXXRecordDecl *RD = nullptr;
2786 if (!ThisType.isNull())
2787 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2788 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2789 RD = MD->getParent();
2790 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2791 return nullptr;
2792
2793 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2794 // is available, suggest inserting 'this->' as a fixit.
2795 SourceLocation Loc = NameInfo.getLoc();
2796 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2797 DB << NameInfo.getName() << RD;
2798
2799 if (!ThisType.isNull()) {
2800 DB << FixItHint::CreateInsertion(Loc, "this->");
2802 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2803 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2804 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2805 }
2806
2807 // Synthesize a fake NNS that points to the derived class. This will
2808 // perform name lookup during template instantiation.
2809 CXXScopeSpec SS;
2810 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2811 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2813 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2814 TemplateArgs);
2815}
2816
2819 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2820 bool HasTrailingLParen, bool IsAddressOfOperand,
2822 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2823 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2824 "cannot be direct & operand and have a trailing lparen");
2825 if (SS.isInvalid())
2826 return ExprError();
2827
2828 TemplateArgumentListInfo TemplateArgsBuffer;
2829
2830 // Decompose the UnqualifiedId into the following data.
2831 DeclarationNameInfo NameInfo;
2832 const TemplateArgumentListInfo *TemplateArgs;
2833 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2834
2835 DeclarationName Name = NameInfo.getName();
2837 SourceLocation NameLoc = NameInfo.getLoc();
2838
2839 if (II && II->isEditorPlaceholder()) {
2840 // FIXME: When typed placeholders are supported we can create a typed
2841 // placeholder expression node.
2842 return ExprError();
2843 }
2844
2845 // This specially handles arguments of attributes appertains to a type of C
2846 // struct field such that the name lookup within a struct finds the member
2847 // name, which is not the case for other contexts in C.
2848 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2849 // See if this is reference to a field of struct.
2850 LookupResult R(*this, NameInfo, LookupMemberName);
2851 // LookupName handles a name lookup from within anonymous struct.
2852 if (LookupName(R, S)) {
2853 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2854 QualType type = VD->getType().getNonReferenceType();
2855 // This will eventually be translated into MemberExpr upon
2856 // the use of instantiated struct fields.
2857 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2858 }
2859 }
2860 }
2861
2862 // Perform the required lookup.
2863 LookupResult R(*this, NameInfo,
2867 if (TemplateKWLoc.isValid() || TemplateArgs) {
2868 // Lookup the template name again to correctly establish the context in
2869 // which it was found. This is really unfortunate as we already did the
2870 // lookup to determine that it was a template name in the first place. If
2871 // this becomes a performance hit, we can work harder to preserve those
2872 // results until we get here but it's likely not worth it.
2873 AssumedTemplateKind AssumedTemplate;
2874 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2875 /*EnteringContext=*/false, TemplateKWLoc,
2876 &AssumedTemplate))
2877 return ExprError();
2878
2879 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2880 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2881 IsAddressOfOperand, TemplateArgs);
2882 } else {
2883 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2884 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2885 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2886
2887 // If the result might be in a dependent base class, this is a dependent
2888 // id-expression.
2889 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2890 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2891 IsAddressOfOperand, TemplateArgs);
2892
2893 // If this reference is in an Objective-C method, then we need to do
2894 // some special Objective-C lookup, too.
2895 if (IvarLookupFollowUp) {
2896 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2897 if (E.isInvalid())
2898 return ExprError();
2899
2900 if (Expr *Ex = E.getAs<Expr>())
2901 return Ex;
2902 }
2903 }
2904
2905 if (R.isAmbiguous())
2906 return ExprError();
2907
2908 // This could be an implicitly declared function reference if the language
2909 // mode allows it as a feature.
2910 if (R.empty() && HasTrailingLParen && II &&
2911 getLangOpts().implicitFunctionsAllowed()) {
2912 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2913 if (D) R.addDecl(D);
2914 }
2915
2916 // Determine whether this name might be a candidate for
2917 // argument-dependent lookup.
2918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2919
2920 if (R.empty() && !ADL) {
2921 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2922 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2923 TemplateKWLoc, TemplateArgs))
2924 return E;
2925 }
2926
2927 // Don't diagnose an empty lookup for inline assembly.
2928 if (IsInlineAsmIdentifier)
2929 return ExprError();
2930
2931 // If this name wasn't predeclared and if this is not a function
2932 // call, diagnose the problem.
2933 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2934 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2935 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2936 "Typo correction callback misconfigured");
2937 if (CCC) {
2938 // Make sure the callback knows what the typo being diagnosed is.
2939 CCC->setTypoName(II);
2940 if (SS.isValid())
2941 CCC->setTypoNNS(SS.getScopeRep());
2942 }
2943 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2944 // a template name, but we happen to have always already looked up the name
2945 // before we get here if it must be a template name.
2946 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2947 {}, nullptr))
2948 return ExprError();
2949
2950 assert(!R.empty() &&
2951 "DiagnoseEmptyLookup returned false but added no results");
2952
2953 // If we found an Objective-C instance variable, let
2954 // LookupInObjCMethod build the appropriate expression to
2955 // reference the ivar.
2956 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2957 R.clear();
2958 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2959 // In a hopelessly buggy code, Objective-C instance variable
2960 // lookup fails and no expression will be built to reference it.
2961 if (!E.isInvalid() && !E.get())
2962 return ExprError();
2963 return E;
2964 }
2965 }
2966
2967 // This is guaranteed from this point on.
2968 assert(!R.empty() || ADL);
2969
2970 // Check whether this might be a C++ implicit instance member access.
2971 // C++ [class.mfct.non-static]p3:
2972 // When an id-expression that is not part of a class member access
2973 // syntax and not used to form a pointer to member is used in the
2974 // body of a non-static member function of class X, if name lookup
2975 // resolves the name in the id-expression to a non-static non-type
2976 // member of some class C, the id-expression is transformed into a
2977 // class member access expression using (*this) as the
2978 // postfix-expression to the left of the . operator.
2979 //
2980 // But we don't actually need to do this for '&' operands if R
2981 // resolved to a function or overloaded function set, because the
2982 // expression is ill-formed if it actually works out to be a
2983 // non-static member function:
2984 //
2985 // C++ [expr.ref]p4:
2986 // Otherwise, if E1.E2 refers to a non-static member function. . .
2987 // [t]he expression can be used only as the left-hand operand of a
2988 // member function call.
2989 //
2990 // There are other safeguards against such uses, but it's important
2991 // to get this right here so that we don't end up making a
2992 // spuriously dependent expression if we're inside a dependent
2993 // instance method.
2994 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2995 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2996 S);
2997
2998 if (TemplateArgs || TemplateKWLoc.isValid()) {
2999
3000 // In C++1y, if this is a variable template id, then check it
3001 // in BuildTemplateIdExpr().
3002 // The single lookup result must be a variable template declaration.
3006 assert(R.getAsSingle<TemplateDecl>() &&
3007 "There should only be one declaration found.");
3008 }
3009
3010 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3011 }
3012
3013 return BuildDeclarationNameExpr(SS, R, ADL);
3014}
3015
3017 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3018 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3019 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3020 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3021
3022 if (R.isAmbiguous())
3023 return ExprError();
3024
3025 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3026 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3027 NameInfo, /*TemplateArgs=*/nullptr);
3028
3029 if (R.empty()) {
3030 // Don't diagnose problems with invalid record decl, the secondary no_member
3031 // diagnostic during template instantiation is likely bogus, e.g. if a class
3032 // is invalid because it's derived from an invalid base class, then missing
3033 // members were likely supposed to be inherited.
3035 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3036 if (CD->isInvalidDecl() || CD->isBeingDefined())
3037 return ExprError();
3038 Diag(NameInfo.getLoc(), diag::err_no_member)
3039 << NameInfo.getName() << DC << SS.getRange();
3040 return ExprError();
3041 }
3042
3043 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3044 QualType ET;
3045 TypeLocBuilder TLB;
3046 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3047 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3048 SS.getScopeRep(), TagD,
3049 /*OwnsTag=*/false);
3050 auto TL = TLB.push<TagTypeLoc>(ET);
3052 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3053 TL.setNameLoc(NameInfo.getLoc());
3054 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3055 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3056 SS.getScopeRep(), TypedefD);
3057 TLB.push<TypedefTypeLoc>(ET).set(
3058 /*ElaboratedKeywordLoc=*/SourceLocation(),
3059 SS.getWithLocInContext(Context), NameInfo.getLoc());
3060 } else {
3061 // FIXME: What else can appear here?
3062 ET = SemaRef.Context.getTypeDeclType(TD);
3063 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3064 assert(SS.isEmpty());
3065 }
3066
3067 // Diagnose a missing typename if this resolved unambiguously to a type in
3068 // a dependent context. If we can recover with a type, downgrade this to
3069 // a warning in Microsoft compatibility mode.
3070 unsigned DiagID = diag::err_typename_missing;
3071 if (RecoveryTSI && getLangOpts().MSVCCompat)
3072 DiagID = diag::ext_typename_missing;
3073 SourceLocation Loc = SS.getBeginLoc();
3074 auto D = Diag(Loc, DiagID);
3075 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3076
3077 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3078 // context.
3079 if (!RecoveryTSI)
3080 return ExprError();
3081
3082 // Only issue the fixit if we're prepared to recover.
3083 D << FixItHint::CreateInsertion(Loc, "typename ");
3084
3085 // Recover by pretending this was an elaborated type.
3086 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3087
3088 return ExprEmpty();
3089 }
3090
3091 // If necessary, build an implicit class member access.
3092 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3094 /*TemplateKWLoc=*/SourceLocation(),
3095 R, /*TemplateArgs=*/nullptr,
3096 /*S=*/nullptr);
3097
3098 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3099}
3100
3102 NestedNameSpecifier Qualifier,
3103 NamedDecl *FoundDecl,
3104 NamedDecl *Member) {
3105 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3106 if (!RD)
3107 return From;
3108
3109 QualType DestRecordType;
3110 QualType DestType;
3111 QualType FromRecordType;
3112 QualType FromType = From->getType();
3113 bool PointerConversions = false;
3114 if (isa<FieldDecl>(Member)) {
3115 DestRecordType = Context.getCanonicalTagType(RD);
3116 auto FromPtrType = FromType->getAs<PointerType>();
3117 DestRecordType = Context.getAddrSpaceQualType(
3118 DestRecordType, FromPtrType
3119 ? FromType->getPointeeType().getAddressSpace()
3120 : FromType.getAddressSpace());
3121
3122 if (FromPtrType) {
3123 DestType = Context.getPointerType(DestRecordType);
3124 FromRecordType = FromPtrType->getPointeeType();
3125 PointerConversions = true;
3126 } else {
3127 DestType = DestRecordType;
3128 FromRecordType = FromType;
3129 }
3130 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3131 if (!Method->isImplicitObjectMemberFunction())
3132 return From;
3133
3134 DestType = Method->getThisType().getNonReferenceType();
3135 DestRecordType = Method->getFunctionObjectParameterType();
3136
3137 if (FromType->getAs<PointerType>()) {
3138 FromRecordType = FromType->getPointeeType();
3139 PointerConversions = true;
3140 } else {
3141 FromRecordType = FromType;
3142 DestType = DestRecordType;
3143 }
3144
3145 LangAS FromAS = FromRecordType.getAddressSpace();
3146 LangAS DestAS = DestRecordType.getAddressSpace();
3147 if (FromAS != DestAS) {
3148 QualType FromRecordTypeWithoutAS =
3149 Context.removeAddrSpaceQualType(FromRecordType);
3150 QualType FromTypeWithDestAS =
3151 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3152 if (PointerConversions)
3153 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3154 From = ImpCastExprToType(From, FromTypeWithDestAS,
3155 CK_AddressSpaceConversion, From->getValueKind())
3156 .get();
3157 }
3158 } else {
3159 // No conversion necessary.
3160 return From;
3161 }
3162
3163 if (DestType->isDependentType() || FromType->isDependentType())
3164 return From;
3165
3166 // If the unqualified types are the same, no conversion is necessary.
3167 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3168 return From;
3169
3170 SourceRange FromRange = From->getSourceRange();
3171 SourceLocation FromLoc = FromRange.getBegin();
3172
3173 ExprValueKind VK = From->getValueKind();
3174
3175 // C++ [class.member.lookup]p8:
3176 // [...] Ambiguities can often be resolved by qualifying a name with its
3177 // class name.
3178 //
3179 // If the member was a qualified name and the qualified referred to a
3180 // specific base subobject type, we'll cast to that intermediate type
3181 // first and then to the object in which the member is declared. That allows
3182 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3183 //
3184 // class Base { public: int x; };
3185 // class Derived1 : public Base { };
3186 // class Derived2 : public Base { };
3187 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3188 //
3189 // void VeryDerived::f() {
3190 // x = 17; // error: ambiguous base subobjects
3191 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3192 // }
3193 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3194 QualType QType = QualType(Qualifier.getAsType(), 0);
3195 assert(QType->isRecordType() && "lookup done with non-record type");
3196
3197 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3198
3199 // In C++98, the qualifier type doesn't actually have to be a base
3200 // type of the object type, in which case we just ignore it.
3201 // Otherwise build the appropriate casts.
3202 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3203 CXXCastPath BasePath;
3204 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3205 FromLoc, FromRange, &BasePath))
3206 return ExprError();
3207
3208 if (PointerConversions)
3209 QType = Context.getPointerType(QType);
3210 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3211 VK, &BasePath).get();
3212
3213 FromType = QType;
3214 FromRecordType = QRecordType;
3215
3216 // If the qualifier type was the same as the destination type,
3217 // we're done.
3218 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3219 return From;
3220 }
3221 }
3222
3223 CXXCastPath BasePath;
3224 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3225 FromLoc, FromRange, &BasePath,
3226 /*IgnoreAccess=*/true))
3227 return ExprError();
3228
3229 // Propagate qualifiers to base subobjects as per:
3230 // C++ [basic.type.qualifier]p1.2:
3231 // A volatile object is [...] a subobject of a volatile object.
3232 Qualifiers FromTypeQuals = FromType.getQualifiers();
3233 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3234 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3235
3236 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3237 &BasePath);
3238}
3239
3241 const LookupResult &R,
3242 bool HasTrailingLParen) {
3243 // Only when used directly as the postfix-expression of a call.
3244 if (!HasTrailingLParen)
3245 return false;
3246
3247 // Never if a scope specifier was provided.
3248 if (SS.isNotEmpty())
3249 return false;
3250
3251 // Only in C++ or ObjC++.
3252 if (!getLangOpts().CPlusPlus)
3253 return false;
3254
3255 // Turn off ADL when we find certain kinds of declarations during
3256 // normal lookup:
3257 for (const NamedDecl *D : R) {
3258 // C++0x [basic.lookup.argdep]p3:
3259 // -- a declaration of a class member
3260 // Since using decls preserve this property, we check this on the
3261 // original decl.
3262 if (D->isCXXClassMember())
3263 return false;
3264
3265 // C++0x [basic.lookup.argdep]p3:
3266 // -- a block-scope function declaration that is not a
3267 // using-declaration
3268 // NOTE: we also trigger this for function templates (in fact, we
3269 // don't check the decl type at all, since all other decl types
3270 // turn off ADL anyway).
3271 if (isa<UsingShadowDecl>(D))
3272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3273 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3274 return false;
3275
3276 // C++0x [basic.lookup.argdep]p3:
3277 // -- a declaration that is neither a function or a function
3278 // template
3279 // And also for builtin functions.
3280 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3281 // But also builtin functions.
3282 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3283 return false;
3284 } else if (!isa<FunctionTemplateDecl>(D))
3285 return false;
3286 }
3287
3288 return true;
3289}
3290
3291
3292/// Diagnoses obvious problems with the use of the given declaration
3293/// as an expression. This is only actually called for lookups that
3294/// were not overloaded, and it doesn't promise that the declaration
3295/// will in fact be used.
3297 bool AcceptInvalid) {
3298 if (D->isInvalidDecl() && !AcceptInvalid)
3299 return true;
3300
3301 if (isa<TypedefNameDecl>(D)) {
3302 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3303 return true;
3304 }
3305
3306 if (isa<ObjCInterfaceDecl>(D)) {
3307 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3308 return true;
3309 }
3310
3311 if (isa<NamespaceDecl>(D)) {
3312 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3313 return true;
3314 }
3315
3316 return false;
3317}
3318
3319// Certain multiversion types should be treated as overloaded even when there is
3320// only one result.
3322 assert(R.isSingleResult() && "Expected only a single result");
3323 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3324 return FD &&
3325 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3326}
3327
3329 LookupResult &R, bool NeedsADL,
3330 bool AcceptInvalidDecl) {
3331 // If this is a single, fully-resolved result and we don't need ADL,
3332 // just build an ordinary singleton decl ref.
3333 if (!NeedsADL && R.isSingleResult() &&
3334 !R.getAsSingle<FunctionTemplateDecl>() &&
3336 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3337 R.getRepresentativeDecl(), nullptr,
3338 AcceptInvalidDecl);
3339
3340 // We only need to check the declaration if there's exactly one
3341 // result, because in the overloaded case the results can only be
3342 // functions and function templates.
3343 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3344 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3345 AcceptInvalidDecl))
3346 return ExprError();
3347
3348 // Otherwise, just build an unresolved lookup expression. Suppress
3349 // any lookup-related diagnostics; we'll hash these out later, when
3350 // we've picked a target.
3351 R.suppressDiagnostics();
3352
3354 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3355 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3356 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3357
3358 return ULE;
3359}
3360
3362 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3363 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3364 bool AcceptInvalidDecl) {
3365 assert(D && "Cannot refer to a NULL declaration");
3366 assert(!isa<FunctionTemplateDecl>(D) &&
3367 "Cannot refer unambiguously to a function template");
3368
3369 SourceLocation Loc = NameInfo.getLoc();
3370 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3371 // Recovery from invalid cases (e.g. D is an invalid Decl).
3372 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3373 // diagnostics, as invalid decls use int as a fallback type.
3374 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3375 }
3376
3377 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3378 // Specifically diagnose references to class templates that are missing
3379 // a template argument list.
3380 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3381 return ExprError();
3382 }
3383
3384 // Make sure that we're referring to a value.
3386 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3387 Diag(D->getLocation(), diag::note_declared_at);
3388 return ExprError();
3389 }
3390
3391 // Check whether this declaration can be used. Note that we suppress
3392 // this check when we're going to perform argument-dependent lookup
3393 // on this function name, because this might not be the function
3394 // that overload resolution actually selects.
3395 if (DiagnoseUseOfDecl(D, Loc))
3396 return ExprError();
3397
3398 auto *VD = cast<ValueDecl>(D);
3399
3400 // Only create DeclRefExpr's for valid Decl's.
3401 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3402 return ExprError();
3403
3404 // Handle members of anonymous structs and unions. If we got here,
3405 // and the reference is to a class member indirect field, then this
3406 // must be the subject of a pointer-to-member expression.
3407 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3408 IndirectField && !IndirectField->isCXXClassMember())
3410 IndirectField);
3411
3412 QualType type = VD->getType();
3413 if (type.isNull())
3414 return ExprError();
3415 ExprValueKind valueKind = VK_PRValue;
3416
3417 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3418 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3419 // is expanded by some outer '...' in the context of the use.
3420 type = type.getNonPackExpansionType();
3421
3422 switch (D->getKind()) {
3423 // Ignore all the non-ValueDecl kinds.
3424#define ABSTRACT_DECL(kind)
3425#define VALUE(type, base)
3426#define DECL(type, base) case Decl::type:
3427#include "clang/AST/DeclNodes.inc"
3428 llvm_unreachable("invalid value decl kind");
3429
3430 // These shouldn't make it here.
3431 case Decl::ObjCAtDefsField:
3432 llvm_unreachable("forming non-member reference to ivar?");
3433
3434 // Enum constants are always r-values and never references.
3435 // Unresolved using declarations are dependent.
3436 case Decl::EnumConstant:
3437 case Decl::UnresolvedUsingValue:
3438 case Decl::OMPDeclareReduction:
3439 case Decl::OMPDeclareMapper:
3440 valueKind = VK_PRValue;
3441 break;
3442
3443 // Fields and indirect fields that got here must be for
3444 // pointer-to-member expressions; we just call them l-values for
3445 // internal consistency, because this subexpression doesn't really
3446 // exist in the high-level semantics.
3447 case Decl::Field:
3448 case Decl::IndirectField:
3449 case Decl::ObjCIvar:
3450 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3451 "building reference to field in C?");
3452
3453 // These can't have reference type in well-formed programs, but
3454 // for internal consistency we do this anyway.
3455 type = type.getNonReferenceType();
3456 valueKind = VK_LValue;
3457 break;
3458
3459 // Non-type template parameters are either l-values or r-values
3460 // depending on the type.
3461 case Decl::NonTypeTemplateParm: {
3462 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3463 type = reftype->getPointeeType();
3464 valueKind = VK_LValue; // even if the parameter is an r-value reference
3465 break;
3466 }
3467
3468 // [expr.prim.id.unqual]p2:
3469 // If the entity is a template parameter object for a template
3470 // parameter of type T, the type of the expression is const T.
3471 // [...] The expression is an lvalue if the entity is a [...] template
3472 // parameter object.
3473 if (type->isRecordType()) {
3474 type = type.getUnqualifiedType().withConst();
3475 valueKind = VK_LValue;
3476 break;
3477 }
3478
3479 // For non-references, we need to strip qualifiers just in case
3480 // the template parameter was declared as 'const int' or whatever.
3481 valueKind = VK_PRValue;
3482 type = type.getUnqualifiedType();
3483 break;
3484 }
3485
3486 case Decl::Var:
3487 case Decl::VarTemplateSpecialization:
3488 case Decl::VarTemplatePartialSpecialization:
3489 case Decl::Decomposition:
3490 case Decl::Binding:
3491 case Decl::OMPCapturedExpr:
3492 // In C, "extern void blah;" is valid and is an r-value.
3493 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3494 type->isVoidType()) {
3495 valueKind = VK_PRValue;
3496 break;
3497 }
3498 [[fallthrough]];
3499
3500 case Decl::ImplicitParam:
3501 case Decl::ParmVar: {
3502 // These are always l-values.
3503 valueKind = VK_LValue;
3504 type = type.getNonReferenceType();
3505
3506 // FIXME: Does the addition of const really only apply in
3507 // potentially-evaluated contexts? Since the variable isn't actually
3508 // captured in an unevaluated context, it seems that the answer is no.
3509 if (!isUnevaluatedContext()) {
3510 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3511 if (!CapturedType.isNull())
3512 type = CapturedType;
3513 }
3514 break;
3515 }
3516
3517 case Decl::Function: {
3518 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3519 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3520 type = Context.BuiltinFnTy;
3521 valueKind = VK_PRValue;
3522 break;
3523 }
3524 }
3525
3526 const FunctionType *fty = type->castAs<FunctionType>();
3527
3528 // If we're referring to a function with an __unknown_anytype
3529 // result type, make the entire expression __unknown_anytype.
3530 if (fty->getReturnType() == Context.UnknownAnyTy) {
3531 type = Context.UnknownAnyTy;
3532 valueKind = VK_PRValue;
3533 break;
3534 }
3535
3536 // Functions are l-values in C++.
3537 if (getLangOpts().CPlusPlus) {
3538 valueKind = VK_LValue;
3539 break;
3540 }
3541
3542 // C99 DR 316 says that, if a function type comes from a
3543 // function definition (without a prototype), that type is only
3544 // used for checking compatibility. Therefore, when referencing
3545 // the function, we pretend that we don't have the full function
3546 // type.
3547 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3548 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3549 fty->getExtInfo());
3550
3551 // Functions are r-values in C.
3552 valueKind = VK_PRValue;
3553 break;
3554 }
3555
3556 case Decl::CXXDeductionGuide:
3557 llvm_unreachable("building reference to deduction guide");
3558
3559 case Decl::MSProperty:
3560 case Decl::MSGuid:
3561 case Decl::TemplateParamObject:
3562 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3563 // capture in OpenMP, or duplicated between host and device?
3564 valueKind = VK_LValue;
3565 break;
3566
3567 case Decl::UnnamedGlobalConstant:
3568 valueKind = VK_LValue;
3569 break;
3570
3571 case Decl::CXXMethod:
3572 // If we're referring to a method with an __unknown_anytype
3573 // result type, make the entire expression __unknown_anytype.
3574 // This should only be possible with a type written directly.
3575 if (const FunctionProtoType *proto =
3576 dyn_cast<FunctionProtoType>(VD->getType()))
3577 if (proto->getReturnType() == Context.UnknownAnyTy) {
3578 type = Context.UnknownAnyTy;
3579 valueKind = VK_PRValue;
3580 break;
3581 }
3582
3583 // C++ methods are l-values if static, r-values if non-static.
3584 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3585 valueKind = VK_LValue;
3586 break;
3587 }
3588 [[fallthrough]];
3589
3590 case Decl::CXXConversion:
3591 case Decl::CXXDestructor:
3592 case Decl::CXXConstructor:
3593 valueKind = VK_PRValue;
3594 break;
3595 }
3596
3597 auto *E =
3598 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3599 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3600 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3601 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3602 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3603 // diagnostics).
3604 if (VD->isInvalidDecl() && E)
3605 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3606 return E;
3607}
3608
3609static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3611 Target.resize(CharByteWidth * (Source.size() + 1));
3612 char *ResultPtr = &Target[0];
3613 const llvm::UTF8 *ErrorPtr;
3614 bool success =
3615 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3616 (void)success;
3617 assert(success);
3618 Target.resize(ResultPtr - &Target[0]);
3619}
3620
3623 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3624 if (!currentDecl) {
3625 Diag(Loc, diag::ext_predef_outside_function);
3626 currentDecl = Context.getTranslationUnitDecl();
3627 }
3628
3629 QualType ResTy;
3630 StringLiteral *SL = nullptr;
3631 if (cast<DeclContext>(currentDecl)->isDependentContext())
3632 ResTy = Context.DependentTy;
3633 else {
3634 // Pre-defined identifiers are of type char[x], where x is the length of
3635 // the string.
3636 bool ForceElaboratedPrinting =
3637 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3638 auto Str =
3639 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3640 unsigned Length = Str.length();
3641
3642 llvm::APInt LengthI(32, Length + 1);
3645 ResTy =
3646 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3647 SmallString<32> RawChars;
3648 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3649 Str, RawChars);
3650 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3652 /*IndexTypeQuals*/ 0);
3654 /*Pascal*/ false, ResTy, Loc);
3655 } else {
3656 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3657 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3659 /*IndexTypeQuals*/ 0);
3661 /*Pascal*/ false, ResTy, Loc);
3662 }
3663 }
3664
3665 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3666 SL);
3667}
3668
3672
3674 SmallString<16> CharBuffer;
3675 bool Invalid = false;
3676 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3677 if (Invalid)
3678 return ExprError();
3679
3680 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3681 PP, Tok.getKind());
3682 if (Literal.hadError())
3683 return ExprError();
3684
3685 QualType Ty;
3686 if (Literal.isWide())
3687 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3688 else if (Literal.isUTF8() && getLangOpts().C23)
3689 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3690 else if (Literal.isUTF8() && getLangOpts().Char8)
3691 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3692 else if (Literal.isUTF16())
3693 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3694 else if (Literal.isUTF32())
3695 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3696 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3697 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3698 else
3699 Ty = Context.CharTy; // 'x' -> char in C++;
3700 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3701
3703 if (Literal.isWide())
3705 else if (Literal.isUTF16())
3707 else if (Literal.isUTF32())
3709 else if (Literal.isUTF8())
3711
3712 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3713 Tok.getLocation());
3714
3715 if (Literal.getUDSuffix().empty())
3716 return Lit;
3717
3718 // We're building a user-defined literal.
3719 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3720 SourceLocation UDSuffixLoc =
3721 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3722
3723 // Make sure we're allowed user-defined literals here.
3724 if (!UDLScope)
3725 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3726
3727 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3728 // operator "" X (ch)
3729 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3730 Lit, Tok.getLocation());
3731}
3732
3734 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3736 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3737 Context.IntTy, Loc);
3738}
3739
3741 QualType Ty, SourceLocation Loc) {
3742 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3743
3744 using llvm::APFloat;
3745 APFloat Val(Format);
3746
3747 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3748 if (RM == llvm::RoundingMode::Dynamic)
3749 RM = llvm::RoundingMode::NearestTiesToEven;
3750 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3751
3752 // Overflow is always an error, but underflow is only an error if
3753 // we underflowed to zero (APFloat reports denormals as underflow).
3754 if ((result & APFloat::opOverflow) ||
3755 ((result & APFloat::opUnderflow) && Val.isZero())) {
3756 unsigned diagnostic;
3757 SmallString<20> buffer;
3758 if (result & APFloat::opOverflow) {
3759 diagnostic = diag::warn_float_overflow;
3760 APFloat::getLargest(Format).toString(buffer);
3761 } else {
3762 diagnostic = diag::warn_float_underflow;
3763 APFloat::getSmallest(Format).toString(buffer);
3764 }
3765
3766 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3767 }
3768
3769 bool isExact = (result == APFloat::opOK);
3770 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3771}
3772
3773bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3774 assert(E && "Invalid expression");
3775
3776 if (E->isValueDependent())
3777 return false;
3778
3779 QualType QT = E->getType();
3780 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3781 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3782 return true;
3783 }
3784
3785 llvm::APSInt ValueAPS;
3787
3788 if (R.isInvalid())
3789 return true;
3790
3791 // GCC allows the value of unroll count to be 0.
3792 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3793 // "The values of 0 and 1 block any unrolling of the loop."
3794 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3795 // '#pragma unroll' cases.
3796 bool ValueIsPositive =
3797 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3798 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3799 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3800 << toString(ValueAPS, 10) << ValueIsPositive;
3801 return true;
3802 }
3803
3804 return false;
3805}
3806
3808 // Fast path for a single digit (which is quite common). A single digit
3809 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3810 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3811 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3812 return ActOnIntegerConstant(Tok.getLocation(), Val);
3813 }
3814
3815 SmallString<128> SpellingBuffer;
3816 // NumericLiteralParser wants to overread by one character. Add padding to
3817 // the buffer in case the token is copied to the buffer. If getSpelling()
3818 // returns a StringRef to the memory buffer, it should have a null char at
3819 // the EOF, so it is also safe.
3820 SpellingBuffer.resize(Tok.getLength() + 1);
3821
3822 // Get the spelling of the token, which eliminates trigraphs, etc.
3823 bool Invalid = false;
3824 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3825 if (Invalid)
3826 return ExprError();
3827
3828 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3829 PP.getSourceManager(), PP.getLangOpts(),
3830 PP.getTargetInfo(), PP.getDiagnostics());
3831 if (Literal.hadError)
3832 return ExprError();
3833
3834 if (Literal.hasUDSuffix()) {
3835 // We're building a user-defined literal.
3836 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3837 SourceLocation UDSuffixLoc =
3838 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3839
3840 // Make sure we're allowed user-defined literals here.
3841 if (!UDLScope)
3842 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3843
3844 QualType CookedTy;
3845 if (Literal.isFloatingLiteral()) {
3846 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3847 // long double, the literal is treated as a call of the form
3848 // operator "" X (f L)
3849 CookedTy = Context.LongDoubleTy;
3850 } else {
3851 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3852 // unsigned long long, the literal is treated as a call of the form
3853 // operator "" X (n ULL)
3854 CookedTy = Context.UnsignedLongLongTy;
3855 }
3856
3857 DeclarationName OpName =
3858 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3861
3862 SourceLocation TokLoc = Tok.getLocation();
3863
3864 // Perform literal operator lookup to determine if we're building a raw
3865 // literal or a cooked one.
3866 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3867 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3868 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3869 /*AllowStringTemplatePack*/ false,
3870 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3872 // Lookup failure for imaginary constants isn't fatal, there's still the
3873 // GNU extension producing _Complex types.
3874 break;
3875 case LOLR_Error:
3876 return ExprError();
3877 case LOLR_Cooked: {
3878 Expr *Lit;
3879 if (Literal.isFloatingLiteral()) {
3880 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3881 } else {
3882 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3883 if (Literal.GetIntegerValue(ResultVal))
3884 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3885 << /* Unsigned */ 1;
3886 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3887 Tok.getLocation());
3888 }
3889 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3890 }
3891
3892 case LOLR_Raw: {
3893 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3894 // literal is treated as a call of the form
3895 // operator "" X ("n")
3896 unsigned Length = Literal.getUDSuffixOffset();
3897 QualType StrTy = Context.getConstantArrayType(
3898 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3899 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3900 Expr *Lit =
3901 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3903 /*Pascal*/ false, StrTy, TokLoc);
3904 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3905 }
3906
3907 case LOLR_Template: {
3908 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3909 // template), L is treated as a call fo the form
3910 // operator "" X <'c1', 'c2', ... 'ck'>()
3911 // where n is the source character sequence c1 c2 ... ck.
3912 TemplateArgumentListInfo ExplicitArgs;
3913 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3914 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3915 llvm::APSInt Value(CharBits, CharIsUnsigned);
3916 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3917 Value = TokSpelling[I];
3918 TemplateArgument Arg(Context, Value, Context.CharTy);
3920 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3921 }
3922 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3923 }
3925 llvm_unreachable("unexpected literal operator lookup result");
3926 }
3927 }
3928
3929 Expr *Res;
3930
3931 if (Literal.isFixedPointLiteral()) {
3932 QualType Ty;
3933
3934 if (Literal.isAccum) {
3935 if (Literal.isHalf) {
3936 Ty = Context.ShortAccumTy;
3937 } else if (Literal.isLong) {
3938 Ty = Context.LongAccumTy;
3939 } else {
3940 Ty = Context.AccumTy;
3941 }
3942 } else if (Literal.isFract) {
3943 if (Literal.isHalf) {
3944 Ty = Context.ShortFractTy;
3945 } else if (Literal.isLong) {
3946 Ty = Context.LongFractTy;
3947 } else {
3948 Ty = Context.FractTy;
3949 }
3950 }
3951
3952 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3953
3954 bool isSigned = !Literal.isUnsigned;
3955 unsigned scale = Context.getFixedPointScale(Ty);
3956 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3957
3958 llvm::APInt Val(bit_width, 0, isSigned);
3959 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3960 bool ValIsZero = Val.isZero() && !Overflowed;
3961
3962 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3963 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3964 // Clause 6.4.4 - The value of a constant shall be in the range of
3965 // representable values for its type, with exception for constants of a
3966 // fract type with a value of exactly 1; such a constant shall denote
3967 // the maximal value for the type.
3968 --Val;
3969 else if (Val.ugt(MaxVal) || Overflowed)
3970 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3971
3973 Tok.getLocation(), scale);
3974 } else if (Literal.isFloatingLiteral()) {
3975 QualType Ty;
3976 if (Literal.isHalf){
3977 if (getLangOpts().HLSL ||
3978 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3979 Ty = Context.HalfTy;
3980 else {
3981 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3982 return ExprError();
3983 }
3984 } else if (Literal.isFloat)
3985 Ty = Context.FloatTy;
3986 else if (Literal.isLong)
3987 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3988 else if (Literal.isFloat16)
3989 Ty = Context.Float16Ty;
3990 else if (Literal.isFloat128)
3991 Ty = Context.Float128Ty;
3992 else if (getLangOpts().HLSL)
3993 Ty = Context.FloatTy;
3994 else
3995 Ty = Context.DoubleTy;
3996
3997 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3998
3999 if (Ty == Context.DoubleTy) {
4000 if (getLangOpts().SinglePrecisionConstants) {
4001 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4002 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4003 }
4004 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4005 "cl_khr_fp64", getLangOpts())) {
4006 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4007 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4009 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4010 }
4011 }
4012 } else if (!Literal.isIntegerLiteral()) {
4013 return ExprError();
4014 } else {
4015 QualType Ty;
4016
4017 // 'z/uz' literals are a C++23 feature.
4018 if (Literal.isSizeT)
4019 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4021 ? diag::warn_cxx20_compat_size_t_suffix
4022 : diag::ext_cxx23_size_t_suffix
4023 : diag::err_cxx23_size_t_suffix);
4024
4025 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4026 // but we do not currently support the suffix in C++ mode because it's not
4027 // entirely clear whether WG21 will prefer this suffix to return a library
4028 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4029 // literals are a C++ extension.
4030 if (Literal.isBitInt)
4031 PP.Diag(Tok.getLocation(),
4032 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4033 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4034 : diag::ext_c23_bitint_suffix);
4035
4036 // Get the value in the widest-possible width. What is "widest" depends on
4037 // whether the literal is a bit-precise integer or not. For a bit-precise
4038 // integer type, try to scan the source to determine how many bits are
4039 // needed to represent the value. This may seem a bit expensive, but trying
4040 // to get the integer value from an overly-wide APInt is *extremely*
4041 // expensive, so the naive approach of assuming
4042 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4043 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4044 if (Literal.isBitInt)
4045 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4046 Literal.getLiteralDigits(), Literal.getRadix());
4047 if (Literal.MicrosoftInteger) {
4048 if (Literal.MicrosoftInteger == 128 &&
4049 !Context.getTargetInfo().hasInt128Type())
4050 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4051 << Literal.isUnsigned;
4052 BitsNeeded = Literal.MicrosoftInteger;
4053 }
4054
4055 llvm::APInt ResultVal(BitsNeeded, 0);
4056
4057 if (Literal.GetIntegerValue(ResultVal)) {
4058 // If this value didn't fit into uintmax_t, error and force to ull.
4059 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4060 << /* Unsigned */ 1;
4061 Ty = Context.UnsignedLongLongTy;
4062 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4063 "long long is not intmax_t?");
4064 } else {
4065 // If this value fits into a ULL, try to figure out what else it fits into
4066 // according to the rules of C99 6.4.4.1p5.
4067
4068 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4069 // be an unsigned int.
4070 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4071
4072 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4073 // suffix for portability of code with C++, but both `l` and `ll` are
4074 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4075 // same.
4076 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4077 Literal.isLong = true;
4078 Literal.isLongLong = false;
4079 }
4080
4081 // Check from smallest to largest, picking the smallest type we can.
4082 unsigned Width = 0;
4083
4084 // Microsoft specific integer suffixes are explicitly sized.
4085 if (Literal.MicrosoftInteger) {
4086 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4087 Width = 8;
4088 Ty = Context.CharTy;
4089 } else {
4090 Width = Literal.MicrosoftInteger;
4091 Ty = Context.getIntTypeForBitwidth(Width,
4092 /*Signed=*/!Literal.isUnsigned);
4093 }
4094 }
4095
4096 // Bit-precise integer literals are automagically-sized based on the
4097 // width required by the literal.
4098 if (Literal.isBitInt) {
4099 // The signed version has one more bit for the sign value. There are no
4100 // zero-width bit-precise integers, even if the literal value is 0.
4101 Width = std::max(ResultVal.getActiveBits(), 1u) +
4102 (Literal.isUnsigned ? 0u : 1u);
4103
4104 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4105 // and reset the type to the largest supported width.
4106 unsigned int MaxBitIntWidth =
4107 Context.getTargetInfo().getMaxBitIntWidth();
4108 if (Width > MaxBitIntWidth) {
4109 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4110 << Literal.isUnsigned;
4111 Width = MaxBitIntWidth;
4112 }
4113
4114 // Reset the result value to the smaller APInt and select the correct
4115 // type to be used. Note, we zext even for signed values because the
4116 // literal itself is always an unsigned value (a preceeding - is a
4117 // unary operator, not part of the literal).
4118 ResultVal = ResultVal.zextOrTrunc(Width);
4119 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4120 }
4121
4122 // Check C++23 size_t literals.
4123 if (Literal.isSizeT) {
4124 assert(!Literal.MicrosoftInteger &&
4125 "size_t literals can't be Microsoft literals");
4126 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4127 Context.getTargetInfo().getSizeType());
4128
4129 // Does it fit in size_t?
4130 if (ResultVal.isIntN(SizeTSize)) {
4131 // Does it fit in ssize_t?
4132 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4133 Ty = Context.getSignedSizeType();
4134 else if (AllowUnsigned)
4135 Ty = Context.getSizeType();
4136 Width = SizeTSize;
4137 }
4138 }
4139
4140 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4141 !Literal.isSizeT) {
4142 // Are int/unsigned possibilities?
4143 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4144
4145 // Does it fit in a unsigned int?
4146 if (ResultVal.isIntN(IntSize)) {
4147 // Does it fit in a signed int?
4148 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4149 Ty = Context.IntTy;
4150 else if (AllowUnsigned)
4151 Ty = Context.UnsignedIntTy;
4152 Width = IntSize;
4153 }
4154 }
4155
4156 // Are long/unsigned long possibilities?
4157 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4158 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4159
4160 // Does it fit in a unsigned long?
4161 if (ResultVal.isIntN(LongSize)) {
4162 // Does it fit in a signed long?
4163 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4164 Ty = Context.LongTy;
4165 else if (AllowUnsigned)
4166 Ty = Context.UnsignedLongTy;
4167 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4168 // is compatible.
4169 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4170 const unsigned LongLongSize =
4171 Context.getTargetInfo().getLongLongWidth();
4172 Diag(Tok.getLocation(),
4174 ? Literal.isLong
4175 ? diag::warn_old_implicitly_unsigned_long_cxx
4176 : /*C++98 UB*/ diag::
4177 ext_old_implicitly_unsigned_long_cxx
4178 : diag::warn_old_implicitly_unsigned_long)
4179 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4180 : /*will be ill-formed*/ 1);
4181 Ty = Context.UnsignedLongTy;
4182 }
4183 Width = LongSize;
4184 }
4185 }
4186
4187 // Check long long if needed.
4188 if (Ty.isNull() && !Literal.isSizeT) {
4189 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4190
4191 // Does it fit in a unsigned long long?
4192 if (ResultVal.isIntN(LongLongSize)) {
4193 // Does it fit in a signed long long?
4194 // To be compatible with MSVC, hex integer literals ending with the
4195 // LL or i64 suffix are always signed in Microsoft mode.
4196 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4197 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4198 Ty = Context.LongLongTy;
4199 else if (AllowUnsigned)
4200 Ty = Context.UnsignedLongLongTy;
4201 Width = LongLongSize;
4202
4203 // 'long long' is a C99 or C++11 feature, whether the literal
4204 // explicitly specified 'long long' or we needed the extra width.
4205 if (getLangOpts().CPlusPlus)
4206 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4207 ? diag::warn_cxx98_compat_longlong
4208 : diag::ext_cxx11_longlong);
4209 else if (!getLangOpts().C99)
4210 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4211 }
4212 }
4213
4214 // If we still couldn't decide a type, we either have 'size_t' literal
4215 // that is out of range, or a decimal literal that does not fit in a
4216 // signed long long and has no U suffix.
4217 if (Ty.isNull()) {
4218 if (Literal.isSizeT)
4219 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4220 << Literal.isUnsigned;
4221 else
4222 Diag(Tok.getLocation(),
4223 diag::ext_integer_literal_too_large_for_signed);
4224 Ty = Context.UnsignedLongLongTy;
4225 Width = Context.getTargetInfo().getLongLongWidth();
4226 }
4227
4228 if (ResultVal.getBitWidth() != Width)
4229 ResultVal = ResultVal.trunc(Width);
4230 }
4231 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4232 }
4233
4234 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4235 if (Literal.isImaginary) {
4236 Res = new (Context) ImaginaryLiteral(Res,
4237 Context.getComplexType(Res->getType()));
4238
4239 // In C++, this is a GNU extension. In C, it's a C2y extension.
4240 unsigned DiagId;
4241 if (getLangOpts().CPlusPlus)
4242 DiagId = diag::ext_gnu_imaginary_constant;
4243 else if (getLangOpts().C2y)
4244 DiagId = diag::warn_c23_compat_imaginary_constant;
4245 else
4246 DiagId = diag::ext_c2y_imaginary_constant;
4247 Diag(Tok.getLocation(), DiagId);
4248 }
4249 return Res;
4250}
4251
4253 assert(E && "ActOnParenExpr() missing expr");
4254 QualType ExprTy = E->getType();
4255 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4256 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4257 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4258 return new (Context) ParenExpr(L, R, E);
4259}
4260
4262 SourceLocation Loc,
4263 SourceRange ArgRange) {
4264 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4265 // scalar or vector data type argument..."
4266 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4267 // type (C99 6.2.5p18) or void.
4268 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4269 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4270 << T << ArgRange;
4271 return true;
4272 }
4273
4274 assert((T->isVoidType() || !T->isIncompleteType()) &&
4275 "Scalar types should always be complete");
4276 return false;
4277}
4278
4280 SourceLocation Loc,
4281 SourceRange ArgRange) {
4282 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4283 if (!T->isVectorType() && !T->isSizelessVectorType())
4284 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4285 << ""
4286 << "__builtin_vectorelements" << T << ArgRange;
4287
4288 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4289 if (T->isSVESizelessBuiltinType()) {
4290 llvm::StringMap<bool> CallerFeatureMap;
4291 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4292 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4293 }
4294 }
4295
4296 return false;
4297}
4298
4300 SourceLocation Loc,
4301 SourceRange ArgRange) {
4302 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4303 return true;
4304
4305 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4306 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4307 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4308 return true;
4309 }
4310
4311 return false;
4312}
4313
4315 SourceLocation Loc,
4316 SourceRange ArgRange,
4317 UnaryExprOrTypeTrait TraitKind) {
4318 // Invalid types must be hard errors for SFINAE in C++.
4319 if (S.LangOpts.CPlusPlus)
4320 return true;
4321
4322 // C99 6.5.3.4p1:
4323 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4324 TraitKind == UETT_PreferredAlignOf) {
4325
4326 // sizeof(function)/alignof(function) is allowed as an extension.
4327 if (T->isFunctionType()) {
4328 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4329 << getTraitSpelling(TraitKind) << ArgRange;
4330 return false;
4331 }
4332
4333 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4334 // this is an error (OpenCL v1.1 s6.3.k)
4335 if (T->isVoidType()) {
4336 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4337 : diag::ext_sizeof_alignof_void_type;
4338 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4339 return false;
4340 }
4341 }
4342 return true;
4343}
4344
4346 SourceLocation Loc,
4347 SourceRange ArgRange,
4348 UnaryExprOrTypeTrait TraitKind) {
4349 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4350 // runtime doesn't allow it.
4351 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4352 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4353 << T << (TraitKind == UETT_SizeOf)
4354 << ArgRange;
4355 return true;
4356 }
4357
4358 return false;
4359}
4360
4361/// Check whether E is a pointer from a decayed array type (the decayed
4362/// pointer type is equal to T) and emit a warning if it is.
4364 const Expr *E) {
4365 // Don't warn if the operation changed the type.
4366 if (T != E->getType())
4367 return;
4368
4369 // Now look for array decays.
4370 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4371 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4372 return;
4373
4374 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4375 << ICE->getType()
4376 << ICE->getSubExpr()->getType();
4377}
4378
4380 UnaryExprOrTypeTrait ExprKind) {
4381 QualType ExprTy = E->getType();
4382 assert(!ExprTy->isReferenceType());
4383
4384 bool IsUnevaluatedOperand =
4385 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4386 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4387 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4388 if (IsUnevaluatedOperand) {
4390 if (Result.isInvalid())
4391 return true;
4392 E = Result.get();
4393 }
4394
4395 // The operand for sizeof and alignof is in an unevaluated expression context,
4396 // so side effects could result in unintended consequences.
4397 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4398 // used to build SFINAE gadgets.
4399 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4400 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4402 !E->getType()->isVariableArrayType() &&
4403 E->HasSideEffects(Context, false))
4404 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4405
4406 if (ExprKind == UETT_VecStep)
4407 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4408 E->getSourceRange());
4409
4410 if (ExprKind == UETT_VectorElements)
4411 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4412 E->getSourceRange());
4413
4414 // Explicitly list some types as extensions.
4415 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4416 E->getSourceRange(), ExprKind))
4417 return false;
4418
4419 // WebAssembly tables are always illegal operands to unary expressions and
4420 // type traits.
4421 if (Context.getTargetInfo().getTriple().isWasm() &&
4423 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4424 << getTraitSpelling(ExprKind);
4425 return true;
4426 }
4427
4428 // 'alignof' applied to an expression only requires the base element type of
4429 // the expression to be complete. 'sizeof' requires the expression's type to
4430 // be complete (and will attempt to complete it if it's an array of unknown
4431 // bound).
4432 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4434 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4435 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4436 getTraitSpelling(ExprKind), E->getSourceRange()))
4437 return true;
4438 } else {
4440 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4441 getTraitSpelling(ExprKind), E->getSourceRange()))
4442 return true;
4443 }
4444
4445 // Completing the expression's type may have changed it.
4446 ExprTy = E->getType();
4447 assert(!ExprTy->isReferenceType());
4448
4449 if (ExprTy->isFunctionType()) {
4450 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4451 << getTraitSpelling(ExprKind) << E->getSourceRange();
4452 return true;
4453 }
4454
4455 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4456 E->getSourceRange(), ExprKind))
4457 return true;
4458
4459 if (ExprKind == UETT_CountOf) {
4460 // The type has to be an array type. We already checked for incomplete
4461 // types above.
4462 QualType ExprType = E->IgnoreParens()->getType();
4463 if (!ExprType->isArrayType()) {
4464 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4465 return true;
4466 }
4467 // FIXME: warn on _Countof on an array parameter. Not warning on it
4468 // currently because there are papers in WG14 about array types which do
4469 // not decay that could impact this behavior, so we want to see if anything
4470 // changes here before coming up with a warning group for _Countof-related
4471 // diagnostics.
4472 }
4473
4474 if (ExprKind == UETT_SizeOf) {
4475 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4476 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4477 QualType OType = PVD->getOriginalType();
4478 QualType Type = PVD->getType();
4479 if (Type->isPointerType() && OType->isArrayType()) {
4480 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4481 << Type << OType;
4482 Diag(PVD->getLocation(), diag::note_declared_at);
4483 }
4484 }
4485 }
4486
4487 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4488 // decays into a pointer and returns an unintended result. This is most
4489 // likely a typo for "sizeof(array) op x".
4490 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4491 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4492 BO->getLHS());
4493 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4494 BO->getRHS());
4495 }
4496 }
4497
4498 return false;
4499}
4500
4501static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4502 // Cannot know anything else if the expression is dependent.
4503 if (E->isTypeDependent())
4504 return false;
4505
4506 if (E->getObjectKind() == OK_BitField) {
4507 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4508 << 1 << E->getSourceRange();
4509 return true;
4510 }
4511
4512 ValueDecl *D = nullptr;
4513 Expr *Inner = E->IgnoreParens();
4514 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4515 D = DRE->getDecl();
4516 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4517 D = ME->getMemberDecl();
4518 }
4519
4520 // If it's a field, require the containing struct to have a
4521 // complete definition so that we can compute the layout.
4522 //
4523 // This can happen in C++11 onwards, either by naming the member
4524 // in a way that is not transformed into a member access expression
4525 // (in an unevaluated operand, for instance), or by naming the member
4526 // in a trailing-return-type.
4527 //
4528 // For the record, since __alignof__ on expressions is a GCC
4529 // extension, GCC seems to permit this but always gives the
4530 // nonsensical answer 0.
4531 //
4532 // We don't really need the layout here --- we could instead just
4533 // directly check for all the appropriate alignment-lowing
4534 // attributes --- but that would require duplicating a lot of
4535 // logic that just isn't worth duplicating for such a marginal
4536 // use-case.
4537 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4538 // Fast path this check, since we at least know the record has a
4539 // definition if we can find a member of it.
4540 if (!FD->getParent()->isCompleteDefinition()) {
4541 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4542 << E->getSourceRange();
4543 return true;
4544 }
4545
4546 // Otherwise, if it's a field, and the field doesn't have
4547 // reference type, then it must have a complete type (or be a
4548 // flexible array member, which we explicitly want to
4549 // white-list anyway), which makes the following checks trivial.
4550 if (!FD->getType()->isReferenceType())
4551 return false;
4552 }
4553
4554 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4555}
4556
4558 E = E->IgnoreParens();
4559
4560 // Cannot know anything else if the expression is dependent.
4561 if (E->isTypeDependent())
4562 return false;
4563
4564 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4565}
4566
4568 CapturingScopeInfo *CSI) {
4569 assert(T->isVariablyModifiedType());
4570 assert(CSI != nullptr);
4571
4572 // We're going to walk down into the type and look for VLA expressions.
4573 do {
4574 const Type *Ty = T.getTypePtr();
4575 switch (Ty->getTypeClass()) {
4576#define TYPE(Class, Base)
4577#define ABSTRACT_TYPE(Class, Base)
4578#define NON_CANONICAL_TYPE(Class, Base)
4579#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4580#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4581#include "clang/AST/TypeNodes.inc"
4582 T = QualType();
4583 break;
4584 // These types are never variably-modified.
4585 case Type::Builtin:
4586 case Type::Complex:
4587 case Type::Vector:
4588 case Type::ExtVector:
4589 case Type::ConstantMatrix:
4590 case Type::Record:
4591 case Type::Enum:
4592 case Type::TemplateSpecialization:
4593 case Type::ObjCObject:
4594 case Type::ObjCInterface:
4595 case Type::ObjCObjectPointer:
4596 case Type::ObjCTypeParam:
4597 case Type::Pipe:
4598 case Type::BitInt:
4599 case Type::HLSLInlineSpirv:
4600 llvm_unreachable("type class is never variably-modified!");
4601 case Type::Adjusted:
4602 T = cast<AdjustedType>(Ty)->getOriginalType();
4603 break;
4604 case Type::Decayed:
4605 T = cast<DecayedType>(Ty)->getPointeeType();
4606 break;
4607 case Type::ArrayParameter:
4608 T = cast<ArrayParameterType>(Ty)->getElementType();
4609 break;
4610 case Type::Pointer:
4611 T = cast<PointerType>(Ty)->getPointeeType();
4612 break;
4613 case Type::BlockPointer:
4614 T = cast<BlockPointerType>(Ty)->getPointeeType();
4615 break;
4616 case Type::LValueReference:
4617 case Type::RValueReference:
4618 T = cast<ReferenceType>(Ty)->getPointeeType();
4619 break;
4620 case Type::MemberPointer:
4621 T = cast<MemberPointerType>(Ty)->getPointeeType();
4622 break;
4623 case Type::ConstantArray:
4624 case Type::IncompleteArray:
4625 // Losing element qualification here is fine.
4626 T = cast<ArrayType>(Ty)->getElementType();
4627 break;
4628 case Type::VariableArray: {
4629 // Losing element qualification here is fine.
4631
4632 // Unknown size indication requires no size computation.
4633 // Otherwise, evaluate and record it.
4634 auto Size = VAT->getSizeExpr();
4635 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4637 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4638
4639 T = VAT->getElementType();
4640 break;
4641 }
4642 case Type::FunctionProto:
4643 case Type::FunctionNoProto:
4644 T = cast<FunctionType>(Ty)->getReturnType();
4645 break;
4646 case Type::Paren:
4647 case Type::TypeOf:
4648 case Type::UnaryTransform:
4649 case Type::Attributed:
4650 case Type::BTFTagAttributed:
4651 case Type::OverflowBehavior:
4652 case Type::HLSLAttributedResource:
4653 case Type::SubstTemplateTypeParm:
4654 case Type::MacroQualified:
4655 case Type::CountAttributed:
4656 // Keep walking after single level desugaring.
4657 T = T.getSingleStepDesugaredType(Context);
4658 break;
4659 case Type::Typedef:
4660 T = cast<TypedefType>(Ty)->desugar();
4661 break;
4662 case Type::Decltype:
4663 T = cast<DecltypeType>(Ty)->desugar();
4664 break;
4665 case Type::PackIndexing:
4666 T = cast<PackIndexingType>(Ty)->desugar();
4667 break;
4668 case Type::Using:
4669 T = cast<UsingType>(Ty)->desugar();
4670 break;
4671 case Type::Auto:
4672 case Type::DeducedTemplateSpecialization:
4673 T = cast<DeducedType>(Ty)->getDeducedType();
4674 break;
4675 case Type::TypeOfExpr:
4676 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4677 break;
4678 case Type::Atomic:
4679 T = cast<AtomicType>(Ty)->getValueType();
4680 break;
4681 case Type::PredefinedSugar:
4682 T = cast<PredefinedSugarType>(Ty)->desugar();
4683 break;
4684 }
4685 } while (!T.isNull() && T->isVariablyModifiedType());
4686}
4687
4689 SourceLocation OpLoc,
4690 SourceRange ExprRange,
4691 UnaryExprOrTypeTrait ExprKind,
4692 StringRef KWName) {
4693 if (ExprType->isDependentType())
4694 return false;
4695
4696 // C++ [expr.sizeof]p2:
4697 // When applied to a reference or a reference type, the result
4698 // is the size of the referenced type.
4699 // C++11 [expr.alignof]p3:
4700 // When alignof is applied to a reference type, the result
4701 // shall be the alignment of the referenced type.
4702 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4703 ExprType = Ref->getPointeeType();
4704
4705 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4706 // When alignof or _Alignof is applied to an array type, the result
4707 // is the alignment of the element type.
4708 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4709 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4710 // If the trait is 'alignof' in C before C2y, the ability to apply the
4711 // trait to an incomplete array is an extension.
4712 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4713 ExprType->isIncompleteArrayType())
4714 Diag(OpLoc, getLangOpts().C2y
4715 ? diag::warn_c2y_compat_alignof_incomplete_array
4716 : diag::ext_c2y_alignof_incomplete_array);
4717 ExprType = Context.getBaseElementType(ExprType);
4718 }
4719
4720 if (ExprKind == UETT_VecStep)
4721 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4722
4723 if (ExprKind == UETT_VectorElements)
4724 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4725 ExprRange);
4726
4727 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4728 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4729 ExprRange);
4730
4731 // Explicitly list some types as extensions.
4732 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4733 ExprKind))
4734 return false;
4735
4737 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4738 KWName, ExprRange))
4739 return true;
4740
4741 if (ExprType->isFunctionType()) {
4742 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4743 return true;
4744 }
4745
4746 if (ExprKind == UETT_CountOf) {
4747 // The type has to be an array type. We already checked for incomplete
4748 // types above.
4749 if (!ExprType->isArrayType()) {
4750 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4751 return true;
4752 }
4753 }
4754
4755 // WebAssembly tables are always illegal operands to unary expressions and
4756 // type traits.
4757 if (Context.getTargetInfo().getTriple().isWasm() &&
4758 ExprType->isWebAssemblyTableType()) {
4759 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4760 << getTraitSpelling(ExprKind);
4761 return true;
4762 }
4763
4764 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4765 ExprKind))
4766 return true;
4767
4768 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4769 if (auto *TT = ExprType->getAs<TypedefType>()) {
4770 for (auto I = FunctionScopes.rbegin(),
4771 E = std::prev(FunctionScopes.rend());
4772 I != E; ++I) {
4773 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4774 if (CSI == nullptr)
4775 break;
4776 DeclContext *DC = nullptr;
4777 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4778 DC = LSI->CallOperator;
4779 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4780 DC = CRSI->TheCapturedDecl;
4781 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4782 DC = BSI->TheDecl;
4783 if (DC) {
4784 if (DC->containsDecl(TT->getDecl()))
4785 break;
4786 captureVariablyModifiedType(Context, ExprType, CSI);
4787 }
4788 }
4789 }
4790 }
4791
4792 return false;
4793}
4794
4796 SourceLocation OpLoc,
4797 UnaryExprOrTypeTrait ExprKind,
4798 SourceRange R) {
4799 if (!TInfo)
4800 return ExprError();
4801
4802 QualType T = TInfo->getType();
4803
4804 if (!T->isDependentType() &&
4805 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4806 getTraitSpelling(ExprKind)))
4807 return ExprError();
4808
4809 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4810 // properly deal with VLAs in nested calls of sizeof and typeof.
4811 if (currentEvaluationContext().isUnevaluated() &&
4812 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4813 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4814 TInfo->getType()->isVariablyModifiedType())
4815 TInfo = TransformToPotentiallyEvaluated(TInfo);
4816
4817 // It's possible that the transformation above failed.
4818 if (!TInfo)
4819 return ExprError();
4820
4821 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4822 return new (Context) UnaryExprOrTypeTraitExpr(
4823 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4824}
4825
4828 UnaryExprOrTypeTrait ExprKind) {
4830 if (PE.isInvalid())
4831 return ExprError();
4832
4833 E = PE.get();
4834
4835 // Verify that the operand is valid.
4836 bool isInvalid = false;
4837 if (E->isTypeDependent()) {
4838 // Delay type-checking for type-dependent expressions.
4839 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4840 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4841 } else if (ExprKind == UETT_VecStep) {
4843 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4844 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4845 isInvalid = true;
4846 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4847 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4848 isInvalid = true;
4849 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4850 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4852 }
4853
4854 if (isInvalid)
4855 return ExprError();
4856
4857 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4858 E->getType()->isVariableArrayType()) {
4860 if (PE.isInvalid()) return ExprError();
4861 E = PE.get();
4862 }
4863
4864 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4865 return new (Context) UnaryExprOrTypeTraitExpr(
4866 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4867}
4868
4871 UnaryExprOrTypeTrait ExprKind, bool IsType,
4872 void *TyOrEx, SourceRange ArgRange) {
4873 // If error parsing type, ignore.
4874 if (!TyOrEx) return ExprError();
4875
4876 if (IsType) {
4877 TypeSourceInfo *TInfo;
4878 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4879 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4880 }
4881
4882 Expr *ArgEx = (Expr *)TyOrEx;
4883 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4884 return Result;
4885}
4886
4888 SourceLocation OpLoc, SourceRange R) {
4889 if (!TInfo)
4890 return true;
4891 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4892 UETT_AlignOf, KWName);
4893}
4894
4896 SourceLocation OpLoc, SourceRange R) {
4897 TypeSourceInfo *TInfo;
4899 &TInfo);
4900 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4901}
4902
4904 bool IsReal) {
4905 if (V.get()->isTypeDependent())
4906 return S.Context.DependentTy;
4907
4908 // _Real and _Imag are only l-values for normal l-values.
4909 if (V.get()->getObjectKind() != OK_Ordinary) {
4910 V = S.DefaultLvalueConversion(V.get());
4911 if (V.isInvalid())
4912 return QualType();
4913 }
4914
4915 // These operators return the element type of a complex type.
4916 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4917 return CT->getElementType();
4918
4919 // Otherwise they pass through real integer and floating point types here.
4920 if (V.get()->getType()->isArithmeticType())
4921 return V.get()->getType();
4922
4923 // Test for placeholders.
4924 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4925 if (PR.isInvalid()) return QualType();
4926 if (PR.get() != V.get()) {
4927 V = PR;
4928 return CheckRealImagOperand(S, V, Loc, IsReal);
4929 }
4930
4931 // Reject anything else.
4932 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4933 << (IsReal ? "__real" : "__imag");
4934 return QualType();
4935}
4936
4937
4938
4941 tok::TokenKind Kind, Expr *Input) {
4943 switch (Kind) {
4944 default: llvm_unreachable("Unknown unary op!");
4945 case tok::plusplus: Opc = UO_PostInc; break;
4946 case tok::minusminus: Opc = UO_PostDec; break;
4947 }
4948
4949 // Since this might is a postfix expression, get rid of ParenListExprs.
4951 if (Result.isInvalid()) return ExprError();
4952 Input = Result.get();
4953
4954 return BuildUnaryOp(S, OpLoc, Opc, Input);
4955}
4956
4957/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4958///
4959/// \return true on error
4961 SourceLocation opLoc,
4962 Expr *op) {
4963 assert(op->getType()->isObjCObjectPointerType());
4965 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4966 return false;
4967
4968 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4970 << op->getSourceRange();
4971 return true;
4972}
4973
4975 auto *BaseNoParens = Base->IgnoreParens();
4976 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4977 return MSProp->getPropertyDecl()->getType()->isArrayType();
4978 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4979}
4980
4981// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4982// Typically this is DependentTy, but can sometimes be more precise.
4983//
4984// There are cases when we could determine a non-dependent type:
4985// - LHS and RHS may have non-dependent types despite being type-dependent
4986// (e.g. unbounded array static members of the current instantiation)
4987// - one may be a dependent-sized array with known element type
4988// - one may be a dependent-typed valid index (enum in current instantiation)
4989//
4990// We *always* return a dependent type, in such cases it is DependentTy.
4991// This avoids creating type-dependent expressions with non-dependent types.
4992// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4994 const ASTContext &Ctx) {
4995 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4996 QualType LTy = LHS->getType(), RTy = RHS->getType();
4997 QualType Result = Ctx.DependentTy;
4998 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4999 if (const PointerType *PT = LTy->getAs<PointerType>())
5000 Result = PT->getPointeeType();
5001 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5002 Result = AT->getElementType();
5003 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5004 if (const PointerType *PT = RTy->getAs<PointerType>())
5005 Result = PT->getPointeeType();
5006 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5007 Result = AT->getElementType();
5008 }
5009 // Ensure we return a dependent type.
5010 return Result->isDependentType() ? Result : Ctx.DependentTy;
5011}
5012
5014 SourceLocation lbLoc,
5015 MultiExprArg ArgExprs,
5016 SourceLocation rbLoc) {
5017
5018 if (base && !base->getType().isNull() &&
5019 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5020 auto *AS = cast<ArraySectionExpr>(base);
5021 if (AS->isOMPArraySection())
5023 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5024 /*Length*/ nullptr,
5025 /*Stride=*/nullptr, rbLoc);
5026
5027 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5028 SourceLocation(), /*Length*/ nullptr,
5029 rbLoc);
5030 }
5031
5032 // Since this might be a postfix expression, get rid of ParenListExprs.
5033 if (isa<ParenListExpr>(base)) {
5035 if (result.isInvalid())
5036 return ExprError();
5037 base = result.get();
5038 }
5039
5040 // Check if base and idx form a MatrixSubscriptExpr.
5041 //
5042 // Helper to check for comma expressions, which are not allowed as indices for
5043 // matrix subscript expressions.
5044 //
5045 // In C++23, we get multiple arguments instead of a comma expression.
5046 auto CheckAndReportCommaError = [&](Expr *E) {
5047 if (ArgExprs.size() > 1 ||
5048 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5049 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5050 << SourceRange(base->getBeginLoc(), rbLoc);
5051 return true;
5052 }
5053 return false;
5054 };
5055 // The matrix subscript operator ([][])is considered a single operator.
5056 // Separating the index expressions by parenthesis is not allowed.
5057 if (base && !base->getType().isNull() &&
5058 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5059 !isa<MatrixSubscriptExpr>(base)) {
5060 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5061 << SourceRange(base->getBeginLoc(), rbLoc);
5062 return ExprError();
5063 }
5064 // If the base is a MatrixSubscriptExpr, try to create a new
5065 // MatrixSubscriptExpr.
5066 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5067 if (matSubscriptE) {
5068 if (CheckAndReportCommaError(ArgExprs.front()))
5069 return ExprError();
5070
5071 assert(matSubscriptE->isIncomplete() &&
5072 "base has to be an incomplete matrix subscript");
5073 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5074 matSubscriptE->getRowIdx(),
5075 ArgExprs.front(), rbLoc);
5076 }
5077 if (base->getType()->isWebAssemblyTableType()) {
5078 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5079 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5080 return ExprError();
5081 }
5082
5083 CheckInvalidBuiltinCountedByRef(base,
5085
5086 // Handle any non-overload placeholder types in the base and index
5087 // expressions. We can't handle overloads here because the other
5088 // operand might be an overloadable type, in which case the overload
5089 // resolution for the operator overload should get the first crack
5090 // at the overload.
5091 bool IsMSPropertySubscript = false;
5092 if (base->getType()->isNonOverloadPlaceholderType()) {
5093 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5094 if (!IsMSPropertySubscript) {
5095 ExprResult result = CheckPlaceholderExpr(base);
5096 if (result.isInvalid())
5097 return ExprError();
5098 base = result.get();
5099 }
5100 }
5101
5102 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5103 if (base->getType()->isMatrixType()) {
5104 if (CheckAndReportCommaError(ArgExprs.front()))
5105 return ExprError();
5106
5107 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5108 rbLoc);
5109 }
5110
5111 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5112 Expr *idx = ArgExprs[0];
5113 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5115 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5116 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5117 << SourceRange(base->getBeginLoc(), rbLoc);
5118 }
5119 }
5120
5121 if (ArgExprs.size() == 1 &&
5122 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5123 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5124 if (result.isInvalid())
5125 return ExprError();
5126 ArgExprs[0] = result.get();
5127 } else {
5128 if (CheckArgsForPlaceholders(ArgExprs))
5129 return ExprError();
5130 }
5131
5132 // Build an unanalyzed expression if either operand is type-dependent.
5133 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5134 (base->isTypeDependent() ||
5136 !isa<PackExpansionExpr>(ArgExprs[0])) {
5137 return new (Context) ArraySubscriptExpr(
5138 base, ArgExprs.front(),
5139 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5140 VK_LValue, OK_Ordinary, rbLoc);
5141 }
5142
5143 // MSDN, property (C++)
5144 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5145 // This attribute can also be used in the declaration of an empty array in a
5146 // class or structure definition. For example:
5147 // __declspec(property(get=GetX, put=PutX)) int x[];
5148 // The above statement indicates that x[] can be used with one or more array
5149 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5150 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5151 if (IsMSPropertySubscript) {
5152 if (ArgExprs.size() > 1) {
5153 Diag(base->getExprLoc(),
5154 diag::err_ms_property_subscript_expects_single_arg);
5155 return ExprError();
5156 }
5157
5158 // Build MS property subscript expression if base is MS property reference
5159 // or MS property subscript.
5160 return new (Context)
5161 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5162 VK_LValue, OK_Ordinary, rbLoc);
5163 }
5164
5165 // Use C++ overloaded-operator rules if either operand has record
5166 // type. The spec says to do this if either type is *overloadable*,
5167 // but enum types can't declare subscript operators or conversion
5168 // operators, so there's nothing interesting for overload resolution
5169 // to do if there aren't any record types involved.
5170 //
5171 // ObjC pointers have their own subscripting logic that is not tied
5172 // to overload resolution and so should not take this path.
5173 //
5174 // Issue a better diagnostic if we tried to pass multiple arguments to
5175 // a builtin subscript operator rather than diagnosing this as a generic
5176 // overload resolution failure.
5177 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5178 !base->getType()->isRecordType() &&
5179 !base->getType()->isObjCObjectPointerType()) {
5180 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5181 << base->getType() << base->getSourceRange();
5182 return ExprError();
5183 }
5184
5186 ((base->getType()->isRecordType() ||
5187 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5188 ArgExprs[0]->getType()->isRecordType())))) {
5189 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5190 }
5191
5192 ExprResult Res =
5193 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5194
5195 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5196 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5197
5198 return Res;
5199}
5200
5203 InitializationKind Kind =
5205 InitializationSequence InitSeq(*this, Entity, Kind, E);
5206 return InitSeq.Perform(*this, Entity, Kind, E);
5207}
5208
5210 Expr *RowIdx,
5211 SourceLocation RBLoc) {
5213 if (BaseR.isInvalid())
5214 return BaseR;
5215 Base = BaseR.get();
5216
5217 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5218 if (RowR.isInvalid())
5219 return RowR;
5220 RowIdx = RowR.get();
5221
5222 // Build an unanalyzed expression if any of the operands is type-dependent.
5223 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5224 return new (Context)
5225 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5226
5227 // Check that IndexExpr is an integer expression. If it is a constant
5228 // expression, check that it is less than Dim (= the number of elements in the
5229 // corresponding dimension).
5230 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5231 bool IsColumnIdx) -> Expr * {
5232 if (!IndexExpr->getType()->isIntegerType() &&
5233 !IndexExpr->isTypeDependent()) {
5234 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5235 << IsColumnIdx;
5236 return nullptr;
5237 }
5238
5239 if (std::optional<llvm::APSInt> Idx =
5240 IndexExpr->getIntegerConstantExpr(Context)) {
5241 if ((*Idx < 0 || *Idx >= Dim)) {
5242 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5243 << IsColumnIdx << Dim;
5244 return nullptr;
5245 }
5246 }
5247
5248 ExprResult ConvExpr = IndexExpr;
5249 assert(!ConvExpr.isInvalid() &&
5250 "should be able to convert any integer type to size type");
5251 return ConvExpr.get();
5252 };
5253
5254 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5255 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5256 if (!RowIdx)
5257 return ExprError();
5258
5259 QualType RowVecQT =
5260 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5261
5262 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5263}
5264
5266 Expr *ColumnIdx,
5267 SourceLocation RBLoc) {
5269 if (BaseR.isInvalid())
5270 return BaseR;
5271 Base = BaseR.get();
5272
5273 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5274 if (RowR.isInvalid())
5275 return RowR;
5276 RowIdx = RowR.get();
5277
5278 if (!ColumnIdx)
5279 return new (Context) MatrixSubscriptExpr(
5280 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5281
5282 // Build an unanalyzed expression if any of the operands is type-dependent.
5283 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5284 ColumnIdx->isTypeDependent())
5285 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5286 Context.DependentTy, RBLoc);
5287
5288 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5289 if (ColumnR.isInvalid())
5290 return ColumnR;
5291 ColumnIdx = ColumnR.get();
5292
5293 // Check that IndexExpr is an integer expression. If it is a constant
5294 // expression, check that it is less than Dim (= the number of elements in the
5295 // corresponding dimension).
5296 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5297 bool IsColumnIdx) -> Expr * {
5298 if (!IndexExpr->getType()->isIntegerType() &&
5299 !IndexExpr->isTypeDependent()) {
5300 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5301 << IsColumnIdx;
5302 return nullptr;
5303 }
5304
5305 if (std::optional<llvm::APSInt> Idx =
5306 IndexExpr->getIntegerConstantExpr(Context)) {
5307 if ((*Idx < 0 || *Idx >= Dim)) {
5308 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5309 << IsColumnIdx << Dim;
5310 return nullptr;
5311 }
5312 }
5313
5314 ExprResult ConvExpr = IndexExpr;
5315 assert(!ConvExpr.isInvalid() &&
5316 "should be able to convert any integer type to size type");
5317 return ConvExpr.get();
5318 };
5319
5320 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5321 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5322 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5323 if (!RowIdx || !ColumnIdx)
5324 return ExprError();
5325
5326 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5327 MTy->getElementType(), RBLoc);
5328}
5329
5330void Sema::CheckAddressOfNoDeref(const Expr *E) {
5331 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5332 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5333
5334 // For expressions like `&(*s).b`, the base is recorded and what should be
5335 // checked.
5336 const MemberExpr *Member = nullptr;
5337 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5338 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5339
5340 LastRecord.PossibleDerefs.erase(StrippedExpr);
5341}
5342
5343void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5345 return;
5346
5347 QualType ResultTy = E->getType();
5348 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5349
5350 // Bail if the element is an array since it is not memory access.
5351 if (isa<ArrayType>(ResultTy))
5352 return;
5353
5354 if (ResultTy->hasAttr(attr::NoDeref)) {
5355 LastRecord.PossibleDerefs.insert(E);
5356 return;
5357 }
5358
5359 // Check if the base type is a pointer to a member access of a struct
5360 // marked with noderef.
5361 const Expr *Base = E->getBase();
5362 QualType BaseTy = Base->getType();
5363 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5364 // Not a pointer access
5365 return;
5366
5367 const MemberExpr *Member = nullptr;
5368 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5369 Member->isArrow())
5370 Base = Member->getBase();
5371
5372 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5373 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5374 LastRecord.PossibleDerefs.insert(E);
5375 }
5376}
5377
5380 Expr *Idx, SourceLocation RLoc) {
5381 Expr *LHSExp = Base;
5382 Expr *RHSExp = Idx;
5383
5386
5387 // Per C++ core issue 1213, the result is an xvalue if either operand is
5388 // a non-lvalue array, and an lvalue otherwise.
5389 if (getLangOpts().CPlusPlus11) {
5390 for (auto *Op : {LHSExp, RHSExp}) {
5391 Op = Op->IgnoreImplicit();
5392 if (Op->getType()->isArrayType() && !Op->isLValue())
5393 VK = VK_XValue;
5394 }
5395 }
5396
5397 // Perform default conversions.
5398 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5400 if (Result.isInvalid())
5401 return ExprError();
5402 LHSExp = Result.get();
5403 }
5405 if (Result.isInvalid())
5406 return ExprError();
5407 RHSExp = Result.get();
5408
5409 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5410
5411 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5412 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5413 // in the subscript position. As a result, we need to derive the array base
5414 // and index from the expression types.
5415 Expr *BaseExpr, *IndexExpr;
5416 QualType ResultType;
5417 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5418 BaseExpr = LHSExp;
5419 IndexExpr = RHSExp;
5420 ResultType =
5422 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5423 BaseExpr = LHSExp;
5424 IndexExpr = RHSExp;
5425 ResultType = PTy->getPointeeType();
5426 } else if (const ObjCObjectPointerType *PTy =
5427 LHSTy->getAs<ObjCObjectPointerType>()) {
5428 BaseExpr = LHSExp;
5429 IndexExpr = RHSExp;
5430
5431 // Use custom logic if this should be the pseudo-object subscript
5432 // expression.
5433 if (!LangOpts.isSubscriptPointerArithmetic())
5434 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5435 nullptr, nullptr);
5436
5437 ResultType = PTy->getPointeeType();
5438 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5439 // Handle the uncommon case of "123[Ptr]".
5440 BaseExpr = RHSExp;
5441 IndexExpr = LHSExp;
5442 ResultType = PTy->getPointeeType();
5443 } else if (const ObjCObjectPointerType *PTy =
5444 RHSTy->getAs<ObjCObjectPointerType>()) {
5445 // Handle the uncommon case of "123[Ptr]".
5446 BaseExpr = RHSExp;
5447 IndexExpr = LHSExp;
5448 ResultType = PTy->getPointeeType();
5449 if (!LangOpts.isSubscriptPointerArithmetic()) {
5450 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5451 << ResultType << BaseExpr->getSourceRange();
5452 return ExprError();
5453 }
5454 } else if (LHSTy->isSubscriptableVectorType()) {
5455 if (LHSTy->isBuiltinType() &&
5456 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5457 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5458 if (BTy->isSVEBool())
5459 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5460 << LHSExp->getSourceRange()
5461 << RHSExp->getSourceRange());
5462 ResultType = BTy->getSveEltType(Context);
5463 } else {
5464 const VectorType *VTy = LHSTy->getAs<VectorType>();
5465 ResultType = VTy->getElementType();
5466 }
5467 BaseExpr = LHSExp; // vectors: V[123]
5468 IndexExpr = RHSExp;
5469 // We apply C++ DR1213 to vector subscripting too.
5470 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5471 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5472 if (Materialized.isInvalid())
5473 return ExprError();
5474 LHSExp = Materialized.get();
5475 }
5476 VK = LHSExp->getValueKind();
5477 if (VK != VK_PRValue)
5478 OK = OK_VectorComponent;
5479
5480 QualType BaseType = BaseExpr->getType();
5481 Qualifiers BaseQuals = BaseType.getQualifiers();
5482 Qualifiers MemberQuals = ResultType.getQualifiers();
5483 Qualifiers Combined = BaseQuals + MemberQuals;
5484 if (Combined != MemberQuals)
5485 ResultType = Context.getQualifiedType(ResultType, Combined);
5486 } else if (LHSTy->isArrayType()) {
5487 // If we see an array that wasn't promoted by
5488 // DefaultFunctionArrayLvalueConversion, it must be an array that
5489 // wasn't promoted because of the C90 rule that doesn't
5490 // allow promoting non-lvalue arrays. Warn, then
5491 // force the promotion here.
5492 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5493 << LHSExp->getSourceRange();
5494 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5495 CK_ArrayToPointerDecay).get();
5496 LHSTy = LHSExp->getType();
5497
5498 BaseExpr = LHSExp;
5499 IndexExpr = RHSExp;
5500 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5501 } else if (RHSTy->isArrayType()) {
5502 // Same as previous, except for 123[f().a] case
5503 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5504 << RHSExp->getSourceRange();
5505 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5506 CK_ArrayToPointerDecay).get();
5507 RHSTy = RHSExp->getType();
5508
5509 BaseExpr = RHSExp;
5510 IndexExpr = LHSExp;
5511 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5512 } else {
5513 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5514 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5515 }
5516 // C99 6.5.2.1p1
5517 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5518 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5519 << IndexExpr->getSourceRange());
5520
5521 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5522 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5523 !IndexExpr->isTypeDependent()) {
5524 std::optional<llvm::APSInt> IntegerContantExpr =
5526 if (!IntegerContantExpr.has_value() ||
5527 IntegerContantExpr.value().isNegative())
5528 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5529 }
5530
5531 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5532 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5533 // type. Note that Functions are not objects, and that (in C99 parlance)
5534 // incomplete types are not object types.
5535 if (ResultType->isFunctionType()) {
5536 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5537 << ResultType << BaseExpr->getSourceRange();
5538 return ExprError();
5539 }
5540
5541 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5542 // GNU extension: subscripting on pointer to void
5543 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5544 << BaseExpr->getSourceRange();
5545
5546 // C forbids expressions of unqualified void type from being l-values.
5547 // See IsCForbiddenLValueType.
5548 if (!ResultType.hasQualifiers())
5549 VK = VK_PRValue;
5550 } else if (!ResultType->isDependentType() &&
5551 !ResultType.isWebAssemblyReferenceType() &&
5553 LLoc, ResultType,
5554 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5555 return ExprError();
5556
5557 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5558 !ResultType.isCForbiddenLValueType());
5559
5561 FunctionScopes.size() > 1) {
5562 if (auto *TT =
5563 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5564 for (auto I = FunctionScopes.rbegin(),
5565 E = std::prev(FunctionScopes.rend());
5566 I != E; ++I) {
5567 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5568 if (CSI == nullptr)
5569 break;
5570 DeclContext *DC = nullptr;
5571 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5572 DC = LSI->CallOperator;
5573 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5574 DC = CRSI->TheCapturedDecl;
5575 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5576 DC = BSI->TheDecl;
5577 if (DC) {
5578 if (DC->containsDecl(TT->getDecl()))
5579 break;
5581 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5582 }
5583 }
5584 }
5585 }
5586
5587 return new (Context)
5588 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5589}
5590
5592 ParmVarDecl *Param, Expr *RewrittenInit,
5593 bool SkipImmediateInvocations) {
5594 if (Param->hasUnparsedDefaultArg()) {
5595 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5596 // If we've already cleared out the location for the default argument,
5597 // that means we're parsing it right now.
5598 if (!UnparsedDefaultArgLocs.count(Param)) {
5599 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5600 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5601 Param->setInvalidDecl();
5602 return true;
5603 }
5604
5605 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5606 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5608 diag::note_default_argument_declared_here);
5609 return true;
5610 }
5611
5612 if (Param->hasUninstantiatedDefaultArg()) {
5613 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5614 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5615 return true;
5616 }
5617
5618 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5619 assert(Init && "default argument but no initializer?");
5620
5621 // If the default expression creates temporaries, we need to
5622 // push them to the current stack of expression temporaries so they'll
5623 // be properly destroyed.
5624 // FIXME: We should really be rebuilding the default argument with new
5625 // bound temporaries; see the comment in PR5810.
5626 // We don't need to do that with block decls, though, because
5627 // blocks in default argument expression can never capture anything.
5628 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5629 // Set the "needs cleanups" bit regardless of whether there are
5630 // any explicit objects.
5631 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5632 // Append all the objects to the cleanup list. Right now, this
5633 // should always be a no-op, because blocks in default argument
5634 // expressions should never be able to capture anything.
5635 assert(!InitWithCleanup->getNumObjects() &&
5636 "default argument expression has capturing blocks?");
5637 }
5638 // C++ [expr.const]p15.1:
5639 // An expression or conversion is in an immediate function context if it is
5640 // potentially evaluated and [...] its innermost enclosing non-block scope
5641 // is a function parameter scope of an immediate function.
5643 *this,
5647 Param);
5648 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5649 SkipImmediateInvocations;
5650 runWithSufficientStackSpace(CallLoc, [&] {
5651 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5652 });
5653 return false;
5654}
5655
5660 }
5661
5662 bool HasImmediateCalls = false;
5663
5664 bool VisitCallExpr(CallExpr *E) override {
5665 if (const FunctionDecl *FD = E->getDirectCallee())
5666 HasImmediateCalls |= FD->isImmediateFunction();
5668 }
5669
5671 if (const FunctionDecl *FD = E->getConstructor())
5672 HasImmediateCalls |= FD->isImmediateFunction();
5674 }
5675
5676 // SourceLocExpr are not immediate invocations
5677 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5678 // need to be rebuilt so that they refer to the correct SourceLocation and
5679 // DeclContext.
5681 HasImmediateCalls = true;
5683 }
5684
5685 // A nested lambda might have parameters with immediate invocations
5686 // in their default arguments.
5687 // The compound statement is not visited (as it does not constitute a
5688 // subexpression).
5689 // FIXME: We should consider visiting and transforming captures
5690 // with init expressions.
5691 bool VisitLambdaExpr(LambdaExpr *E) override {
5692 return VisitCXXMethodDecl(E->getCallOperator());
5693 }
5694
5696 return TraverseStmt(E->getExpr());
5697 }
5698
5700 return TraverseStmt(E->getExpr());
5701 }
5702};
5703
5705 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5708
5709 bool AlwaysRebuild() { return true; }
5710
5711 // Lambda can only have immediate invocations in the default
5712 // args of their parameters, which is transformed upon calling the closure.
5713 // The body is not a subexpression, so we have nothing to do.
5714 // FIXME: Immediate calls in capture initializers should be transformed.
5717
5718 // Make sure we don't rebuild the this pointer as it would
5719 // cause it to incorrectly point it to the outermost class
5720 // in the case of nested struct initialization.
5722
5723 // Rewrite to source location to refer to the context in which they are used.
5725 DeclContext *DC = E->getParentContext();
5726 if (DC == SemaRef.CurContext)
5727 return E;
5728
5729 // FIXME: During instantiation, because the rebuild of defaults arguments
5730 // is not always done in the context of the template instantiator,
5731 // we run the risk of producing a dependent source location
5732 // that would never be rebuilt.
5733 // This usually happens during overload resolution, or in contexts
5734 // where the value of the source location does not matter.
5735 // However, we should find a better way to deal with source location
5736 // of function templates.
5737 if (!SemaRef.CurrentInstantiationScope ||
5738 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5739 DC = SemaRef.CurContext;
5740
5741 return getDerived().RebuildSourceLocExpr(
5742 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5743 }
5744};
5745
5747 FunctionDecl *FD, ParmVarDecl *Param,
5748 Expr *Init) {
5749 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5750
5751 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5752 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5753 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5754 InitializationContext =
5756 if (!InitializationContext.has_value())
5757 InitializationContext.emplace(CallLoc, Param, CurContext);
5758
5759 if (!Init && !Param->hasUnparsedDefaultArg()) {
5760 // Mark that we are replacing a default argument first.
5761 // If we are instantiating a template we won't have to
5762 // retransform immediate calls.
5763 // C++ [expr.const]p15.1:
5764 // An expression or conversion is in an immediate function context if it
5765 // is potentially evaluated and [...] its innermost enclosing non-block
5766 // scope is a function parameter scope of an immediate function.
5768 *this,
5772 Param);
5773
5774 if (Param->hasUninstantiatedDefaultArg()) {
5775 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5776 return ExprError();
5777 }
5778 // CWG2631
5779 // An immediate invocation that is not evaluated where it appears is
5780 // evaluated and checked for whether it is a constant expression at the
5781 // point where the enclosing initializer is used in a function call.
5783 if (!NestedDefaultChecking)
5784 V.TraverseDecl(Param);
5785
5786 // Rewrite the call argument that was created from the corresponding
5787 // parameter's default argument.
5788 if (V.HasImmediateCalls ||
5789 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5790 if (V.HasImmediateCalls)
5791 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5792 CallLoc, Param, CurContext};
5793 // Pass down lifetime extending flag, and collect temporaries in
5794 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5798 ExprResult Res;
5799 runWithSufficientStackSpace(CallLoc, [&] {
5800 Res = Immediate.TransformInitializer(Param->getInit(),
5801 /*NotCopy=*/false);
5802 });
5803 if (Res.isInvalid())
5804 return ExprError();
5805 Res = ConvertParamDefaultArgument(Param, Res.get(),
5806 Res.get()->getBeginLoc());
5807 if (Res.isInvalid())
5808 return ExprError();
5809 Init = Res.get();
5810 }
5811 }
5812
5814 CallLoc, FD, Param, Init,
5815 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5816 return ExprError();
5817
5818 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5819 Init, InitializationContext->Context);
5820}
5821
5823 FieldDecl *Field) {
5824 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5825 return Pattern;
5826 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5827 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5829 ClassPattern->lookup(Field->getDeclName());
5830 auto Rng = llvm::make_filter_range(
5831 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5832 if (Rng.empty())
5833 return nullptr;
5834 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5835 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5836 // && "Duplicated instantiation pattern for field decl");
5837 return cast<FieldDecl>(*Rng.begin());
5838}
5839
5841 assert(Field->hasInClassInitializer());
5842
5843 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5844
5845 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5846
5847 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5848 InitializationContext =
5850 if (!InitializationContext.has_value())
5851 InitializationContext.emplace(Loc, Field, CurContext);
5852
5853 Expr *Init = nullptr;
5854
5855 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5856 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5859
5860 if (!Field->getInClassInitializer()) {
5861 // Maybe we haven't instantiated the in-class initializer. Go check the
5862 // pattern FieldDecl to see if it has one.
5863 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5864 FieldDecl *Pattern =
5866 assert(Pattern && "We must have set the Pattern!");
5867 if (!Pattern->hasInClassInitializer() ||
5868 InstantiateInClassInitializer(Loc, Field, Pattern,
5870 Field->setInvalidDecl();
5871 return ExprError();
5872 }
5873 }
5874 }
5875
5876 // CWG2631
5877 // An immediate invocation that is not evaluated where it appears is
5878 // evaluated and checked for whether it is a constant expression at the
5879 // point where the enclosing initializer is used in a [...] a constructor
5880 // definition, or an aggregate initialization.
5882 if (!NestedDefaultChecking)
5883 V.TraverseDecl(Field);
5884
5885 // CWG1815
5886 // Support lifetime extension of temporary created by aggregate
5887 // initialization using a default member initializer. We should rebuild
5888 // the initializer in a lifetime extension context if the initializer
5889 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5890 // extension code recurses into the default initializer and does lifetime
5891 // extension when warranted.
5892 bool ContainsAnyTemporaries =
5893 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5894 if (Field->getInClassInitializer() &&
5895 !Field->getInClassInitializer()->containsErrors() &&
5896 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5897 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5898 CurContext};
5899 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5900 NestedDefaultChecking;
5901 // Pass down lifetime extending flag, and collect temporaries in
5902 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5906 ExprResult Res;
5908 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5909 /*CXXDirectInit=*/false);
5910 });
5911 if (!Res.isInvalid())
5912 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5913 if (Res.isInvalid()) {
5914 Field->setInvalidDecl();
5915 return ExprError();
5916 }
5917 Init = Res.get();
5918 }
5919
5920 if (Field->getInClassInitializer()) {
5921 Expr *E = Init ? Init : Field->getInClassInitializer();
5922 if (!NestedDefaultChecking)
5924 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5925 });
5928 // C++11 [class.base.init]p7:
5929 // The initialization of each base and member constitutes a
5930 // full-expression.
5931 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5932 if (Res.isInvalid()) {
5933 Field->setInvalidDecl();
5934 return ExprError();
5935 }
5936 Init = Res.get();
5937
5938 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5939 Field, InitializationContext->Context,
5940 Init);
5941 }
5942
5943 // DR1351:
5944 // If the brace-or-equal-initializer of a non-static data member
5945 // invokes a defaulted default constructor of its class or of an
5946 // enclosing class in a potentially evaluated subexpression, the
5947 // program is ill-formed.
5948 //
5949 // This resolution is unworkable: the exception specification of the
5950 // default constructor can be needed in an unevaluated context, in
5951 // particular, in the operand of a noexcept-expression, and we can be
5952 // unable to compute an exception specification for an enclosed class.
5953 //
5954 // Any attempt to resolve the exception specification of a defaulted default
5955 // constructor before the initializer is lexically complete will ultimately
5956 // come here at which point we can diagnose it.
5957 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5958 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5959 << OutermostClass << Field;
5960 Diag(Field->getEndLoc(),
5961 diag::note_default_member_initializer_not_yet_parsed);
5962 // Recover by marking the field invalid, unless we're in a SFINAE context.
5963 if (!isSFINAEContext())
5964 Field->setInvalidDecl();
5965 return ExprError();
5966}
5967
5969 const FunctionProtoType *Proto,
5970 Expr *Fn) {
5971 if (Proto && Proto->isVariadic()) {
5972 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5974 else if (Fn && Fn->getType()->isBlockPointerType())
5976 else if (FDecl) {
5977 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5978 if (Method->isInstance())
5980 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5983 }
5985}
5986
5987namespace {
5988class FunctionCallCCC final : public FunctionCallFilterCCC {
5989public:
5990 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5991 unsigned NumArgs, MemberExpr *ME)
5992 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5993 FunctionName(FuncName) {}
5994
5995 bool ValidateCandidate(const TypoCorrection &candidate) override {
5996 if (!candidate.getCorrectionSpecifier() ||
5997 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5998 return false;
5999 }
6000
6002 }
6003
6004 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6005 return std::make_unique<FunctionCallCCC>(*this);
6006 }
6007
6008private:
6009 const IdentifierInfo *const FunctionName;
6010};
6011}
6012
6014 FunctionDecl *FDecl,
6015 ArrayRef<Expr *> Args) {
6016 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6017 DeclarationName FuncName = FDecl->getDeclName();
6018 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6019
6020 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6021 if (TypoCorrection Corrected = S.CorrectTypo(
6023 S.getScopeForContext(S.CurContext), nullptr, CCC,
6025 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6026 if (Corrected.isOverloaded()) {
6029 for (NamedDecl *CD : Corrected) {
6030 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6032 OCS);
6033 }
6034 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6035 case OR_Success:
6036 ND = Best->FoundDecl;
6037 Corrected.setCorrectionDecl(ND);
6038 break;
6039 default:
6040 break;
6041 }
6042 }
6043 ND = ND->getUnderlyingDecl();
6045 return Corrected;
6046 }
6047 }
6048 return TypoCorrection();
6049}
6050
6051// [C++26][[expr.unary.op]/p4
6052// A pointer to member is only formed when an explicit &
6053// is used and its operand is a qualified-id not enclosed in parentheses.
6055 if (!isa<ParenExpr>(Fn))
6056 return false;
6057
6058 Fn = Fn->IgnoreParens();
6059
6060 auto *UO = dyn_cast<UnaryOperator>(Fn);
6061 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6062 return false;
6063 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6064 return DRE->hasQualifier();
6065 }
6066 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6067 return bool(OVL->getQualifier());
6068 return false;
6069}
6070
6071bool
6073 FunctionDecl *FDecl,
6074 const FunctionProtoType *Proto,
6075 ArrayRef<Expr *> Args,
6076 SourceLocation RParenLoc,
6077 bool IsExecConfig) {
6078 // Bail out early if calling a builtin with custom typechecking.
6079 if (FDecl)
6080 if (unsigned ID = FDecl->getBuiltinID())
6081 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6082 return false;
6083
6084 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6085 // assignment, to the types of the corresponding parameter, ...
6086
6087 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6088 bool HasExplicitObjectParameter =
6089 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6090 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6091 unsigned NumParams = Proto->getNumParams();
6092 bool Invalid = false;
6093 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6094 unsigned FnKind = Fn->getType()->isBlockPointerType()
6095 ? 1 /* block */
6096 : (IsExecConfig ? 3 /* kernel function (exec config) */
6097 : 0 /* function */);
6098
6099 // If too few arguments are available (and we don't have default
6100 // arguments for the remaining parameters), don't make the call.
6101 if (Args.size() < NumParams) {
6102 if (Args.size() < MinArgs) {
6103 TypoCorrection TC;
6104 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6105 unsigned diag_id =
6106 MinArgs == NumParams && !Proto->isVariadic()
6107 ? diag::err_typecheck_call_too_few_args_suggest
6108 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6110 TC, PDiag(diag_id)
6111 << FnKind << MinArgs - ExplicitObjectParameterOffset
6112 << static_cast<unsigned>(Args.size()) -
6113 ExplicitObjectParameterOffset
6114 << HasExplicitObjectParameter << TC.getCorrectionRange());
6115 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6116 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6117 ->getDeclName())
6118 Diag(RParenLoc,
6119 MinArgs == NumParams && !Proto->isVariadic()
6120 ? diag::err_typecheck_call_too_few_args_one
6121 : diag::err_typecheck_call_too_few_args_at_least_one)
6122 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6123 << HasExplicitObjectParameter << Fn->getSourceRange();
6124 else
6125 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6126 ? diag::err_typecheck_call_too_few_args
6127 : diag::err_typecheck_call_too_few_args_at_least)
6128 << FnKind << MinArgs - ExplicitObjectParameterOffset
6129 << static_cast<unsigned>(Args.size()) -
6130 ExplicitObjectParameterOffset
6131 << HasExplicitObjectParameter << Fn->getSourceRange();
6132
6133 // Emit the location of the prototype.
6134 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6135 Diag(FDecl->getLocation(), diag::note_callee_decl)
6136 << FDecl << FDecl->getParametersSourceRange();
6137
6138 return true;
6139 }
6140 // We reserve space for the default arguments when we create
6141 // the call expression, before calling ConvertArgumentsForCall.
6142 assert((Call->getNumArgs() == NumParams) &&
6143 "We should have reserved space for the default arguments before!");
6144 }
6145
6146 // If too many are passed and not variadic, error on the extras and drop
6147 // them.
6148 if (Args.size() > NumParams) {
6149 if (!Proto->isVariadic()) {
6150 TypoCorrection TC;
6151 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6152 unsigned diag_id =
6153 MinArgs == NumParams && !Proto->isVariadic()
6154 ? diag::err_typecheck_call_too_many_args_suggest
6155 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6157 TC, PDiag(diag_id)
6158 << FnKind << NumParams - ExplicitObjectParameterOffset
6159 << static_cast<unsigned>(Args.size()) -
6160 ExplicitObjectParameterOffset
6161 << HasExplicitObjectParameter << TC.getCorrectionRange());
6162 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6163 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6164 ->getDeclName())
6165 Diag(Args[NumParams]->getBeginLoc(),
6166 MinArgs == NumParams
6167 ? diag::err_typecheck_call_too_many_args_one
6168 : diag::err_typecheck_call_too_many_args_at_most_one)
6169 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6170 << static_cast<unsigned>(Args.size()) -
6171 ExplicitObjectParameterOffset
6172 << HasExplicitObjectParameter << Fn->getSourceRange()
6173 << SourceRange(Args[NumParams]->getBeginLoc(),
6174 Args.back()->getEndLoc());
6175 else
6176 Diag(Args[NumParams]->getBeginLoc(),
6177 MinArgs == NumParams
6178 ? diag::err_typecheck_call_too_many_args
6179 : diag::err_typecheck_call_too_many_args_at_most)
6180 << FnKind << NumParams - ExplicitObjectParameterOffset
6181 << static_cast<unsigned>(Args.size()) -
6182 ExplicitObjectParameterOffset
6183 << HasExplicitObjectParameter << Fn->getSourceRange()
6184 << SourceRange(Args[NumParams]->getBeginLoc(),
6185 Args.back()->getEndLoc());
6186
6187 // Emit the location of the prototype.
6188 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6189 Diag(FDecl->getLocation(), diag::note_callee_decl)
6190 << FDecl << FDecl->getParametersSourceRange();
6191
6192 // This deletes the extra arguments.
6193 Call->shrinkNumArgs(NumParams);
6194 return true;
6195 }
6196 }
6197 SmallVector<Expr *, 8> AllArgs;
6198 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6199
6200 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6201 AllArgs, CallType);
6202 if (Invalid)
6203 return true;
6204 unsigned TotalNumArgs = AllArgs.size();
6205 for (unsigned i = 0; i < TotalNumArgs; ++i)
6206 Call->setArg(i, AllArgs[i]);
6207
6208 Call->computeDependence();
6209 return false;
6210}
6211
6213 const FunctionProtoType *Proto,
6214 unsigned FirstParam, ArrayRef<Expr *> Args,
6215 SmallVectorImpl<Expr *> &AllArgs,
6216 VariadicCallType CallType, bool AllowExplicit,
6217 bool IsListInitialization) {
6218 unsigned NumParams = Proto->getNumParams();
6219 bool Invalid = false;
6220 size_t ArgIx = 0;
6221 // Continue to check argument types (even if we have too few/many args).
6222 for (unsigned i = FirstParam; i < NumParams; i++) {
6223 QualType ProtoArgType = Proto->getParamType(i);
6224
6225 Expr *Arg;
6226 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6227 if (ArgIx < Args.size()) {
6228 Arg = Args[ArgIx++];
6229
6230 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6231 diag::err_call_incomplete_argument, Arg))
6232 return true;
6233
6234 // Strip the unbridged-cast placeholder expression off, if applicable.
6235 bool CFAudited = false;
6236 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6237 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6238 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6239 Arg = ObjC().stripARCUnbridgedCast(Arg);
6240 else if (getLangOpts().ObjCAutoRefCount &&
6241 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6242 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6243 CFAudited = true;
6244
6245 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6246 ProtoArgType->isBlockPointerType())
6247 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6248 BE->getBlockDecl()->setDoesNotEscape();
6249 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6251 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6252 if (ArgExpr.isInvalid())
6253 return true;
6254 Arg = ArgExpr.getAs<Expr>();
6255 }
6256
6257 InitializedEntity Entity =
6259 ProtoArgType)
6261 Context, ProtoArgType, Proto->isParamConsumed(i));
6262
6263 // Remember that parameter belongs to a CF audited API.
6264 if (CFAudited)
6265 Entity.setParameterCFAudited();
6266
6267 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6268 // function boundaries is a common oversight.
6269 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6270 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6271 bool isPedantic =
6272 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6273 Diag(Arg->getExprLoc(),
6274 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6275 : diag::warn_obt_discarded_at_function_boundary)
6276 << Arg->getType() << ProtoArgType;
6277 }
6278
6280 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6281 if (ArgE.isInvalid())
6282 return true;
6283
6284 Arg = ArgE.getAs<Expr>();
6285 } else {
6286 assert(Param && "can't use default arguments without a known callee");
6287
6288 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6289 if (ArgExpr.isInvalid())
6290 return true;
6291
6292 Arg = ArgExpr.getAs<Expr>();
6293 }
6294
6295 // Check for array bounds violations for each argument to the call. This
6296 // check only triggers warnings when the argument isn't a more complex Expr
6297 // with its own checking, such as a BinaryOperator.
6298 CheckArrayAccess(Arg);
6299
6300 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6301 CheckStaticArrayArgument(CallLoc, Param, Arg);
6302
6303 AllArgs.push_back(Arg);
6304 }
6305
6306 // If this is a variadic call, handle args passed through "...".
6307 if (CallType != VariadicCallType::DoesNotApply) {
6308 // Assume that extern "C" functions with variadic arguments that
6309 // return __unknown_anytype aren't *really* variadic.
6310 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6311 FDecl->isExternC()) {
6312 for (Expr *A : Args.slice(ArgIx)) {
6313 QualType paramType; // ignored
6314 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6315 Invalid |= arg.isInvalid();
6316 AllArgs.push_back(arg.get());
6317 }
6318
6319 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6320 } else {
6321 for (Expr *A : Args.slice(ArgIx)) {
6322 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6323 Invalid |= Arg.isInvalid();
6324 AllArgs.push_back(Arg.get());
6325 }
6326 }
6327
6328 // Check for array bounds violations.
6329 for (Expr *A : Args.slice(ArgIx))
6330 CheckArrayAccess(A);
6331 }
6332 return Invalid;
6333}
6334
6336 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6337 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6338 TL = DTL.getOriginalLoc();
6339 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6340 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6341 << ATL.getLocalSourceRange();
6342}
6343
6344void
6346 ParmVarDecl *Param,
6347 const Expr *ArgExpr) {
6348 // Static array parameters are not supported in C++.
6349 if (!Param || getLangOpts().CPlusPlus)
6350 return;
6351
6352 QualType OrigTy = Param->getOriginalType();
6353
6354 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6355 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6356 return;
6357
6358 if (ArgExpr->isNullPointerConstant(Context,
6360 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6361 DiagnoseCalleeStaticArrayParam(*this, Param);
6362 return;
6363 }
6364
6365 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6366 if (!CAT)
6367 return;
6368
6369 const ConstantArrayType *ArgCAT =
6370 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6371 if (!ArgCAT)
6372 return;
6373
6374 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6375 ArgCAT->getElementType())) {
6376 if (ArgCAT->getSize().ult(CAT->getSize())) {
6377 Diag(CallLoc, diag::warn_static_array_too_small)
6378 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6379 << (unsigned)CAT->getZExtSize() << 0;
6380 DiagnoseCalleeStaticArrayParam(*this, Param);
6381 }
6382 return;
6383 }
6384
6385 std::optional<CharUnits> ArgSize =
6387 std::optional<CharUnits> ParmSize =
6389 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6390 Diag(CallLoc, diag::warn_static_array_too_small)
6391 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6392 << (unsigned)ParmSize->getQuantity() << 1;
6393 DiagnoseCalleeStaticArrayParam(*this, Param);
6394 }
6395}
6396
6397/// Given a function expression of unknown-any type, try to rebuild it
6398/// to have a function type.
6400
6401/// Is the given type a placeholder that we need to lower out
6402/// immediately during argument processing?
6404 // Placeholders are never sugared.
6405 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6406 if (!placeholder) return false;
6407
6408 switch (placeholder->getKind()) {
6409 // Ignore all the non-placeholder types.
6410#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6411 case BuiltinType::Id:
6412#include "clang/Basic/OpenCLImageTypes.def"
6413#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6414 case BuiltinType::Id:
6415#include "clang/Basic/OpenCLExtensionTypes.def"
6416 // In practice we'll never use this, since all SVE types are sugared
6417 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6418#define SVE_TYPE(Name, Id, SingletonId) \
6419 case BuiltinType::Id:
6420#include "clang/Basic/AArch64ACLETypes.def"
6421#define PPC_VECTOR_TYPE(Name, Id, Size) \
6422 case BuiltinType::Id:
6423#include "clang/Basic/PPCTypes.def"
6424#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6425#include "clang/Basic/RISCVVTypes.def"
6426#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6427#include "clang/Basic/WebAssemblyReferenceTypes.def"
6428#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6429#include "clang/Basic/AMDGPUTypes.def"
6430#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6431#include "clang/Basic/HLSLIntangibleTypes.def"
6432#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6433#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6434#include "clang/AST/BuiltinTypes.def"
6435 return false;
6436
6437 case BuiltinType::UnresolvedTemplate:
6438 // We cannot lower out overload sets; they might validly be resolved
6439 // by the call machinery.
6440 case BuiltinType::Overload:
6441 return false;
6442
6443 // Unbridged casts in ARC can be handled in some call positions and
6444 // should be left in place.
6445 case BuiltinType::ARCUnbridgedCast:
6446 return false;
6447
6448 // Pseudo-objects should be converted as soon as possible.
6449 case BuiltinType::PseudoObject:
6450 return true;
6451
6452 // The debugger mode could theoretically but currently does not try
6453 // to resolve unknown-typed arguments based on known parameter types.
6454 case BuiltinType::UnknownAny:
6455 return true;
6456
6457 // These are always invalid as call arguments and should be reported.
6458 case BuiltinType::BoundMember:
6459 case BuiltinType::BuiltinFn:
6460 case BuiltinType::IncompleteMatrixIdx:
6461 case BuiltinType::ArraySection:
6462 case BuiltinType::OMPArrayShaping:
6463 case BuiltinType::OMPIterator:
6464 return true;
6465
6466 }
6467 llvm_unreachable("bad builtin type kind");
6468}
6469
6471 // Apply this processing to all the arguments at once instead of
6472 // dying at the first failure.
6473 bool hasInvalid = false;
6474 for (size_t i = 0, e = args.size(); i != e; i++) {
6475 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6476 ExprResult result = CheckPlaceholderExpr(args[i]);
6477 if (result.isInvalid()) hasInvalid = true;
6478 else args[i] = result.get();
6479 }
6480 }
6481 return hasInvalid;
6482}
6483
6484/// If a builtin function has a pointer argument with no explicit address
6485/// space, then it should be able to accept a pointer to any address
6486/// space as input. In order to do this, we need to replace the
6487/// standard builtin declaration with one that uses the same address space
6488/// as the call.
6489///
6490/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6491/// it does not contain any pointer arguments without
6492/// an address space qualifer. Otherwise the rewritten
6493/// FunctionDecl is returned.
6494/// TODO: Handle pointer return types.
6496 FunctionDecl *FDecl,
6497 MultiExprArg ArgExprs) {
6498
6499 QualType DeclType = FDecl->getType();
6500 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6501
6502 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6503 ArgExprs.size() < FT->getNumParams())
6504 return nullptr;
6505
6506 bool NeedsNewDecl = false;
6507 unsigned i = 0;
6508 SmallVector<QualType, 8> OverloadParams;
6509
6510 {
6511 // The lvalue conversions in this loop are only for type resolution and
6512 // don't actually occur.
6515 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6516
6517 for (QualType ParamType : FT->param_types()) {
6518
6519 // Convert array arguments to pointer to simplify type lookup.
6520 ExprResult ArgRes =
6522 if (ArgRes.isInvalid())
6523 return nullptr;
6524 Expr *Arg = ArgRes.get();
6525 QualType ArgType = Arg->getType();
6526 if (!ParamType->isPointerType() ||
6527 ParamType->getPointeeType().hasAddressSpace() ||
6528 !ArgType->isPointerType() ||
6529 !ArgType->getPointeeType().hasAddressSpace() ||
6530 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6531 OverloadParams.push_back(ParamType);
6532 continue;
6533 }
6534
6535 QualType PointeeType = ParamType->getPointeeType();
6536 NeedsNewDecl = true;
6537 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6538
6539 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6540 OverloadParams.push_back(Context.getPointerType(PointeeType));
6541 }
6542 }
6543
6544 if (!NeedsNewDecl)
6545 return nullptr;
6546
6548 EPI.Variadic = FT->isVariadic();
6549 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6550 OverloadParams, EPI);
6551 DeclContext *Parent = FDecl->getParent();
6552 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6553 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6554 FDecl->getIdentifier(), OverloadTy,
6555 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6556 false,
6557 /*hasPrototype=*/true);
6559 FT = cast<FunctionProtoType>(OverloadTy);
6560 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6561 QualType ParamType = FT->getParamType(i);
6562 ParmVarDecl *Parm =
6563 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6564 SourceLocation(), nullptr, ParamType,
6565 /*TInfo=*/nullptr, SC_None, nullptr);
6566 Parm->setScopeInfo(0, i);
6567 Params.push_back(Parm);
6568 }
6569 OverloadDecl->setParams(Params);
6570 // We cannot merge host/device attributes of redeclarations. They have to
6571 // be consistent when created.
6572 if (Sema->LangOpts.CUDA) {
6573 if (FDecl->hasAttr<CUDAHostAttr>())
6574 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6575 if (FDecl->hasAttr<CUDADeviceAttr>())
6576 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6577 }
6578 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6579 return OverloadDecl;
6580}
6581
6582static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6583 FunctionDecl *Callee,
6584 MultiExprArg ArgExprs) {
6585 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6586 // similar attributes) really don't like it when functions are called with an
6587 // invalid number of args.
6588 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6589 /*PartialOverloading=*/false) &&
6590 !Callee->isVariadic())
6591 return;
6592 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6593 return;
6594
6595 if (const EnableIfAttr *Attr =
6596 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6597 S.Diag(Fn->getBeginLoc(),
6598 isa<CXXMethodDecl>(Callee)
6599 ? diag::err_ovl_no_viable_member_function_in_call
6600 : diag::err_ovl_no_viable_function_in_call)
6601 << Callee << Callee->getSourceRange();
6602 S.Diag(Callee->getLocation(),
6603 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6604 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6605 return;
6606 }
6607}
6608
6610 const UnresolvedMemberExpr *const UME, Sema &S) {
6611
6612 const auto GetFunctionLevelDCIfCXXClass =
6613 [](Sema &S) -> const CXXRecordDecl * {
6614 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6615 if (!DC || !DC->getParent())
6616 return nullptr;
6617
6618 // If the call to some member function was made from within a member
6619 // function body 'M' return return 'M's parent.
6620 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6621 return MD->getParent()->getCanonicalDecl();
6622 // else the call was made from within a default member initializer of a
6623 // class, so return the class.
6624 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6625 return RD->getCanonicalDecl();
6626 return nullptr;
6627 };
6628 // If our DeclContext is neither a member function nor a class (in the
6629 // case of a lambda in a default member initializer), we can't have an
6630 // enclosing 'this'.
6631
6632 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6633 if (!CurParentClass)
6634 return false;
6635
6636 // The naming class for implicit member functions call is the class in which
6637 // name lookup starts.
6638 const CXXRecordDecl *const NamingClass =
6640 assert(NamingClass && "Must have naming class even for implicit access");
6641
6642 // If the unresolved member functions were found in a 'naming class' that is
6643 // related (either the same or derived from) to the class that contains the
6644 // member function that itself contained the implicit member access.
6645
6646 return CurParentClass == NamingClass ||
6647 CurParentClass->isDerivedFrom(NamingClass);
6648}
6649
6650static void
6652 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6653
6654 if (!UME)
6655 return;
6656
6657 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6658 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6659 // already been captured, or if this is an implicit member function call (if
6660 // it isn't, an attempt to capture 'this' should already have been made).
6661 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6662 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6663 return;
6664
6665 // Check if the naming class in which the unresolved members were found is
6666 // related (same as or is a base of) to the enclosing class.
6667
6669 return;
6670
6671
6672 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6673 // If the enclosing function is not dependent, then this lambda is
6674 // capture ready, so if we can capture this, do so.
6675 if (!EnclosingFunctionCtx->isDependentContext()) {
6676 // If the current lambda and all enclosing lambdas can capture 'this' -
6677 // then go ahead and capture 'this' (since our unresolved overload set
6678 // contains at least one non-static member function).
6679 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6680 S.CheckCXXThisCapture(CallLoc);
6681 } else if (S.CurContext->isDependentContext()) {
6682 // ... since this is an implicit member reference, that might potentially
6683 // involve a 'this' capture, mark 'this' for potential capture in
6684 // enclosing lambdas.
6685 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6686 CurLSI->addPotentialThisCapture(CallLoc);
6687 }
6688}
6689
6690// Once a call is fully resolved, warn for unqualified calls to specific
6691// C++ standard functions, like move and forward.
6693 const CallExpr *Call) {
6694 // We are only checking unary move and forward so exit early here.
6695 if (Call->getNumArgs() != 1)
6696 return;
6697
6698 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6699 if (!E || isa<UnresolvedLookupExpr>(E))
6700 return;
6701 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6702 if (!DRE || !DRE->getLocation().isValid())
6703 return;
6704
6705 if (DRE->getQualifier())
6706 return;
6707
6708 const FunctionDecl *FD = Call->getDirectCallee();
6709 if (!FD)
6710 return;
6711
6712 // Only warn for some functions deemed more frequent or problematic.
6713 unsigned BuiltinID = FD->getBuiltinID();
6714 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6715 return;
6716
6717 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6719 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6720}
6721
6723 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6724 Expr *ExecConfig) {
6726 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6727 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6728 if (Call.isInvalid())
6729 return Call;
6730
6731 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6732 // language modes.
6733 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6734 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6735 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6736 << ULE->getName();
6737 }
6738
6739 if (LangOpts.OpenMP)
6740 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6741 ExecConfig);
6742 if (LangOpts.CPlusPlus) {
6743 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6745
6746 // If we previously found that the id-expression of this call refers to a
6747 // consteval function but the call is dependent, we should not treat is an
6748 // an invalid immediate call.
6749 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6750 DRE && Call.get()->isValueDependent()) {
6752 }
6753 }
6754 return Call;
6755}
6756
6757// Any type that could be used to form a callable expression
6758static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6759 QualType T = E->getType();
6760 if (T->isDependentType())
6761 return true;
6762
6763 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6764 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6765 T->isFunctionType() || T->isFunctionReferenceType() ||
6766 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6767 T->isBlockPointerType() || T->isRecordType())
6768 return true;
6769
6772}
6773
6775 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6776 Expr *ExecConfig, bool IsExecConfig,
6777 bool AllowRecovery) {
6778 // Since this might be a postfix expression, get rid of ParenListExprs.
6780 if (Result.isInvalid()) return ExprError();
6781 Fn = Result.get();
6782
6783 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6784 // later, when we check boolean conditions, for now we merely forward it
6785 // without any additional checking.
6786 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6787 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6788 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6789
6790 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6791 QualType FnPtrTy = Context.getPointerType(FD->getType());
6792 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6793 return CallExpr::Create(
6794 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6796 }
6797 }
6798
6799 if (CheckArgsForPlaceholders(ArgExprs))
6800 return ExprError();
6801
6802 // The result of __builtin_counted_by_ref cannot be used as a function
6803 // argument. It allows leaking and modification of bounds safety information.
6804 for (const Expr *Arg : ArgExprs)
6805 if (CheckInvalidBuiltinCountedByRef(Arg,
6807 return ExprError();
6808
6809 if (getLangOpts().CPlusPlus) {
6810 // If this is a pseudo-destructor expression, build the call immediately.
6812 if (!ArgExprs.empty()) {
6813 // Pseudo-destructor calls should not have any arguments.
6814 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6816 SourceRange(ArgExprs.front()->getBeginLoc(),
6817 ArgExprs.back()->getEndLoc()));
6818 }
6819
6820 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6821 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6822 }
6823 if (Fn->getType() == Context.PseudoObjectTy) {
6824 ExprResult result = CheckPlaceholderExpr(Fn);
6825 if (result.isInvalid()) return ExprError();
6826 Fn = result.get();
6827 }
6828
6829 // Determine whether this is a dependent call inside a C++ template,
6830 // in which case we won't do any semantic analysis now.
6831 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6832 if (ExecConfig) {
6834 cast<CallExpr>(ExecConfig), ArgExprs,
6835 Context.DependentTy, VK_PRValue,
6836 RParenLoc, CurFPFeatureOverrides());
6837 } else {
6838
6840 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6841 Fn->getBeginLoc());
6842
6843 // If the type of the function itself is not dependent
6844 // check that it is a reasonable as a function, as type deduction
6845 // later assume the CallExpr has a sensible TYPE.
6846 if (!MayBeFunctionType(Context, Fn))
6847 return ExprError(
6848 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6849 << Fn->getType() << Fn->getSourceRange());
6850
6851 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6852 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6853 }
6854 }
6855
6856 // Determine whether this is a call to an object (C++ [over.call.object]).
6857 if (Fn->getType()->isRecordType())
6858 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6859 RParenLoc);
6860
6861 if (Fn->getType() == Context.UnknownAnyTy) {
6862 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6863 if (result.isInvalid()) return ExprError();
6864 Fn = result.get();
6865 }
6866
6867 if (Fn->getType() == Context.BoundMemberTy) {
6868 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6869 RParenLoc, ExecConfig, IsExecConfig,
6870 AllowRecovery);
6871 }
6872 }
6873
6874 // Check for overloaded calls. This can happen even in C due to extensions.
6875 if (Fn->getType() == Context.OverloadTy) {
6877
6878 // We aren't supposed to apply this logic if there's an '&' involved.
6881 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6882 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6883 OverloadExpr *ovl = find.Expression;
6884 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6886 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6887 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6888 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6889 RParenLoc, ExecConfig, IsExecConfig,
6890 AllowRecovery);
6891 }
6892 }
6893
6894 // If we're directly calling a function, get the appropriate declaration.
6895 if (Fn->getType() == Context.UnknownAnyTy) {
6896 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6897 if (result.isInvalid()) return ExprError();
6898 Fn = result.get();
6899 }
6900
6901 Expr *NakedFn = Fn->IgnoreParens();
6902
6903 bool CallingNDeclIndirectly = false;
6904 NamedDecl *NDecl = nullptr;
6905 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6906 if (UnOp->getOpcode() == UO_AddrOf) {
6907 CallingNDeclIndirectly = true;
6908 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6909 }
6910 }
6911
6912 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6913 NDecl = DRE->getDecl();
6914
6915 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6916 if (FDecl && FDecl->getBuiltinID()) {
6917 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6918 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6919 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
6920 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
6922 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6923 }
6924 }
6925
6926 // Rewrite the function decl for this builtin by replacing parameters
6927 // with no explicit address space with the address space of the arguments
6928 // in ArgExprs.
6929 if ((FDecl =
6930 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6931 NDecl = FDecl;
6933 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6934 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6935 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
6936 }
6937 }
6938 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6939 NDecl = ME->getMemberDecl();
6940
6941 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6942 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6943 FD, /*Complain=*/true, Fn->getBeginLoc()))
6944 return ExprError();
6945
6946 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6947
6948 // If this expression is a call to a builtin function in HIP compilation,
6949 // allow a pointer-type argument to default address space to be passed as a
6950 // pointer-type parameter to a non-default address space. If Arg is declared
6951 // in the default address space and Param is declared in a non-default
6952 // address space, perform an implicit address space cast to the parameter
6953 // type.
6954 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6955 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6956 ++Idx) {
6957 ParmVarDecl *Param = FD->getParamDecl(Idx);
6958 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6959 !ArgExprs[Idx]->getType()->isPointerType())
6960 continue;
6961
6962 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6963 auto ArgTy = ArgExprs[Idx]->getType();
6964 auto ArgPtTy = ArgTy->getPointeeType();
6965 auto ArgAS = ArgPtTy.getAddressSpace();
6966
6967 // Add address space cast if target address spaces are different
6968 bool NeedImplicitASC =
6969 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6970 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6971 // or from specific AS which has target AS matching that of Param.
6973 if (!NeedImplicitASC)
6974 continue;
6975
6976 // First, ensure that the Arg is an RValue.
6977 if (ArgExprs[Idx]->isGLValue()) {
6978 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
6979 if (Res.isInvalid())
6980 return ExprError();
6981 ArgExprs[Idx] = Res.get();
6982 }
6983
6984 // Construct a new arg type with address space of Param
6985 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6986 ArgPtQuals.setAddressSpace(ParamAS);
6987 auto NewArgPtTy =
6988 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6989 auto NewArgTy =
6990 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6991 ArgTy.getQualifiers());
6992
6993 // Finally perform an implicit address space cast
6994 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6995 CK_AddressSpaceConversion)
6996 .get();
6997 }
6998 }
6999 }
7000
7001 if (Context.isDependenceAllowed() &&
7002 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7003 assert(!getLangOpts().CPlusPlus);
7004 assert((Fn->containsErrors() ||
7005 llvm::any_of(ArgExprs,
7006 [](clang::Expr *E) { return E->containsErrors(); })) &&
7007 "should only occur in error-recovery path.");
7008 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7009 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7010 }
7011 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7012 ExecConfig, IsExecConfig);
7013}
7014
7016 MultiExprArg CallArgs) {
7017 std::string Name = Context.BuiltinInfo.getName(Id);
7018 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7020 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7021
7022 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7023 assert(BuiltInDecl && "failed to find builtin declaration");
7024
7025 ExprResult DeclRef =
7026 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7027 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7028
7030 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7031
7032 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7033 return Call.get();
7034}
7035
7037 SourceLocation BuiltinLoc,
7038 SourceLocation RParenLoc) {
7039 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7040 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7041}
7042
7044 SourceLocation BuiltinLoc,
7045 SourceLocation RParenLoc) {
7048 QualType SrcTy = E->getType();
7049 if (!SrcTy->isDependentType() &&
7050 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7051 return ExprError(
7052 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7053 << DestTy << SrcTy << E->getSourceRange());
7054 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7055}
7056
7058 SourceLocation BuiltinLoc,
7059 SourceLocation RParenLoc) {
7060 TypeSourceInfo *TInfo;
7061 GetTypeFromParser(ParsedDestTy, &TInfo);
7062 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7063}
7064
7066 SourceLocation LParenLoc,
7067 ArrayRef<Expr *> Args,
7068 SourceLocation RParenLoc, Expr *Config,
7069 bool IsExecConfig, ADLCallKind UsesADL) {
7070 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7071 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7072
7073 auto IsSJLJ = [&] {
7074 switch (BuiltinID) {
7075 case Builtin::BI__builtin_longjmp:
7076 case Builtin::BI__builtin_setjmp:
7077 case Builtin::BI__sigsetjmp:
7078 case Builtin::BI_longjmp:
7079 case Builtin::BI_setjmp:
7080 case Builtin::BIlongjmp:
7081 case Builtin::BIsetjmp:
7082 case Builtin::BIsiglongjmp:
7083 case Builtin::BIsigsetjmp:
7084 return true;
7085 default:
7086 return false;
7087 }
7088 };
7089
7090 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7091 if (!CurrentDefer.empty() && IsSJLJ()) {
7092 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7093 // for more than just blocks (e.g. lambdas, nested classes...).
7094 Scope *DeferParent = CurrentDefer.back().first;
7095 Scope *Block = CurScope->getBlockParent();
7096 if (DeferParent->Contains(*CurScope) &&
7097 (!Block || !DeferParent->Contains(*Block)))
7098 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7099 }
7100
7101 // Functions with 'interrupt' attribute cannot be called directly.
7102 if (FDecl) {
7103 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7104 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7105 return ExprError();
7106 }
7107 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7108 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7109 return ExprError();
7110 }
7111 }
7112
7113 // X86 interrupt handlers may only call routines with attribute
7114 // no_caller_saved_registers since there is no efficient way to
7115 // save and restore the non-GPR state.
7116 if (auto *Caller = getCurFunctionDecl()) {
7117 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7118 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7119 const TargetInfo &TI = Context.getTargetInfo();
7120 bool HasNonGPRRegisters =
7121 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7122 if (HasNonGPRRegisters &&
7123 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7124 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7125 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7126 if (FDecl)
7127 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7128 }
7129 }
7130 }
7131
7132 // Extract the return type from the builtin function pointer type.
7133 QualType ResultTy;
7134 if (BuiltinID)
7135 ResultTy = FDecl->getCallResultType();
7136 else
7137 ResultTy = Context.BoolTy;
7138
7139 // Promote the function operand.
7140 // We special-case function promotion here because we only allow promoting
7141 // builtin functions to function pointers in the callee of a call.
7143 if (BuiltinID &&
7144 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7145 // FIXME Several builtins still have setType in
7146 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7147 // Builtins.td to ensure they are correct before removing setType calls.
7148 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7149 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7150 } else
7152 if (Result.isInvalid())
7153 return ExprError();
7154 Fn = Result.get();
7155
7156 // Check for a valid function type, but only if it is not a builtin which
7157 // requires custom type checking. These will be handled by
7158 // CheckBuiltinFunctionCall below just after creation of the call expression.
7159 const FunctionType *FuncT = nullptr;
7160 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7161 retry:
7162 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7163 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7164 // have type pointer to function".
7165 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7166 if (!FuncT)
7167 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7168 << Fn->getType() << Fn->getSourceRange());
7169 } else if (const BlockPointerType *BPT =
7170 Fn->getType()->getAs<BlockPointerType>()) {
7171 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7172 } else {
7173 // Handle calls to expressions of unknown-any type.
7174 if (Fn->getType() == Context.UnknownAnyTy) {
7175 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7176 if (rewrite.isInvalid())
7177 return ExprError();
7178 Fn = rewrite.get();
7179 goto retry;
7180 }
7181
7182 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7183 << Fn->getType() << Fn->getSourceRange());
7184 }
7185 }
7186
7187 // Get the number of parameters in the function prototype, if any.
7188 // We will allocate space for max(Args.size(), NumParams) arguments
7189 // in the call expression.
7190 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7191 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7192
7193 CallExpr *TheCall;
7194 if (Config) {
7195 assert(UsesADL == ADLCallKind::NotADL &&
7196 "CUDAKernelCallExpr should not use ADL");
7197 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7198 Args, ResultTy, VK_PRValue, RParenLoc,
7199 CurFPFeatureOverrides(), NumParams);
7200 } else {
7201 TheCall =
7202 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7203 CurFPFeatureOverrides(), NumParams, UsesADL);
7204 }
7205
7206 // Bail out early if calling a builtin with custom type checking.
7207 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7208 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7209 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7210 E = CheckForImmediateInvocation(E, FDecl);
7211 return E;
7212 }
7213
7214 if (getLangOpts().CUDA) {
7215 if (Config) {
7216 // CUDA: Kernel calls must be to global functions
7217 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7218 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7219 << FDecl << Fn->getSourceRange());
7220
7221 // CUDA: Kernel function must have 'void' return type
7222 if (!FuncT->getReturnType()->isVoidType() &&
7223 !FuncT->getReturnType()->getAs<AutoType>() &&
7225 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7226 << Fn->getType() << Fn->getSourceRange());
7227 } else {
7228 // CUDA: Calls to global functions must be configured
7229 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7230 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7231 << FDecl << Fn->getSourceRange());
7232 }
7233 }
7234
7235 // Check for a valid return type
7236 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7237 FDecl))
7238 return ExprError();
7239
7240 // We know the result type of the call, set it.
7241 TheCall->setType(FuncT->getCallResultType(Context));
7243
7244 // WebAssembly tables can't be used as arguments.
7245 if (Context.getTargetInfo().getTriple().isWasm()) {
7246 for (const Expr *Arg : Args) {
7247 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7248 return ExprError(Diag(Arg->getExprLoc(),
7249 diag::err_wasm_table_as_function_parameter));
7250 }
7251 }
7252 }
7253
7254 if (Proto) {
7255 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7256 IsExecConfig))
7257 return ExprError();
7258 } else {
7259 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7260
7261 if (FDecl) {
7262 // Check if we have too few/too many template arguments, based
7263 // on our knowledge of the function definition.
7264 const FunctionDecl *Def = nullptr;
7265 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7266 Proto = Def->getType()->getAs<FunctionProtoType>();
7267 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7268 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7269 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7270 }
7271
7272 // If the function we're calling isn't a function prototype, but we have
7273 // a function prototype from a prior declaratiom, use that prototype.
7274 if (!FDecl->hasPrototype())
7275 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7276 }
7277
7278 // If we still haven't found a prototype to use but there are arguments to
7279 // the call, diagnose this as calling a function without a prototype.
7280 // However, if we found a function declaration, check to see if
7281 // -Wdeprecated-non-prototype was disabled where the function was declared.
7282 // If so, we will silence the diagnostic here on the assumption that this
7283 // interface is intentional and the user knows what they're doing. We will
7284 // also silence the diagnostic if there is a function declaration but it
7285 // was implicitly defined (the user already gets diagnostics about the
7286 // creation of the implicit function declaration, so the additional warning
7287 // is not helpful).
7288 if (!Proto && !Args.empty() &&
7289 (!FDecl || (!FDecl->isImplicit() &&
7290 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7291 FDecl->getLocation()))))
7292 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7293 << (FDecl != nullptr) << FDecl;
7294
7295 // Promote the arguments (C99 6.5.2.2p6).
7296 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7297 Expr *Arg = Args[i];
7298
7299 if (Proto && i < Proto->getNumParams()) {
7301 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7302 ExprResult ArgE =
7304 if (ArgE.isInvalid())
7305 return true;
7306
7307 Arg = ArgE.getAs<Expr>();
7308
7309 } else {
7311
7312 if (ArgE.isInvalid())
7313 return true;
7314
7315 Arg = ArgE.getAs<Expr>();
7316 }
7317
7318 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7319 diag::err_call_incomplete_argument, Arg))
7320 return ExprError();
7321
7322 TheCall->setArg(i, Arg);
7323 }
7324 TheCall->computeDependence();
7325 }
7326
7327 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7328 if (Method->isImplicitObjectMemberFunction())
7329 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7330 << Fn->getSourceRange() << 0);
7331
7332 // Check for sentinels
7333 if (NDecl)
7334 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7335
7336 // Warn for unions passing across security boundary (CMSE).
7337 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7338 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7339 if (const auto *RT =
7340 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7341 if (RT->getDecl()->isOrContainsUnion())
7342 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7343 << 0 << i;
7344 }
7345 }
7346 }
7347
7348 // Do special checking on direct calls to functions.
7349 if (FDecl) {
7350 if (CheckFunctionCall(FDecl, TheCall, Proto))
7351 return ExprError();
7352
7353 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7354
7355 if (BuiltinID)
7356 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7357 } else if (NDecl) {
7358 if (CheckPointerCall(NDecl, TheCall, Proto))
7359 return ExprError();
7360 } else {
7361 if (CheckOtherCall(TheCall, Proto))
7362 return ExprError();
7363 }
7364
7365 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7366}
7367
7370 SourceLocation RParenLoc, Expr *InitExpr) {
7371 assert(Ty && "ActOnCompoundLiteral(): missing type");
7372 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7373
7374 TypeSourceInfo *TInfo;
7375 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7376 if (!TInfo)
7377 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7378
7379 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7380}
7381
7384 SourceLocation RParenLoc, Expr *LiteralExpr) {
7385 QualType literalType = TInfo->getType();
7386
7387 if (literalType->isArrayType()) {
7389 LParenLoc, Context.getBaseElementType(literalType),
7390 diag::err_array_incomplete_or_sizeless_type,
7391 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7392 return ExprError();
7393 if (literalType->isVariableArrayType()) {
7394 // C23 6.7.10p4: An entity of variable length array type shall not be
7395 // initialized except by an empty initializer.
7396 //
7397 // The C extension warnings are issued from ParseBraceInitializer() and
7398 // do not need to be issued here. However, we continue to issue an error
7399 // in the case there are initializers or we are compiling C++. We allow
7400 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7401 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7402 // FIXME: should we allow this construct in C++ when it makes sense to do
7403 // so?
7404 //
7405 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7406 // shall specify an object type or an array of unknown size, but not a
7407 // variable length array type. This seems odd, as it allows 'int a[size] =
7408 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7409 // says, this is what's implemented here for C (except for the extension
7410 // that permits constant foldable size arrays)
7411
7412 auto diagID = LangOpts.CPlusPlus
7413 ? diag::err_variable_object_no_init
7414 : diag::err_compound_literal_with_vla_type;
7415 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7416 diagID))
7417 return ExprError();
7418 }
7419 } else if (!literalType->isDependentType() &&
7420 RequireCompleteType(LParenLoc, literalType,
7421 diag::err_typecheck_decl_incomplete_type,
7422 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7423 return ExprError();
7424
7425 InitializedEntity Entity
7429 SourceRange(LParenLoc, RParenLoc),
7430 /*InitList=*/true);
7431 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7432 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7433 &literalType);
7434 if (Result.isInvalid())
7435 return ExprError();
7436 LiteralExpr = Result.get();
7437
7438 // We treat the compound literal as being at file scope if it's not in a
7439 // function or method body, or within the function's prototype scope. This
7440 // means the following compound literal is not at file scope:
7441 // void func(char *para[(int [1]){ 0 }[0]);
7442 const Scope *S = getCurScope();
7443 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7444 !S->isInCFunctionScope() &&
7445 (!S || !S->isFunctionPrototypeScope());
7446
7447 // In C, compound literals are l-values for some reason.
7448 // For GCC compatibility, in C++, file-scope array compound literals with
7449 // constant initializers are also l-values, and compound literals are
7450 // otherwise prvalues.
7451 //
7452 // (GCC also treats C++ list-initialized file-scope array prvalues with
7453 // constant initializers as l-values, but that's non-conforming, so we don't
7454 // follow it there.)
7455 //
7456 // FIXME: It would be better to handle the lvalue cases as materializing and
7457 // lifetime-extending a temporary object, but our materialized temporaries
7458 // representation only supports lifetime extension from a variable, not "out
7459 // of thin air".
7460 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7461 // is bound to the result of applying array-to-pointer decay to the compound
7462 // literal.
7463 // FIXME: GCC supports compound literals of reference type, which should
7464 // obviously have a value kind derived from the kind of reference involved.
7466 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7467 ? VK_PRValue
7468 : VK_LValue;
7469
7470 // C99 6.5.2.5
7471 // "If the compound literal occurs outside the body of a function, the
7472 // initializer list shall consist of constant expressions."
7473 if (IsFileScope)
7474 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7475 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7476 Expr *Init = ILE->getInit(i);
7477 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7478 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7479 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7480 << Init->getSourceBitField();
7481 return ExprError();
7482 }
7483
7484 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7485 }
7486
7487 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7488 LiteralExpr, IsFileScope);
7489 if (IsFileScope) {
7490 if (!LiteralExpr->isTypeDependent() &&
7491 !LiteralExpr->isValueDependent() &&
7492 !literalType->isDependentType()) // C99 6.5.2.5p3
7493 if (CheckForConstantInitializer(LiteralExpr))
7494 return ExprError();
7495 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7496 literalType.getAddressSpace() != LangAS::Default) {
7497 // Embedded-C extensions to C99 6.5.2.5:
7498 // "If the compound literal occurs inside the body of a function, the
7499 // type name shall not be qualified by an address-space qualifier."
7500 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7501 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7502 return ExprError();
7503 }
7504
7505 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7506 // Compound literals that have automatic storage duration are destroyed at
7507 // the end of the scope in C; in C++, they're just temporaries.
7508
7509 // Emit diagnostics if it is or contains a C union type that is non-trivial
7510 // to destruct.
7515
7516 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7517 if (literalType.isDestructedType()) {
7518 Cleanup.setExprNeedsCleanups(true);
7519 ExprCleanupObjects.push_back(E);
7521 }
7522 }
7523
7526 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7527 E->getInitializer()->getExprLoc());
7528
7529 return MaybeBindToTemporary(E);
7530}
7531
7534 SourceLocation RBraceLoc) {
7535 // Only produce each kind of designated initialization diagnostic once.
7536 SourceLocation FirstDesignator;
7537 bool DiagnosedArrayDesignator = false;
7538 bool DiagnosedNestedDesignator = false;
7539 bool DiagnosedMixedDesignator = false;
7540
7541 // Check that any designated initializers are syntactically valid in the
7542 // current language mode.
7543 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7544 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7545 if (FirstDesignator.isInvalid())
7546 FirstDesignator = DIE->getBeginLoc();
7547
7548 if (!getLangOpts().CPlusPlus)
7549 break;
7550
7551 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7552 DiagnosedNestedDesignator = true;
7553 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7554 << DIE->getDesignatorsSourceRange();
7555 }
7556
7557 for (auto &Desig : DIE->designators()) {
7558 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7559 DiagnosedArrayDesignator = true;
7560 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7561 << Desig.getSourceRange();
7562 }
7563 }
7564
7565 if (!DiagnosedMixedDesignator &&
7566 !isa<DesignatedInitExpr>(InitArgList[0])) {
7567 DiagnosedMixedDesignator = true;
7568 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7569 << DIE->getSourceRange();
7570 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7571 << InitArgList[0]->getSourceRange();
7572 }
7573 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7574 isa<DesignatedInitExpr>(InitArgList[0])) {
7575 DiagnosedMixedDesignator = true;
7576 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7577 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7578 << DIE->getSourceRange();
7579 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7580 << InitArgList[I]->getSourceRange();
7581 }
7582 }
7583
7584 if (FirstDesignator.isValid()) {
7585 // Only diagnose designated initiaization as a C++20 extension if we didn't
7586 // already diagnose use of (non-C++20) C99 designator syntax.
7587 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7588 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7589 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7590 ? diag::warn_cxx17_compat_designated_init
7591 : diag::ext_cxx_designated_init);
7592 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7593 Diag(FirstDesignator, diag::ext_designated_init);
7594 }
7595 }
7596
7597 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7598}
7599
7602 SourceLocation RBraceLoc) {
7603 // Semantic analysis for initializers is done by ActOnDeclarator() and
7604 // CheckInitializer() - it requires knowledge of the object being initialized.
7605
7606 // Immediately handle non-overload placeholders. Overloads can be
7607 // resolved contextually, but everything else here can't.
7608 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7609 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7610 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7611
7612 // Ignore failures; dropping the entire initializer list because
7613 // of one failure would be terrible for indexing/etc.
7614 if (result.isInvalid()) continue;
7615
7616 InitArgList[I] = result.get();
7617 }
7618 }
7619
7620 InitListExpr *E =
7621 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7622 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7623 return E;
7624}
7625
7627 assert(E.get()->getType()->isBlockPointerType());
7628 assert(E.get()->isPRValue());
7629
7630 // Only do this in an r-value context.
7631 if (!getLangOpts().ObjCAutoRefCount) return;
7632
7634 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7635 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7636 Cleanup.setExprNeedsCleanups(true);
7637}
7638
7640 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7641 // Also, callers should have filtered out the invalid cases with
7642 // pointers. Everything else should be possible.
7643
7644 QualType SrcTy = Src.get()->getType();
7645 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7646 return CK_NoOp;
7647
7648 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7650 llvm_unreachable("member pointer type in C");
7651
7652 case Type::STK_CPointer:
7655 switch (DestTy->getScalarTypeKind()) {
7656 case Type::STK_CPointer: {
7657 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7658 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7659 if (SrcAS != DestAS)
7660 return CK_AddressSpaceConversion;
7661 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7662 return CK_NoOp;
7663 return CK_BitCast;
7664 }
7666 return (SrcKind == Type::STK_BlockPointer
7667 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7669 if (SrcKind == Type::STK_ObjCObjectPointer)
7670 return CK_BitCast;
7671 if (SrcKind == Type::STK_CPointer)
7672 return CK_CPointerToObjCPointerCast;
7674 return CK_BlockPointerToObjCPointerCast;
7675 case Type::STK_Bool:
7676 return CK_PointerToBoolean;
7677 case Type::STK_Integral:
7678 return CK_PointerToIntegral;
7679 case Type::STK_Floating:
7684 llvm_unreachable("illegal cast from pointer");
7685 }
7686 llvm_unreachable("Should have returned before this");
7687
7689 switch (DestTy->getScalarTypeKind()) {
7691 return CK_FixedPointCast;
7692 case Type::STK_Bool:
7693 return CK_FixedPointToBoolean;
7694 case Type::STK_Integral:
7695 return CK_FixedPointToIntegral;
7696 case Type::STK_Floating:
7697 return CK_FixedPointToFloating;
7700 Diag(Src.get()->getExprLoc(),
7701 diag::err_unimplemented_conversion_with_fixed_point_type)
7702 << DestTy;
7703 return CK_IntegralCast;
7704 case Type::STK_CPointer:
7708 llvm_unreachable("illegal cast to pointer type");
7709 }
7710 llvm_unreachable("Should have returned before this");
7711
7712 case Type::STK_Bool: // casting from bool is like casting from an integer
7713 case Type::STK_Integral:
7714 switch (DestTy->getScalarTypeKind()) {
7715 case Type::STK_CPointer:
7720 return CK_NullToPointer;
7721 return CK_IntegralToPointer;
7722 case Type::STK_Bool:
7723 return CK_IntegralToBoolean;
7724 case Type::STK_Integral:
7725 return CK_IntegralCast;
7726 case Type::STK_Floating:
7727 return CK_IntegralToFloating;
7729 Src = ImpCastExprToType(Src.get(),
7730 DestTy->castAs<ComplexType>()->getElementType(),
7731 CK_IntegralCast);
7732 return CK_IntegralRealToComplex;
7734 Src = ImpCastExprToType(Src.get(),
7735 DestTy->castAs<ComplexType>()->getElementType(),
7736 CK_IntegralToFloating);
7737 return CK_FloatingRealToComplex;
7739 llvm_unreachable("member pointer type in C");
7741 return CK_IntegralToFixedPoint;
7742 }
7743 llvm_unreachable("Should have returned before this");
7744
7745 case Type::STK_Floating:
7746 switch (DestTy->getScalarTypeKind()) {
7747 case Type::STK_Floating:
7748 return CK_FloatingCast;
7749 case Type::STK_Bool:
7750 return CK_FloatingToBoolean;
7751 case Type::STK_Integral:
7752 return CK_FloatingToIntegral;
7754 Src = ImpCastExprToType(Src.get(),
7755 DestTy->castAs<ComplexType>()->getElementType(),
7756 CK_FloatingCast);
7757 return CK_FloatingRealToComplex;
7759 Src = ImpCastExprToType(Src.get(),
7760 DestTy->castAs<ComplexType>()->getElementType(),
7761 CK_FloatingToIntegral);
7762 return CK_IntegralRealToComplex;
7763 case Type::STK_CPointer:
7766 llvm_unreachable("valid float->pointer cast?");
7768 llvm_unreachable("member pointer type in C");
7770 return CK_FloatingToFixedPoint;
7771 }
7772 llvm_unreachable("Should have returned before this");
7773
7775 switch (DestTy->getScalarTypeKind()) {
7777 return CK_FloatingComplexCast;
7779 return CK_FloatingComplexToIntegralComplex;
7780 case Type::STK_Floating: {
7781 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7782 if (Context.hasSameType(ET, DestTy))
7783 return CK_FloatingComplexToReal;
7784 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7785 return CK_FloatingCast;
7786 }
7787 case Type::STK_Bool:
7788 return CK_FloatingComplexToBoolean;
7789 case Type::STK_Integral:
7790 Src = ImpCastExprToType(Src.get(),
7791 SrcTy->castAs<ComplexType>()->getElementType(),
7792 CK_FloatingComplexToReal);
7793 return CK_FloatingToIntegral;
7794 case Type::STK_CPointer:
7797 llvm_unreachable("valid complex float->pointer cast?");
7799 llvm_unreachable("member pointer type in C");
7801 Diag(Src.get()->getExprLoc(),
7802 diag::err_unimplemented_conversion_with_fixed_point_type)
7803 << SrcTy;
7804 return CK_IntegralCast;
7805 }
7806 llvm_unreachable("Should have returned before this");
7807
7809 switch (DestTy->getScalarTypeKind()) {
7811 return CK_IntegralComplexToFloatingComplex;
7813 return CK_IntegralComplexCast;
7814 case Type::STK_Integral: {
7815 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7816 if (Context.hasSameType(ET, DestTy))
7817 return CK_IntegralComplexToReal;
7818 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7819 return CK_IntegralCast;
7820 }
7821 case Type::STK_Bool:
7822 return CK_IntegralComplexToBoolean;
7823 case Type::STK_Floating:
7824 Src = ImpCastExprToType(Src.get(),
7825 SrcTy->castAs<ComplexType>()->getElementType(),
7826 CK_IntegralComplexToReal);
7827 return CK_IntegralToFloating;
7828 case Type::STK_CPointer:
7831 llvm_unreachable("valid complex int->pointer cast?");
7833 llvm_unreachable("member pointer type in C");
7835 Diag(Src.get()->getExprLoc(),
7836 diag::err_unimplemented_conversion_with_fixed_point_type)
7837 << SrcTy;
7838 return CK_IntegralCast;
7839 }
7840 llvm_unreachable("Should have returned before this");
7841 }
7842
7843 llvm_unreachable("Unhandled scalar cast");
7844}
7845
7846static bool breakDownVectorType(QualType type, uint64_t &len,
7847 QualType &eltType) {
7848 // Vectors are simple.
7849 if (const VectorType *vecType = type->getAs<VectorType>()) {
7850 len = vecType->getNumElements();
7851 eltType = vecType->getElementType();
7852 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7853 return true;
7854 }
7855
7856 // We allow lax conversion to and from non-vector types, but only if
7857 // they're real types (i.e. non-complex, non-pointer scalar types).
7858 if (!type->isRealType()) return false;
7859
7860 len = 1;
7861 eltType = type;
7862 return true;
7863}
7864
7866 assert(srcTy->isVectorType() || destTy->isVectorType());
7867
7868 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7869 if (!FirstType->isSVESizelessBuiltinType())
7870 return false;
7871
7872 const auto *VecTy = SecondType->getAs<VectorType>();
7873 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7874 };
7875
7876 return ValidScalableConversion(srcTy, destTy) ||
7877 ValidScalableConversion(destTy, srcTy);
7878}
7879
7881 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7882 return false;
7883
7884 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7885 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7886
7887 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7888 matSrcType->getNumColumns() == matDestType->getNumColumns();
7889}
7890
7892 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7893
7894 uint64_t SrcLen, DestLen;
7895 QualType SrcEltTy, DestEltTy;
7896 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7897 return false;
7898 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7899 return false;
7900
7901 // ASTContext::getTypeSize will return the size rounded up to a
7902 // power of 2, so instead of using that, we need to use the raw
7903 // element size multiplied by the element count.
7904 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7905 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7906
7907 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7908}
7909
7911 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7912 "expected at least one type to be a vector here");
7913
7914 bool IsSrcTyAltivec =
7915 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7917 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7919 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7921
7922 bool IsDestTyAltivec = DestTy->isVectorType() &&
7923 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7925 (DestTy->castAs<VectorType>()->getVectorKind() ==
7927 (DestTy->castAs<VectorType>()->getVectorKind() ==
7929
7930 return (IsSrcTyAltivec || IsDestTyAltivec);
7931}
7932
7934 assert(destTy->isVectorType() || srcTy->isVectorType());
7935
7936 // Disallow lax conversions between scalars and ExtVectors (these
7937 // conversions are allowed for other vector types because common headers
7938 // depend on them). Most scalar OP ExtVector cases are handled by the
7939 // splat path anyway, which does what we want (convert, not bitcast).
7940 // What this rules out for ExtVectors is crazy things like char4*float.
7941 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7942 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7943
7944 return areVectorTypesSameSize(srcTy, destTy);
7945}
7946
7948 assert(destTy->isVectorType() || srcTy->isVectorType());
7949
7950 switch (Context.getLangOpts().getLaxVectorConversions()) {
7952 return false;
7953
7955 if (!srcTy->isIntegralOrEnumerationType()) {
7956 auto *Vec = srcTy->getAs<VectorType>();
7957 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7958 return false;
7959 }
7960 if (!destTy->isIntegralOrEnumerationType()) {
7961 auto *Vec = destTy->getAs<VectorType>();
7962 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7963 return false;
7964 }
7965 // OK, integer (vector) -> integer (vector) bitcast.
7966 break;
7967
7969 break;
7970 }
7971
7972 return areLaxCompatibleVectorTypes(srcTy, destTy);
7973}
7974
7976 CastKind &Kind) {
7977 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7978 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7979 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7980 << DestTy << SrcTy << R;
7981 }
7982 } else if (SrcTy->isMatrixType()) {
7983 return Diag(R.getBegin(),
7984 diag::err_invalid_conversion_between_matrix_and_type)
7985 << SrcTy << DestTy << R;
7986 } else if (DestTy->isMatrixType()) {
7987 return Diag(R.getBegin(),
7988 diag::err_invalid_conversion_between_matrix_and_type)
7989 << DestTy << SrcTy << R;
7990 }
7991
7992 Kind = CK_MatrixCast;
7993 return false;
7994}
7995
7997 CastKind &Kind) {
7998 assert(VectorTy->isVectorType() && "Not a vector type!");
7999
8000 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8001 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8002 return Diag(R.getBegin(),
8003 Ty->isVectorType() ?
8004 diag::err_invalid_conversion_between_vectors :
8005 diag::err_invalid_conversion_between_vector_and_integer)
8006 << VectorTy << Ty << R;
8007 } else
8008 return Diag(R.getBegin(),
8009 diag::err_invalid_conversion_between_vector_and_scalar)
8010 << VectorTy << Ty << R;
8011
8012 Kind = CK_BitCast;
8013 return false;
8014}
8015
8017 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8018
8019 if (DestElemTy == SplattedExpr->getType())
8020 return SplattedExpr;
8021
8022 assert(DestElemTy->isFloatingType() ||
8023 DestElemTy->isIntegralOrEnumerationType());
8024
8025 CastKind CK;
8026 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8027 // OpenCL requires that we convert `true` boolean expressions to -1, but
8028 // only when splatting vectors.
8029 if (DestElemTy->isFloatingType()) {
8030 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8031 // in two steps: boolean to signed integral, then to floating.
8032 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8033 CK_BooleanToSignedIntegral);
8034 SplattedExpr = CastExprRes.get();
8035 CK = CK_IntegralToFloating;
8036 } else {
8037 CK = CK_BooleanToSignedIntegral;
8038 }
8039 } else {
8040 ExprResult CastExprRes = SplattedExpr;
8041 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8042 if (CastExprRes.isInvalid())
8043 return ExprError();
8044 SplattedExpr = CastExprRes.get();
8045 }
8046 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8047}
8048
8050 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8051
8052 if (DestElemTy == SplattedExpr->getType())
8053 return SplattedExpr;
8054
8055 assert(DestElemTy->isFloatingType() ||
8056 DestElemTy->isIntegralOrEnumerationType());
8057
8058 ExprResult CastExprRes = SplattedExpr;
8059 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8060 if (CastExprRes.isInvalid())
8061 return ExprError();
8062 SplattedExpr = CastExprRes.get();
8063
8064 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8065}
8066
8068 Expr *CastExpr, CastKind &Kind) {
8069 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8070
8071 QualType SrcTy = CastExpr->getType();
8072
8073 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8074 // an ExtVectorType.
8075 // In OpenCL, casts between vectors of different types are not allowed.
8076 // (See OpenCL 6.2).
8077 if (SrcTy->isVectorType()) {
8078 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8079 (getLangOpts().OpenCL &&
8080 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8081 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8082 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8083 << DestTy << SrcTy << R;
8084 return ExprError();
8085 }
8086 Kind = CK_BitCast;
8087 return CastExpr;
8088 }
8089
8090 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8091 // conversion will take place first from scalar to elt type, and then
8092 // splat from elt type to vector.
8093 if (SrcTy->isPointerType())
8094 return Diag(R.getBegin(),
8095 diag::err_invalid_conversion_between_vector_and_scalar)
8096 << DestTy << SrcTy << R;
8097
8098 Kind = CK_VectorSplat;
8099 return prepareVectorSplat(DestTy, CastExpr);
8100}
8101
8102/// Check that a call to alloc_size function specifies sufficient space for the
8103/// destination type.
8104static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8105 const Expr *E) {
8106 QualType SourceType = E->getType();
8107 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8108 DestType == SourceType)
8109 return;
8110
8111 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8112 if (!CE)
8113 return;
8114
8115 // Find the total size allocated by the function call.
8116 if (!CE->getCalleeAllocSizeAttr())
8117 return;
8118 std::optional<llvm::APInt> AllocSize =
8119 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8120 // Allocations of size zero are permitted as a special case. They are usually
8121 // done intentionally.
8122 if (!AllocSize || AllocSize->isZero())
8123 return;
8124 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8125
8126 QualType TargetType = DestType->getPointeeType();
8127 // Find the destination size. As a special case function types have size of
8128 // one byte to match the sizeof operator behavior.
8129 auto LhsSize = TargetType->isFunctionType()
8130 ? CharUnits::One()
8131 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8132 if (LhsSize && Size < LhsSize)
8133 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8134 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8135}
8136
8139 Declarator &D, ParsedType &Ty,
8140 SourceLocation RParenLoc, Expr *CastExpr) {
8141 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8142 "ActOnCastExpr(): missing type or expr");
8143
8145 if (D.isInvalidType())
8146 return ExprError();
8147
8148 if (getLangOpts().CPlusPlus) {
8149 // Check that there are no default arguments (C++ only).
8151 }
8152
8154
8155 QualType castType = castTInfo->getType();
8156 Ty = CreateParsedType(castType, castTInfo);
8157
8158 bool isVectorLiteral = false;
8159
8160 // Check for an altivec or OpenCL literal,
8161 // i.e. all the elements are integer constants.
8162 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8163 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8164 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8165 && castType->isVectorType() && (PE || PLE)) {
8166 if (PLE && PLE->getNumExprs() == 0) {
8167 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8168 return ExprError();
8169 }
8170 if (PE || PLE->getNumExprs() == 1) {
8171 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8172 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8173 isVectorLiteral = true;
8174 }
8175 else
8176 isVectorLiteral = true;
8177 }
8178
8179 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8180 // then handle it as such.
8181 if (isVectorLiteral)
8182 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8183
8184 // If the Expr being casted is a ParenListExpr, handle it specially.
8185 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8186 // sequence of BinOp comma operators.
8189 if (Result.isInvalid()) return ExprError();
8190 CastExpr = Result.get();
8191 }
8192
8193 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8194 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8195
8197
8199
8201
8202 CheckSufficientAllocSize(*this, castType, CastExpr);
8203
8204 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8205}
8206
8208 SourceLocation RParenLoc, Expr *E,
8209 TypeSourceInfo *TInfo) {
8210 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8211 "Expected paren or paren list expression");
8212
8213 Expr **exprs;
8214 unsigned numExprs;
8215 Expr *subExpr;
8216 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8217 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8218 LiteralLParenLoc = PE->getLParenLoc();
8219 LiteralRParenLoc = PE->getRParenLoc();
8220 exprs = PE->getExprs();
8221 numExprs = PE->getNumExprs();
8222 } else { // isa<ParenExpr> by assertion at function entrance
8223 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8224 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8225 subExpr = cast<ParenExpr>(E)->getSubExpr();
8226 exprs = &subExpr;
8227 numExprs = 1;
8228 }
8229
8230 QualType Ty = TInfo->getType();
8231 assert(Ty->isVectorType() && "Expected vector type");
8232
8233 SmallVector<Expr *, 8> initExprs;
8234 const VectorType *VTy = Ty->castAs<VectorType>();
8235 unsigned numElems = VTy->getNumElements();
8236
8237 // '(...)' form of vector initialization in AltiVec: the number of
8238 // initializers must be one or must match the size of the vector.
8239 // If a single value is specified in the initializer then it will be
8240 // replicated to all the components of the vector
8242 VTy->getElementType()))
8243 return ExprError();
8245 // The number of initializers must be one or must match the size of the
8246 // vector. If a single value is specified in the initializer then it will
8247 // be replicated to all the components of the vector
8248 if (numExprs == 1) {
8249 QualType ElemTy = VTy->getElementType();
8250 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8251 if (Literal.isInvalid())
8252 return ExprError();
8253 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8254 PrepareScalarCast(Literal, ElemTy));
8255 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8256 }
8257 else if (numExprs < numElems) {
8258 Diag(E->getExprLoc(),
8259 diag::err_incorrect_number_of_vector_initializers);
8260 return ExprError();
8261 }
8262 else
8263 initExprs.append(exprs, exprs + numExprs);
8264 }
8265 else {
8266 // For OpenCL, when the number of initializers is a single value,
8267 // it will be replicated to all components of the vector.
8269 numExprs == 1) {
8270 QualType SrcTy = exprs[0]->getType();
8271 if (!SrcTy->isArithmeticType()) {
8272 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8273 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8274 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8275 return ExprError();
8276 }
8277 QualType ElemTy = VTy->getElementType();
8278 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8279 if (Literal.isInvalid())
8280 return ExprError();
8281 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8282 PrepareScalarCast(Literal, ElemTy));
8283 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8284 }
8285
8286 initExprs.append(exprs, exprs + numExprs);
8287 }
8288 // FIXME: This means that pretty-printing the final AST will produce curly
8289 // braces instead of the original commas.
8290 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8291 initExprs, LiteralRParenLoc);
8292 initE->setType(Ty);
8293 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8294}
8295
8298 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8299 if (!E)
8300 return OrigExpr;
8301
8302 ExprResult Result(E->getExpr(0));
8303
8304 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8305 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8306 E->getExpr(i));
8307
8308 if (Result.isInvalid()) return ExprError();
8309
8310 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8311}
8312
8318
8320 unsigned NumUserSpecifiedExprs,
8321 SourceLocation InitLoc,
8322 SourceLocation LParenLoc,
8323 SourceLocation RParenLoc) {
8324 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8325 InitLoc, LParenLoc, RParenLoc);
8326}
8327
8328bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8329 SourceLocation QuestionLoc) {
8330 const Expr *NullExpr = LHSExpr;
8331 const Expr *NonPointerExpr = RHSExpr;
8335
8336 if (NullKind == Expr::NPCK_NotNull) {
8337 NullExpr = RHSExpr;
8338 NonPointerExpr = LHSExpr;
8339 NullKind =
8342 }
8343
8344 if (NullKind == Expr::NPCK_NotNull)
8345 return false;
8346
8347 if (NullKind == Expr::NPCK_ZeroExpression)
8348 return false;
8349
8350 if (NullKind == Expr::NPCK_ZeroLiteral) {
8351 // In this case, check to make sure that we got here from a "NULL"
8352 // string in the source code.
8353 NullExpr = NullExpr->IgnoreParenImpCasts();
8354 SourceLocation loc = NullExpr->getExprLoc();
8355 if (!findMacroSpelling(loc, "NULL"))
8356 return false;
8357 }
8358
8359 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8360 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8361 << NonPointerExpr->getType() << DiagType
8362 << NonPointerExpr->getSourceRange();
8363 return true;
8364}
8365
8366/// Return false if the condition expression is valid, true otherwise.
8367static bool checkCondition(Sema &S, const Expr *Cond,
8368 SourceLocation QuestionLoc) {
8369 QualType CondTy = Cond->getType();
8370
8371 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8372 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8373 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8374 << CondTy << Cond->getSourceRange();
8375 return true;
8376 }
8377
8378 // C99 6.5.15p2
8379 if (CondTy->isScalarType()) return false;
8380
8381 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8382 << CondTy << Cond->getSourceRange();
8383 return true;
8384}
8385
8386/// Return false if the NullExpr can be promoted to PointerTy,
8387/// true otherwise.
8389 QualType PointerTy) {
8390 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8391 !NullExpr.get()->isNullPointerConstant(S.Context,
8393 return true;
8394
8395 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8396 return false;
8397}
8398
8399/// Checks compatibility between two pointers and return the resulting
8400/// type.
8402 ExprResult &RHS,
8403 SourceLocation Loc) {
8404 QualType LHSTy = LHS.get()->getType();
8405 QualType RHSTy = RHS.get()->getType();
8406
8407 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8408 // Two identical pointers types are always compatible.
8409 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8410 }
8411
8412 QualType lhptee, rhptee;
8413
8414 // Get the pointee types.
8415 bool IsBlockPointer = false;
8416 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8417 lhptee = LHSBTy->getPointeeType();
8418 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8419 IsBlockPointer = true;
8420 } else {
8421 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8422 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8423 }
8424
8425 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8426 // differently qualified versions of compatible types, the result type is
8427 // a pointer to an appropriately qualified version of the composite
8428 // type.
8429
8430 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8431 // clause doesn't make sense for our extensions. E.g. address space 2 should
8432 // be incompatible with address space 3: they may live on different devices or
8433 // anything.
8434 Qualifiers lhQual = lhptee.getQualifiers();
8435 Qualifiers rhQual = rhptee.getQualifiers();
8436
8437 LangAS ResultAddrSpace = LangAS::Default;
8438 LangAS LAddrSpace = lhQual.getAddressSpace();
8439 LangAS RAddrSpace = rhQual.getAddressSpace();
8440
8441 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8442 // spaces is disallowed.
8443 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8444 ResultAddrSpace = LAddrSpace;
8445 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8446 ResultAddrSpace = RAddrSpace;
8447 else {
8448 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8449 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8450 << RHS.get()->getSourceRange();
8451 return QualType();
8452 }
8453
8454 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8455 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8456 lhQual.removeCVRQualifiers();
8457 rhQual.removeCVRQualifiers();
8458
8459 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8460 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8461 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8462 << RHS.get()->getSourceRange();
8463 return QualType();
8464 }
8465
8466 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8467 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8468 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8469 // qual types are compatible iff
8470 // * corresponded types are compatible
8471 // * CVR qualifiers are equal
8472 // * address spaces are equal
8473 // Thus for conditional operator we merge CVR and address space unqualified
8474 // pointees and if there is a composite type we return a pointer to it with
8475 // merged qualifiers.
8476 LHSCastKind =
8477 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8478 RHSCastKind =
8479 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8480 lhQual.removeAddressSpace();
8481 rhQual.removeAddressSpace();
8482
8483 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8484 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8485
8486 QualType CompositeTy = S.Context.mergeTypes(
8487 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8488 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8489
8490 if (CompositeTy.isNull()) {
8491 // In this situation, we assume void* type. No especially good
8492 // reason, but this is what gcc does, and we do have to pick
8493 // to get a consistent AST.
8494 QualType incompatTy;
8495 incompatTy = S.Context.getPointerType(
8496 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8497 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8498 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8499
8500 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8501 // for casts between types with incompatible address space qualifiers.
8502 // For the following code the compiler produces casts between global and
8503 // local address spaces of the corresponded innermost pointees:
8504 // local int *global *a;
8505 // global int *global *b;
8506 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8507 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8508 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8509 << RHS.get()->getSourceRange();
8510
8511 return incompatTy;
8512 }
8513
8514 // The pointer types are compatible.
8515 // In case of OpenCL ResultTy should have the address space qualifier
8516 // which is a superset of address spaces of both the 2nd and the 3rd
8517 // operands of the conditional operator.
8518 QualType ResultTy = [&, ResultAddrSpace]() {
8519 if (S.getLangOpts().OpenCL) {
8520 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8521 CompositeQuals.setAddressSpace(ResultAddrSpace);
8522 return S.Context
8523 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8524 .withCVRQualifiers(MergedCVRQual);
8525 }
8526 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8527 }();
8528 if (IsBlockPointer)
8529 ResultTy = S.Context.getBlockPointerType(ResultTy);
8530 else
8531 ResultTy = S.Context.getPointerType(ResultTy);
8532
8533 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8534 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8535 return ResultTy;
8536}
8537
8538/// Return the resulting type when the operands are both block pointers.
8540 ExprResult &LHS,
8541 ExprResult &RHS,
8542 SourceLocation Loc) {
8543 QualType LHSTy = LHS.get()->getType();
8544 QualType RHSTy = RHS.get()->getType();
8545
8546 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8547 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8549 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8550 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8551 return destType;
8552 }
8553 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8554 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8555 << RHS.get()->getSourceRange();
8556 return QualType();
8557 }
8558
8559 // We have 2 block pointer types.
8560 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8561}
8562
8563/// Return the resulting type when the operands are both pointers.
8564static QualType
8566 ExprResult &RHS,
8567 SourceLocation Loc) {
8568 // get the pointer types
8569 QualType LHSTy = LHS.get()->getType();
8570 QualType RHSTy = RHS.get()->getType();
8571
8572 // get the "pointed to" types
8573 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8574 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8575
8576 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8577 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8578 // Figure out necessary qualifiers (C99 6.5.15p6)
8579 QualType destPointee
8580 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8581 QualType destType = S.Context.getPointerType(destPointee);
8582 // Add qualifiers if necessary.
8583 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8584 // Promote to void*.
8585 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8586 return destType;
8587 }
8588 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8589 QualType destPointee
8590 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8591 QualType destType = S.Context.getPointerType(destPointee);
8592 // Add qualifiers if necessary.
8593 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8594 // Promote to void*.
8595 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8596 return destType;
8597 }
8598
8599 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8600}
8601
8602/// Return false if the first expression is not an integer and the second
8603/// expression is not a pointer, true otherwise.
8605 Expr* PointerExpr, SourceLocation Loc,
8606 bool IsIntFirstExpr) {
8607 if (!PointerExpr->getType()->isPointerType() ||
8608 !Int.get()->getType()->isIntegerType())
8609 return false;
8610
8611 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8612 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8613
8614 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8615 << Expr1->getType() << Expr2->getType()
8616 << Expr1->getSourceRange() << Expr2->getSourceRange();
8617 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8618 CK_IntegralToPointer);
8619 return true;
8620}
8621
8622/// Simple conversion between integer and floating point types.
8623///
8624/// Used when handling the OpenCL conditional operator where the
8625/// condition is a vector while the other operands are scalar.
8626///
8627/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8628/// types are either integer or floating type. Between the two
8629/// operands, the type with the higher rank is defined as the "result
8630/// type". The other operand needs to be promoted to the same type. No
8631/// other type promotion is allowed. We cannot use
8632/// UsualArithmeticConversions() for this purpose, since it always
8633/// promotes promotable types.
8635 ExprResult &RHS,
8636 SourceLocation QuestionLoc) {
8638 if (LHS.isInvalid())
8639 return QualType();
8641 if (RHS.isInvalid())
8642 return QualType();
8643
8644 // For conversion purposes, we ignore any qualifiers.
8645 // For example, "const float" and "float" are equivalent.
8646 QualType LHSType =
8648 QualType RHSType =
8650
8651 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8652 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8653 << LHSType << LHS.get()->getSourceRange();
8654 return QualType();
8655 }
8656
8657 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8658 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8659 << RHSType << RHS.get()->getSourceRange();
8660 return QualType();
8661 }
8662
8663 // If both types are identical, no conversion is needed.
8664 if (LHSType == RHSType)
8665 return LHSType;
8666
8667 // Now handle "real" floating types (i.e. float, double, long double).
8668 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8669 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8670 /*IsCompAssign = */ false);
8671
8672 // Finally, we have two differing integer types.
8674 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8675}
8676
8677/// Convert scalar operands to a vector that matches the
8678/// condition in length.
8679///
8680/// Used when handling the OpenCL conditional operator where the
8681/// condition is a vector while the other operands are scalar.
8682///
8683/// We first compute the "result type" for the scalar operands
8684/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8685/// into a vector of that type where the length matches the condition
8686/// vector type. s6.11.6 requires that the element types of the result
8687/// and the condition must have the same number of bits.
8688static QualType
8690 QualType CondTy, SourceLocation QuestionLoc) {
8691 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8692 if (ResTy.isNull()) return QualType();
8693
8694 const VectorType *CV = CondTy->getAs<VectorType>();
8695 assert(CV);
8696
8697 // Determine the vector result type
8698 unsigned NumElements = CV->getNumElements();
8699 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8700
8701 // Ensure that all types have the same number of bits
8703 != S.Context.getTypeSize(ResTy)) {
8704 // Since VectorTy is created internally, it does not pretty print
8705 // with an OpenCL name. Instead, we just print a description.
8706 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8707 SmallString<64> Str;
8708 llvm::raw_svector_ostream OS(Str);
8709 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8710 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8711 << CondTy << OS.str();
8712 return QualType();
8713 }
8714
8715 // Convert operands to the vector result type
8716 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8717 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8718
8719 return VectorTy;
8720}
8721
8722/// Return false if this is a valid OpenCL condition vector
8724 SourceLocation QuestionLoc) {
8725 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8726 // integral type.
8727 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8728 assert(CondTy);
8729 QualType EleTy = CondTy->getElementType();
8730 if (EleTy->isIntegerType()) return false;
8731
8732 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8733 << Cond->getType() << Cond->getSourceRange();
8734 return true;
8735}
8736
8737/// Return false if the vector condition type and the vector
8738/// result type are compatible.
8739///
8740/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8741/// number of elements, and their element types have the same number
8742/// of bits.
8743static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8744 SourceLocation QuestionLoc) {
8745 const VectorType *CV = CondTy->getAs<VectorType>();
8746 const VectorType *RV = VecResTy->getAs<VectorType>();
8747 assert(CV && RV);
8748
8749 if (CV->getNumElements() != RV->getNumElements()) {
8750 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8751 << CondTy << VecResTy;
8752 return true;
8753 }
8754
8755 QualType CVE = CV->getElementType();
8756 QualType RVE = RV->getElementType();
8757
8758 // Boolean vectors are permitted outside of OpenCL mode.
8759 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8760 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8761 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8762 << CondTy << VecResTy;
8763 return true;
8764 }
8765
8766 return false;
8767}
8768
8769/// Return the resulting type for the conditional operator in
8770/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8771/// s6.3.i) when the condition is a vector type.
8772static QualType
8774 ExprResult &LHS, ExprResult &RHS,
8775 SourceLocation QuestionLoc) {
8777 if (Cond.isInvalid())
8778 return QualType();
8779 QualType CondTy = Cond.get()->getType();
8780
8781 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8782 return QualType();
8783
8784 // If either operand is a vector then find the vector type of the
8785 // result as specified in OpenCL v1.1 s6.3.i.
8786 if (LHS.get()->getType()->isVectorType() ||
8787 RHS.get()->getType()->isVectorType()) {
8788 bool IsBoolVecLang =
8789 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8790 QualType VecResTy =
8791 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8792 /*isCompAssign*/ false,
8793 /*AllowBothBool*/ true,
8794 /*AllowBoolConversions*/ false,
8795 /*AllowBooleanOperation*/ IsBoolVecLang,
8796 /*ReportInvalid*/ true);
8797 if (VecResTy.isNull())
8798 return QualType();
8799 // The result type must match the condition type as specified in
8800 // OpenCL v1.1 s6.11.6.
8801 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8802 return QualType();
8803 return VecResTy;
8804 }
8805
8806 // Both operands are scalar.
8807 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8808}
8809
8810/// Return true if the Expr is block type
8811static bool checkBlockType(Sema &S, const Expr *E) {
8812 if (E->getType()->isBlockPointerType()) {
8813 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8814 return true;
8815 }
8816
8817 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8818 QualType Ty = CE->getCallee()->getType();
8819 if (Ty->isBlockPointerType()) {
8820 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8821 return true;
8822 }
8823 }
8824 return false;
8825}
8826
8827/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8828/// In that case, LHS = cond.
8829/// C99 6.5.15
8832 ExprObjectKind &OK,
8833 SourceLocation QuestionLoc) {
8834
8835 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8836 if (!LHSResult.isUsable()) return QualType();
8837 LHS = LHSResult;
8838
8839 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8840 if (!RHSResult.isUsable()) return QualType();
8841 RHS = RHSResult;
8842
8843 // C++ is sufficiently different to merit its own checker.
8844 if (getLangOpts().CPlusPlus)
8845 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8846
8847 VK = VK_PRValue;
8848 OK = OK_Ordinary;
8849
8850 if (Context.isDependenceAllowed() &&
8851 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8852 RHS.get()->isTypeDependent())) {
8853 assert(!getLangOpts().CPlusPlus);
8854 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8855 RHS.get()->containsErrors()) &&
8856 "should only occur in error-recovery path.");
8857 return Context.DependentTy;
8858 }
8859
8860 // The OpenCL operator with a vector condition is sufficiently
8861 // different to merit its own checker.
8862 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8863 Cond.get()->getType()->isExtVectorType())
8864 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8865
8866 // First, check the condition.
8868 if (Cond.isInvalid())
8869 return QualType();
8870 if (checkCondition(*this, Cond.get(), QuestionLoc))
8871 return QualType();
8872
8873 // Handle vectors.
8874 if (LHS.get()->getType()->isVectorType() ||
8875 RHS.get()->getType()->isVectorType())
8876 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8877 /*AllowBothBool*/ true,
8878 /*AllowBoolConversions*/ false,
8879 /*AllowBooleanOperation*/ false,
8880 /*ReportInvalid*/ true);
8881
8882 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8884 if (LHS.isInvalid() || RHS.isInvalid())
8885 return QualType();
8886
8887 // WebAssembly tables are not allowed as conditional LHS or RHS.
8888 QualType LHSTy = LHS.get()->getType();
8889 QualType RHSTy = RHS.get()->getType();
8890 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8891 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8893 return QualType();
8894 }
8895
8896 // Diagnose attempts to convert between __ibm128, __float128 and long double
8897 // where such conversions currently can't be handled.
8898 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8899 Diag(QuestionLoc,
8900 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8902 return QualType();
8903 }
8904
8905 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8906 // selection operator (?:).
8907 if (getLangOpts().OpenCL &&
8908 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8909 return QualType();
8910 }
8911
8912 // If both operands have arithmetic type, do the usual arithmetic conversions
8913 // to find a common type: C99 6.5.15p3,5.
8914 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8915 // Disallow invalid arithmetic conversions, such as those between bit-
8916 // precise integers types of different sizes, or between a bit-precise
8917 // integer and another type.
8918 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8919 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8920 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8921 << RHS.get()->getSourceRange();
8922 return QualType();
8923 }
8924
8925 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8926 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8927
8928 return ResTy;
8929 }
8930
8931 // If both operands are the same structure or union type, the result is that
8932 // type.
8933 // FIXME: Type of conditional expression must be complete in C mode.
8934 if (LHSTy->isRecordType() &&
8935 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8936 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8937 RHSTy.getUnqualifiedType());
8938
8939 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8940 // The following || allows only one side to be void (a GCC-ism).
8941 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8942 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8943 // UsualArithmeticConversions already handled the case where both sides
8944 // are the same type.
8945 } else if (RHSTy->isVoidType()) {
8946 ResTy = RHSTy;
8947 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8948 << RHS.get()->getSourceRange();
8949 } else {
8950 ResTy = LHSTy;
8951 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8952 << LHS.get()->getSourceRange();
8953 }
8954 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8955 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8956 return ResTy;
8957 }
8958
8959 // C23 6.5.15p7:
8960 // ... if both the second and third operands have nullptr_t type, the
8961 // result also has that type.
8962 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8963 return ResTy;
8964
8965 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8966 // the type of the other operand."
8967 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8968 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8969
8970 // All objective-c pointer type analysis is done here.
8971 QualType compositeType =
8972 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8973 if (LHS.isInvalid() || RHS.isInvalid())
8974 return QualType();
8975 if (!compositeType.isNull())
8976 return compositeType;
8977
8978
8979 // Handle block pointer types.
8980 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8981 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8982 QuestionLoc);
8983
8984 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8985 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8986 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8987 QuestionLoc);
8988
8989 // GCC compatibility: soften pointer/integer mismatch. Note that
8990 // null pointers have been filtered out by this point.
8991 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8992 /*IsIntFirstExpr=*/true))
8993 return RHSTy;
8994 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8995 /*IsIntFirstExpr=*/false))
8996 return LHSTy;
8997
8998 // Emit a better diagnostic if one of the expressions is a null pointer
8999 // constant and the other is not a pointer type. In this case, the user most
9000 // likely forgot to take the address of the other expression.
9001 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9002 return QualType();
9003
9004 // Finally, if the LHS and RHS types are canonically the same type, we can
9005 // use the common sugared type.
9006 if (Context.hasSameType(LHSTy, RHSTy))
9007 return Context.getCommonSugaredType(LHSTy, RHSTy);
9008
9009 // Otherwise, the operands are not compatible.
9010 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9011 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9012 << RHS.get()->getSourceRange();
9013 return QualType();
9014}
9015
9016/// SuggestParentheses - Emit a note with a fixit hint that wraps
9017/// ParenRange in parentheses.
9019 const PartialDiagnostic &Note,
9020 SourceRange ParenRange) {
9021 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9022 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9023 EndLoc.isValid()) {
9024 Self.Diag(Loc, Note)
9025 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9026 << FixItHint::CreateInsertion(EndLoc, ")");
9027 } else {
9028 // We can't display the parentheses, so just show the bare note.
9029 Self.Diag(Loc, Note) << ParenRange;
9030 }
9031}
9032
9034 return BinaryOperator::isAdditiveOp(Opc) ||
9036 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9037 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9038 // not any of the logical operators. Bitwise-xor is commonly used as a
9039 // logical-xor because there is no logical-xor operator. The logical
9040 // operators, including uses of xor, have a high false positive rate for
9041 // precedence warnings.
9042}
9043
9044/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9045/// expression, either using a built-in or overloaded operator,
9046/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9047/// expression.
9048static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9049 const Expr **RHSExprs) {
9050 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9051 E = E->IgnoreImpCasts();
9053 E = E->IgnoreImpCasts();
9054 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9055 E = MTE->getSubExpr();
9056 E = E->IgnoreImpCasts();
9057 }
9058
9059 // Built-in binary operator.
9060 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9061 OP && IsArithmeticOp(OP->getOpcode())) {
9062 *Opcode = OP->getOpcode();
9063 *RHSExprs = OP->getRHS();
9064 return true;
9065 }
9066
9067 // Overloaded operator.
9068 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9069 if (Call->getNumArgs() != 2)
9070 return false;
9071
9072 // Make sure this is really a binary operator that is safe to pass into
9073 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9074 OverloadedOperatorKind OO = Call->getOperator();
9075 if (OO < OO_Plus || OO > OO_Arrow ||
9076 OO == OO_PlusPlus || OO == OO_MinusMinus)
9077 return false;
9078
9080 if (IsArithmeticOp(OpKind)) {
9081 *Opcode = OpKind;
9082 *RHSExprs = Call->getArg(1);
9083 return true;
9084 }
9085 }
9086
9087 return false;
9088}
9089
9090/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9091/// or is a logical expression such as (x==y) which has int type, but is
9092/// commonly interpreted as boolean.
9093static bool ExprLooksBoolean(const Expr *E) {
9094 E = E->IgnoreParenImpCasts();
9095
9096 if (E->getType()->isBooleanType())
9097 return true;
9098 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9099 return OP->isComparisonOp() || OP->isLogicalOp();
9100 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9101 return OP->getOpcode() == UO_LNot;
9102 if (E->getType()->isPointerType())
9103 return true;
9104 // FIXME: What about overloaded operator calls returning "unspecified boolean
9105 // type"s (commonly pointer-to-members)?
9106
9107 return false;
9108}
9109
9110/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9111/// and binary operator are mixed in a way that suggests the programmer assumed
9112/// the conditional operator has higher precedence, for example:
9113/// "int x = a + someBinaryCondition ? 1 : 2".
9115 Expr *Condition, const Expr *LHSExpr,
9116 const Expr *RHSExpr) {
9117 BinaryOperatorKind CondOpcode;
9118 const Expr *CondRHS;
9119
9120 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9121 return;
9122 if (!ExprLooksBoolean(CondRHS))
9123 return;
9124
9125 // The condition is an arithmetic binary expression, with a right-
9126 // hand side that looks boolean, so warn.
9127
9128 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9129 ? diag::warn_precedence_bitwise_conditional
9130 : diag::warn_precedence_conditional;
9131
9132 Self.Diag(OpLoc, DiagID)
9133 << Condition->getSourceRange()
9134 << BinaryOperator::getOpcodeStr(CondOpcode);
9135
9137 Self, OpLoc,
9138 Self.PDiag(diag::note_precedence_silence)
9139 << BinaryOperator::getOpcodeStr(CondOpcode),
9140 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9141
9142 SuggestParentheses(Self, OpLoc,
9143 Self.PDiag(diag::note_precedence_conditional_first),
9144 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9145}
9146
9147/// Compute the nullability of a conditional expression.
9149 QualType LHSTy, QualType RHSTy,
9150 ASTContext &Ctx) {
9151 if (!ResTy->isAnyPointerType())
9152 return ResTy;
9153
9154 auto GetNullability = [](QualType Ty) {
9155 std::optional<NullabilityKind> Kind = Ty->getNullability();
9156 if (Kind) {
9157 // For our purposes, treat _Nullable_result as _Nullable.
9160 return *Kind;
9161 }
9163 };
9164
9165 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9166 NullabilityKind MergedKind;
9167
9168 // Compute nullability of a binary conditional expression.
9169 if (IsBin) {
9170 if (LHSKind == NullabilityKind::NonNull)
9171 MergedKind = NullabilityKind::NonNull;
9172 else
9173 MergedKind = RHSKind;
9174 // Compute nullability of a normal conditional expression.
9175 } else {
9176 if (LHSKind == NullabilityKind::Nullable ||
9177 RHSKind == NullabilityKind::Nullable)
9178 MergedKind = NullabilityKind::Nullable;
9179 else if (LHSKind == NullabilityKind::NonNull)
9180 MergedKind = RHSKind;
9181 else if (RHSKind == NullabilityKind::NonNull)
9182 MergedKind = LHSKind;
9183 else
9184 MergedKind = NullabilityKind::Unspecified;
9185 }
9186
9187 // Return if ResTy already has the correct nullability.
9188 if (GetNullability(ResTy) == MergedKind)
9189 return ResTy;
9190
9191 // Strip all nullability from ResTy.
9192 while (ResTy->getNullability())
9193 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9194
9195 // Create a new AttributedType with the new nullability kind.
9196 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9197}
9198
9200 SourceLocation ColonLoc,
9201 Expr *CondExpr, Expr *LHSExpr,
9202 Expr *RHSExpr) {
9203 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9204 // was the condition.
9205 OpaqueValueExpr *opaqueValue = nullptr;
9206 Expr *commonExpr = nullptr;
9207 if (!LHSExpr) {
9208 commonExpr = CondExpr;
9209 // Lower out placeholder types first. This is important so that we don't
9210 // try to capture a placeholder. This happens in few cases in C++; such
9211 // as Objective-C++'s dictionary subscripting syntax.
9212 if (commonExpr->hasPlaceholderType()) {
9213 ExprResult result = CheckPlaceholderExpr(commonExpr);
9214 if (!result.isUsable()) return ExprError();
9215 commonExpr = result.get();
9216 }
9217 // We usually want to apply unary conversions *before* saving, except
9218 // in the special case of a C++ l-value conditional.
9219 if (!(getLangOpts().CPlusPlus
9220 && !commonExpr->isTypeDependent()
9221 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9222 && commonExpr->isGLValue()
9223 && commonExpr->isOrdinaryOrBitFieldObject()
9224 && RHSExpr->isOrdinaryOrBitFieldObject()
9225 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9226 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9227 if (commonRes.isInvalid())
9228 return ExprError();
9229 commonExpr = commonRes.get();
9230 }
9231
9232 // If the common expression is a class or array prvalue, materialize it
9233 // so that we can safely refer to it multiple times.
9234 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9235 commonExpr->getType()->isArrayType())) {
9236 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9237 if (MatExpr.isInvalid())
9238 return ExprError();
9239 commonExpr = MatExpr.get();
9240 }
9241
9242 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9243 commonExpr->getType(),
9244 commonExpr->getValueKind(),
9245 commonExpr->getObjectKind(),
9246 commonExpr);
9247 LHSExpr = CondExpr = opaqueValue;
9248 }
9249
9250 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9253 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9254 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9255 VK, OK, QuestionLoc);
9256 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9257 RHS.isInvalid())
9258 return ExprError();
9259
9260 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9261 RHS.get());
9262
9263 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9264
9265 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9266 Context);
9267
9268 if (!commonExpr)
9269 return new (Context)
9270 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9271 RHS.get(), result, VK, OK);
9272
9274 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9275 ColonLoc, result, VK, OK);
9276}
9277
9279 unsigned FromAttributes = 0, ToAttributes = 0;
9280 if (const auto *FromFn =
9281 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9282 FromAttributes =
9283 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9284 if (const auto *ToFn =
9285 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9286 ToAttributes =
9287 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9288
9289 return FromAttributes != ToAttributes;
9290}
9291
9292// checkPointerTypesForAssignment - This is a very tricky routine (despite
9293// being closely modeled after the C99 spec:-). The odd characteristic of this
9294// routine is it effectively iqnores the qualifiers on the top level pointee.
9295// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9296// FIXME: add a couple examples in this comment.
9298 QualType LHSType,
9299 QualType RHSType,
9300 SourceLocation Loc) {
9301 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9302 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9303
9304 // get the "pointed to" type (ignoring qualifiers at the top level)
9305 const Type *lhptee, *rhptee;
9306 Qualifiers lhq, rhq;
9307 std::tie(lhptee, lhq) =
9308 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9309 std::tie(rhptee, rhq) =
9310 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9311
9313
9314 // C99 6.5.16.1p1: This following citation is common to constraints
9315 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9316 // qualifiers of the type *pointed to* by the right;
9317
9318 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9319 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9321 // Ignore lifetime for further calculation.
9322 lhq.removeObjCLifetime();
9323 rhq.removeObjCLifetime();
9324 }
9325
9326 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9327 // Treat address-space mismatches as fatal.
9328 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9330
9331 // It's okay to add or remove GC or lifetime qualifiers when converting to
9332 // and from void*.
9335 S.getASTContext()) &&
9336 (lhptee->isVoidType() || rhptee->isVoidType()))
9337 ; // keep old
9338
9339 // Treat lifetime mismatches as fatal.
9340 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9342
9343 // Treat pointer-auth mismatches as fatal.
9344 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9346
9347 // For GCC/MS compatibility, other qualifier mismatches are treated
9348 // as still compatible in C.
9349 else
9351 }
9352
9353 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9354 // incomplete type and the other is a pointer to a qualified or unqualified
9355 // version of void...
9356 if (lhptee->isVoidType()) {
9357 if (rhptee->isIncompleteOrObjectType())
9358 return ConvTy;
9359
9360 // As an extension, we allow cast to/from void* to function pointer.
9361 assert(rhptee->isFunctionType());
9363 }
9364
9365 if (rhptee->isVoidType()) {
9366 // In C, void * to another pointer type is compatible, but we want to note
9367 // that there will be an implicit conversion happening here.
9368 if (lhptee->isIncompleteOrObjectType())
9369 return ConvTy == AssignConvertType::Compatible &&
9370 !S.getLangOpts().CPlusPlus
9372 : ConvTy;
9373
9374 // As an extension, we allow cast to/from void* to function pointer.
9375 assert(lhptee->isFunctionType());
9377 }
9378
9379 if (!S.Diags.isIgnored(
9380 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9381 Loc) &&
9382 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9383 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9385
9386 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9387 // unqualified versions of compatible types, ...
9388 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9389
9390 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9391 if (!S.Context.hasSameType(ltrans, rtrans)) {
9392 QualType LUnderlying =
9393 ltrans->isOverflowBehaviorType()
9394 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9395 : ltrans;
9396 QualType RUnderlying =
9397 rtrans->isOverflowBehaviorType()
9398 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9399 : rtrans;
9400
9401 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9403
9404 ltrans = LUnderlying;
9405 rtrans = RUnderlying;
9406 }
9407 }
9408
9409 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9410 // Check if the pointee types are compatible ignoring the sign.
9411 // We explicitly check for char so that we catch "char" vs
9412 // "unsigned char" on systems where "char" is unsigned.
9413 if (lhptee->isCharType())
9414 ltrans = S.Context.UnsignedCharTy;
9415 else if (lhptee->hasSignedIntegerRepresentation())
9416 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9417
9418 if (rhptee->isCharType())
9419 rtrans = S.Context.UnsignedCharTy;
9420 else if (rhptee->hasSignedIntegerRepresentation())
9421 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9422
9423 if (ltrans == rtrans) {
9424 // Types are compatible ignoring the sign. Qualifier incompatibility
9425 // takes priority over sign incompatibility because the sign
9426 // warning can be disabled.
9427 if (!S.IsAssignConvertCompatible(ConvTy))
9428 return ConvTy;
9429
9431 }
9432
9433 // If we are a multi-level pointer, it's possible that our issue is simply
9434 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9435 // the eventual target type is the same and the pointers have the same
9436 // level of indirection, this must be the issue.
9437 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9438 do {
9439 std::tie(lhptee, lhq) =
9440 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9441 std::tie(rhptee, rhq) =
9442 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9443
9444 // Inconsistent address spaces at this point is invalid, even if the
9445 // address spaces would be compatible.
9446 // FIXME: This doesn't catch address space mismatches for pointers of
9447 // different nesting levels, like:
9448 // __local int *** a;
9449 // int ** b = a;
9450 // It's not clear how to actually determine when such pointers are
9451 // invalidly incompatible.
9452 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9453 return AssignConvertType::
9454 IncompatibleNestedPointerAddressSpaceMismatch;
9455
9456 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9457
9458 if (lhptee == rhptee)
9460 }
9461
9462 // General pointer incompatibility takes priority over qualifiers.
9463 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9466 }
9467 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9468 // hasSameType, so we can skip further checks.
9469 const auto *LFT = ltrans->getAs<FunctionType>();
9470 const auto *RFT = rtrans->getAs<FunctionType>();
9471 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9472 // The invocation of IsFunctionConversion below will try to transform rtrans
9473 // to obtain an exact match for ltrans. This should not fail because of
9474 // mismatches in result type and parameter types, they were already checked
9475 // by typesAreCompatible above. So we will recreate rtrans (or where
9476 // appropriate ltrans) using the result type and parameter types from ltrans
9477 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9478 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9479 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9480 if (LFPT && RFPT) {
9481 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9482 LFPT->getParamTypes(),
9483 RFPT->getExtProtoInfo());
9484 } else if (LFPT) {
9486 EPI.ExtInfo = RFT->getExtInfo();
9487 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9488 LFPT->getParamTypes(), EPI);
9489 } else if (RFPT) {
9490 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9491 // all of its ExtProtoInfo. Transform ltrans instead.
9493 EPI.ExtInfo = LFT->getExtInfo();
9494 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9495 RFPT->getParamTypes(), EPI);
9496 } else {
9497 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9498 RFT->getExtInfo());
9499 }
9500 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9501 !S.IsFunctionConversion(rtrans, ltrans))
9503 }
9504 return ConvTy;
9505}
9506
9507/// checkBlockPointerTypesForAssignment - This routine determines whether two
9508/// block pointer types are compatible or whether a block and normal pointer
9509/// are compatible. It is more restrict than comparing two function pointer
9510// types.
9512 QualType LHSType,
9513 QualType RHSType) {
9514 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9515 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9516
9517 QualType lhptee, rhptee;
9518
9519 // get the "pointed to" type (ignoring qualifiers at the top level)
9520 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9521 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9522
9523 // In C++, the types have to match exactly.
9524 if (S.getLangOpts().CPlusPlus)
9526
9528
9529 // For blocks we enforce that qualifiers are identical.
9530 Qualifiers LQuals = lhptee.getLocalQualifiers();
9531 Qualifiers RQuals = rhptee.getLocalQualifiers();
9532 if (S.getLangOpts().OpenCL) {
9533 LQuals.removeAddressSpace();
9534 RQuals.removeAddressSpace();
9535 }
9536 if (LQuals != RQuals)
9538
9539 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9540 // assignment.
9541 // The current behavior is similar to C++ lambdas. A block might be
9542 // assigned to a variable iff its return type and parameters are compatible
9543 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9544 // an assignment. Presumably it should behave in way that a function pointer
9545 // assignment does in C, so for each parameter and return type:
9546 // * CVR and address space of LHS should be a superset of CVR and address
9547 // space of RHS.
9548 // * unqualified types should be compatible.
9549 if (S.getLangOpts().OpenCL) {
9551 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9552 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9554 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9556
9557 return ConvTy;
9558}
9559
9560/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9561/// for assignment compatibility.
9563 QualType LHSType,
9564 QualType RHSType) {
9565 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9566 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9567
9568 if (LHSType->isObjCBuiltinType()) {
9569 // Class is not compatible with ObjC object pointers.
9570 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9571 !RHSType->isObjCQualifiedClassType())
9574 }
9575 if (RHSType->isObjCBuiltinType()) {
9576 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9577 !LHSType->isObjCQualifiedClassType())
9580 }
9581 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9582 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9583
9584 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9585 // make an exception for id<P>
9586 !LHSType->isObjCQualifiedIdType())
9588
9589 if (S.Context.typesAreCompatible(LHSType, RHSType))
9591 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9594}
9595
9597 QualType LHSType,
9598 QualType RHSType) {
9599 // Fake up an opaque expression. We don't actually care about what
9600 // cast operations are required, so if CheckAssignmentConstraints
9601 // adds casts to this they'll be wasted, but fortunately that doesn't
9602 // usually happen on valid code.
9603 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9604 ExprResult RHSPtr = &RHSExpr;
9605 CastKind K;
9606
9607 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9608}
9609
9610/// This helper function returns true if QT is a vector type that has element
9611/// type ElementType.
9612static bool isVector(QualType QT, QualType ElementType) {
9613 if (const VectorType *VT = QT->getAs<VectorType>())
9614 return VT->getElementType().getCanonicalType() == ElementType;
9615 return false;
9616}
9617
9618/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9619/// has code to accommodate several GCC extensions when type checking
9620/// pointers. Here are some objectionable examples that GCC considers warnings:
9621///
9622/// int a, *pint;
9623/// short *pshort;
9624/// struct foo *pfoo;
9625///
9626/// pint = pshort; // warning: assignment from incompatible pointer type
9627/// a = pint; // warning: assignment makes integer from pointer without a cast
9628/// pint = a; // warning: assignment makes pointer from integer without a cast
9629/// pint = pfoo; // warning: assignment from incompatible pointer type
9630///
9631/// As a result, the code for dealing with pointers is more complex than the
9632/// C99 spec dictates.
9633///
9634/// Sets 'Kind' for any result kind except Incompatible.
9636 ExprResult &RHS,
9637 CastKind &Kind,
9638 bool ConvertRHS) {
9639 QualType RHSType = RHS.get()->getType();
9640 QualType OrigLHSType = LHSType;
9641
9642 // Get canonical types. We're not formatting these types, just comparing
9643 // them.
9644 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9645 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9646
9647 // Common case: no conversion required.
9648 if (LHSType == RHSType) {
9649 Kind = CK_NoOp;
9651 }
9652
9653 // If the LHS has an __auto_type, there are no additional type constraints
9654 // to be worried about.
9655 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9656 if (AT->isGNUAutoType()) {
9657 Kind = CK_NoOp;
9659 }
9660 }
9661
9662 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9663 switch (OBTResult) {
9665 Kind = CK_NoOp;
9668 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9672 break;
9673 }
9674
9675 // Check for incompatible OBT types in pointer pointee types
9676 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9677 QualType LHSPointee = LHSType->getPointeeType();
9678 QualType RHSPointee = RHSType->getPointeeType();
9679 if ((LHSPointee->isOverflowBehaviorType() ||
9680 RHSPointee->isOverflowBehaviorType()) &&
9681 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9682 Kind = CK_NoOp;
9684 }
9685 }
9686
9687 // If we have an atomic type, try a non-atomic assignment, then just add an
9688 // atomic qualification step.
9689 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9691 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9693 return Result;
9694 if (Kind != CK_NoOp && ConvertRHS)
9695 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9696 Kind = CK_NonAtomicToAtomic;
9697 return Result;
9698 }
9699
9700 // If the left-hand side is a reference type, then we are in a
9701 // (rare!) case where we've allowed the use of references in C,
9702 // e.g., as a parameter type in a built-in function. In this case,
9703 // just make sure that the type referenced is compatible with the
9704 // right-hand side type. The caller is responsible for adjusting
9705 // LHSType so that the resulting expression does not have reference
9706 // type.
9707 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9708 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9709 Kind = CK_LValueBitCast;
9711 }
9713 }
9714
9715 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9716 // of an ExtVector type to the same ExtVector type.
9717 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9718 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9719 // Implicit conversions require the same number of elements.
9720 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9722
9723 if (LHSType->isExtVectorBoolType() &&
9724 RHSExtType->getElementType()->isIntegerType()) {
9725 Kind = CK_IntegralToBoolean;
9727 }
9728 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9729 if (Context.getLangOpts().OpenCL &&
9730 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9731 Kind = CK_BitCast;
9733 }
9735 }
9736 if (RHSType->isArithmeticType()) {
9737 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9738 if (ConvertRHS)
9739 RHS = prepareVectorSplat(LHSType, RHS.get());
9740 Kind = CK_VectorSplat;
9742 }
9743 }
9744
9745 // Conversions to or from vector type.
9746 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9747 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9748 // Allow assignments of an AltiVec vector type to an equivalent GCC
9749 // vector type and vice versa
9750 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9751 Kind = CK_BitCast;
9753 }
9754
9755 // If we are allowing lax vector conversions, and LHS and RHS are both
9756 // vectors, the total size only needs to be the same. This is a bitcast;
9757 // no bits are changed but the result type is different.
9758 if (isLaxVectorConversion(RHSType, LHSType)) {
9759 // The default for lax vector conversions with Altivec vectors will
9760 // change, so if we are converting between vector types where
9761 // at least one is an Altivec vector, emit a warning.
9762 if (Context.getTargetInfo().getTriple().isPPC() &&
9763 anyAltivecTypes(RHSType, LHSType) &&
9764 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9765 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9766 << RHSType << LHSType;
9767 Kind = CK_BitCast;
9769 }
9770 }
9771
9772 // When the RHS comes from another lax conversion (e.g. binops between
9773 // scalars and vectors) the result is canonicalized as a vector. When the
9774 // LHS is also a vector, the lax is allowed by the condition above. Handle
9775 // the case where LHS is a scalar.
9776 if (LHSType->isScalarType()) {
9777 const VectorType *VecType = RHSType->getAs<VectorType>();
9778 if (VecType && VecType->getNumElements() == 1 &&
9779 isLaxVectorConversion(RHSType, LHSType)) {
9780 if (Context.getTargetInfo().getTriple().isPPC() &&
9782 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9784 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9785 << RHSType << LHSType;
9786 ExprResult *VecExpr = &RHS;
9787 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9788 Kind = CK_BitCast;
9790 }
9791 }
9792
9793 // Allow assignments between fixed-length and sizeless SVE vectors.
9794 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9795 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9796 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9797 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9798 Kind = CK_BitCast;
9800 }
9801
9802 // Allow assignments between fixed-length and sizeless RVV vectors.
9803 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9804 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9805 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9806 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9807 Kind = CK_BitCast;
9809 }
9810 }
9811
9813 }
9814
9815 // Diagnose attempts to convert between __ibm128, __float128 and long double
9816 // where such conversions currently can't be handled.
9817 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9819
9820 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9821 // discards the imaginary part.
9822 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9823 !LHSType->getAs<ComplexType>())
9825
9826 // Arithmetic conversions.
9827 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9828 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9829 if (ConvertRHS)
9830 Kind = PrepareScalarCast(RHS, LHSType);
9832 }
9833
9834 // Conversions to normal pointers.
9835 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9836 // U* -> T*
9837 if (isa<PointerType>(RHSType)) {
9838 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9839 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9840 if (AddrSpaceL != AddrSpaceR)
9841 Kind = CK_AddressSpaceConversion;
9842 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9843 Kind = CK_NoOp;
9844 else
9845 Kind = CK_BitCast;
9846 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9847 RHS.get()->getBeginLoc());
9848 }
9849
9850 // int -> T*
9851 if (RHSType->isIntegerType()) {
9852 Kind = CK_IntegralToPointer; // FIXME: null?
9854 }
9855
9856 // C pointers are not compatible with ObjC object pointers,
9857 // with two exceptions:
9858 if (isa<ObjCObjectPointerType>(RHSType)) {
9859 // - conversions to void*
9860 if (LHSPointer->getPointeeType()->isVoidType()) {
9861 Kind = CK_BitCast;
9863 }
9864
9865 // - conversions from 'Class' to the redefinition type
9866 if (RHSType->isObjCClassType() &&
9867 Context.hasSameType(LHSType,
9868 Context.getObjCClassRedefinitionType())) {
9869 Kind = CK_BitCast;
9871 }
9872
9873 Kind = CK_BitCast;
9875 }
9876
9877 // U^ -> void*
9878 if (RHSType->getAs<BlockPointerType>()) {
9879 if (LHSPointer->getPointeeType()->isVoidType()) {
9880 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9881 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9882 ->getPointeeType()
9883 .getAddressSpace();
9884 Kind =
9885 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9887 }
9888 }
9889
9891 }
9892
9893 // Conversions to block pointers.
9894 if (isa<BlockPointerType>(LHSType)) {
9895 // U^ -> T^
9896 if (RHSType->isBlockPointerType()) {
9897 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9898 ->getPointeeType()
9899 .getAddressSpace();
9900 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9901 ->getPointeeType()
9902 .getAddressSpace();
9903 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9904 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9905 }
9906
9907 // int or null -> T^
9908 if (RHSType->isIntegerType()) {
9909 Kind = CK_IntegralToPointer; // FIXME: null
9911 }
9912
9913 // id -> T^
9914 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9915 Kind = CK_AnyPointerToBlockPointerCast;
9917 }
9918
9919 // void* -> T^
9920 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9921 if (RHSPT->getPointeeType()->isVoidType()) {
9922 Kind = CK_AnyPointerToBlockPointerCast;
9924 }
9925
9927 }
9928
9929 // Conversions to Objective-C pointers.
9930 if (isa<ObjCObjectPointerType>(LHSType)) {
9931 // A* -> B*
9932 if (RHSType->isObjCObjectPointerType()) {
9933 Kind = CK_BitCast;
9934 AssignConvertType result =
9935 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9936 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9938 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9940 return result;
9941 }
9942
9943 // int or null -> A*
9944 if (RHSType->isIntegerType()) {
9945 Kind = CK_IntegralToPointer; // FIXME: null
9947 }
9948
9949 // In general, C pointers are not compatible with ObjC object pointers,
9950 // with two exceptions:
9951 if (isa<PointerType>(RHSType)) {
9952 Kind = CK_CPointerToObjCPointerCast;
9953
9954 // - conversions from 'void*'
9955 if (RHSType->isVoidPointerType()) {
9957 }
9958
9959 // - conversions to 'Class' from its redefinition type
9960 if (LHSType->isObjCClassType() &&
9961 Context.hasSameType(RHSType,
9962 Context.getObjCClassRedefinitionType())) {
9964 }
9965
9967 }
9968
9969 // Only under strict condition T^ is compatible with an Objective-C pointer.
9970 if (RHSType->isBlockPointerType() &&
9972 if (ConvertRHS)
9974 Kind = CK_BlockPointerToObjCPointerCast;
9976 }
9977
9979 }
9980
9981 // Conversion to nullptr_t (C23 only)
9982 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9985 // null -> nullptr_t
9986 Kind = CK_NullToPointer;
9988 }
9989
9990 // Conversions from pointers that are not covered by the above.
9991 if (isa<PointerType>(RHSType)) {
9992 // T* -> _Bool
9993 if (LHSType == Context.BoolTy) {
9994 Kind = CK_PointerToBoolean;
9996 }
9997
9998 // T* -> int
9999 if (LHSType->isIntegerType()) {
10000 Kind = CK_PointerToIntegral;
10002 }
10003
10005 }
10006
10007 // Conversions from Objective-C pointers that are not covered by the above.
10008 if (isa<ObjCObjectPointerType>(RHSType)) {
10009 // T* -> _Bool
10010 if (LHSType == Context.BoolTy) {
10011 Kind = CK_PointerToBoolean;
10013 }
10014
10015 // T* -> int
10016 if (LHSType->isIntegerType()) {
10017 Kind = CK_PointerToIntegral;
10019 }
10020
10022 }
10023
10024 // struct A -> struct B
10025 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10026 if (Context.typesAreCompatible(LHSType, RHSType)) {
10027 Kind = CK_NoOp;
10029 }
10030 }
10031
10032 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10033 Kind = CK_IntToOCLSampler;
10035 }
10036
10038}
10039
10040/// Constructs a transparent union from an expression that is
10041/// used to initialize the transparent union.
10043 ExprResult &EResult, QualType UnionType,
10044 FieldDecl *Field) {
10045 // Build an initializer list that designates the appropriate member
10046 // of the transparent union.
10047 Expr *E = EResult.get();
10049 E, SourceLocation());
10050 Initializer->setType(UnionType);
10051 Initializer->setInitializedFieldInUnion(Field);
10052
10053 // Build a compound literal constructing a value of the transparent
10054 // union type from this initializer list.
10055 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10056 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10057 VK_PRValue, Initializer, false);
10058}
10059
10062 ExprResult &RHS) {
10063 QualType RHSType = RHS.get()->getType();
10064
10065 // If the ArgType is a Union type, we want to handle a potential
10066 // transparent_union GCC extension.
10067 const RecordType *UT = ArgType->getAsUnionType();
10068 if (!UT)
10070
10071 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10072 if (!UD->hasAttr<TransparentUnionAttr>())
10074
10075 // The field to initialize within the transparent union.
10076 FieldDecl *InitField = nullptr;
10077 // It's compatible if the expression matches any of the fields.
10078 for (auto *it : UD->fields()) {
10079 if (it->getType()->isPointerType()) {
10080 // If the transparent union contains a pointer type, we allow:
10081 // 1) void pointer
10082 // 2) null pointer constant
10083 if (RHSType->isPointerType())
10084 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10085 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10086 InitField = it;
10087 break;
10088 }
10089
10092 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10093 CK_NullToPointer);
10094 InitField = it;
10095 break;
10096 }
10097 }
10098
10099 CastKind Kind;
10100 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10102 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10103 InitField = it;
10104 break;
10105 }
10106 }
10107
10108 if (!InitField)
10110
10111 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10113}
10114
10116 ExprResult &CallerRHS,
10117 bool Diagnose,
10118 bool DiagnoseCFAudited,
10119 bool ConvertRHS) {
10120 // We need to be able to tell the caller whether we diagnosed a problem, if
10121 // they ask us to issue diagnostics.
10122 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10123
10124 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10125 // we can't avoid *all* modifications at the moment, so we need some somewhere
10126 // to put the updated value.
10127 ExprResult LocalRHS = CallerRHS;
10128 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10129
10130 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10131 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10132 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10133 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10134 Diag(RHS.get()->getExprLoc(),
10135 diag::warn_noderef_to_dereferenceable_pointer)
10136 << RHS.get()->getSourceRange();
10137 }
10138 }
10139 }
10140
10141 if (getLangOpts().CPlusPlus) {
10142 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10143 // C++ 5.17p3: If the left operand is not of class type, the
10144 // expression is implicitly converted (C++ 4) to the
10145 // cv-unqualified type of the left operand.
10146 QualType RHSType = RHS.get()->getType();
10147 if (Diagnose) {
10148 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10150 } else {
10153 /*SuppressUserConversions=*/false,
10154 AllowedExplicit::None,
10155 /*InOverloadResolution=*/false,
10156 /*CStyle=*/false,
10157 /*AllowObjCWritebackConversion=*/false);
10158 if (ICS.isFailure())
10160 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10162 }
10163 if (RHS.isInvalid())
10166 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10167 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10169
10170 // Check if OBT is being discarded during assignment
10171 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10172 if (RHSType->isOverflowBehaviorType() &&
10173 !LHSType->isOverflowBehaviorType()) {
10175 }
10176
10177 return result;
10178 }
10179
10180 // FIXME: Currently, we fall through and treat C++ classes like C
10181 // structures.
10182 // FIXME: We also fall through for atomics; not sure what should
10183 // happen there, though.
10184 } else if (RHS.get()->getType() == Context.OverloadTy) {
10185 // As a set of extensions to C, we support overloading on functions. These
10186 // functions need to be resolved here.
10187 DeclAccessPair DAP;
10189 RHS.get(), LHSType, /*Complain=*/false, DAP))
10190 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10191 else
10193 }
10194
10195 // This check seems unnatural, however it is necessary to ensure the proper
10196 // conversion of functions/arrays. If the conversion were done for all
10197 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10198 // expressions that suppress this implicit conversion (&, sizeof). This needs
10199 // to happen before we check for null pointer conversions because C does not
10200 // undergo the same implicit conversions as C++ does above (by the calls to
10201 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10202 // lvalue to rvalue cast before checking for null pointer constraints. This
10203 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10204 //
10205 // Suppress this for references: C++ 8.5.3p5.
10206 if (!LHSType->isReferenceType()) {
10207 // FIXME: We potentially allocate here even if ConvertRHS is false.
10209 if (RHS.isInvalid())
10211 }
10212
10213 // The constraints are expressed in terms of the atomic, qualified, or
10214 // unqualified type of the LHS.
10215 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10216
10217 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10218 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10219 if ((LHSTypeAfterConversion->isPointerType() ||
10220 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10221 LHSTypeAfterConversion->isBlockPointerType()) &&
10222 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10226 if (Diagnose || ConvertRHS) {
10227 CastKind Kind;
10228 CXXCastPath Path;
10229 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10230 /*IgnoreBaseAccess=*/false, Diagnose);
10231
10232 // If there is a conversion of some kind, check to see what kind of
10233 // pointer conversion happened so we can diagnose a C++ compatibility
10234 // diagnostic if the conversion is invalid. This only matters if the RHS
10235 // is some kind of void pointer. We have a carve-out when the RHS is from
10236 // a macro expansion because the use of a macro may indicate different
10237 // code between C and C++. Consider: char *s = NULL; where NULL is
10238 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10239 // C++, which is valid in C++.
10240 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10241 !RHS.get()->getBeginLoc().isMacroID()) {
10242 QualType CanRHS =
10244 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10245 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10246 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10247 RHS.get()->getExprLoc());
10248 // Anything that's not considered perfectly compatible would be
10249 // incompatible in C++.
10252 }
10253 }
10254
10255 if (ConvertRHS)
10256 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10257 }
10258 return Ret;
10259 }
10260 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10261 // unqualified bool, and the right operand is a pointer or its type is
10262 // nullptr_t.
10263 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10264 RHS.get()->getType()->isNullPtrType()) {
10265 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10266 // only handles nullptr -> _Bool due to needing an extra conversion
10267 // step.
10268 // We model this by converting from nullptr -> void * and then let the
10269 // conversion from void * -> _Bool happen naturally.
10270 if (Diagnose || ConvertRHS) {
10271 CastKind Kind;
10272 CXXCastPath Path;
10273 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10274 /*IgnoreBaseAccess=*/false, Diagnose);
10275 if (ConvertRHS)
10276 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10277 &Path);
10278 }
10279 }
10280
10281 // OpenCL queue_t type assignment.
10282 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10284 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10286 }
10287
10288 CastKind Kind;
10289 AssignConvertType result =
10290 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10291
10292 // If assigning a void * created by an allocation function call to some other
10293 // type, check that the allocated size is sufficient for that type.
10294 if (result != AssignConvertType::Incompatible &&
10295 RHS.get()->getType()->isVoidPointerType())
10296 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10297
10298 // C99 6.5.16.1p2: The value of the right operand is converted to the
10299 // type of the assignment expression.
10300 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10301 // so that we can use references in built-in functions even in C.
10302 // The getNonReferenceType() call makes sure that the resulting expression
10303 // does not have reference type.
10304 if (result != AssignConvertType::Incompatible &&
10305 RHS.get()->getType() != LHSType) {
10307 Expr *E = RHS.get();
10308
10309 // Check for various Objective-C errors. If we are not reporting
10310 // diagnostics and just checking for errors, e.g., during overload
10311 // resolution, return Incompatible to indicate the failure.
10312 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10313 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10315 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10316 if (!Diagnose)
10318 }
10319 if (getLangOpts().ObjC &&
10320 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10321 E->getType(), E, Diagnose) ||
10322 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10323 if (!Diagnose)
10325 // Replace the expression with a corrected version and continue so we
10326 // can find further errors.
10327 RHS = E;
10329 }
10330
10331 if (ConvertRHS)
10332 RHS = ImpCastExprToType(E, Ty, Kind);
10333 }
10334
10335 return result;
10336}
10337
10338namespace {
10339/// The original operand to an operator, prior to the application of the usual
10340/// arithmetic conversions and converting the arguments of a builtin operator
10341/// candidate.
10342struct OriginalOperand {
10343 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10344 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10345 Op = MTE->getSubExpr();
10346 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10347 Op = BTE->getSubExpr();
10348 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10349 Orig = ICE->getSubExprAsWritten();
10350 Conversion = ICE->getConversionFunction();
10351 }
10352 }
10353
10354 QualType getType() const { return Orig->getType(); }
10355
10356 Expr *Orig;
10357 NamedDecl *Conversion;
10358};
10359}
10360
10362 ExprResult &RHS) {
10363 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10364
10365 Diag(Loc, diag::err_typecheck_invalid_operands)
10366 << OrigLHS.getType() << OrigRHS.getType()
10367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10368
10369 // If a user-defined conversion was applied to either of the operands prior
10370 // to applying the built-in operator rules, tell the user about it.
10371 if (OrigLHS.Conversion) {
10372 Diag(OrigLHS.Conversion->getLocation(),
10373 diag::note_typecheck_invalid_operands_converted)
10374 << 0 << LHS.get()->getType();
10375 }
10376 if (OrigRHS.Conversion) {
10377 Diag(OrigRHS.Conversion->getLocation(),
10378 diag::note_typecheck_invalid_operands_converted)
10379 << 1 << RHS.get()->getType();
10380 }
10381
10382 return QualType();
10383}
10384
10386 ExprResult &RHS) {
10387 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10388 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10389
10390 bool LHSNatVec = LHSType->isVectorType();
10391 bool RHSNatVec = RHSType->isVectorType();
10392
10393 if (!(LHSNatVec && RHSNatVec)) {
10394 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10395 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10396 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10397 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10398 << Vector->getSourceRange();
10399 return QualType();
10400 }
10401
10402 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10403 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10404 << RHS.get()->getSourceRange();
10405
10406 return QualType();
10407}
10408
10409/// Try to convert a value of non-vector type to a vector type by converting
10410/// the type to the element type of the vector and then performing a splat.
10411/// If the language is OpenCL, we only use conversions that promote scalar
10412/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10413/// for float->int.
10414///
10415/// OpenCL V2.0 6.2.6.p2:
10416/// An error shall occur if any scalar operand type has greater rank
10417/// than the type of the vector element.
10418///
10419/// \param scalar - if non-null, actually perform the conversions
10420/// \return true if the operation fails (but without diagnosing the failure)
10422 QualType scalarTy,
10423 QualType vectorEltTy,
10424 QualType vectorTy,
10425 unsigned &DiagID) {
10426 // The conversion to apply to the scalar before splatting it,
10427 // if necessary.
10428 CastKind scalarCast = CK_NoOp;
10429
10430 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10431 scalarCast = CK_IntegralToBoolean;
10432 } else if (vectorEltTy->isIntegralType(S.Context)) {
10433 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10434 (scalarTy->isIntegerType() &&
10435 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10436 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10437 return true;
10438 }
10439 if (!scalarTy->isIntegralType(S.Context))
10440 return true;
10441 scalarCast = CK_IntegralCast;
10442 } else if (vectorEltTy->isRealFloatingType()) {
10443 if (scalarTy->isRealFloatingType()) {
10444 if (S.getLangOpts().OpenCL &&
10445 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10446 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10447 return true;
10448 }
10449 scalarCast = CK_FloatingCast;
10450 }
10451 else if (scalarTy->isIntegralType(S.Context))
10452 scalarCast = CK_IntegralToFloating;
10453 else
10454 return true;
10455 } else {
10456 return true;
10457 }
10458
10459 // Adjust scalar if desired.
10460 if (scalar) {
10461 if (scalarCast != CK_NoOp)
10462 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10463 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10464 }
10465 return false;
10466}
10467
10468/// Convert vector E to a vector with the same number of elements but different
10469/// element type.
10470static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10471 const auto *VecTy = E->getType()->getAs<VectorType>();
10472 assert(VecTy && "Expression E must be a vector");
10473 QualType NewVecTy =
10474 VecTy->isExtVectorType()
10475 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10476 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10477 VecTy->getVectorKind());
10478
10479 // Look through the implicit cast. Return the subexpression if its type is
10480 // NewVecTy.
10481 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10482 if (ICE->getSubExpr()->getType() == NewVecTy)
10483 return ICE->getSubExpr();
10484
10485 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10486 return S.ImpCastExprToType(E, NewVecTy, Cast);
10487}
10488
10489/// Test if a (constant) integer Int can be casted to another integer type
10490/// IntTy without losing precision.
10492 QualType OtherIntTy) {
10493 Expr *E = Int->get();
10495 return false;
10496
10497 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10498
10499 // Reject cases where the value of the Int is unknown as that would
10500 // possibly cause truncation, but accept cases where the scalar can be
10501 // demoted without loss of precision.
10502 Expr::EvalResult EVResult;
10503 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10504 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10505 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10506 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10507
10508 if (CstInt) {
10509 // If the scalar is constant and is of a higher order and has more active
10510 // bits that the vector element type, reject it.
10511 llvm::APSInt Result = EVResult.Val.getInt();
10512 unsigned NumBits = IntSigned
10513 ? (Result.isNegative() ? Result.getSignificantBits()
10514 : Result.getActiveBits())
10515 : Result.getActiveBits();
10516 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10517 return true;
10518
10519 // If the signedness of the scalar type and the vector element type
10520 // differs and the number of bits is greater than that of the vector
10521 // element reject it.
10522 return (IntSigned != OtherIntSigned &&
10523 NumBits > S.Context.getIntWidth(OtherIntTy));
10524 }
10525
10526 // Reject cases where the value of the scalar is not constant and it's
10527 // order is greater than that of the vector element type.
10528 return (Order < 0);
10529}
10530
10531/// Test if a (constant) integer Int can be casted to floating point type
10532/// FloatTy without losing precision.
10534 QualType FloatTy) {
10535 if (Int->get()->containsErrors())
10536 return false;
10537
10538 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10539
10540 // Determine if the integer constant can be expressed as a floating point
10541 // number of the appropriate type.
10542 Expr::EvalResult EVResult;
10543 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10544
10545 uint64_t Bits = 0;
10546 if (CstInt) {
10547 // Reject constants that would be truncated if they were converted to
10548 // the floating point type. Test by simple to/from conversion.
10549 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10550 // could be avoided if there was a convertFromAPInt method
10551 // which could signal back if implicit truncation occurred.
10552 llvm::APSInt Result = EVResult.Val.getInt();
10553 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10554 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10555 llvm::APFloat::rmTowardZero);
10556 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10558 bool Ignored = false;
10559 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10560 &Ignored);
10561 if (Result != ConvertBack)
10562 return true;
10563 } else {
10564 // Reject types that cannot be fully encoded into the mantissa of
10565 // the float.
10566 Bits = S.Context.getTypeSize(IntTy);
10567 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10568 S.Context.getFloatTypeSemantics(FloatTy));
10569 if (Bits > FloatPrec)
10570 return true;
10571 }
10572
10573 return false;
10574}
10575
10576/// Attempt to convert and splat Scalar into a vector whose types matches
10577/// Vector following GCC conversion rules. The rule is that implicit
10578/// conversion can occur when Scalar can be casted to match Vector's element
10579/// type without causing truncation of Scalar.
10581 ExprResult *Vector) {
10582 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10583 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10584 QualType VectorEltTy;
10585
10586 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10587 assert(!isa<ExtVectorType>(VT) &&
10588 "ExtVectorTypes should not be handled here!");
10589 VectorEltTy = VT->getElementType();
10590 } else if (VectorTy->isSveVLSBuiltinType()) {
10591 VectorEltTy =
10592 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10593 } else {
10594 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10595 }
10596
10597 // Reject cases where the vector element type or the scalar element type are
10598 // not integral or floating point types.
10599 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10600 return true;
10601
10602 // The conversion to apply to the scalar before splatting it,
10603 // if necessary.
10604 CastKind ScalarCast = CK_NoOp;
10605
10606 // Accept cases where the vector elements are integers and the scalar is
10607 // an integer.
10608 // FIXME: Notionally if the scalar was a floating point value with a precise
10609 // integral representation, we could cast it to an appropriate integer
10610 // type and then perform the rest of the checks here. GCC will perform
10611 // this conversion in some cases as determined by the input language.
10612 // We should accept it on a language independent basis.
10613 if (VectorEltTy->isIntegralType(S.Context) &&
10614 ScalarTy->isIntegralType(S.Context) &&
10615 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10616
10617 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10618 return true;
10619
10620 ScalarCast = CK_IntegralCast;
10621 } else if (VectorEltTy->isIntegralType(S.Context) &&
10622 ScalarTy->isRealFloatingType()) {
10623 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10624 ScalarCast = CK_FloatingToIntegral;
10625 else
10626 return true;
10627 } else if (VectorEltTy->isRealFloatingType()) {
10628 if (ScalarTy->isRealFloatingType()) {
10629
10630 // Reject cases where the scalar type is not a constant and has a higher
10631 // Order than the vector element type.
10632 llvm::APFloat Result(0.0);
10633
10634 // Determine whether this is a constant scalar. In the event that the
10635 // value is dependent (and thus cannot be evaluated by the constant
10636 // evaluator), skip the evaluation. This will then diagnose once the
10637 // expression is instantiated.
10638 bool CstScalar = Scalar->get()->isValueDependent() ||
10639 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10640 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10641 if (!CstScalar && Order < 0)
10642 return true;
10643
10644 // If the scalar cannot be safely casted to the vector element type,
10645 // reject it.
10646 if (CstScalar) {
10647 bool Truncated = false;
10648 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10649 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10650 if (Truncated)
10651 return true;
10652 }
10653
10654 ScalarCast = CK_FloatingCast;
10655 } else if (ScalarTy->isIntegralType(S.Context)) {
10656 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10657 return true;
10658
10659 ScalarCast = CK_IntegralToFloating;
10660 } else
10661 return true;
10662 } else if (ScalarTy->isEnumeralType())
10663 return true;
10664
10665 // Adjust scalar if desired.
10666 if (ScalarCast != CK_NoOp)
10667 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10668 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10669 return false;
10670}
10671
10673 SourceLocation Loc, bool IsCompAssign,
10674 bool AllowBothBool,
10675 bool AllowBoolConversions,
10676 bool AllowBoolOperation,
10677 bool ReportInvalid) {
10678 if (!IsCompAssign) {
10680 if (LHS.isInvalid())
10681 return QualType();
10682 }
10684 if (RHS.isInvalid())
10685 return QualType();
10686
10687 // For conversion purposes, we ignore any qualifiers.
10688 // For example, "const float" and "float" are equivalent.
10689 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10690 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10691
10692 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10693 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10694 assert(LHSVecType || RHSVecType);
10695
10696 if (getLangOpts().HLSL)
10697 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10698 IsCompAssign);
10699
10700 // Any operation with MFloat8 type is only possible with C intrinsics
10701 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10702 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10703 return InvalidOperands(Loc, LHS, RHS);
10704
10705 // AltiVec-style "vector bool op vector bool" combinations are allowed
10706 // for some operators but not others.
10707 if (!AllowBothBool && LHSVecType &&
10708 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10709 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10710 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10711
10712 // This operation may not be performed on boolean vectors.
10713 if (!AllowBoolOperation &&
10714 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10715 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10716
10717 // If the vector types are identical, return.
10718 if (Context.hasSameType(LHSType, RHSType))
10719 return Context.getCommonSugaredType(LHSType, RHSType);
10720
10721 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10722 if (LHSVecType && RHSVecType &&
10723 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10724 if (isa<ExtVectorType>(LHSVecType)) {
10725 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10726 return LHSType;
10727 }
10728
10729 if (!IsCompAssign)
10730 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10731 return RHSType;
10732 }
10733
10734 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10735 // can be mixed, with the result being the non-bool type. The non-bool
10736 // operand must have integer element type.
10737 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10738 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10739 (Context.getTypeSize(LHSVecType->getElementType()) ==
10740 Context.getTypeSize(RHSVecType->getElementType()))) {
10741 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10742 LHSVecType->getElementType()->isIntegerType() &&
10743 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10744 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10745 return LHSType;
10746 }
10747 if (!IsCompAssign &&
10748 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10749 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10750 RHSVecType->getElementType()->isIntegerType()) {
10751 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10752 return RHSType;
10753 }
10754 }
10755
10756 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10757 // invalid since the ambiguity can affect the ABI.
10758 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10759 unsigned &SVEorRVV) {
10760 const VectorType *VecType = SecondType->getAs<VectorType>();
10761 SVEorRVV = 0;
10762 if (FirstType->isSizelessBuiltinType() && VecType) {
10765 return true;
10771 SVEorRVV = 1;
10772 return true;
10773 }
10774 }
10775
10776 return false;
10777 };
10778
10779 unsigned SVEorRVV;
10780 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10781 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10782 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10783 << SVEorRVV << LHSType << RHSType;
10784 return QualType();
10785 }
10786
10787 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10788 // invalid since the ambiguity can affect the ABI.
10789 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10790 unsigned &SVEorRVV) {
10791 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10792 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10793
10794 SVEorRVV = 0;
10795 if (FirstVecType && SecondVecType) {
10796 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10797 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10798 SecondVecType->getVectorKind() ==
10800 return true;
10801 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10802 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10803 SecondVecType->getVectorKind() ==
10805 SecondVecType->getVectorKind() ==
10807 SecondVecType->getVectorKind() ==
10809 SVEorRVV = 1;
10810 return true;
10811 }
10812 }
10813 return false;
10814 }
10815
10816 if (SecondVecType &&
10817 SecondVecType->getVectorKind() == VectorKind::Generic) {
10818 if (FirstType->isSVESizelessBuiltinType())
10819 return true;
10820 if (FirstType->isRVVSizelessBuiltinType()) {
10821 SVEorRVV = 1;
10822 return true;
10823 }
10824 }
10825
10826 return false;
10827 };
10828
10829 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10830 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10831 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10832 << SVEorRVV << LHSType << RHSType;
10833 return QualType();
10834 }
10835
10836 // If there's a vector type and a scalar, try to convert the scalar to
10837 // the vector element type and splat.
10838 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10839 if (!RHSVecType) {
10840 if (isa<ExtVectorType>(LHSVecType)) {
10841 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10842 LHSVecType->getElementType(), LHSType,
10843 DiagID))
10844 return LHSType;
10845 } else {
10846 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10847 return LHSType;
10848 }
10849 }
10850 if (!LHSVecType) {
10851 if (isa<ExtVectorType>(RHSVecType)) {
10852 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10853 LHSType, RHSVecType->getElementType(),
10854 RHSType, DiagID))
10855 return RHSType;
10856 } else {
10857 if (LHS.get()->isLValue() ||
10858 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10859 return RHSType;
10860 }
10861 }
10862
10863 // FIXME: The code below also handles conversion between vectors and
10864 // non-scalars, we should break this down into fine grained specific checks
10865 // and emit proper diagnostics.
10866 QualType VecType = LHSVecType ? LHSType : RHSType;
10867 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10868 QualType OtherType = LHSVecType ? RHSType : LHSType;
10869 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10870 if (isLaxVectorConversion(OtherType, VecType)) {
10871 if (Context.getTargetInfo().getTriple().isPPC() &&
10872 anyAltivecTypes(RHSType, LHSType) &&
10873 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10874 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10875 // If we're allowing lax vector conversions, only the total (data) size
10876 // needs to be the same. For non compound assignment, if one of the types is
10877 // scalar, the result is always the vector type.
10878 if (!IsCompAssign) {
10879 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10880 return VecType;
10881 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10882 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10883 // type. Note that this is already done by non-compound assignments in
10884 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10885 // <1 x T> -> T. The result is also a vector type.
10886 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10887 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10888 ExprResult *RHSExpr = &RHS;
10889 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10890 return VecType;
10891 }
10892 }
10893
10894 // Okay, the expression is invalid.
10895
10896 // If there's a non-vector, non-real operand, diagnose that.
10897 if ((!RHSVecType && !RHSType->isRealType()) ||
10898 (!LHSVecType && !LHSType->isRealType())) {
10899 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10900 << LHSType << RHSType
10901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10902 return QualType();
10903 }
10904
10905 // OpenCL V1.1 6.2.6.p1:
10906 // If the operands are of more than one vector type, then an error shall
10907 // occur. Implicit conversions between vector types are not permitted, per
10908 // section 6.2.1.
10909 if (getLangOpts().OpenCL &&
10910 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10911 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10912 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10913 << RHSType;
10914 return QualType();
10915 }
10916
10917
10918 // If there is a vector type that is not a ExtVector and a scalar, we reach
10919 // this point if scalar could not be converted to the vector's element type
10920 // without truncation.
10921 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10922 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10923 QualType Scalar = LHSVecType ? RHSType : LHSType;
10924 QualType Vector = LHSVecType ? LHSType : RHSType;
10925 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10926 Diag(Loc,
10927 diag::err_typecheck_vector_not_convertable_implict_truncation)
10928 << ScalarOrVector << Scalar << Vector;
10929
10930 return QualType();
10931 }
10932
10933 // Otherwise, use the generic diagnostic.
10934 Diag(Loc, DiagID)
10935 << LHSType << RHSType
10936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10937 return QualType();
10938}
10939
10941 SourceLocation Loc,
10942 bool IsCompAssign,
10943 ArithConvKind OperationKind) {
10944 if (!IsCompAssign) {
10946 if (LHS.isInvalid())
10947 return QualType();
10948 }
10950 if (RHS.isInvalid())
10951 return QualType();
10952
10953 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10954 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10955
10956 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10957 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10958
10959 unsigned DiagID = diag::err_typecheck_invalid_operands;
10960 if ((OperationKind == ArithConvKind::Arithmetic) &&
10961 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10962 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10963 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10964 << RHS.get()->getSourceRange();
10965 return QualType();
10966 }
10967
10968 if (Context.hasSameType(LHSType, RHSType))
10969 return LHSType;
10970
10971 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10972 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10973 return LHSType;
10974 }
10975 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10976 if (LHS.get()->isLValue() ||
10977 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10978 return RHSType;
10979 }
10980
10981 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10982 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10983 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10984 << LHSType << RHSType << LHS.get()->getSourceRange()
10985 << RHS.get()->getSourceRange();
10986 return QualType();
10987 }
10988
10989 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10990 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10991 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10992 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10993 << LHSType << RHSType << LHS.get()->getSourceRange()
10994 << RHS.get()->getSourceRange();
10995 return QualType();
10996 }
10997
10998 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10999 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11000 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11001 bool ScalarOrVector =
11002 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11003
11004 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11005 << ScalarOrVector << Scalar << Vector;
11006
11007 return QualType();
11008 }
11009
11010 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11011 << RHS.get()->getSourceRange();
11012 return QualType();
11013}
11014
11015// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11016// expression. These are mainly cases where the null pointer is used as an
11017// integer instead of a pointer.
11019 SourceLocation Loc, bool IsCompare) {
11020 // The canonical way to check for a GNU null is with isNullPointerConstant,
11021 // but we use a bit of a hack here for speed; this is a relatively
11022 // hot path, and isNullPointerConstant is slow.
11023 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11024 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11025
11026 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11027
11028 // Avoid analyzing cases where the result will either be invalid (and
11029 // diagnosed as such) or entirely valid and not something to warn about.
11030 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11031 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11032 return;
11033
11034 // Comparison operations would not make sense with a null pointer no matter
11035 // what the other expression is.
11036 if (!IsCompare) {
11037 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11038 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11039 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11040 return;
11041 }
11042
11043 // The rest of the operations only make sense with a null pointer
11044 // if the other expression is a pointer.
11045 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11046 NonNullType->canDecayToPointerType())
11047 return;
11048
11049 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11050 << LHSNull /* LHS is NULL */ << NonNullType
11051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11052}
11053
11055 SourceLocation OpLoc) {
11056 // If the divisor is real, then this is real/real or complex/real division.
11057 // Either way there can be no precision loss.
11058 auto *CT = DivisorTy->getAs<ComplexType>();
11059 if (!CT)
11060 return;
11061
11062 QualType ElementType = CT->getElementType().getCanonicalType();
11063 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11065 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11066 return;
11067
11068 ASTContext &Ctx = S.getASTContext();
11069 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11070 const llvm::fltSemantics &ElementTypeSemantics =
11071 Ctx.getFloatTypeSemantics(ElementType);
11072 const llvm::fltSemantics &HigherElementTypeSemantics =
11073 Ctx.getFloatTypeSemantics(HigherElementType);
11074
11075 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11076 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11077 (HigherElementType == Ctx.LongDoubleTy &&
11078 !Ctx.getTargetInfo().hasLongDoubleType())) {
11079 // Retain the location of the first use of higher precision type.
11082 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11083 if (Type == HigherElementType) {
11084 Num++;
11085 return;
11086 }
11087 }
11088 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11089 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11090 }
11091}
11092
11094 SourceLocation Loc) {
11095 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11096 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11097 if (!LUE || !RUE)
11098 return;
11099 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11100 RUE->getKind() != UETT_SizeOf)
11101 return;
11102
11103 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11104 QualType LHSTy = LHSArg->getType();
11105 QualType RHSTy;
11106
11107 if (RUE->isArgumentType())
11108 RHSTy = RUE->getArgumentType().getNonReferenceType();
11109 else
11110 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11111
11112 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11113 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11114 return;
11115
11116 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11117 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11118 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11119 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11120 << LHSArgDecl;
11121 }
11122 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11123 QualType ArrayElemTy = ArrayTy->getElementType();
11124 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11125 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11126 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11127 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11128 return;
11129 S.Diag(Loc, diag::warn_division_sizeof_array)
11130 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11131 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11132 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11133 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11134 << LHSArgDecl;
11135 }
11136
11137 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11138 }
11139}
11140
11142 ExprResult &RHS,
11143 SourceLocation Loc, bool IsDiv) {
11144 // Check for division/remainder by zero.
11145 Expr::EvalResult RHSValue;
11146 if (!RHS.get()->isValueDependent() &&
11147 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11148 RHSValue.Val.getInt() == 0)
11149 S.DiagRuntimeBehavior(Loc, RHS.get(),
11150 S.PDiag(diag::warn_remainder_division_by_zero)
11151 << IsDiv << RHS.get()->getSourceRange());
11152}
11153
11154static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11155 const ExprResult &LHS, const ExprResult &RHS,
11156 BinaryOperatorKind Opc) {
11157 if (!LHS.isUsable() || !RHS.isUsable())
11158 return;
11159 const Expr *LHSExpr = LHS.get();
11160 const Expr *RHSExpr = RHS.get();
11161 const QualType LHSType = LHSExpr->getType();
11162 const QualType RHSType = RHSExpr->getType();
11163 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11164 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11165 if (!LHSIsScoped && !RHSIsScoped)
11166 return;
11167 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11168 return;
11169 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11170 return;
11171 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11172 return;
11173 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11174 SourceLocation BeginLoc = expr->getBeginLoc();
11175 QualType IntType = type->castAs<EnumType>()
11176 ->getDecl()
11177 ->getDefinitionOrSelf()
11178 ->getIntegerType();
11179 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11180 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11181 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11182 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11183 };
11184 if (LHSIsScoped) {
11185 DiagnosticHelper(LHSExpr, LHSType);
11186 }
11187 if (RHSIsScoped) {
11188 DiagnosticHelper(RHSExpr, RHSType);
11189 }
11190}
11191
11193 SourceLocation Loc,
11194 BinaryOperatorKind Opc) {
11195 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11196 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11197
11198 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11199
11200 QualType LHSTy = LHS.get()->getType();
11201 QualType RHSTy = RHS.get()->getType();
11202 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11203 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11204 /*AllowBothBool*/ getLangOpts().AltiVec,
11205 /*AllowBoolConversions*/ false,
11206 /*AllowBooleanOperation*/ false,
11207 /*ReportInvalid*/ true);
11208 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11209 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11211 if (!IsDiv &&
11212 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11213 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11214 // For division, only matrix-by-scalar is supported. Other combinations with
11215 // matrix types are invalid.
11216 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11217 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11218
11220 LHS, RHS, Loc,
11222 if (LHS.isInvalid() || RHS.isInvalid())
11223 return QualType();
11224
11225 if (compType.isNull() || !compType->isArithmeticType()) {
11226 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11227 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11228 return ResultTy;
11229 }
11230 if (IsDiv) {
11231 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11232 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11233 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11234 }
11235 return compType;
11236}
11237
11239 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11240 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11241
11242 // Note: This check is here to simplify the double exclusions of
11243 // scalar and vector HLSL checks. No getLangOpts().HLSL
11244 // is needed since all languages exlcude doubles.
11245 if (LHS.get()->getType()->isDoubleType() ||
11246 RHS.get()->getType()->isDoubleType() ||
11247 (LHS.get()->getType()->isVectorType() && LHS.get()
11248 ->getType()
11249 ->getAs<VectorType>()
11250 ->getElementType()
11251 ->isDoubleType()) ||
11252 (RHS.get()->getType()->isVectorType() && RHS.get()
11253 ->getType()
11254 ->getAs<VectorType>()
11255 ->getElementType()
11256 ->isDoubleType()))
11257 return InvalidOperands(Loc, LHS, RHS);
11258
11259 if (LHS.get()->getType()->isVectorType() ||
11260 RHS.get()->getType()->isVectorType()) {
11261 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11262 RHS.get()->getType()->hasIntegerRepresentation()) ||
11263 (getLangOpts().HLSL &&
11264 (LHS.get()->getType()->hasFloatingRepresentation() ||
11266 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11267 /*AllowBothBool*/ getLangOpts().AltiVec,
11268 /*AllowBoolConversions*/ false,
11269 /*AllowBooleanOperation*/ false,
11270 /*ReportInvalid*/ true);
11271 return InvalidOperands(Loc, LHS, RHS);
11272 }
11273
11274 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11275 RHS.get()->getType()->isSveVLSBuiltinType()) {
11276 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11278 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11280
11281 return InvalidOperands(Loc, LHS, RHS);
11282 }
11283
11285 LHS, RHS, Loc,
11287 if (LHS.isInvalid() || RHS.isInvalid())
11288 return QualType();
11289
11290 if (compType.isNull() ||
11291 (!compType->isIntegerType() &&
11292 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11293 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11294 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11295 IsCompAssign ? BO_RemAssign : BO_Rem);
11296 return ResultTy;
11297 }
11298 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11299 return compType;
11300}
11301
11302/// Diagnose invalid arithmetic on two void pointers.
11304 Expr *LHSExpr, Expr *RHSExpr) {
11305 S.Diag(Loc, S.getLangOpts().CPlusPlus
11306 ? diag::err_typecheck_pointer_arith_void_type
11307 : diag::ext_gnu_void_ptr)
11308 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11309 << RHSExpr->getSourceRange();
11310}
11311
11312/// Diagnose invalid arithmetic on a void pointer.
11314 Expr *Pointer) {
11315 S.Diag(Loc, S.getLangOpts().CPlusPlus
11316 ? diag::err_typecheck_pointer_arith_void_type
11317 : diag::ext_gnu_void_ptr)
11318 << 0 /* one pointer */ << Pointer->getSourceRange();
11319}
11320
11321/// Diagnose invalid arithmetic on a null pointer.
11322///
11323/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11324/// idiom, which we recognize as a GNU extension.
11325///
11327 Expr *Pointer, bool IsGNUIdiom) {
11328 if (IsGNUIdiom)
11329 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11330 << Pointer->getSourceRange();
11331 else
11332 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11333 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11334}
11335
11336/// Diagnose invalid subraction on a null pointer.
11337///
11339 Expr *Pointer, bool BothNull) {
11340 // Null - null is valid in C++ [expr.add]p7
11341 if (BothNull && S.getLangOpts().CPlusPlus)
11342 return;
11343
11344 // Is this s a macro from a system header?
11346 return;
11347
11349 S.PDiag(diag::warn_pointer_sub_null_ptr)
11350 << S.getLangOpts().CPlusPlus
11351 << Pointer->getSourceRange());
11352}
11353
11354/// Diagnose invalid arithmetic on two function pointers.
11356 Expr *LHS, Expr *RHS) {
11357 assert(LHS->getType()->isAnyPointerType());
11358 assert(RHS->getType()->isAnyPointerType());
11359 S.Diag(Loc, S.getLangOpts().CPlusPlus
11360 ? diag::err_typecheck_pointer_arith_function_type
11361 : diag::ext_gnu_ptr_func_arith)
11362 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11363 // We only show the second type if it differs from the first.
11365 RHS->getType())
11366 << RHS->getType()->getPointeeType()
11367 << LHS->getSourceRange() << RHS->getSourceRange();
11368}
11369
11370/// Diagnose invalid arithmetic on a function pointer.
11372 Expr *Pointer) {
11373 assert(Pointer->getType()->isAnyPointerType());
11374 S.Diag(Loc, S.getLangOpts().CPlusPlus
11375 ? diag::err_typecheck_pointer_arith_function_type
11376 : diag::ext_gnu_ptr_func_arith)
11377 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11378 << 0 /* one pointer, so only one type */
11379 << Pointer->getSourceRange();
11380}
11381
11382/// Emit error if Operand is incomplete pointer type
11383///
11384/// \returns True if pointer has incomplete type
11386 Expr *Operand) {
11387 QualType ResType = Operand->getType();
11388 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11389 ResType = ResAtomicType->getValueType();
11390
11391 assert(ResType->isAnyPointerType());
11392 QualType PointeeTy = ResType->getPointeeType();
11393 return S.RequireCompleteSizedType(
11394 Loc, PointeeTy,
11395 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11396 Operand->getSourceRange());
11397}
11398
11399/// Check the validity of an arithmetic pointer operand.
11400///
11401/// If the operand has pointer type, this code will check for pointer types
11402/// which are invalid in arithmetic operations. These will be diagnosed
11403/// appropriately, including whether or not the use is supported as an
11404/// extension.
11405///
11406/// \returns True when the operand is valid to use (even if as an extension).
11408 Expr *Operand) {
11409 QualType ResType = Operand->getType();
11410 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11411 ResType = ResAtomicType->getValueType();
11412
11413 if (!ResType->isAnyPointerType()) return true;
11414
11415 QualType PointeeTy = ResType->getPointeeType();
11416 if (PointeeTy->isVoidType()) {
11417 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11418 return !S.getLangOpts().CPlusPlus;
11419 }
11420 if (PointeeTy->isFunctionType()) {
11421 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11422 return !S.getLangOpts().CPlusPlus;
11423 }
11424
11425 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11426
11427 return true;
11428}
11429
11430/// Check the validity of a binary arithmetic operation w.r.t. pointer
11431/// operands.
11432///
11433/// This routine will diagnose any invalid arithmetic on pointer operands much
11434/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11435/// for emitting a single diagnostic even for operations where both LHS and RHS
11436/// are (potentially problematic) pointers.
11437///
11438/// \returns True when the operand is valid to use (even if as an extension).
11440 Expr *LHSExpr, Expr *RHSExpr) {
11441 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11442 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11443 if (!isLHSPointer && !isRHSPointer) return true;
11444
11445 QualType LHSPointeeTy, RHSPointeeTy;
11446 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11447 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11448
11449 // if both are pointers check if operation is valid wrt address spaces
11450 if (isLHSPointer && isRHSPointer) {
11451 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11452 S.getASTContext())) {
11453 S.Diag(Loc,
11454 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11455 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11456 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11457 return false;
11458 }
11459 }
11460
11461 // Check for arithmetic on pointers to incomplete types.
11462 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11463 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11464 if (isLHSVoidPtr || isRHSVoidPtr) {
11465 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11466 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11467 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11468
11469 return !S.getLangOpts().CPlusPlus;
11470 }
11471
11472 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11473 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11474 if (isLHSFuncPtr || isRHSFuncPtr) {
11475 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11476 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11477 RHSExpr);
11478 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11479
11480 return !S.getLangOpts().CPlusPlus;
11481 }
11482
11483 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11484 return false;
11485 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11486 return false;
11487
11488 return true;
11489}
11490
11491/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11492/// literal.
11494 Expr *LHSExpr, Expr *RHSExpr) {
11495 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11496 Expr* IndexExpr = RHSExpr;
11497 if (!StrExpr) {
11498 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11499 IndexExpr = LHSExpr;
11500 }
11501
11502 bool IsStringPlusInt = StrExpr &&
11504 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11505 return;
11506
11507 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11508 Self.Diag(OpLoc, diag::warn_string_plus_int)
11509 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11510
11511 // Only print a fixit for "str" + int, not for int + "str".
11512 if (IndexExpr == RHSExpr) {
11513 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11514 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11515 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11517 << FixItHint::CreateInsertion(EndLoc, "]");
11518 } else
11519 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11520}
11521
11522/// Emit a warning when adding a char literal to a string.
11524 Expr *LHSExpr, Expr *RHSExpr) {
11525 const Expr *StringRefExpr = LHSExpr;
11526 const CharacterLiteral *CharExpr =
11527 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11528
11529 if (!CharExpr) {
11530 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11531 StringRefExpr = RHSExpr;
11532 }
11533
11534 if (!CharExpr || !StringRefExpr)
11535 return;
11536
11537 const QualType StringType = StringRefExpr->getType();
11538
11539 // Return if not a PointerType.
11540 if (!StringType->isAnyPointerType())
11541 return;
11542
11543 // Return if not a CharacterType.
11544 if (!StringType->getPointeeType()->isAnyCharacterType())
11545 return;
11546
11547 ASTContext &Ctx = Self.getASTContext();
11548 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11549
11550 const QualType CharType = CharExpr->getType();
11551 if (!CharType->isAnyCharacterType() &&
11552 CharType->isIntegerType() &&
11553 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11554 Self.Diag(OpLoc, diag::warn_string_plus_char)
11555 << DiagRange << Ctx.CharTy;
11556 } else {
11557 Self.Diag(OpLoc, diag::warn_string_plus_char)
11558 << DiagRange << CharExpr->getType();
11559 }
11560
11561 // Only print a fixit for str + char, not for char + str.
11562 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11563 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11564 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11565 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11567 << FixItHint::CreateInsertion(EndLoc, "]");
11568 } else {
11569 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11570 }
11571}
11572
11573/// Emit error when two pointers are incompatible.
11575 Expr *LHSExpr, Expr *RHSExpr) {
11576 assert(LHSExpr->getType()->isAnyPointerType());
11577 assert(RHSExpr->getType()->isAnyPointerType());
11578 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11579 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11580 << RHSExpr->getSourceRange();
11581}
11582
11583// C99 6.5.6
11586 QualType* CompLHSTy) {
11587 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11588
11589 if (LHS.get()->getType()->isVectorType() ||
11590 RHS.get()->getType()->isVectorType()) {
11591 QualType compType =
11592 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11593 /*AllowBothBool*/ getLangOpts().AltiVec,
11594 /*AllowBoolConversions*/ getLangOpts().ZVector,
11595 /*AllowBooleanOperation*/ false,
11596 /*ReportInvalid*/ true);
11597 if (CompLHSTy) *CompLHSTy = compType;
11598 return compType;
11599 }
11600
11601 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11602 RHS.get()->getType()->isSveVLSBuiltinType()) {
11603 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11605 if (CompLHSTy)
11606 *CompLHSTy = compType;
11607 return compType;
11608 }
11609
11610 if (LHS.get()->getType()->isConstantMatrixType() ||
11611 RHS.get()->getType()->isConstantMatrixType()) {
11612 QualType compType =
11613 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11614 if (CompLHSTy)
11615 *CompLHSTy = compType;
11616 return compType;
11617 }
11618
11620 LHS, RHS, Loc,
11622 if (LHS.isInvalid() || RHS.isInvalid())
11623 return QualType();
11624
11625 // Diagnose "string literal" '+' int and string '+' "char literal".
11626 if (Opc == BO_Add) {
11627 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11628 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11629 }
11630
11631 // handle the common case first (both operands are arithmetic).
11632 if (!compType.isNull() && compType->isArithmeticType()) {
11633 if (CompLHSTy) *CompLHSTy = compType;
11634 return compType;
11635 }
11636
11637 // Type-checking. Ultimately the pointer's going to be in PExp;
11638 // note that we bias towards the LHS being the pointer.
11639 Expr *PExp = LHS.get(), *IExp = RHS.get();
11640
11641 bool isObjCPointer;
11642 if (PExp->getType()->isPointerType()) {
11643 isObjCPointer = false;
11644 } else if (PExp->getType()->isObjCObjectPointerType()) {
11645 isObjCPointer = true;
11646 } else {
11647 std::swap(PExp, IExp);
11648 if (PExp->getType()->isPointerType()) {
11649 isObjCPointer = false;
11650 } else if (PExp->getType()->isObjCObjectPointerType()) {
11651 isObjCPointer = true;
11652 } else {
11653 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11654 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11655 return ResultTy;
11656 }
11657 }
11658 assert(PExp->getType()->isAnyPointerType());
11659
11660 if (!IExp->getType()->isIntegerType())
11661 return InvalidOperands(Loc, LHS, RHS);
11662
11663 // Adding to a null pointer results in undefined behavior.
11666 // In C++ adding zero to a null pointer is defined.
11667 Expr::EvalResult KnownVal;
11668 if (!getLangOpts().CPlusPlus ||
11669 (!IExp->isValueDependent() &&
11670 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11671 KnownVal.Val.getInt() != 0))) {
11672 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11674 Context, BO_Add, PExp, IExp);
11675 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11676 }
11677 }
11678
11679 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11680 return QualType();
11681
11682 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11683 return QualType();
11684
11685 // Arithmetic on label addresses is normally allowed, except when we add
11686 // a ptrauth signature to the addresses.
11687 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11688 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11689 << /*addition*/ 1;
11690 return QualType();
11691 }
11692
11693 // Check array bounds for pointer arithemtic
11694 CheckArrayAccess(PExp, IExp);
11695
11696 if (CompLHSTy) {
11697 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11698 if (LHSTy.isNull()) {
11699 LHSTy = LHS.get()->getType();
11700 if (Context.isPromotableIntegerType(LHSTy))
11701 LHSTy = Context.getPromotedIntegerType(LHSTy);
11702 }
11703 *CompLHSTy = LHSTy;
11704 }
11705
11706 return PExp->getType();
11707}
11708
11709// C99 6.5.6
11711 SourceLocation Loc,
11713 QualType *CompLHSTy) {
11714 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11715
11716 if (LHS.get()->getType()->isVectorType() ||
11717 RHS.get()->getType()->isVectorType()) {
11718 QualType compType =
11719 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11720 /*AllowBothBool*/ getLangOpts().AltiVec,
11721 /*AllowBoolConversions*/ getLangOpts().ZVector,
11722 /*AllowBooleanOperation*/ false,
11723 /*ReportInvalid*/ true);
11724 if (CompLHSTy) *CompLHSTy = compType;
11725 return compType;
11726 }
11727
11728 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11729 RHS.get()->getType()->isSveVLSBuiltinType()) {
11730 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11732 if (CompLHSTy)
11733 *CompLHSTy = compType;
11734 return compType;
11735 }
11736
11737 if (LHS.get()->getType()->isConstantMatrixType() ||
11738 RHS.get()->getType()->isConstantMatrixType()) {
11739 QualType compType =
11740 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11741 if (CompLHSTy)
11742 *CompLHSTy = compType;
11743 return compType;
11744 }
11745
11747 LHS, RHS, Loc,
11749 if (LHS.isInvalid() || RHS.isInvalid())
11750 return QualType();
11751
11752 // Enforce type constraints: C99 6.5.6p3.
11753
11754 // Handle the common case first (both operands are arithmetic).
11755 if (!compType.isNull() && compType->isArithmeticType()) {
11756 if (CompLHSTy) *CompLHSTy = compType;
11757 return compType;
11758 }
11759
11760 // Either ptr - int or ptr - ptr.
11761 if (LHS.get()->getType()->isAnyPointerType()) {
11762 QualType lpointee = LHS.get()->getType()->getPointeeType();
11763
11764 // Diagnose bad cases where we step over interface counts.
11765 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11766 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11767 return QualType();
11768
11769 // Arithmetic on label addresses is normally allowed, except when we add
11770 // a ptrauth signature to the addresses.
11771 if (isa<AddrLabelExpr>(LHS.get()) &&
11772 getLangOpts().PointerAuthIndirectGotos) {
11773 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11774 << /*subtraction*/ 0;
11775 return QualType();
11776 }
11777
11778 // The result type of a pointer-int computation is the pointer type.
11779 if (RHS.get()->getType()->isIntegerType()) {
11780 // Subtracting from a null pointer should produce a warning.
11781 // The last argument to the diagnose call says this doesn't match the
11782 // GNU int-to-pointer idiom.
11785 // In C++ adding zero to a null pointer is defined.
11786 Expr::EvalResult KnownVal;
11787 if (!getLangOpts().CPlusPlus ||
11788 (!RHS.get()->isValueDependent() &&
11789 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11790 KnownVal.Val.getInt() != 0))) {
11791 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11792 }
11793 }
11794
11795 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11796 return QualType();
11797
11798 // Check array bounds for pointer arithemtic
11799 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11800 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11801
11802 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11803 return LHS.get()->getType();
11804 }
11805
11806 // Handle pointer-pointer subtractions.
11807 if (const PointerType *RHSPTy
11808 = RHS.get()->getType()->getAs<PointerType>()) {
11809 QualType rpointee = RHSPTy->getPointeeType();
11810
11811 if (getLangOpts().CPlusPlus) {
11812 // Pointee types must be the same: C++ [expr.add]
11813 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11814 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11815 }
11816 } else {
11817 // Pointee types must be compatible C99 6.5.6p3
11818 if (!Context.typesAreCompatible(
11819 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11820 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11821 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11822 return QualType();
11823 }
11824 }
11825
11827 LHS.get(), RHS.get()))
11828 return QualType();
11829
11830 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11832 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11834
11835 // Subtracting nullptr or from nullptr is suspect
11836 if (LHSIsNullPtr)
11837 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11838 if (RHSIsNullPtr)
11839 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11840
11841 // The pointee type may have zero size. As an extension, a structure or
11842 // union may have zero size or an array may have zero length. In this
11843 // case subtraction does not make sense.
11844 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11845 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11846 if (ElementSize.isZero()) {
11847 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11848 << rpointee.getUnqualifiedType()
11849 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11850 }
11851 }
11852
11853 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11854 return Context.getPointerDiffType();
11855 }
11856 }
11857
11858 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11859 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11860 return ResultTy;
11861}
11862
11864 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11865 return ET->getDecl()->isScoped();
11866 return false;
11867}
11868
11871 QualType LHSType) {
11872 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11873 // so skip remaining warnings as we don't want to modify values within Sema.
11874 if (S.getLangOpts().OpenCL)
11875 return;
11876
11877 if (Opc == BO_Shr &&
11879 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11880
11881 // Check right/shifter operand
11882 Expr::EvalResult RHSResult;
11883 if (RHS.get()->isValueDependent() ||
11884 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11885 return;
11886 llvm::APSInt Right = RHSResult.Val.getInt();
11887
11888 if (Right.isNegative()) {
11889 S.DiagRuntimeBehavior(Loc, RHS.get(),
11890 S.PDiag(diag::warn_shift_negative)
11891 << RHS.get()->getSourceRange());
11892 return;
11893 }
11894
11895 QualType LHSExprType = LHS.get()->getType();
11896 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11897 if (LHSExprType->isBitIntType())
11898 LeftSize = S.Context.getIntWidth(LHSExprType);
11899 else if (LHSExprType->isFixedPointType()) {
11900 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11901 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11902 }
11903 if (Right.uge(LeftSize)) {
11904 S.DiagRuntimeBehavior(Loc, RHS.get(),
11905 S.PDiag(diag::warn_shift_gt_typewidth)
11906 << RHS.get()->getSourceRange());
11907 return;
11908 }
11909
11910 // FIXME: We probably need to handle fixed point types specially here.
11911 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11912 return;
11913
11914 // When left shifting an ICE which is signed, we can check for overflow which
11915 // according to C++ standards prior to C++2a has undefined behavior
11916 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11917 // more than the maximum value representable in the result type, so never
11918 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11919 // expression is still probably a bug.)
11920 Expr::EvalResult LHSResult;
11921 if (LHS.get()->isValueDependent() ||
11923 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11924 return;
11925 llvm::APSInt Left = LHSResult.Val.getInt();
11926
11927 // Don't warn if signed overflow is defined, then all the rest of the
11928 // diagnostics will not be triggered because the behavior is defined.
11929 // Also don't warn in C++20 mode (and newer), as signed left shifts
11930 // always wrap and never overflow.
11931 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11932 return;
11933
11934 // If LHS does not have a non-negative value then, the
11935 // behavior is undefined before C++2a. Warn about it.
11936 if (Left.isNegative()) {
11937 S.DiagRuntimeBehavior(Loc, LHS.get(),
11938 S.PDiag(diag::warn_shift_lhs_negative)
11939 << LHS.get()->getSourceRange());
11940 return;
11941 }
11942
11943 llvm::APInt ResultBits =
11944 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11945 if (ResultBits.ule(LeftSize))
11946 return;
11947 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11948 Result = Result.shl(Right);
11949
11950 // Print the bit representation of the signed integer as an unsigned
11951 // hexadecimal number.
11952 SmallString<40> HexResult;
11953 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11954
11955 // If we are only missing a sign bit, this is less likely to result in actual
11956 // bugs -- if the result is cast back to an unsigned type, it will have the
11957 // expected value. Thus we place this behind a different warning that can be
11958 // turned off separately if needed.
11959 if (ResultBits - 1 == LeftSize) {
11960 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11961 << HexResult << LHSType
11962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11963 return;
11964 }
11965
11966 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11967 << HexResult.str() << Result.getSignificantBits() << LHSType
11968 << Left.getBitWidth() << LHS.get()->getSourceRange()
11969 << RHS.get()->getSourceRange();
11970}
11971
11972/// Return the resulting type when a vector is shifted
11973/// by a scalar or vector shift amount.
11975 SourceLocation Loc, bool IsCompAssign) {
11976 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11977 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11978 !LHS.get()->getType()->isVectorType()) {
11979 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11980 << RHS.get()->getType() << LHS.get()->getType()
11981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11982 return QualType();
11983 }
11984
11985 if (!IsCompAssign) {
11986 LHS = S.UsualUnaryConversions(LHS.get());
11987 if (LHS.isInvalid()) return QualType();
11988 }
11989
11990 RHS = S.UsualUnaryConversions(RHS.get());
11991 if (RHS.isInvalid()) return QualType();
11992
11993 QualType LHSType = LHS.get()->getType();
11994 // Note that LHS might be a scalar because the routine calls not only in
11995 // OpenCL case.
11996 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11997 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11998
11999 // Note that RHS might not be a vector.
12000 QualType RHSType = RHS.get()->getType();
12001 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12002 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12003
12004 // Do not allow shifts for boolean vectors.
12005 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12006 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12007 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12008 << LHS.get()->getType() << RHS.get()->getType()
12009 << LHS.get()->getSourceRange();
12010 return QualType();
12011 }
12012
12013 // The operands need to be integers.
12014 if (!LHSEleType->isIntegerType()) {
12015 S.Diag(Loc, diag::err_typecheck_expect_int)
12016 << LHS.get()->getType() << LHS.get()->getSourceRange();
12017 return QualType();
12018 }
12019
12020 if (!RHSEleType->isIntegerType()) {
12021 S.Diag(Loc, diag::err_typecheck_expect_int)
12022 << RHS.get()->getType() << RHS.get()->getSourceRange();
12023 return QualType();
12024 }
12025
12026 if (!LHSVecTy) {
12027 assert(RHSVecTy);
12028 if (IsCompAssign)
12029 return RHSType;
12030 if (LHSEleType != RHSEleType) {
12031 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12032 LHSEleType = RHSEleType;
12033 }
12034 QualType VecTy =
12035 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12036 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12037 LHSType = VecTy;
12038 } else if (RHSVecTy) {
12039 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12040 // are applied component-wise. So if RHS is a vector, then ensure
12041 // that the number of elements is the same as LHS...
12042 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12043 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12044 << LHS.get()->getType() << RHS.get()->getType()
12045 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12046 return QualType();
12047 }
12048 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12049 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12050 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12051 if (LHSBT != RHSBT &&
12052 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12053 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12054 << LHS.get()->getType() << RHS.get()->getType()
12055 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12056 }
12057 }
12058 } else {
12059 // ...else expand RHS to match the number of elements in LHS.
12060 QualType VecTy =
12061 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12062 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12063 }
12064
12065 return LHSType;
12066}
12067
12069 ExprResult &RHS, SourceLocation Loc,
12070 bool IsCompAssign) {
12071 if (!IsCompAssign) {
12072 LHS = S.UsualUnaryConversions(LHS.get());
12073 if (LHS.isInvalid())
12074 return QualType();
12075 }
12076
12077 RHS = S.UsualUnaryConversions(RHS.get());
12078 if (RHS.isInvalid())
12079 return QualType();
12080
12081 QualType LHSType = LHS.get()->getType();
12082 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12083 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12084 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12085 : LHSType;
12086
12087 // Note that RHS might not be a vector
12088 QualType RHSType = RHS.get()->getType();
12089 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12090 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12091 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12092 : RHSType;
12093
12094 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12095 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12096 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12097 << LHSType << RHSType << LHS.get()->getSourceRange();
12098 return QualType();
12099 }
12100
12101 if (!LHSEleType->isIntegerType()) {
12102 S.Diag(Loc, diag::err_typecheck_expect_int)
12103 << LHS.get()->getType() << LHS.get()->getSourceRange();
12104 return QualType();
12105 }
12106
12107 if (!RHSEleType->isIntegerType()) {
12108 S.Diag(Loc, diag::err_typecheck_expect_int)
12109 << RHS.get()->getType() << RHS.get()->getSourceRange();
12110 return QualType();
12111 }
12112
12113 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12114 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12115 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12116 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12117 << LHSType << RHSType << LHS.get()->getSourceRange()
12118 << RHS.get()->getSourceRange();
12119 return QualType();
12120 }
12121
12122 if (!LHSType->isSveVLSBuiltinType()) {
12123 assert(RHSType->isSveVLSBuiltinType());
12124 if (IsCompAssign)
12125 return RHSType;
12126 if (LHSEleType != RHSEleType) {
12127 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12128 LHSEleType = RHSEleType;
12129 }
12130 const llvm::ElementCount VecSize =
12131 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12132 QualType VecTy =
12133 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12134 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12135 LHSType = VecTy;
12136 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12137 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12138 S.Context.getTypeSize(LHSBuiltinTy)) {
12139 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12140 << LHSType << RHSType << LHS.get()->getSourceRange()
12141 << RHS.get()->getSourceRange();
12142 return QualType();
12143 }
12144 } else {
12145 const llvm::ElementCount VecSize =
12146 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12147 if (LHSEleType != RHSEleType) {
12148 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12149 RHSEleType = LHSEleType;
12150 }
12151 QualType VecTy =
12152 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12153 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12154 }
12155
12156 return LHSType;
12157}
12158
12159// C99 6.5.7
12162 bool IsCompAssign) {
12163 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12164
12165 // Vector shifts promote their scalar inputs to vector type.
12166 if (LHS.get()->getType()->isVectorType() ||
12167 RHS.get()->getType()->isVectorType()) {
12168 if (LangOpts.ZVector) {
12169 // The shift operators for the z vector extensions work basically
12170 // like general shifts, except that neither the LHS nor the RHS is
12171 // allowed to be a "vector bool".
12172 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12173 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12174 return InvalidOperands(Loc, LHS, RHS);
12175 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12176 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12177 return InvalidOperands(Loc, LHS, RHS);
12178 }
12179 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12180 }
12181
12182 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12183 RHS.get()->getType()->isSveVLSBuiltinType())
12184 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12185
12186 // Shifts don't perform usual arithmetic conversions, they just do integer
12187 // promotions on each operand. C99 6.5.7p3
12188
12189 // For the LHS, do usual unary conversions, but then reset them away
12190 // if this is a compound assignment.
12191 ExprResult OldLHS = LHS;
12192 LHS = UsualUnaryConversions(LHS.get());
12193 if (LHS.isInvalid())
12194 return QualType();
12195 QualType LHSType = LHS.get()->getType();
12196 if (IsCompAssign) LHS = OldLHS;
12197
12198 // The RHS is simpler.
12199 RHS = UsualUnaryConversions(RHS.get());
12200 if (RHS.isInvalid())
12201 return QualType();
12202 QualType RHSType = RHS.get()->getType();
12203
12204 // C99 6.5.7p2: Each of the operands shall have integer type.
12205 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12206 if ((!LHSType->isFixedPointOrIntegerType() &&
12207 !LHSType->hasIntegerRepresentation()) ||
12208 !RHSType->hasIntegerRepresentation()) {
12209 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12210 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12211 return ResultTy;
12212 }
12213
12214 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12215
12216 // "The type of the result is that of the promoted left operand."
12217 return LHSType;
12218}
12219
12220/// Diagnose bad pointer comparisons.
12222 ExprResult &LHS, ExprResult &RHS,
12223 bool IsError) {
12224 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12225 : diag::ext_typecheck_comparison_of_distinct_pointers)
12226 << LHS.get()->getType() << RHS.get()->getType()
12227 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12228}
12229
12230/// Returns false if the pointers are converted to a composite type,
12231/// true otherwise.
12233 ExprResult &LHS, ExprResult &RHS) {
12234 // C++ [expr.rel]p2:
12235 // [...] Pointer conversions (4.10) and qualification
12236 // conversions (4.4) are performed on pointer operands (or on
12237 // a pointer operand and a null pointer constant) to bring
12238 // them to their composite pointer type. [...]
12239 //
12240 // C++ [expr.eq]p1 uses the same notion for (in)equality
12241 // comparisons of pointers.
12242
12243 QualType LHSType = LHS.get()->getType();
12244 QualType RHSType = RHS.get()->getType();
12245 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12246 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12247
12248 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12249 if (T.isNull()) {
12250 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12251 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12252 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12253 else
12254 S.InvalidOperands(Loc, LHS, RHS);
12255 return true;
12256 }
12257
12258 return false;
12259}
12260
12262 ExprResult &LHS,
12263 ExprResult &RHS,
12264 bool IsError) {
12265 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12266 : diag::ext_typecheck_comparison_of_fptr_to_void)
12267 << LHS.get()->getType() << RHS.get()->getType()
12268 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12269}
12270
12272 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12273 case Stmt::ObjCArrayLiteralClass:
12274 case Stmt::ObjCDictionaryLiteralClass:
12275 case Stmt::ObjCStringLiteralClass:
12276 case Stmt::ObjCBoxedExprClass:
12277 return true;
12278 default:
12279 // Note that ObjCBoolLiteral is NOT an object literal!
12280 return false;
12281 }
12282}
12283
12284static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12287
12288 // If this is not actually an Objective-C object, bail out.
12289 if (!Type)
12290 return false;
12291
12292 // Get the LHS object's interface type.
12293 QualType InterfaceType = Type->getPointeeType();
12294
12295 // If the RHS isn't an Objective-C object, bail out.
12296 if (!RHS->getType()->isObjCObjectPointerType())
12297 return false;
12298
12299 // Try to find the -isEqual: method.
12300 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12301 ObjCMethodDecl *Method =
12302 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12303 /*IsInstance=*/true);
12304 if (!Method) {
12305 if (Type->isObjCIdType()) {
12306 // For 'id', just check the global pool.
12307 Method =
12309 /*receiverId=*/true);
12310 } else {
12311 // Check protocols.
12312 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12313 /*IsInstance=*/true);
12314 }
12315 }
12316
12317 if (!Method)
12318 return false;
12319
12320 QualType T = Method->parameters()[0]->getType();
12321 if (!T->isObjCObjectPointerType())
12322 return false;
12323
12324 QualType R = Method->getReturnType();
12325 if (!R->isScalarType())
12326 return false;
12327
12328 return true;
12329}
12330
12332 ExprResult &LHS, ExprResult &RHS,
12334 Expr *Literal;
12335 Expr *Other;
12336 if (isObjCObjectLiteral(LHS)) {
12337 Literal = LHS.get();
12338 Other = RHS.get();
12339 } else {
12340 Literal = RHS.get();
12341 Other = LHS.get();
12342 }
12343
12344 // Don't warn on comparisons against nil.
12345 Other = Other->IgnoreParenCasts();
12346 if (Other->isNullPointerConstant(S.getASTContext(),
12348 return;
12349
12350 // This should be kept in sync with warn_objc_literal_comparison.
12351 // LK_String should always be after the other literals, since it has its own
12352 // warning flag.
12353 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12354 assert(LiteralKind != SemaObjC::LK_Block);
12355 if (LiteralKind == SemaObjC::LK_None) {
12356 llvm_unreachable("Unknown Objective-C object literal kind");
12357 }
12358
12359 if (LiteralKind == SemaObjC::LK_String)
12360 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12361 << Literal->getSourceRange();
12362 else
12363 S.Diag(Loc, diag::warn_objc_literal_comparison)
12364 << LiteralKind << Literal->getSourceRange();
12365
12367 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12368 SourceLocation Start = LHS.get()->getBeginLoc();
12370 CharSourceRange OpRange =
12372
12373 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12374 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12375 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12376 << FixItHint::CreateInsertion(End, "]");
12377 }
12378}
12379
12380/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12382 ExprResult &RHS, SourceLocation Loc,
12383 BinaryOperatorKind Opc) {
12384 // Check that left hand side is !something.
12385 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12386 if (!UO || UO->getOpcode() != UO_LNot) return;
12387
12388 // Only check if the right hand side is non-bool arithmetic type.
12389 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12390
12391 // Make sure that the something in !something is not bool.
12392 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12393 if (SubExpr->isKnownToHaveBooleanValue()) return;
12394
12395 // Emit warning.
12396 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12397 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12398 << Loc << IsBitwiseOp;
12399
12400 // First note suggest !(x < y)
12401 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12402 SourceLocation FirstClose = RHS.get()->getEndLoc();
12403 FirstClose = S.getLocForEndOfToken(FirstClose);
12404 if (FirstClose.isInvalid())
12405 FirstOpen = SourceLocation();
12406 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12407 << IsBitwiseOp
12408 << FixItHint::CreateInsertion(FirstOpen, "(")
12409 << FixItHint::CreateInsertion(FirstClose, ")");
12410
12411 // Second note suggests (!x) < y
12412 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12413 SourceLocation SecondClose = LHS.get()->getEndLoc();
12414 SecondClose = S.getLocForEndOfToken(SecondClose);
12415 if (SecondClose.isInvalid())
12416 SecondOpen = SourceLocation();
12417 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12418 << FixItHint::CreateInsertion(SecondOpen, "(")
12419 << FixItHint::CreateInsertion(SecondClose, ")");
12420}
12421
12422// Returns true if E refers to a non-weak array.
12423static bool checkForArray(const Expr *E) {
12424 const ValueDecl *D = nullptr;
12425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12426 D = DR->getDecl();
12427 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12428 if (Mem->isImplicitAccess())
12429 D = Mem->getMemberDecl();
12430 }
12431 if (!D)
12432 return false;
12433 return D->getType()->isArrayType() && !D->isWeak();
12434}
12435
12436/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12437/// pointer and size is an unsigned integer. Return whether the result is
12438/// always true/false.
12439static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12440 const Expr *RHS,
12441 BinaryOperatorKind Opc) {
12442 if (!LHS->getType()->isPointerType() ||
12443 S.getLangOpts().PointerOverflowDefined)
12444 return std::nullopt;
12445
12446 // Canonicalize to >= or < predicate.
12447 switch (Opc) {
12448 case BO_GE:
12449 case BO_LT:
12450 break;
12451 case BO_GT:
12452 std::swap(LHS, RHS);
12453 Opc = BO_LT;
12454 break;
12455 case BO_LE:
12456 std::swap(LHS, RHS);
12457 Opc = BO_GE;
12458 break;
12459 default:
12460 return std::nullopt;
12461 }
12462
12463 auto *BO = dyn_cast<BinaryOperator>(LHS);
12464 if (!BO || BO->getOpcode() != BO_Add)
12465 return std::nullopt;
12466
12467 Expr *Other;
12468 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12469 Other = BO->getRHS();
12470 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12471 Other = BO->getLHS();
12472 else
12473 return std::nullopt;
12474
12475 if (!Other->getType()->isUnsignedIntegerType())
12476 return std::nullopt;
12477
12478 return Opc == BO_GE;
12479}
12480
12481/// Diagnose some forms of syntactically-obvious tautological comparison.
12483 Expr *LHS, Expr *RHS,
12484 BinaryOperatorKind Opc) {
12485 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12486 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12487
12488 QualType LHSType = LHS->getType();
12489 QualType RHSType = RHS->getType();
12490 if (LHSType->hasFloatingRepresentation() ||
12491 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12493 return;
12494
12495 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12496 // Tautological diagnostics.
12497 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12498 return;
12499
12500 // Comparisons between two array types are ill-formed for operator<=>, so
12501 // we shouldn't emit any additional warnings about it.
12502 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12503 return;
12504
12505 // For non-floating point types, check for self-comparisons of the form
12506 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12507 // often indicate logic errors in the program.
12508 //
12509 // NOTE: Don't warn about comparison expressions resulting from macro
12510 // expansion. Also don't warn about comparisons which are only self
12511 // comparisons within a template instantiation. The warnings should catch
12512 // obvious cases in the definition of the template anyways. The idea is to
12513 // warn when the typed comparison operator will always evaluate to the same
12514 // result.
12515
12516 // Used for indexing into %select in warn_comparison_always
12517 enum {
12518 AlwaysConstant,
12519 AlwaysTrue,
12520 AlwaysFalse,
12521 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12522 };
12523
12524 // C++1a [array.comp]:
12525 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12526 // operands of array type.
12527 // C++2a [depr.array.comp]:
12528 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12529 // operands of array type are deprecated.
12530 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12531 RHSStripped->getType()->isArrayType()) {
12532 auto IsDeprArrayComparionIgnored =
12533 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12534 auto DiagID = S.getLangOpts().CPlusPlus26
12535 ? diag::warn_array_comparison_cxx26
12536 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12537 ? diag::warn_array_comparison
12538 : diag::warn_depr_array_comparison;
12539 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12540 << LHSStripped->getType() << RHSStripped->getType();
12541 // Carry on to produce the tautological comparison warning, if this
12542 // expression is potentially-evaluated, we can resolve the array to a
12543 // non-weak declaration, and so on.
12544 }
12545
12546 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12547 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12548 unsigned Result;
12549 switch (Opc) {
12550 case BO_EQ:
12551 case BO_LE:
12552 case BO_GE:
12553 Result = AlwaysTrue;
12554 break;
12555 case BO_NE:
12556 case BO_LT:
12557 case BO_GT:
12558 Result = AlwaysFalse;
12559 break;
12560 case BO_Cmp:
12561 Result = AlwaysEqual;
12562 break;
12563 default:
12564 Result = AlwaysConstant;
12565 break;
12566 }
12567 S.DiagRuntimeBehavior(Loc, nullptr,
12568 S.PDiag(diag::warn_comparison_always)
12569 << 0 /*self-comparison*/
12570 << Result);
12571 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12572 // What is it always going to evaluate to?
12573 unsigned Result;
12574 switch (Opc) {
12575 case BO_EQ: // e.g. array1 == array2
12576 Result = AlwaysFalse;
12577 break;
12578 case BO_NE: // e.g. array1 != array2
12579 Result = AlwaysTrue;
12580 break;
12581 default: // e.g. array1 <= array2
12582 // The best we can say is 'a constant'
12583 Result = AlwaysConstant;
12584 break;
12585 }
12586 S.DiagRuntimeBehavior(Loc, nullptr,
12587 S.PDiag(diag::warn_comparison_always)
12588 << 1 /*array comparison*/
12589 << Result);
12590 } else if (std::optional<bool> Res =
12591 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12592 S.DiagRuntimeBehavior(Loc, nullptr,
12593 S.PDiag(diag::warn_comparison_always)
12594 << 2 /*pointer comparison*/
12595 << (*Res ? AlwaysTrue : AlwaysFalse));
12596 }
12597 }
12598
12599 if (isa<CastExpr>(LHSStripped))
12600 LHSStripped = LHSStripped->IgnoreParenCasts();
12601 if (isa<CastExpr>(RHSStripped))
12602 RHSStripped = RHSStripped->IgnoreParenCasts();
12603
12604 // Warn about comparisons against a string constant (unless the other
12605 // operand is null); the user probably wants string comparison function.
12606 Expr *LiteralString = nullptr;
12607 Expr *LiteralStringStripped = nullptr;
12608 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12609 !RHSStripped->isNullPointerConstant(S.Context,
12611 LiteralString = LHS;
12612 LiteralStringStripped = LHSStripped;
12613 } else if ((isa<StringLiteral>(RHSStripped) ||
12614 isa<ObjCEncodeExpr>(RHSStripped)) &&
12615 !LHSStripped->isNullPointerConstant(S.Context,
12617 LiteralString = RHS;
12618 LiteralStringStripped = RHSStripped;
12619 }
12620
12621 if (LiteralString) {
12622 S.DiagRuntimeBehavior(Loc, nullptr,
12623 S.PDiag(diag::warn_stringcompare)
12624 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12625 << LiteralString->getSourceRange());
12626 }
12627}
12628
12630 switch (CK) {
12631 default: {
12632#ifndef NDEBUG
12633 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12634 << "\n";
12635#endif
12636 llvm_unreachable("unhandled cast kind");
12637 }
12638 case CK_UserDefinedConversion:
12639 return ICK_Identity;
12640 case CK_LValueToRValue:
12641 return ICK_Lvalue_To_Rvalue;
12642 case CK_ArrayToPointerDecay:
12643 return ICK_Array_To_Pointer;
12644 case CK_FunctionToPointerDecay:
12646 case CK_IntegralCast:
12648 case CK_FloatingCast:
12650 case CK_IntegralToFloating:
12651 case CK_FloatingToIntegral:
12652 return ICK_Floating_Integral;
12653 case CK_IntegralComplexCast:
12654 case CK_FloatingComplexCast:
12655 case CK_FloatingComplexToIntegralComplex:
12656 case CK_IntegralComplexToFloatingComplex:
12658 case CK_FloatingComplexToReal:
12659 case CK_FloatingRealToComplex:
12660 case CK_IntegralComplexToReal:
12661 case CK_IntegralRealToComplex:
12662 return ICK_Complex_Real;
12663 case CK_HLSLArrayRValue:
12664 return ICK_HLSL_Array_RValue;
12665 }
12666}
12667
12669 QualType FromType,
12670 SourceLocation Loc) {
12671 // Check for a narrowing implicit conversion.
12674 SCS.setToType(0, FromType);
12675 SCS.setToType(1, ToType);
12676 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12677 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12678
12679 APValue PreNarrowingValue;
12680 QualType PreNarrowingType;
12681 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12682 PreNarrowingType,
12683 /*IgnoreFloatToIntegralConversion*/ true)) {
12685 // Implicit conversion to a narrower type, but the expression is
12686 // value-dependent so we can't tell whether it's actually narrowing.
12687 case NK_Not_Narrowing:
12688 return false;
12689
12691 // Implicit conversion to a narrower type, and the value is not a constant
12692 // expression.
12693 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12694 << /*Constant*/ 1
12695 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12696 return true;
12697
12699 // Implicit conversion to a narrower type, and the value is not a constant
12700 // expression.
12701 case NK_Type_Narrowing:
12702 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12703 << /*Constant*/ 0 << FromType << ToType;
12704 // TODO: It's not a constant expression, but what if the user intended it
12705 // to be? Can we produce notes to help them figure out why it isn't?
12706 return true;
12707 }
12708 llvm_unreachable("unhandled case in switch");
12709}
12710
12712 ExprResult &LHS,
12713 ExprResult &RHS,
12714 SourceLocation Loc) {
12715 QualType LHSType = LHS.get()->getType();
12716 QualType RHSType = RHS.get()->getType();
12717 // Dig out the original argument type and expression before implicit casts
12718 // were applied. These are the types/expressions we need to check the
12719 // [expr.spaceship] requirements against.
12720 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12721 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12722 QualType LHSStrippedType = LHSStripped.get()->getType();
12723 QualType RHSStrippedType = RHSStripped.get()->getType();
12724
12725 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12726 // other is not, the program is ill-formed.
12727 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12728 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12729 return QualType();
12730 }
12731
12732 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12733 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12734 RHSStrippedType->isEnumeralType();
12735 if (NumEnumArgs == 1) {
12736 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12737 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12738 if (OtherTy->hasFloatingRepresentation()) {
12739 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12740 return QualType();
12741 }
12742 }
12743 if (NumEnumArgs == 2) {
12744 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12745 // type E, the operator yields the result of converting the operands
12746 // to the underlying type of E and applying <=> to the converted operands.
12747 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12748 S.InvalidOperands(Loc, LHS, RHS);
12749 return QualType();
12750 }
12751 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12752 assert(IntType->isArithmeticType());
12753
12754 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12755 // promote the boolean type, and all other promotable integer types, to
12756 // avoid this.
12757 if (S.Context.isPromotableIntegerType(IntType))
12758 IntType = S.Context.getPromotedIntegerType(IntType);
12759
12760 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12761 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12762 LHSType = RHSType = IntType;
12763 }
12764
12765 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12766 // usual arithmetic conversions are applied to the operands.
12767 QualType Type =
12769 if (LHS.isInvalid() || RHS.isInvalid())
12770 return QualType();
12771 if (Type.isNull()) {
12772 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12773 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12774 return ResultTy;
12775 }
12776
12777 std::optional<ComparisonCategoryType> CCT =
12779 if (!CCT)
12780 return S.InvalidOperands(Loc, LHS, RHS);
12781
12782 bool HasNarrowing = checkThreeWayNarrowingConversion(
12783 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12784 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12785 RHS.get()->getBeginLoc());
12786 if (HasNarrowing)
12787 return QualType();
12788
12789 assert(!Type.isNull() && "composite type for <=> has not been set");
12790
12793}
12794
12796 ExprResult &RHS,
12797 SourceLocation Loc,
12798 BinaryOperatorKind Opc) {
12799 if (Opc == BO_Cmp)
12800 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12801
12802 // C99 6.5.8p3 / C99 6.5.9p4
12803 QualType Type =
12805 if (LHS.isInvalid() || RHS.isInvalid())
12806 return QualType();
12807 if (Type.isNull()) {
12808 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12809 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12810 return ResultTy;
12811 }
12812 assert(Type->isArithmeticType() || Type->isEnumeralType());
12813
12815 return S.InvalidOperands(Loc, LHS, RHS);
12816
12817 // Check for comparisons of floating point operands using != and ==.
12819 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12820
12821 // The result of comparisons is 'bool' in C++, 'int' in C.
12823}
12824
12826 if (!NullE.get()->getType()->isAnyPointerType())
12827 return;
12828 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12829 if (!E.get()->getType()->isAnyPointerType() &&
12833 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12834 if (CL->getValue() == 0)
12835 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12836 << NullValue
12838 NullValue ? "NULL" : "(void *)0");
12839 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12840 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12841 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12842 if (T == Context.CharTy)
12843 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12844 << NullValue
12846 NullValue ? "NULL" : "(void *)0");
12847 }
12848 }
12849}
12850
12851// C99 6.5.8, C++ [expr.rel]
12853 SourceLocation Loc,
12854 BinaryOperatorKind Opc) {
12855 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12856 bool IsThreeWay = Opc == BO_Cmp;
12857 bool IsOrdered = IsRelational || IsThreeWay;
12858 auto IsAnyPointerType = [](ExprResult E) {
12859 QualType Ty = E.get()->getType();
12860 return Ty->isPointerType() || Ty->isMemberPointerType();
12861 };
12862
12863 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12864 // type, array-to-pointer, ..., conversions are performed on both operands to
12865 // bring them to their composite type.
12866 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12867 // any type-related checks.
12868 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12870 if (LHS.isInvalid())
12871 return QualType();
12873 if (RHS.isInvalid())
12874 return QualType();
12875 } else {
12876 LHS = DefaultLvalueConversion(LHS.get());
12877 if (LHS.isInvalid())
12878 return QualType();
12879 RHS = DefaultLvalueConversion(RHS.get());
12880 if (RHS.isInvalid())
12881 return QualType();
12882 }
12883
12884 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12888 }
12889
12890 // Handle vector comparisons separately.
12891 if (LHS.get()->getType()->isVectorType() ||
12892 RHS.get()->getType()->isVectorType())
12893 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12894
12895 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12896 RHS.get()->getType()->isSveVLSBuiltinType())
12897 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12898
12899 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12900 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12901
12902 QualType LHSType = LHS.get()->getType();
12903 QualType RHSType = RHS.get()->getType();
12904 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12905 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12906 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12907
12908 if ((LHSType->isPointerType() &&
12910 (RHSType->isPointerType() &&
12912 return InvalidOperands(Loc, LHS, RHS);
12913
12914 const Expr::NullPointerConstantKind LHSNullKind =
12916 const Expr::NullPointerConstantKind RHSNullKind =
12918 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12919 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12920
12921 auto computeResultTy = [&]() {
12922 if (Opc != BO_Cmp)
12923 return QualType(Context.getLogicalOperationType());
12924 assert(getLangOpts().CPlusPlus);
12925 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12926
12927 QualType CompositeTy = LHS.get()->getType();
12928 assert(!CompositeTy->isReferenceType());
12929
12930 std::optional<ComparisonCategoryType> CCT =
12932 if (!CCT)
12933 return InvalidOperands(Loc, LHS, RHS);
12934
12935 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12936 // P0946R0: Comparisons between a null pointer constant and an object
12937 // pointer result in std::strong_equality, which is ill-formed under
12938 // P1959R0.
12939 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12940 << (LHSIsNull ? LHS.get()->getSourceRange()
12941 : RHS.get()->getSourceRange());
12942 return QualType();
12943 }
12944
12947 };
12948
12949 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12950 bool IsEquality = Opc == BO_EQ;
12951 if (RHSIsNull)
12952 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12953 RHS.get()->getSourceRange());
12954 else
12955 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12956 LHS.get()->getSourceRange());
12957 }
12958
12959 if (IsOrdered && LHSType->isFunctionPointerType() &&
12960 RHSType->isFunctionPointerType()) {
12961 // Valid unless a relational comparison of function pointers
12962 bool IsError = Opc == BO_Cmp;
12963 auto DiagID =
12964 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12965 : getLangOpts().CPlusPlus
12966 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12967 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12968 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12969 << RHS.get()->getSourceRange();
12970 if (IsError)
12971 return QualType();
12972 }
12973
12974 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12975 (RHSType->isIntegerType() && !RHSIsNull)) {
12976 // Skip normal pointer conversion checks in this case; we have better
12977 // diagnostics for this below.
12978 } else if (getLangOpts().CPlusPlus) {
12979 // Equality comparison of a function pointer to a void pointer is invalid,
12980 // but we allow it as an extension.
12981 // FIXME: If we really want to allow this, should it be part of composite
12982 // pointer type computation so it works in conditionals too?
12983 if (!IsOrdered &&
12984 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12985 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12986 // This is a gcc extension compatibility comparison.
12987 // In a SFINAE context, we treat this as a hard error to maintain
12988 // conformance with the C++ standard.
12989 bool IsError = isSFINAEContext();
12990 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
12991
12992 if (IsError)
12993 return QualType();
12994
12995 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12996 return computeResultTy();
12997 }
12998
12999 // C++ [expr.eq]p2:
13000 // If at least one operand is a pointer [...] bring them to their
13001 // composite pointer type.
13002 // C++ [expr.spaceship]p6
13003 // If at least one of the operands is of pointer type, [...] bring them
13004 // to their composite pointer type.
13005 // C++ [expr.rel]p2:
13006 // If both operands are pointers, [...] bring them to their composite
13007 // pointer type.
13008 // For <=>, the only valid non-pointer types are arrays and functions, and
13009 // we already decayed those, so this is really the same as the relational
13010 // comparison rule.
13011 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13012 (IsOrdered ? 2 : 1) &&
13013 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13014 RHSType->isObjCObjectPointerType()))) {
13015 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13016 return QualType();
13017 return computeResultTy();
13018 }
13019 } else if (LHSType->isPointerType() &&
13020 RHSType->isPointerType()) { // C99 6.5.8p2
13021 // All of the following pointer-related warnings are GCC extensions, except
13022 // when handling null pointer constants.
13023 QualType LCanPointeeTy =
13025 QualType RCanPointeeTy =
13027
13028 // C99 6.5.9p2 and C99 6.5.8p2
13029 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13030 RCanPointeeTy.getUnqualifiedType())) {
13031 if (IsRelational) {
13032 // Pointers both need to point to complete or incomplete types
13033 if ((LCanPointeeTy->isIncompleteType() !=
13034 RCanPointeeTy->isIncompleteType()) &&
13035 !getLangOpts().C11) {
13036 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13037 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13038 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13039 << RCanPointeeTy->isIncompleteType();
13040 }
13041 }
13042 } else if (!IsRelational &&
13043 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13044 // Valid unless comparison between non-null pointer and function pointer
13045 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13046 && !LHSIsNull && !RHSIsNull)
13047 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13048 /*isError*/false);
13049 } else {
13050 // Invalid
13051 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13052 }
13053 if (LCanPointeeTy != RCanPointeeTy) {
13054 // Treat NULL constant as a special case in OpenCL.
13055 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13056 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13057 getASTContext())) {
13058 Diag(Loc,
13059 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13060 << LHSType << RHSType << 0 /* comparison */
13061 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13062 }
13063 }
13064 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13065 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13066 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13067 : CK_BitCast;
13068
13069 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13070 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13071 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13072 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13073 bool ChangingCFIUncheckedCallee =
13074 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13075
13076 if (LHSIsNull && !RHSIsNull)
13077 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13078 else if (!ChangingCFIUncheckedCallee)
13079 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13080 }
13081 return computeResultTy();
13082 }
13083
13084
13085 // C++ [expr.eq]p4:
13086 // Two operands of type std::nullptr_t or one operand of type
13087 // std::nullptr_t and the other a null pointer constant compare
13088 // equal.
13089 // C23 6.5.9p5:
13090 // If both operands have type nullptr_t or one operand has type nullptr_t
13091 // and the other is a null pointer constant, they compare equal if the
13092 // former is a null pointer.
13093 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13094 if (LHSType->isNullPtrType()) {
13095 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13096 return computeResultTy();
13097 }
13098 if (RHSType->isNullPtrType()) {
13099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13100 return computeResultTy();
13101 }
13102 }
13103
13104 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13105 // C23 6.5.9p6:
13106 // Otherwise, at least one operand is a pointer. If one is a pointer and
13107 // the other is a null pointer constant or has type nullptr_t, they
13108 // compare equal
13109 if (LHSIsNull && RHSType->isPointerType()) {
13110 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13111 return computeResultTy();
13112 }
13113 if (RHSIsNull && LHSType->isPointerType()) {
13114 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13115 return computeResultTy();
13116 }
13117 }
13118
13119 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13120 // These aren't covered by the composite pointer type rules.
13121 if (!IsOrdered && RHSType->isNullPtrType() &&
13122 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13124 return computeResultTy();
13125 }
13126 if (!IsOrdered && LHSType->isNullPtrType() &&
13127 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13128 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13129 return computeResultTy();
13130 }
13131
13132 if (getLangOpts().CPlusPlus) {
13133 if (IsRelational &&
13134 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13135 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13136 // HACK: Relational comparison of nullptr_t against a pointer type is
13137 // invalid per DR583, but we allow it within std::less<> and friends,
13138 // since otherwise common uses of it break.
13139 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13140 // friends to have std::nullptr_t overload candidates.
13141 DeclContext *DC = CurContext;
13142 if (isa<FunctionDecl>(DC))
13143 DC = DC->getParent();
13144 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13145 if (CTSD->isInStdNamespace() &&
13146 llvm::StringSwitch<bool>(CTSD->getName())
13147 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13148 .Default(false)) {
13149 if (RHSType->isNullPtrType())
13150 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13151 else
13152 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13153 return computeResultTy();
13154 }
13155 }
13156 }
13157
13158 // C++ [expr.eq]p2:
13159 // If at least one operand is a pointer to member, [...] bring them to
13160 // their composite pointer type.
13161 if (!IsOrdered &&
13162 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13163 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13164 return QualType();
13165 else
13166 return computeResultTy();
13167 }
13168 }
13169
13170 // Handle block pointer types.
13171 if (!IsOrdered && LHSType->isBlockPointerType() &&
13172 RHSType->isBlockPointerType()) {
13173 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13174 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13175
13176 if (!LHSIsNull && !RHSIsNull &&
13177 !Context.typesAreCompatible(lpointee, rpointee)) {
13178 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13179 << LHSType << RHSType << LHS.get()->getSourceRange()
13180 << RHS.get()->getSourceRange();
13181 }
13182 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13183 return computeResultTy();
13184 }
13185
13186 // Allow block pointers to be compared with null pointer constants.
13187 if (!IsOrdered
13188 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13189 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13190 if (!LHSIsNull && !RHSIsNull) {
13191 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13193 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13194 ->getPointeeType()->isVoidType())))
13195 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13196 << LHSType << RHSType << LHS.get()->getSourceRange()
13197 << RHS.get()->getSourceRange();
13198 }
13199 if (LHSIsNull && !RHSIsNull)
13200 LHS = ImpCastExprToType(LHS.get(), RHSType,
13201 RHSType->isPointerType() ? CK_BitCast
13202 : CK_AnyPointerToBlockPointerCast);
13203 else
13204 RHS = ImpCastExprToType(RHS.get(), LHSType,
13205 LHSType->isPointerType() ? CK_BitCast
13206 : CK_AnyPointerToBlockPointerCast);
13207 return computeResultTy();
13208 }
13209
13210 if (LHSType->isObjCObjectPointerType() ||
13211 RHSType->isObjCObjectPointerType()) {
13212 const PointerType *LPT = LHSType->getAs<PointerType>();
13213 const PointerType *RPT = RHSType->getAs<PointerType>();
13214 if (LPT || RPT) {
13215 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13216 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13217
13218 if (!LPtrToVoid && !RPtrToVoid &&
13219 !Context.typesAreCompatible(LHSType, RHSType)) {
13220 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13221 /*isError*/false);
13222 }
13223 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13224 // the RHS, but we have test coverage for this behavior.
13225 // FIXME: Consider using convertPointersToCompositeType in C++.
13226 if (LHSIsNull && !RHSIsNull) {
13227 Expr *E = LHS.get();
13228 if (getLangOpts().ObjCAutoRefCount)
13229 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13231 LHS = ImpCastExprToType(E, RHSType,
13232 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13233 }
13234 else {
13235 Expr *E = RHS.get();
13236 if (getLangOpts().ObjCAutoRefCount)
13237 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13239 /*Diagnose=*/true,
13240 /*DiagnoseCFAudited=*/false, Opc);
13241 RHS = ImpCastExprToType(E, LHSType,
13242 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13243 }
13244 return computeResultTy();
13245 }
13246 if (LHSType->isObjCObjectPointerType() &&
13247 RHSType->isObjCObjectPointerType()) {
13248 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13249 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13250 /*isError*/false);
13252 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13253
13254 if (LHSIsNull && !RHSIsNull)
13255 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13256 else
13257 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13258 return computeResultTy();
13259 }
13260
13261 if (!IsOrdered && LHSType->isBlockPointerType() &&
13263 LHS = ImpCastExprToType(LHS.get(), RHSType,
13264 CK_BlockPointerToObjCPointerCast);
13265 return computeResultTy();
13266 } else if (!IsOrdered &&
13268 RHSType->isBlockPointerType()) {
13269 RHS = ImpCastExprToType(RHS.get(), LHSType,
13270 CK_BlockPointerToObjCPointerCast);
13271 return computeResultTy();
13272 }
13273 }
13274 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13275 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13276 unsigned DiagID = 0;
13277 bool isError = false;
13278 if (LangOpts.DebuggerSupport) {
13279 // Under a debugger, allow the comparison of pointers to integers,
13280 // since users tend to want to compare addresses.
13281 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13282 (RHSIsNull && RHSType->isIntegerType())) {
13283 if (IsOrdered) {
13284 isError = getLangOpts().CPlusPlus;
13285 DiagID =
13286 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13287 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13288 }
13289 } else if (getLangOpts().CPlusPlus) {
13290 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13291 isError = true;
13292 } else if (IsOrdered)
13293 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13294 else
13295 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13296
13297 if (DiagID) {
13298 Diag(Loc, DiagID)
13299 << LHSType << RHSType << LHS.get()->getSourceRange()
13300 << RHS.get()->getSourceRange();
13301 if (isError)
13302 return QualType();
13303 }
13304
13305 if (LHSType->isIntegerType())
13306 LHS = ImpCastExprToType(LHS.get(), RHSType,
13307 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13308 else
13309 RHS = ImpCastExprToType(RHS.get(), LHSType,
13310 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13311 return computeResultTy();
13312 }
13313
13314 // Handle block pointers.
13315 if (!IsOrdered && RHSIsNull
13316 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13317 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13318 return computeResultTy();
13319 }
13320 if (!IsOrdered && LHSIsNull
13321 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13322 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13323 return computeResultTy();
13324 }
13325
13326 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13327 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13328 return computeResultTy();
13329 }
13330
13331 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13332 return computeResultTy();
13333 }
13334
13335 if (LHSIsNull && RHSType->isQueueT()) {
13336 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13337 return computeResultTy();
13338 }
13339
13340 if (LHSType->isQueueT() && RHSIsNull) {
13341 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13342 return computeResultTy();
13343 }
13344 }
13345
13346 return InvalidOperands(Loc, LHS, RHS);
13347}
13348
13350 const VectorType *VTy = V->castAs<VectorType>();
13351 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13352
13353 if (isa<ExtVectorType>(VTy)) {
13354 if (VTy->isExtVectorBoolType())
13355 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13356 if (TypeSize == Context.getTypeSize(Context.CharTy))
13357 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13358 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13359 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13360 if (TypeSize == Context.getTypeSize(Context.IntTy))
13361 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13362 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13363 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13364 if (TypeSize == Context.getTypeSize(Context.LongTy))
13365 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13366 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13367 "Unhandled vector element size in vector compare");
13368 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13369 }
13370
13371 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13372 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13374 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13375 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13377 if (TypeSize == Context.getTypeSize(Context.LongTy))
13378 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13380 if (TypeSize == Context.getTypeSize(Context.IntTy))
13381 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13383 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13384 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13386 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13387 "Unhandled vector element size in vector compare");
13388 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13390}
13391
13393 const BuiltinType *VTy = V->castAs<BuiltinType>();
13394 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13395
13396 const QualType ETy = V->getSveEltType(Context);
13397 const auto TypeSize = Context.getTypeSize(ETy);
13398
13399 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13400 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13401 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13402}
13403
13405 SourceLocation Loc,
13406 BinaryOperatorKind Opc) {
13407 if (Opc == BO_Cmp) {
13408 Diag(Loc, diag::err_three_way_vector_comparison);
13409 return QualType();
13410 }
13411
13412 // Check to make sure we're operating on vectors of the same type and width,
13413 // Allowing one side to be a scalar of element type.
13414 QualType vType =
13415 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13416 /*AllowBothBool*/ true,
13417 /*AllowBoolConversions*/ getLangOpts().ZVector,
13418 /*AllowBooleanOperation*/ true,
13419 /*ReportInvalid*/ true);
13420 if (vType.isNull())
13421 return vType;
13422
13423 QualType LHSType = LHS.get()->getType();
13424
13425 // Determine the return type of a vector compare. By default clang will return
13426 // a scalar for all vector compares except vector bool and vector pixel.
13427 // With the gcc compiler we will always return a vector type and with the xl
13428 // compiler we will always return a scalar type. This switch allows choosing
13429 // which behavior is prefered.
13430 if (getLangOpts().AltiVec) {
13431 switch (getLangOpts().getAltivecSrcCompat()) {
13433 // If AltiVec, the comparison results in a numeric type, i.e.
13434 // bool for C++, int for C
13435 if (vType->castAs<VectorType>()->getVectorKind() ==
13437 return Context.getLogicalOperationType();
13438 else
13439 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13440 break;
13442 // For GCC we always return the vector type.
13443 break;
13445 return Context.getLogicalOperationType();
13446 break;
13447 }
13448 }
13449
13450 // For non-floating point types, check for self-comparisons of the form
13451 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13452 // often indicate logic errors in the program.
13453 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13454
13455 // Check for comparisons of floating point operands using != and ==.
13456 if (LHSType->hasFloatingRepresentation()) {
13457 assert(RHS.get()->getType()->hasFloatingRepresentation());
13458 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13459 }
13460
13461 // Return a signed type for the vector.
13462 return GetSignedVectorType(vType);
13463}
13464
13466 ExprResult &RHS,
13467 SourceLocation Loc,
13468 BinaryOperatorKind Opc) {
13469 if (Opc == BO_Cmp) {
13470 Diag(Loc, diag::err_three_way_vector_comparison);
13471 return QualType();
13472 }
13473
13474 // Check to make sure we're operating on vectors of the same type and width,
13475 // Allowing one side to be a scalar of element type.
13477 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13478
13479 if (vType.isNull())
13480 return vType;
13481
13482 QualType LHSType = LHS.get()->getType();
13483
13484 // For non-floating point types, check for self-comparisons of the form
13485 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13486 // often indicate logic errors in the program.
13487 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13488
13489 // Check for comparisons of floating point operands using != and ==.
13490 if (LHSType->hasFloatingRepresentation()) {
13491 assert(RHS.get()->getType()->hasFloatingRepresentation());
13492 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13493 }
13494
13495 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13496 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13497
13498 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13499 RHSBuiltinTy->isSVEBool())
13500 return LHSType;
13501
13502 // Return a signed type for the vector.
13503 return GetSignedSizelessVectorType(vType);
13504}
13505
13506static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13507 const ExprResult &XorRHS,
13508 const SourceLocation Loc) {
13509 // Do not diagnose macros.
13510 if (Loc.isMacroID())
13511 return;
13512
13513 // Do not diagnose if both LHS and RHS are macros.
13514 if (XorLHS.get()->getExprLoc().isMacroID() &&
13515 XorRHS.get()->getExprLoc().isMacroID())
13516 return;
13517
13518 bool Negative = false;
13519 bool ExplicitPlus = false;
13520 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13521 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13522
13523 if (!LHSInt)
13524 return;
13525 if (!RHSInt) {
13526 // Check negative literals.
13527 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13528 UnaryOperatorKind Opc = UO->getOpcode();
13529 if (Opc != UO_Minus && Opc != UO_Plus)
13530 return;
13531 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13532 if (!RHSInt)
13533 return;
13534 Negative = (Opc == UO_Minus);
13535 ExplicitPlus = !Negative;
13536 } else {
13537 return;
13538 }
13539 }
13540
13541 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13542 llvm::APInt RightSideValue = RHSInt->getValue();
13543 if (LeftSideValue != 2 && LeftSideValue != 10)
13544 return;
13545
13546 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13547 return;
13548
13550 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13551 llvm::StringRef ExprStr =
13553
13554 CharSourceRange XorRange =
13556 llvm::StringRef XorStr =
13558 // Do not diagnose if xor keyword/macro is used.
13559 if (XorStr == "xor")
13560 return;
13561
13562 std::string LHSStr = std::string(Lexer::getSourceText(
13563 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13564 S.getSourceManager(), S.getLangOpts()));
13565 std::string RHSStr = std::string(Lexer::getSourceText(
13566 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13567 S.getSourceManager(), S.getLangOpts()));
13568
13569 if (Negative) {
13570 RightSideValue = -RightSideValue;
13571 RHSStr = "-" + RHSStr;
13572 } else if (ExplicitPlus) {
13573 RHSStr = "+" + RHSStr;
13574 }
13575
13576 StringRef LHSStrRef = LHSStr;
13577 StringRef RHSStrRef = RHSStr;
13578 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13579 // literals.
13580 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13581 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13582 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13583 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13584 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13585 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13586 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13587 return;
13588
13589 bool SuggestXor =
13590 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13591 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13592 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13593 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13594 std::string SuggestedExpr = "1 << " + RHSStr;
13595 bool Overflow = false;
13596 llvm::APInt One = (LeftSideValue - 1);
13597 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13598 if (Overflow) {
13599 if (RightSideIntValue < 64)
13600 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13601 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13602 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13603 else if (RightSideIntValue == 64)
13604 S.Diag(Loc, diag::warn_xor_used_as_pow)
13605 << ExprStr << toString(XorValue, 10, true);
13606 else
13607 return;
13608 } else {
13609 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13610 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13611 << toString(PowValue, 10, true)
13613 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13614 }
13615
13616 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13617 << ("0x2 ^ " + RHSStr) << SuggestXor;
13618 } else if (LeftSideValue == 10) {
13619 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13620 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13621 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13622 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13623 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13624 << ("0xA ^ " + RHSStr) << SuggestXor;
13625 }
13626}
13627
13629 SourceLocation Loc,
13630 BinaryOperatorKind Opc) {
13631 // Ensure that either both operands are of the same vector type, or
13632 // one operand is of a vector type and the other is of its element type.
13633 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13634 /*AllowBothBool*/ true,
13635 /*AllowBoolConversions*/ false,
13636 /*AllowBooleanOperation*/ false,
13637 /*ReportInvalid*/ false);
13638 if (vType.isNull())
13639 return InvalidOperands(Loc, LHS, RHS);
13640 if (getLangOpts().OpenCL &&
13641 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13643 return InvalidOperands(Loc, LHS, RHS);
13644 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13645 // usage of the logical operators && and || with vectors in C. This
13646 // check could be notionally dropped.
13647 if (!getLangOpts().CPlusPlus &&
13648 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13649 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13650 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13651 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13652 // `select` functions.
13653 if (getLangOpts().HLSL &&
13654 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13655 (void)InvalidOperands(Loc, LHS, RHS);
13656 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13657 return QualType();
13658 }
13659
13660 return GetSignedVectorType(LHS.get()->getType());
13661}
13662
13664 SourceLocation Loc,
13665 BinaryOperatorKind Opc) {
13666
13667 if (!getLangOpts().HLSL) {
13668 assert(false && "Logical operands are not supported in C\\C++");
13669 return QualType();
13670 }
13671
13672 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13673 (void)InvalidOperands(Loc, LHS, RHS);
13674 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13675 return QualType();
13676 }
13677 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13678 << getLangOpts().getHLSLVersion();
13679 return QualType();
13680}
13681
13683 SourceLocation Loc,
13684 bool IsCompAssign) {
13685 if (!IsCompAssign) {
13687 if (LHS.isInvalid())
13688 return QualType();
13689 }
13691 if (RHS.isInvalid())
13692 return QualType();
13693
13694 // For conversion purposes, we ignore any qualifiers.
13695 // For example, "const float" and "float" are equivalent.
13696 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13697 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13698
13699 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13700 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13701 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13702
13703 if (Context.hasSameType(LHSType, RHSType))
13704 return Context.getCommonSugaredType(LHSType, RHSType);
13705
13706 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13707 // case we have to return InvalidOperands.
13708 ExprResult OriginalLHS = LHS;
13709 ExprResult OriginalRHS = RHS;
13710 if (LHSMatType && !RHSMatType) {
13711 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13712 if (!RHS.isInvalid())
13713 return LHSType;
13714
13715 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13716 }
13717
13718 if (!LHSMatType && RHSMatType) {
13719 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13720 if (!LHS.isInvalid())
13721 return RHSType;
13722 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13723 }
13724
13725 return InvalidOperands(Loc, LHS, RHS);
13726}
13727
13729 SourceLocation Loc,
13730 bool IsCompAssign) {
13731 if (!IsCompAssign) {
13733 if (LHS.isInvalid())
13734 return QualType();
13735 }
13737 if (RHS.isInvalid())
13738 return QualType();
13739
13740 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13741 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13742 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13743
13744 if (LHSMatType && RHSMatType) {
13745 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13746 return InvalidOperands(Loc, LHS, RHS);
13747
13748 if (Context.hasSameType(LHSMatType, RHSMatType))
13749 return Context.getCommonSugaredType(
13750 LHS.get()->getType().getUnqualifiedType(),
13751 RHS.get()->getType().getUnqualifiedType());
13752
13753 QualType LHSELTy = LHSMatType->getElementType(),
13754 RHSELTy = RHSMatType->getElementType();
13755 if (!Context.hasSameType(LHSELTy, RHSELTy))
13756 return InvalidOperands(Loc, LHS, RHS);
13757
13758 return Context.getConstantMatrixType(
13759 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13760 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13761 }
13762 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13763}
13764
13766 switch (Opc) {
13767 default:
13768 return false;
13769 case BO_And:
13770 case BO_AndAssign:
13771 case BO_Or:
13772 case BO_OrAssign:
13773 case BO_Xor:
13774 case BO_XorAssign:
13775 return true;
13776 }
13777}
13778
13780 SourceLocation Loc,
13781 BinaryOperatorKind Opc) {
13782 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13783
13784 bool IsCompAssign =
13785 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13786
13787 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13788
13789 if (LHS.get()->getType()->isVectorType() ||
13790 RHS.get()->getType()->isVectorType()) {
13791 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13793 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13794 /*AllowBothBool*/ true,
13795 /*AllowBoolConversions*/ getLangOpts().ZVector,
13796 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13797 /*ReportInvalid*/ true);
13798 return InvalidOperands(Loc, LHS, RHS);
13799 }
13800
13801 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13802 RHS.get()->getType()->isSveVLSBuiltinType()) {
13803 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13805 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13807 return InvalidOperands(Loc, LHS, RHS);
13808 }
13809
13810 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13811 RHS.get()->getType()->isSveVLSBuiltinType()) {
13812 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13814 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13816 return InvalidOperands(Loc, LHS, RHS);
13817 }
13818
13819 if (Opc == BO_And)
13820 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13821
13822 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13824 return InvalidOperands(Loc, LHS, RHS);
13825
13826 ExprResult LHSResult = LHS, RHSResult = RHS;
13828 LHSResult, RHSResult, Loc,
13830 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13831 return QualType();
13832 LHS = LHSResult.get();
13833 RHS = RHSResult.get();
13834
13835 if (Opc == BO_Xor)
13836 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13837
13838 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13839 return compType;
13840 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13841 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13842 return ResultTy;
13843}
13844
13845// C99 6.5.[13,14]
13847 SourceLocation Loc,
13848 BinaryOperatorKind Opc) {
13849 // Check vector operands differently.
13850 if (LHS.get()->getType()->isVectorType() ||
13851 RHS.get()->getType()->isVectorType())
13852 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13853
13854 if (LHS.get()->getType()->isConstantMatrixType() ||
13855 RHS.get()->getType()->isConstantMatrixType())
13856 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13857
13858 bool EnumConstantInBoolContext = false;
13859 for (const ExprResult &HS : {LHS, RHS}) {
13860 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13861 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13862 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13863 EnumConstantInBoolContext = true;
13864 }
13865 }
13866
13867 if (EnumConstantInBoolContext)
13868 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13869
13870 // WebAssembly tables can't be used with logical operators.
13871 QualType LHSTy = LHS.get()->getType();
13872 QualType RHSTy = RHS.get()->getType();
13873 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13874 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13875 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13876 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13877 return InvalidOperands(Loc, LHS, RHS);
13878 }
13879
13880 // Diagnose cases where the user write a logical and/or but probably meant a
13881 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13882 // is a constant.
13883 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13884 !LHS.get()->getType()->isBooleanType() &&
13885 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13886 // Don't warn in macros or template instantiations.
13887 !Loc.isMacroID() && !inTemplateInstantiation()) {
13888 // If the RHS can be constant folded, and if it constant folds to something
13889 // that isn't 0 or 1 (which indicate a potential logical operation that
13890 // happened to fold to true/false) then warn.
13891 // Parens on the RHS are ignored.
13892 Expr::EvalResult EVResult;
13893 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13894 llvm::APSInt Result = EVResult.Val.getInt();
13895 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13896 !RHS.get()->getExprLoc().isMacroID()) ||
13897 (Result != 0 && Result != 1)) {
13898 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13899 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13900 // Suggest replacing the logical operator with the bitwise version
13901 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13902 << (Opc == BO_LAnd ? "&" : "|")
13905 Opc == BO_LAnd ? "&" : "|");
13906 if (Opc == BO_LAnd)
13907 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13908 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13911 RHS.get()->getEndLoc()));
13912 }
13913 }
13914 }
13915
13916 if (!Context.getLangOpts().CPlusPlus) {
13917 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13918 // not operate on the built-in scalar and vector float types.
13919 if (Context.getLangOpts().OpenCL &&
13920 Context.getLangOpts().OpenCLVersion < 120) {
13921 if (LHS.get()->getType()->isFloatingType() ||
13922 RHS.get()->getType()->isFloatingType())
13923 return InvalidOperands(Loc, LHS, RHS);
13924 }
13925
13926 LHS = UsualUnaryConversions(LHS.get());
13927 if (LHS.isInvalid())
13928 return QualType();
13929
13930 RHS = UsualUnaryConversions(RHS.get());
13931 if (RHS.isInvalid())
13932 return QualType();
13933
13934 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13936 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13938
13939 if (!LHS.get()->getType()->isScalarType() ||
13940 !RHS.get()->getType()->isScalarType())
13941 return InvalidOperands(Loc, LHS, RHS);
13942
13943 return Context.IntTy;
13944 }
13945
13946 // The following is safe because we only use this method for
13947 // non-overloadable operands.
13948
13949 // C++ [expr.log.and]p1
13950 // C++ [expr.log.or]p1
13951 // The operands are both contextually converted to type bool.
13953 if (LHSRes.isInvalid()) {
13954 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13955 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13956 return ResultTy;
13957 }
13958 LHS = LHSRes;
13959
13961 if (RHSRes.isInvalid()) {
13962 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13963 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13964 return ResultTy;
13965 }
13966 RHS = RHSRes;
13967
13968 // C++ [expr.log.and]p2
13969 // C++ [expr.log.or]p2
13970 // The result is a bool.
13971 return Context.BoolTy;
13972}
13973
13974static bool IsReadonlyMessage(Expr *E, Sema &S) {
13975 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13976 if (!ME) return false;
13977 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13978 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13980 if (!Base) return false;
13981 return Base->getMethodDecl() != nullptr;
13982}
13983
13984/// Is the given expression (which must be 'const') a reference to a
13985/// variable which was originally non-const, but which has become
13986/// 'const' due to being captured within a block?
13989 assert(E->isLValue() && E->getType().isConstQualified());
13990 E = E->IgnoreParens();
13991
13992 // Must be a reference to a declaration from an enclosing scope.
13993 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13994 if (!DRE) return NCCK_None;
13996
13997 ValueDecl *Value = DRE->getDecl();
13998
13999 // The declaration must be a value which is not declared 'const'.
14001 return NCCK_None;
14002
14003 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14004 if (Binding) {
14005 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14006 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14007 return NCCK_Lambda;
14008 }
14009
14010 VarDecl *Var = dyn_cast<VarDecl>(Value);
14011 if (!Var)
14012 return NCCK_None;
14013 if (Var->getType()->isReferenceType())
14014 return NCCK_None;
14015
14016 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14017
14018 // Decide whether the first capture was for a block or a lambda.
14019 DeclContext *DC = S.CurContext, *Prev = nullptr;
14020 // Decide whether the first capture was for a block or a lambda.
14021 while (DC) {
14022 // For init-capture, it is possible that the variable belongs to the
14023 // template pattern of the current context.
14024 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14025 if (Var->isInitCapture() &&
14026 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14027 break;
14028 if (DC == Var->getDeclContext())
14029 break;
14030 Prev = DC;
14031 DC = DC->getParent();
14032 }
14033 // Unless we have an init-capture, we've gone one step too far.
14034 if (!Var->isInitCapture())
14035 DC = Prev;
14036 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14037}
14038
14039static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14040 Ty = Ty.getNonReferenceType();
14041 if (IsDereference && Ty->isPointerType())
14042 Ty = Ty->getPointeeType();
14043 return !Ty.isConstQualified();
14044}
14045
14046// Update err_typecheck_assign_const and note_typecheck_assign_const
14047// when this enum is changed.
14048enum {
14053 ConstUnknown, // Keep as last element
14054};
14055
14056/// Emit the "read-only variable not assignable" error and print notes to give
14057/// more information about why the variable is not assignable, such as pointing
14058/// to the declaration of a const variable, showing that a method is const, or
14059/// that the function is returning a const reference.
14060static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14061 SourceLocation Loc) {
14062 SourceRange ExprRange = E->getSourceRange();
14063
14064 // Only emit one error on the first const found. All other consts will emit
14065 // a note to the error.
14066 bool DiagnosticEmitted = false;
14067
14068 // Track if the current expression is the result of a dereference, and if the
14069 // next checked expression is the result of a dereference.
14070 bool IsDereference = false;
14071 bool NextIsDereference = false;
14072
14073 // Loop to process MemberExpr chains.
14074 while (true) {
14075 IsDereference = NextIsDereference;
14076
14078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14079 NextIsDereference = ME->isArrow();
14080 const ValueDecl *VD = ME->getMemberDecl();
14081 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14082 // Mutable fields can be modified even if the class is const.
14083 if (Field->isMutable()) {
14084 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14085 break;
14086 }
14087
14088 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14089 if (!DiagnosticEmitted) {
14090 S.Diag(Loc, diag::err_typecheck_assign_const)
14091 << ExprRange << ConstMember << false /*static*/ << Field
14092 << Field->getType();
14093 DiagnosticEmitted = true;
14094 }
14095 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14096 << ConstMember << false /*static*/ << Field << Field->getType()
14097 << Field->getSourceRange();
14098 }
14099 E = ME->getBase();
14100 continue;
14101 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14102 if (VDecl->getType().isConstQualified()) {
14103 if (!DiagnosticEmitted) {
14104 S.Diag(Loc, diag::err_typecheck_assign_const)
14105 << ExprRange << ConstMember << true /*static*/ << VDecl
14106 << VDecl->getType();
14107 DiagnosticEmitted = true;
14108 }
14109 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14110 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14111 << VDecl->getSourceRange();
14112 }
14113 // Static fields do not inherit constness from parents.
14114 break;
14115 }
14116 break; // End MemberExpr
14117 } else if (const ArraySubscriptExpr *ASE =
14118 dyn_cast<ArraySubscriptExpr>(E)) {
14119 E = ASE->getBase()->IgnoreParenImpCasts();
14120 continue;
14121 } else if (const ExtVectorElementExpr *EVE =
14122 dyn_cast<ExtVectorElementExpr>(E)) {
14123 E = EVE->getBase()->IgnoreParenImpCasts();
14124 continue;
14125 }
14126 break;
14127 }
14128
14129 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14130 // Function calls
14131 const FunctionDecl *FD = CE->getDirectCallee();
14132 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14133 if (!DiagnosticEmitted) {
14134 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14135 << ConstFunction << FD;
14136 DiagnosticEmitted = true;
14137 }
14139 diag::note_typecheck_assign_const)
14140 << ConstFunction << FD << FD->getReturnType()
14141 << FD->getReturnTypeSourceRange();
14142 }
14143 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14144 // Point to variable declaration.
14145 if (const ValueDecl *VD = DRE->getDecl()) {
14146 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14147 if (!DiagnosticEmitted) {
14148 S.Diag(Loc, diag::err_typecheck_assign_const)
14149 << ExprRange << ConstVariable << VD << VD->getType();
14150 DiagnosticEmitted = true;
14151 }
14152 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14153 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14154 }
14155 }
14156 } else if (isa<CXXThisExpr>(E)) {
14157 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14158 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14159 if (MD->isConst()) {
14160 if (!DiagnosticEmitted) {
14161 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14162 << ExprRange << MD;
14163 DiagnosticEmitted = true;
14164 }
14165 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14166 << MD << MD->getSourceRange();
14167 }
14168 }
14169 }
14170 }
14171
14172 if (DiagnosticEmitted)
14173 return;
14174
14175 // Can't determine a more specific message, so display the generic error.
14176 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14177}
14178
14184
14186 const RecordType *Ty,
14187 SourceLocation Loc, SourceRange Range,
14188 OriginalExprKind OEK,
14189 bool &DiagnosticEmitted) {
14190 std::vector<const RecordType *> RecordTypeList;
14191 RecordTypeList.push_back(Ty);
14192 unsigned NextToCheckIndex = 0;
14193 // We walk the record hierarchy breadth-first to ensure that we print
14194 // diagnostics in field nesting order.
14195 while (RecordTypeList.size() > NextToCheckIndex) {
14196 bool IsNested = NextToCheckIndex > 0;
14197 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14198 ->getDecl()
14200 ->fields()) {
14201 // First, check every field for constness.
14202 QualType FieldTy = Field->getType();
14203 if (FieldTy.isConstQualified()) {
14204 if (!DiagnosticEmitted) {
14205 S.Diag(Loc, diag::err_typecheck_assign_const)
14206 << Range << NestedConstMember << OEK << VD
14207 << IsNested << Field;
14208 DiagnosticEmitted = true;
14209 }
14210 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14211 << NestedConstMember << IsNested << Field
14212 << FieldTy << Field->getSourceRange();
14213 }
14214
14215 // Then we append it to the list to check next in order.
14216 FieldTy = FieldTy.getCanonicalType();
14217 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14218 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14219 RecordTypeList.push_back(FieldRecTy);
14220 }
14221 }
14222 ++NextToCheckIndex;
14223 }
14224}
14225
14226/// Emit an error for the case where a record we are trying to assign to has a
14227/// const-qualified field somewhere in its hierarchy.
14228static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14229 SourceLocation Loc) {
14230 QualType Ty = E->getType();
14231 assert(Ty->isRecordType() && "lvalue was not record?");
14232 SourceRange Range = E->getSourceRange();
14233 const auto *RTy = Ty->getAsCanonical<RecordType>();
14234 bool DiagEmitted = false;
14235
14236 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14237 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14238 Range, OEK_Member, DiagEmitted);
14239 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14240 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14241 Range, OEK_Variable, DiagEmitted);
14242 else
14243 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14244 Range, OEK_LValue, DiagEmitted);
14245 if (!DiagEmitted)
14246 DiagnoseConstAssignment(S, E, Loc);
14247}
14248
14249/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14250/// emit an error and return true. If so, return false.
14252 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14253
14255
14256 SourceLocation OrigLoc = Loc;
14258 &Loc);
14259 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14261 if (IsLV == Expr::MLV_Valid)
14262 return false;
14263
14264 unsigned DiagID = 0;
14265 bool NeedType = false;
14266 switch (IsLV) { // C99 6.5.16p2
14268 // Use a specialized diagnostic when we're assigning to an object
14269 // from an enclosing function or block.
14271 if (NCCK == NCCK_Block)
14272 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14273 else
14274 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14275 break;
14276 }
14277
14278 // In ARC, use some specialized diagnostics for occasions where we
14279 // infer 'const'. These are always pseudo-strong variables.
14280 if (S.getLangOpts().ObjCAutoRefCount) {
14281 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14282 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14283 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14284
14285 // Use the normal diagnostic if it's pseudo-__strong but the
14286 // user actually wrote 'const'.
14287 if (var->isARCPseudoStrong() &&
14288 (!var->getTypeSourceInfo() ||
14289 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14290 // There are three pseudo-strong cases:
14291 // - self
14292 ObjCMethodDecl *method = S.getCurMethodDecl();
14293 if (method && var == method->getSelfDecl()) {
14294 DiagID = method->isClassMethod()
14295 ? diag::err_typecheck_arc_assign_self_class_method
14296 : diag::err_typecheck_arc_assign_self;
14297
14298 // - Objective-C externally_retained attribute.
14299 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14300 isa<ParmVarDecl>(var)) {
14301 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14302
14303 // - fast enumeration variables
14304 } else {
14305 DiagID = diag::err_typecheck_arr_assign_enumeration;
14306 }
14307
14308 SourceRange Assign;
14309 if (Loc != OrigLoc)
14310 Assign = SourceRange(OrigLoc, OrigLoc);
14311 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14312 // We need to preserve the AST regardless, so migration tool
14313 // can do its job.
14314 return false;
14315 }
14316 }
14317 }
14318
14319 // If none of the special cases above are triggered, then this is a
14320 // simple const assignment.
14321 if (DiagID == 0) {
14322 DiagnoseConstAssignment(S, E, Loc);
14323 return true;
14324 }
14325
14326 break;
14328 DiagnoseConstAssignment(S, E, Loc);
14329 return true;
14332 return true;
14335 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14336 NeedType = true;
14337 break;
14339 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14340 NeedType = true;
14341 break;
14343 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14344 break;
14345 case Expr::MLV_Valid:
14346 llvm_unreachable("did not take early return for MLV_Valid");
14350 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14351 break;
14354 return S.RequireCompleteType(Loc, E->getType(),
14355 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14357 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14358 break;
14360 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14361 break;
14363 llvm_unreachable("readonly properties should be processed differently");
14365 DiagID = diag::err_readonly_message_assignment;
14366 break;
14368 DiagID = diag::err_no_subobject_property_setting;
14369 break;
14370 }
14371
14372 SourceRange Assign;
14373 if (Loc != OrigLoc)
14374 Assign = SourceRange(OrigLoc, OrigLoc);
14375 if (NeedType)
14376 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14377 else
14378 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14379 return true;
14380}
14381
14382static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14383 SourceLocation Loc,
14384 Sema &Sema) {
14386 return;
14388 return;
14389 if (Loc.isInvalid() || Loc.isMacroID())
14390 return;
14391 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14392 return;
14393
14394 // C / C++ fields
14395 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14396 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14397 if (ML && MR) {
14398 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14399 return;
14400 const ValueDecl *LHSDecl =
14402 const ValueDecl *RHSDecl =
14404 if (LHSDecl != RHSDecl)
14405 return;
14406 if (LHSDecl->getType().isVolatileQualified())
14407 return;
14408 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14409 if (RefTy->getPointeeType().isVolatileQualified())
14410 return;
14411
14412 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14413 }
14414
14415 // Objective-C instance variables
14416 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14417 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14418 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14419 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14420 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14421 if (RL && RR && RL->getDecl() == RR->getDecl())
14422 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14423 }
14424}
14425
14426// C99 6.5.16.1
14428 SourceLocation Loc,
14429 QualType CompoundType,
14430 BinaryOperatorKind Opc) {
14431 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14432
14433 // Verify that LHS is a modifiable lvalue, and emit error if not.
14434 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14435 return QualType();
14436
14437 QualType LHSType = LHSExpr->getType();
14438 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14439 CompoundType;
14440
14441 if (RHS.isUsable()) {
14442 // Even if this check fails don't return early to allow the best
14443 // possible error recovery and to allow any subsequent diagnostics to
14444 // work.
14445 const ValueDecl *Assignee = nullptr;
14446 bool ShowFullyQualifiedAssigneeName = false;
14447 // In simple cases describe what is being assigned to
14448 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14449 Assignee = DR->getDecl();
14450 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14451 Assignee = ME->getMemberDecl();
14452 ShowFullyQualifiedAssigneeName = true;
14453 }
14454
14456 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14457 ShowFullyQualifiedAssigneeName);
14458 }
14459
14460 // OpenCL v1.2 s6.1.1.1 p2:
14461 // The half data type can only be used to declare a pointer to a buffer that
14462 // contains half values
14463 if (getLangOpts().OpenCL &&
14464 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14465 LHSType->isHalfType()) {
14466 Diag(Loc, diag::err_opencl_half_load_store) << 1
14467 << LHSType.getUnqualifiedType();
14468 return QualType();
14469 }
14470
14471 // WebAssembly tables can't be used on RHS of an assignment expression.
14472 if (RHSType->isWebAssemblyTableType()) {
14473 Diag(Loc, diag::err_wasm_table_art) << 0;
14474 return QualType();
14475 }
14476
14477 AssignConvertType ConvTy;
14478 if (CompoundType.isNull()) {
14479 Expr *RHSCheck = RHS.get();
14480
14481 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14482
14483 QualType LHSTy(LHSType);
14484 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14485 if (RHS.isInvalid())
14486 return QualType();
14487 // Special case of NSObject attributes on c-style pointer types.
14489 ((Context.isObjCNSObjectType(LHSType) &&
14490 RHSType->isObjCObjectPointerType()) ||
14491 (Context.isObjCNSObjectType(RHSType) &&
14492 LHSType->isObjCObjectPointerType())))
14494
14495 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14496 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14497
14498 // If the RHS is a unary plus or minus, check to see if they = and + are
14499 // right next to each other. If so, the user may have typo'd "x =+ 4"
14500 // instead of "x += 4".
14501 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14502 RHSCheck = ICE->getSubExpr();
14503 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14504 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14505 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14506 // Only if the two operators are exactly adjacent.
14507 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14508 // And there is a space or other character before the subexpr of the
14509 // unary +/-. We don't want to warn on "x=-1".
14510 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14511 UO->getSubExpr()->getBeginLoc().isFileID()) {
14512 Diag(Loc, diag::warn_not_compound_assign)
14513 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14514 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14515 }
14516 }
14517
14518 if (IsAssignConvertCompatible(ConvTy)) {
14519 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14520 // Warn about retain cycles where a block captures the LHS, but
14521 // not if the LHS is a simple variable into which the block is
14522 // being stored...unless that variable can be captured by reference!
14523 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14524 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14525 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14526 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14527 }
14528
14529 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14531 // It is safe to assign a weak reference into a strong variable.
14532 // Although this code can still have problems:
14533 // id x = self.weakProp;
14534 // id y = self.weakProp;
14535 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14536 // paths through the function. This should be revisited if
14537 // -Wrepeated-use-of-weak is made flow-sensitive.
14538 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14539 // variable, which will be valid for the current autorelease scope.
14540 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14541 RHS.get()->getBeginLoc()))
14543
14544 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14545 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14546 }
14547 }
14548 } else {
14549 // Compound assignment "x += y"
14550 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14551 }
14552
14553 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14555 return QualType();
14556
14557 CheckForNullPointerDereference(*this, LHSExpr);
14558
14559 AssignedEntity AE{LHSExpr};
14560 checkAssignmentLifetime(*this, AE, RHS.get());
14561
14562 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14563 if (CompoundType.isNull()) {
14564 // C++2a [expr.ass]p5:
14565 // A simple-assignment whose left operand is of a volatile-qualified
14566 // type is deprecated unless the assignment is either a discarded-value
14567 // expression or an unevaluated operand
14568 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14569 }
14570 }
14571
14572 // C11 6.5.16p3: The type of an assignment expression is the type of the
14573 // left operand would have after lvalue conversion.
14574 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14575 // qualified type, the value has the unqualified version of the type of the
14576 // lvalue; additionally, if the lvalue has atomic type, the value has the
14577 // non-atomic version of the type of the lvalue.
14578 // C++ 5.17p1: the type of the assignment expression is that of its left
14579 // operand.
14580 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14581}
14582
14583// Scenarios to ignore if expression E is:
14584// 1. an explicit cast expression into void
14585// 2. a function call expression that returns void
14586static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14587 E = E->IgnoreParens();
14588
14589 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14590 if (CE->getCastKind() == CK_ToVoid) {
14591 return true;
14592 }
14593
14594 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14595 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14596 CE->getSubExpr()->getType()->isDependentType()) {
14597 return true;
14598 }
14599 }
14600
14601 if (const auto *CE = dyn_cast<CallExpr>(E))
14602 return CE->getCallReturnType(Context)->isVoidType();
14603 return false;
14604}
14605
14607 // No warnings in macros
14608 if (Loc.isMacroID())
14609 return;
14610
14611 // Don't warn in template instantiations.
14613 return;
14614
14615 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14616 // instead, skip more than needed, then call back into here with the
14617 // CommaVisitor in SemaStmt.cpp.
14618 // The listed locations are the initialization and increment portions
14619 // of a for loop. The additional checks are on the condition of
14620 // if statements, do/while loops, and for loops.
14621 // Differences in scope flags for C89 mode requires the extra logic.
14622 const unsigned ForIncrementFlags =
14623 getLangOpts().C99 || getLangOpts().CPlusPlus
14626 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14627 const unsigned ScopeFlags = getCurScope()->getFlags();
14628 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14629 (ScopeFlags & ForInitFlags) == ForInitFlags)
14630 return;
14631
14632 // If there are multiple comma operators used together, get the RHS of the
14633 // of the comma operator as the LHS.
14634 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14635 if (BO->getOpcode() != BO_Comma)
14636 break;
14637 LHS = BO->getRHS();
14638 }
14639
14640 // Only allow some expressions on LHS to not warn.
14641 if (IgnoreCommaOperand(LHS, Context))
14642 return;
14643
14644 Diag(Loc, diag::warn_comma_operator);
14645 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14646 << LHS->getSourceRange()
14648 LangOpts.CPlusPlus ? "static_cast<void>("
14649 : "(void)(")
14650 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14651 ")");
14652}
14653
14654// C99 6.5.17
14656 SourceLocation Loc) {
14657 LHS = S.CheckPlaceholderExpr(LHS.get());
14658 RHS = S.CheckPlaceholderExpr(RHS.get());
14659 if (LHS.isInvalid() || RHS.isInvalid())
14660 return QualType();
14661
14662 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14663 // operands, but not unary promotions.
14664 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14665
14666 // So we treat the LHS as a ignored value, and in C++ we allow the
14667 // containing site to determine what should be done with the RHS.
14668 LHS = S.IgnoredValueConversions(LHS.get());
14669 if (LHS.isInvalid())
14670 return QualType();
14671
14672 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14673
14674 if (!S.getLangOpts().CPlusPlus) {
14676 if (RHS.isInvalid())
14677 return QualType();
14678 if (!RHS.get()->getType()->isVoidType())
14679 S.RequireCompleteType(Loc, RHS.get()->getType(),
14680 diag::err_incomplete_type);
14681 }
14682
14683 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14684 S.DiagnoseCommaOperator(LHS.get(), Loc);
14685
14686 return RHS.get()->getType();
14687}
14688
14689/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14690/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14693 ExprObjectKind &OK,
14694 SourceLocation OpLoc, bool IsInc,
14695 bool IsPrefix) {
14696 QualType ResType = Op->getType();
14697 // Atomic types can be used for increment / decrement where the non-atomic
14698 // versions can, so ignore the _Atomic() specifier for the purpose of
14699 // checking.
14700 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14701 ResType = ResAtomicType->getValueType();
14702
14703 assert(!ResType.isNull() && "no type for increment/decrement expression");
14704
14705 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14706 // Decrement of bool is not allowed.
14707 if (!IsInc) {
14708 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14709 return QualType();
14710 }
14711 // Increment of bool sets it to true, but is deprecated.
14712 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14713 : diag::warn_increment_bool)
14714 << Op->getSourceRange();
14715 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14716 // Error on enum increments and decrements in C++ mode
14717 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14718 return QualType();
14719 } else if (ResType->isRealType()) {
14720 // OK!
14721 } else if (ResType->isPointerType()) {
14722 // C99 6.5.2.4p2, 6.5.6p2
14723 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14724 return QualType();
14725 } else if (ResType->isOverflowBehaviorType()) {
14726 // OK!
14727 } else if (ResType->isObjCObjectPointerType()) {
14728 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14729 // Otherwise, we just need a complete type.
14730 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14731 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14732 return QualType();
14733 } else if (ResType->isAnyComplexType()) {
14734 // C99 does not support ++/-- on complex types, we allow as an extension.
14735 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14736 : diag::ext_c2y_increment_complex)
14737 << IsInc << Op->getSourceRange();
14738 } else if (ResType->isPlaceholderType()) {
14740 if (PR.isInvalid()) return QualType();
14741 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14742 IsInc, IsPrefix);
14743 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14744 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14745 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14746 (ResType->castAs<VectorType>()->getVectorKind() !=
14748 // The z vector extensions allow ++ and -- for non-bool vectors.
14749 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14750 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14751 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14752 } else {
14753 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14754 << ResType << int(IsInc) << Op->getSourceRange();
14755 return QualType();
14756 }
14757 // At this point, we know we have a real, complex or pointer type.
14758 // Now make sure the operand is a modifiable lvalue.
14759 if (CheckForModifiableLvalue(Op, OpLoc, S))
14760 return QualType();
14761 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14762 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14763 // An operand with volatile-qualified type is deprecated
14764 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14765 << IsInc << ResType;
14766 }
14767 // In C++, a prefix increment is the same type as the operand. Otherwise
14768 // (in C or with postfix), the increment is the unqualified type of the
14769 // operand.
14770 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14771 VK = VK_LValue;
14772 OK = Op->getObjectKind();
14773 return ResType;
14774 } else {
14775 VK = VK_PRValue;
14776 return ResType.getUnqualifiedType();
14777 }
14778}
14779
14780/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14781/// This routine allows us to typecheck complex/recursive expressions
14782/// where the declaration is needed for type checking. We only need to
14783/// handle cases when the expression references a function designator
14784/// or is an lvalue. Here are some examples:
14785/// - &(x) => x
14786/// - &*****f => f for f a function designator.
14787/// - &s.xx => s
14788/// - &s.zz[1].yy -> s, if zz is an array
14789/// - *(x + 1) -> x, if x is an array
14790/// - &"123"[2] -> 0
14791/// - & __real__ x -> x
14792///
14793/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14794/// members.
14796 switch (E->getStmtClass()) {
14797 case Stmt::DeclRefExprClass:
14798 return cast<DeclRefExpr>(E)->getDecl();
14799 case Stmt::MemberExprClass:
14800 // If this is an arrow operator, the address is an offset from
14801 // the base's value, so the object the base refers to is
14802 // irrelevant.
14803 if (cast<MemberExpr>(E)->isArrow())
14804 return nullptr;
14805 // Otherwise, the expression refers to a part of the base
14806 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14807 case Stmt::ArraySubscriptExprClass: {
14808 // FIXME: This code shouldn't be necessary! We should catch the implicit
14809 // promotion of register arrays earlier.
14810 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14811 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14812 if (ICE->getSubExpr()->getType()->isArrayType())
14813 return getPrimaryDecl(ICE->getSubExpr());
14814 }
14815 return nullptr;
14816 }
14817 case Stmt::UnaryOperatorClass: {
14819
14820 switch(UO->getOpcode()) {
14821 case UO_Real:
14822 case UO_Imag:
14823 case UO_Extension:
14824 return getPrimaryDecl(UO->getSubExpr());
14825 default:
14826 return nullptr;
14827 }
14828 }
14829 case Stmt::ParenExprClass:
14830 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14831 case Stmt::ImplicitCastExprClass:
14832 // If the result of an implicit cast is an l-value, we care about
14833 // the sub-expression; otherwise, the result here doesn't matter.
14834 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14835 case Stmt::CXXUuidofExprClass:
14836 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14837 default:
14838 return nullptr;
14839 }
14840}
14841
14842namespace {
14843enum {
14844 AO_Bit_Field = 0,
14845 AO_Vector_Element = 1,
14846 AO_Property_Expansion = 2,
14847 AO_Register_Variable = 3,
14848 AO_Matrix_Element = 4,
14849 AO_No_Error = 5
14850};
14851}
14852/// Diagnose invalid operand for address of operations.
14853///
14854/// \param Type The type of operand which cannot have its address taken.
14856 Expr *E, unsigned Type) {
14857 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14858}
14859
14861 const Expr *Op,
14862 const CXXMethodDecl *MD) {
14863 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14864
14865 if (Op != DRE)
14866 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14867 << Op->getSourceRange();
14868
14869 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14870 if (isa<CXXDestructorDecl>(MD))
14871 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14872 << DRE->getSourceRange();
14873
14874 if (DRE->getQualifier())
14875 return false;
14876
14877 if (MD->getParent()->getName().empty())
14878 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14879 << DRE->getSourceRange();
14880
14881 SmallString<32> Str;
14882 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14883 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14884 << DRE->getSourceRange()
14885 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14886}
14887
14889 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14890 if (PTy->getKind() == BuiltinType::Overload) {
14891 Expr *E = OrigOp.get()->IgnoreParens();
14892 if (!isa<OverloadExpr>(E)) {
14893 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14894 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14895 << OrigOp.get()->getSourceRange();
14896 return QualType();
14897 }
14898
14902 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14903 << OrigOp.get()->getSourceRange();
14904 return QualType();
14905 }
14906
14907 return Context.OverloadTy;
14908 }
14909
14910 if (PTy->getKind() == BuiltinType::UnknownAny)
14911 return Context.UnknownAnyTy;
14912
14913 if (PTy->getKind() == BuiltinType::BoundMember) {
14914 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14915 << OrigOp.get()->getSourceRange();
14916 return QualType();
14917 }
14918
14919 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14920 if (OrigOp.isInvalid()) return QualType();
14921 }
14922
14923 if (OrigOp.get()->isTypeDependent())
14924 return Context.DependentTy;
14925
14926 assert(!OrigOp.get()->hasPlaceholderType());
14927
14928 // Make sure to ignore parentheses in subsequent checks
14929 Expr *op = OrigOp.get()->IgnoreParens();
14930
14931 // In OpenCL captures for blocks called as lambda functions
14932 // are located in the private address space. Blocks used in
14933 // enqueue_kernel can be located in a different address space
14934 // depending on a vendor implementation. Thus preventing
14935 // taking an address of the capture to avoid invalid AS casts.
14936 if (LangOpts.OpenCL) {
14937 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14938 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14939 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14940 return QualType();
14941 }
14942 }
14943
14944 if (getLangOpts().C99) {
14945 // Implement C99-only parts of addressof rules.
14946 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14947 if (uOp->getOpcode() == UO_Deref)
14948 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14949 // (assuming the deref expression is valid).
14950 return uOp->getSubExpr()->getType();
14951 }
14952 // Technically, there should be a check for array subscript
14953 // expressions here, but the result of one is always an lvalue anyway.
14954 }
14955 ValueDecl *dcl = getPrimaryDecl(op);
14956
14957 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14958 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14959 op->getBeginLoc()))
14960 return QualType();
14961
14963 unsigned AddressOfError = AO_No_Error;
14964
14965 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14966 bool IsError = isSFINAEContext();
14967 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14968 : diag::ext_typecheck_addrof_temporary)
14969 << op->getType() << op->getSourceRange();
14970 if (IsError)
14971 return QualType();
14972 // Materialize the temporary as an lvalue so that we can take its address.
14973 OrigOp = op =
14974 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14975 } else if (isa<ObjCSelectorExpr>(op)) {
14976 return Context.getPointerType(op->getType());
14977 } else if (lval == Expr::LV_MemberFunction) {
14978 // If it's an instance method, make a member pointer.
14979 // The expression must have exactly the form &A::foo.
14980
14981 // If the underlying expression isn't a decl ref, give up.
14982 if (!isa<DeclRefExpr>(op)) {
14983 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14984 << OrigOp.get()->getSourceRange();
14985 return QualType();
14986 }
14987 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14989
14990 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14991 QualType MPTy = Context.getMemberPointerType(
14992 op->getType(), DRE->getQualifier(), MD->getParent());
14993
14994 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14995 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14996 // When pointer authentication is enabled, argument and return types of
14997 // vitual member functions must be complete. This is because vitrual
14998 // member function pointers are implemented using virtual dispatch
14999 // thunks and the thunks cannot be emitted if the argument or return
15000 // types are incomplete.
15001 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15002 SourceLocation DeclRefLoc,
15003 SourceLocation RetArgTypeLoc) {
15004 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15005 Diag(DeclRefLoc,
15006 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15007 Diag(RetArgTypeLoc,
15008 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15009 << T;
15010 return true;
15011 }
15012 return false;
15013 };
15014 QualType RetTy = MD->getReturnType();
15015 bool IsIncomplete =
15016 !RetTy->isVoidType() &&
15017 ReturnOrParamTypeIsIncomplete(
15018 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15019 for (auto *PVD : MD->parameters())
15020 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15021 PVD->getBeginLoc());
15022 if (IsIncomplete)
15023 return QualType();
15024 }
15025
15026 // Under the MS ABI, lock down the inheritance model now.
15027 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15028 (void)isCompleteType(OpLoc, MPTy);
15029 return MPTy;
15030 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15031 // C99 6.5.3.2p1
15032 // The operand must be either an l-value or a function designator
15033 if (!op->getType()->isFunctionType()) {
15034 // Use a special diagnostic for loads from property references.
15035 if (isa<PseudoObjectExpr>(op)) {
15036 AddressOfError = AO_Property_Expansion;
15037 } else {
15038 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15039 << op->getType() << op->getSourceRange();
15040 return QualType();
15041 }
15042 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15043 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15044 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15045 }
15046
15047 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15048 // The operand cannot be a bit-field
15049 AddressOfError = AO_Bit_Field;
15050 } else if (op->getObjectKind() == OK_VectorComponent) {
15051 // The operand cannot be an element of a vector
15052 AddressOfError = AO_Vector_Element;
15053 } else if (op->getObjectKind() == OK_MatrixComponent) {
15054 // The operand cannot be an element of a matrix.
15055 AddressOfError = AO_Matrix_Element;
15056 } else if (dcl) { // C99 6.5.3.2p1
15057 // We have an lvalue with a decl. Make sure the decl is not declared
15058 // with the register storage-class specifier.
15059 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15060 // in C++ it is not error to take address of a register
15061 // variable (c++03 7.1.1P3)
15062 if (vd->getStorageClass() == SC_Register &&
15064 AddressOfError = AO_Register_Variable;
15065 }
15066 } else if (isa<MSPropertyDecl>(dcl)) {
15067 AddressOfError = AO_Property_Expansion;
15068 } else if (isa<FunctionTemplateDecl>(dcl)) {
15069 return Context.OverloadTy;
15070 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15071 // Okay: we can take the address of a field.
15072 // Could be a pointer to member, though, if there is an explicit
15073 // scope qualifier for the class.
15074
15075 // [C++26] [expr.prim.id.general]
15076 // If an id-expression E denotes a non-static non-type member
15077 // of some class C [...] and if E is a qualified-id, E is
15078 // not the un-parenthesized operand of the unary & operator [...]
15079 // the id-expression is transformed into a class member access expression.
15080 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15081 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15082 DeclContext *Ctx = dcl->getDeclContext();
15083 if (Ctx && Ctx->isRecord()) {
15084 if (dcl->getType()->isReferenceType()) {
15085 Diag(OpLoc,
15086 diag::err_cannot_form_pointer_to_member_of_reference_type)
15087 << dcl->getDeclName() << dcl->getType();
15088 return QualType();
15089 }
15090
15091 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15092 Ctx = Ctx->getParent();
15093
15094 QualType MPTy = Context.getMemberPointerType(
15095 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15096 // Under the MS ABI, lock down the inheritance model now.
15097 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15098 (void)isCompleteType(OpLoc, MPTy);
15099 return MPTy;
15100 }
15101 }
15105 llvm_unreachable("Unknown/unexpected decl type");
15106 }
15107
15108 if (AddressOfError != AO_No_Error) {
15109 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15110 return QualType();
15111 }
15112
15113 if (lval == Expr::LV_IncompleteVoidType) {
15114 // Taking the address of a void variable is technically illegal, but we
15115 // allow it in cases which are otherwise valid.
15116 // Example: "extern void x; void* y = &x;".
15117 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15118 }
15119
15120 // If the operand has type "type", the result has type "pointer to type".
15121 if (op->getType()->isObjCObjectType())
15122 return Context.getObjCObjectPointerType(op->getType());
15123
15124 // Cannot take the address of WebAssembly references or tables.
15125 if (Context.getTargetInfo().getTriple().isWasm()) {
15126 QualType OpTy = op->getType();
15127 if (OpTy.isWebAssemblyReferenceType()) {
15128 Diag(OpLoc, diag::err_wasm_ca_reference)
15129 << 1 << OrigOp.get()->getSourceRange();
15130 return QualType();
15131 }
15132 if (OpTy->isWebAssemblyTableType()) {
15133 Diag(OpLoc, diag::err_wasm_table_pr)
15134 << 1 << OrigOp.get()->getSourceRange();
15135 return QualType();
15136 }
15137 }
15138
15139 CheckAddressOfPackedMember(op);
15140
15141 return Context.getPointerType(op->getType());
15142}
15143
15144static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15145 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15146 if (!DRE)
15147 return;
15148 const Decl *D = DRE->getDecl();
15149 if (!D)
15150 return;
15151 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15152 if (!Param)
15153 return;
15154 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15155 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15156 return;
15157 if (FunctionScopeInfo *FD = S.getCurFunction())
15158 FD->ModifiedNonNullParams.insert(Param);
15159}
15160
15161/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15163 SourceLocation OpLoc,
15164 bool IsAfterAmp = false) {
15165 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15166 if (ConvResult.isInvalid())
15167 return QualType();
15168 Op = ConvResult.get();
15169 QualType OpTy = Op->getType();
15170 QualType Result;
15171
15173 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15174 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15175 Op->getSourceRange());
15176 }
15177
15178 if (const PointerType *PT = OpTy->getAs<PointerType>())
15179 {
15180 Result = PT->getPointeeType();
15181 }
15182 else if (const ObjCObjectPointerType *OPT =
15184 Result = OPT->getPointeeType();
15185 else {
15187 if (PR.isInvalid()) return QualType();
15188 if (PR.get() != Op)
15189 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15190 }
15191
15192 if (Result.isNull()) {
15193 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15194 << OpTy << Op->getSourceRange();
15195 return QualType();
15196 }
15197
15198 if (Result->isVoidType()) {
15199 // C++ [expr.unary.op]p1:
15200 // [...] the expression to which [the unary * operator] is applied shall
15201 // be a pointer to an object type, or a pointer to a function type
15202 LangOptions LO = S.getLangOpts();
15203 if (LO.CPlusPlus)
15204 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15205 << OpTy << Op->getSourceRange();
15206 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15207 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15208 << OpTy << Op->getSourceRange();
15209 }
15210
15211 // Dereferences are usually l-values...
15212 VK = VK_LValue;
15213
15214 // ...except that certain expressions are never l-values in C.
15215 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15216 VK = VK_PRValue;
15217
15218 return Result;
15219}
15220
15221BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15223 switch (Kind) {
15224 default: llvm_unreachable("Unknown binop!");
15225 case tok::periodstar: Opc = BO_PtrMemD; break;
15226 case tok::arrowstar: Opc = BO_PtrMemI; break;
15227 case tok::star: Opc = BO_Mul; break;
15228 case tok::slash: Opc = BO_Div; break;
15229 case tok::percent: Opc = BO_Rem; break;
15230 case tok::plus: Opc = BO_Add; break;
15231 case tok::minus: Opc = BO_Sub; break;
15232 case tok::lessless: Opc = BO_Shl; break;
15233 case tok::greatergreater: Opc = BO_Shr; break;
15234 case tok::lessequal: Opc = BO_LE; break;
15235 case tok::less: Opc = BO_LT; break;
15236 case tok::greaterequal: Opc = BO_GE; break;
15237 case tok::greater: Opc = BO_GT; break;
15238 case tok::exclaimequal: Opc = BO_NE; break;
15239 case tok::equalequal: Opc = BO_EQ; break;
15240 case tok::spaceship: Opc = BO_Cmp; break;
15241 case tok::amp: Opc = BO_And; break;
15242 case tok::caret: Opc = BO_Xor; break;
15243 case tok::pipe: Opc = BO_Or; break;
15244 case tok::ampamp: Opc = BO_LAnd; break;
15245 case tok::pipepipe: Opc = BO_LOr; break;
15246 case tok::equal: Opc = BO_Assign; break;
15247 case tok::starequal: Opc = BO_MulAssign; break;
15248 case tok::slashequal: Opc = BO_DivAssign; break;
15249 case tok::percentequal: Opc = BO_RemAssign; break;
15250 case tok::plusequal: Opc = BO_AddAssign; break;
15251 case tok::minusequal: Opc = BO_SubAssign; break;
15252 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15253 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15254 case tok::ampequal: Opc = BO_AndAssign; break;
15255 case tok::caretequal: Opc = BO_XorAssign; break;
15256 case tok::pipeequal: Opc = BO_OrAssign; break;
15257 case tok::comma: Opc = BO_Comma; break;
15258 }
15259 return Opc;
15260}
15261
15263 tok::TokenKind Kind) {
15265 switch (Kind) {
15266 default: llvm_unreachable("Unknown unary op!");
15267 case tok::plusplus: Opc = UO_PreInc; break;
15268 case tok::minusminus: Opc = UO_PreDec; break;
15269 case tok::amp: Opc = UO_AddrOf; break;
15270 case tok::star: Opc = UO_Deref; break;
15271 case tok::plus: Opc = UO_Plus; break;
15272 case tok::minus: Opc = UO_Minus; break;
15273 case tok::tilde: Opc = UO_Not; break;
15274 case tok::exclaim: Opc = UO_LNot; break;
15275 case tok::kw___real: Opc = UO_Real; break;
15276 case tok::kw___imag: Opc = UO_Imag; break;
15277 case tok::kw___extension__: Opc = UO_Extension; break;
15278 }
15279 return Opc;
15280}
15281
15282const FieldDecl *
15284 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15285 // common for setters.
15286 // struct A {
15287 // int X;
15288 // -void setX(int X) { X = X; }
15289 // +void setX(int X) { this->X = X; }
15290 // };
15291
15292 // Only consider parameters for self assignment fixes.
15293 if (!isa<ParmVarDecl>(SelfAssigned))
15294 return nullptr;
15295 const auto *Method =
15296 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15297 if (!Method)
15298 return nullptr;
15299
15300 const CXXRecordDecl *Parent = Method->getParent();
15301 // In theory this is fixable if the lambda explicitly captures this, but
15302 // that's added complexity that's rarely going to be used.
15303 if (Parent->isLambda())
15304 return nullptr;
15305
15306 // FIXME: Use an actual Lookup operation instead of just traversing fields
15307 // in order to get base class fields.
15308 auto Field =
15309 llvm::find_if(Parent->fields(),
15310 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15311 return F->getDeclName() == Name;
15312 });
15313 return (Field != Parent->field_end()) ? *Field : nullptr;
15314}
15315
15316/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15317/// This warning suppressed in the event of macro expansions.
15318static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15319 SourceLocation OpLoc, bool IsBuiltin) {
15321 return;
15322 if (S.isUnevaluatedContext())
15323 return;
15324 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15325 return;
15326 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15327 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15328 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15329 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15330 if (!LHSDeclRef || !RHSDeclRef ||
15331 LHSDeclRef->getLocation().isMacroID() ||
15332 RHSDeclRef->getLocation().isMacroID())
15333 return;
15334 const ValueDecl *LHSDecl =
15335 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15336 const ValueDecl *RHSDecl =
15337 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15338 if (LHSDecl != RHSDecl)
15339 return;
15340 if (LHSDecl->getType().isVolatileQualified())
15341 return;
15342 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15343 if (RefTy->getPointeeType().isVolatileQualified())
15344 return;
15345
15346 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15347 : diag::warn_self_assignment_overloaded)
15348 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15349 << RHSExpr->getSourceRange();
15350 if (const FieldDecl *SelfAssignField =
15352 Diag << 1 << SelfAssignField
15353 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15354 else
15355 Diag << 0;
15356}
15357
15358/// Check if a bitwise-& is performed on an Objective-C pointer. This
15359/// is usually indicative of introspection within the Objective-C pointer.
15361 SourceLocation OpLoc) {
15362 if (!S.getLangOpts().ObjC)
15363 return;
15364
15365 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15366 const Expr *LHS = L.get();
15367 const Expr *RHS = R.get();
15368
15370 ObjCPointerExpr = LHS;
15371 OtherExpr = RHS;
15372 }
15373 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15374 ObjCPointerExpr = RHS;
15375 OtherExpr = LHS;
15376 }
15377
15378 // This warning is deliberately made very specific to reduce false
15379 // positives with logic that uses '&' for hashing. This logic mainly
15380 // looks for code trying to introspect into tagged pointers, which
15381 // code should generally never do.
15382 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15383 unsigned Diag = diag::warn_objc_pointer_masking;
15384 // Determine if we are introspecting the result of performSelectorXXX.
15385 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15386 // Special case messages to -performSelector and friends, which
15387 // can return non-pointer values boxed in a pointer value.
15388 // Some clients may wish to silence warnings in this subcase.
15389 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15390 Selector S = ME->getSelector();
15391 StringRef SelArg0 = S.getNameForSlot(0);
15392 if (SelArg0.starts_with("performSelector"))
15393 Diag = diag::warn_objc_pointer_masking_performSelector;
15394 }
15395
15396 S.Diag(OpLoc, Diag)
15397 << ObjCPointerExpr->getSourceRange();
15398 }
15399}
15400
15401// This helper function promotes a binary operator's operands (which are of a
15402// half vector type) to a vector of floats and then truncates the result to
15403// a vector of either half or short.
15405 BinaryOperatorKind Opc, QualType ResultTy,
15407 bool IsCompAssign, SourceLocation OpLoc,
15408 FPOptionsOverride FPFeatures) {
15409 auto &Context = S.getASTContext();
15410 assert((isVector(ResultTy, Context.HalfTy) ||
15411 isVector(ResultTy, Context.ShortTy)) &&
15412 "Result must be a vector of half or short");
15413 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15414 isVector(RHS.get()->getType(), Context.HalfTy) &&
15415 "both operands expected to be a half vector");
15416
15417 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15418 QualType BinOpResTy = RHS.get()->getType();
15419
15420 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15421 // change BinOpResTy to a vector of ints.
15422 if (isVector(ResultTy, Context.ShortTy))
15423 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15424
15425 if (IsCompAssign)
15426 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15427 ResultTy, VK, OK, OpLoc, FPFeatures,
15428 BinOpResTy, BinOpResTy);
15429
15430 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15431 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15432 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15433 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15434}
15435
15436/// Returns true if conversion between vectors of halfs and vectors of floats
15437/// is needed.
15438static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15439 Expr *E0, Expr *E1 = nullptr) {
15440 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15442 return false;
15443
15444 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15445 QualType Ty = E->IgnoreImplicit()->getType();
15446
15447 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15448 // to vectors of floats. Although the element type of the vectors is __fp16,
15449 // the vectors shouldn't be treated as storage-only types. See the
15450 // discussion here: https://reviews.llvm.org/rG825235c140e7
15451 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15452 if (VT->getVectorKind() == VectorKind::Neon)
15453 return false;
15454 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15455 }
15456 return false;
15457 };
15458
15459 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15460}
15461
15463 BinaryOperatorKind Opc, Expr *LHSExpr,
15464 Expr *RHSExpr, bool ForFoldExpression) {
15465 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15466 // The syntax only allows initializer lists on the RHS of assignment,
15467 // so we don't need to worry about accepting invalid code for
15468 // non-assignment operators.
15469 // C++11 5.17p9:
15470 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15471 // of x = {} is x = T().
15473 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15474 InitializedEntity Entity =
15476 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15477 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15478 if (Init.isInvalid())
15479 return Init;
15480 RHSExpr = Init.get();
15481 }
15482
15483 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15484 QualType ResultTy; // Result type of the binary operator.
15485 // The following two variables are used for compound assignment operators
15486 QualType CompLHSTy; // Type of LHS after promotions for computation
15487 QualType CompResultTy; // Type of computation result
15490 bool ConvertHalfVec = false;
15491
15492 if (!LHS.isUsable() || !RHS.isUsable())
15493 return ExprError();
15494
15495 if (getLangOpts().OpenCL) {
15496 QualType LHSTy = LHSExpr->getType();
15497 QualType RHSTy = RHSExpr->getType();
15498 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15499 // the ATOMIC_VAR_INIT macro.
15500 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15501 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15502 if (BO_Assign == Opc)
15503 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15504 else
15505 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15506 return ExprError();
15507 }
15508
15509 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15510 // only with a builtin functions and therefore should be disallowed here.
15511 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15512 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15513 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15514 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15515 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15516 return ExprError();
15517 }
15518 }
15519
15520 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15521 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15522
15523 switch (Opc) {
15524 case BO_Assign:
15525 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15526 if (getLangOpts().CPlusPlus &&
15527 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15528 VK = LHS.get()->getValueKind();
15529 OK = LHS.get()->getObjectKind();
15530 }
15531 if (!ResultTy.isNull()) {
15532 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15533 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15534
15535 // Avoid copying a block to the heap if the block is assigned to a local
15536 // auto variable that is declared in the same scope as the block. This
15537 // optimization is unsafe if the local variable is declared in an outer
15538 // scope. For example:
15539 //
15540 // BlockTy b;
15541 // {
15542 // b = ^{...};
15543 // }
15544 // // It is unsafe to invoke the block here if it wasn't copied to the
15545 // // heap.
15546 // b();
15547
15548 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15549 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15550 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15551 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15552 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15553
15555 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15557 }
15558 RecordModifiableNonNullParam(*this, LHS.get());
15559 break;
15560 case BO_PtrMemD:
15561 case BO_PtrMemI:
15562 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15563 Opc == BO_PtrMemI);
15564 break;
15565 case BO_Mul:
15566 case BO_Div:
15567 ConvertHalfVec = true;
15568 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15569 break;
15570 case BO_Rem:
15571 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15572 break;
15573 case BO_Add:
15574 ConvertHalfVec = true;
15575 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15576 break;
15577 case BO_Sub:
15578 ConvertHalfVec = true;
15579 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15580 break;
15581 case BO_Shl:
15582 case BO_Shr:
15583 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15584 break;
15585 case BO_LE:
15586 case BO_LT:
15587 case BO_GE:
15588 case BO_GT:
15589 ConvertHalfVec = true;
15590 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15591
15592 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15593 !ForFoldExpression && BI && BI->isComparisonOp())
15594 Diag(OpLoc, diag::warn_consecutive_comparison)
15595 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15596
15597 break;
15598 case BO_EQ:
15599 case BO_NE:
15600 ConvertHalfVec = true;
15601 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15602 break;
15603 case BO_Cmp:
15604 ConvertHalfVec = true;
15605 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15606 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15607 break;
15608 case BO_And:
15609 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15610 [[fallthrough]];
15611 case BO_Xor:
15612 case BO_Or:
15613 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15614 break;
15615 case BO_LAnd:
15616 case BO_LOr:
15617 ConvertHalfVec = true;
15618 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15619 break;
15620 case BO_MulAssign:
15621 case BO_DivAssign:
15622 ConvertHalfVec = true;
15623 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15624 CompLHSTy = CompResultTy;
15625 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15626 ResultTy =
15627 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15628 break;
15629 case BO_RemAssign:
15630 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15631 CompLHSTy = CompResultTy;
15632 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15633 ResultTy =
15634 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15635 break;
15636 case BO_AddAssign:
15637 ConvertHalfVec = true;
15638 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15639 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15640 ResultTy =
15641 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15642 break;
15643 case BO_SubAssign:
15644 ConvertHalfVec = true;
15645 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15646 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15647 ResultTy =
15648 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15649 break;
15650 case BO_ShlAssign:
15651 case BO_ShrAssign:
15652 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15653 CompLHSTy = CompResultTy;
15654 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15655 ResultTy =
15656 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15657 break;
15658 case BO_AndAssign:
15659 case BO_OrAssign: // fallthrough
15660 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15661 [[fallthrough]];
15662 case BO_XorAssign:
15663 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15664 CompLHSTy = CompResultTy;
15665 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15666 ResultTy =
15667 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15668 break;
15669 case BO_Comma:
15670 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15671 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15672 VK = RHS.get()->getValueKind();
15673 OK = RHS.get()->getObjectKind();
15674 }
15675 break;
15676 }
15677 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15678 return ExprError();
15679
15680 // Some of the binary operations require promoting operands of half vector to
15681 // float vectors and truncating the result back to half vector. For now, we do
15682 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15683 // arm64).
15684 assert(
15685 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15686 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15687 "both sides are half vectors or neither sides are");
15688 ConvertHalfVec =
15689 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15690
15691 // Check for array bounds violations for both sides of the BinaryOperator
15692 CheckArrayAccess(LHS.get());
15693 CheckArrayAccess(RHS.get());
15694
15695 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15696 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15697 &Context.Idents.get("object_setClass"),
15699 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15700 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15701 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15703 "object_setClass(")
15704 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15705 ",")
15706 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15707 }
15708 else
15709 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15710 }
15711 else if (const ObjCIvarRefExpr *OIRE =
15712 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15713 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15714
15715 // Opc is not a compound assignment if CompResultTy is null.
15716 if (CompResultTy.isNull()) {
15717 if (ConvertHalfVec)
15718 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15719 OpLoc, CurFPFeatureOverrides());
15720 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15721 VK, OK, OpLoc, CurFPFeatureOverrides());
15722 }
15723
15724 // Handle compound assignments.
15725 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15727 VK = VK_LValue;
15728 OK = LHS.get()->getObjectKind();
15729 }
15730
15731 // The LHS is not converted to the result type for fixed-point compound
15732 // assignment as the common type is computed on demand. Reset the CompLHSTy
15733 // to the LHS type we would have gotten after unary conversions.
15734 if (CompResultTy->isFixedPointType())
15735 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15736
15737 if (ConvertHalfVec)
15738 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15739 OpLoc, CurFPFeatureOverrides());
15740
15742 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15743 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15744}
15745
15746/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15747/// operators are mixed in a way that suggests that the programmer forgot that
15748/// comparison operators have higher precedence. The most typical example of
15749/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15751 SourceLocation OpLoc, Expr *LHSExpr,
15752 Expr *RHSExpr) {
15753 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15754 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15755
15756 // Check that one of the sides is a comparison operator and the other isn't.
15757 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15758 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15759 if (isLeftComp == isRightComp)
15760 return;
15761
15762 // Bitwise operations are sometimes used as eager logical ops.
15763 // Don't diagnose this.
15764 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15765 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15766 if (isLeftBitwise || isRightBitwise)
15767 return;
15768
15769 SourceRange DiagRange = isLeftComp
15770 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15771 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15772 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15773 SourceRange ParensRange =
15774 isLeftComp
15775 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15776 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15777
15778 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15779 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15780 SuggestParentheses(Self, OpLoc,
15781 Self.PDiag(diag::note_precedence_silence) << OpStr,
15782 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15783 SuggestParentheses(Self, OpLoc,
15784 Self.PDiag(diag::note_precedence_bitwise_first)
15786 ParensRange);
15787}
15788
15789/// It accepts a '&&' expr that is inside a '||' one.
15790/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15791/// in parentheses.
15792static void
15794 BinaryOperator *Bop) {
15795 assert(Bop->getOpcode() == BO_LAnd);
15796 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15797 << Bop->getSourceRange() << OpLoc;
15799 Self.PDiag(diag::note_precedence_silence)
15800 << Bop->getOpcodeStr(),
15801 Bop->getSourceRange());
15802}
15803
15804/// Look for '&&' in the left hand of a '||' expr.
15806 Expr *LHSExpr, Expr *RHSExpr) {
15807 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15808 if (Bop->getOpcode() == BO_LAnd) {
15809 // If it's "string_literal && a || b" don't warn since the precedence
15810 // doesn't matter.
15811 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15812 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15813 } else if (Bop->getOpcode() == BO_LOr) {
15814 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15815 // If it's "a || b && string_literal || c" we didn't warn earlier for
15816 // "a || b && string_literal", but warn now.
15817 if (RBop->getOpcode() == BO_LAnd &&
15818 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15819 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15820 }
15821 }
15822 }
15823}
15824
15825/// Look for '&&' in the right hand of a '||' expr.
15827 Expr *LHSExpr, Expr *RHSExpr) {
15828 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15829 if (Bop->getOpcode() == BO_LAnd) {
15830 // If it's "a || b && string_literal" don't warn since the precedence
15831 // doesn't matter.
15832 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15833 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15834 }
15835 }
15836}
15837
15838/// Look for bitwise op in the left or right hand of a bitwise op with
15839/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15840/// the '&' expression in parentheses.
15842 SourceLocation OpLoc, Expr *SubExpr) {
15843 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15844 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15845 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15846 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15847 << Bop->getSourceRange() << OpLoc;
15848 SuggestParentheses(S, Bop->getOperatorLoc(),
15849 S.PDiag(diag::note_precedence_silence)
15850 << Bop->getOpcodeStr(),
15851 Bop->getSourceRange());
15852 }
15853 }
15854}
15855
15857 Expr *SubExpr, StringRef Shift) {
15858 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15859 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15860 StringRef Op = Bop->getOpcodeStr();
15861 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15862 << Bop->getSourceRange() << OpLoc << Shift << Op;
15863 SuggestParentheses(S, Bop->getOperatorLoc(),
15864 S.PDiag(diag::note_precedence_silence) << Op,
15865 Bop->getSourceRange());
15866 }
15867 }
15868}
15869
15871 Expr *LHSExpr, Expr *RHSExpr) {
15872 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15873 if (!OCE)
15874 return;
15875
15876 FunctionDecl *FD = OCE->getDirectCallee();
15877 if (!FD || !FD->isOverloadedOperator())
15878 return;
15879
15881 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15882 return;
15883
15884 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15885 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15886 << (Kind == OO_LessLess);
15888 S.PDiag(diag::note_precedence_silence)
15889 << (Kind == OO_LessLess ? "<<" : ">>"),
15890 OCE->getSourceRange());
15892 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15893 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15894}
15895
15896/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15897/// precedence.
15899 SourceLocation OpLoc, Expr *LHSExpr,
15900 Expr *RHSExpr){
15901 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15903 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15904
15905 // Diagnose "arg1 & arg2 | arg3"
15906 if ((Opc == BO_Or || Opc == BO_Xor) &&
15907 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15908 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15909 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15910 }
15911
15912 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15913 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15914 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15915 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15916 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15917 }
15918
15919 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15920 || Opc == BO_Shr) {
15921 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15922 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15923 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15924 }
15925
15926 // Warn on overloaded shift operators and comparisons, such as:
15927 // cout << 5 == 4;
15929 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15930}
15931
15933 tok::TokenKind Kind,
15934 Expr *LHSExpr, Expr *RHSExpr) {
15935 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15936 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15937 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15938
15939 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15940 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15941
15945
15946 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15947 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15948
15949 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15950}
15951
15953 UnresolvedSetImpl &Functions) {
15955 if (OverOp != OO_None && OverOp != OO_Equal)
15956 LookupOverloadedOperatorName(OverOp, S, Functions);
15957
15958 // In C++20 onwards, we may have a second operator to look up.
15959 if (getLangOpts().CPlusPlus20) {
15961 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15962 }
15963}
15964
15965/// Build an overloaded binary operator expression in the given scope.
15968 Expr *LHS, Expr *RHS) {
15969 switch (Opc) {
15970 case BO_Assign:
15971 // In the non-overloaded case, we warn about self-assignment (x = x) for
15972 // both simple assignment and certain compound assignments where algebra
15973 // tells us the operation yields a constant result. When the operator is
15974 // overloaded, we can't do the latter because we don't want to assume that
15975 // those algebraic identities still apply; for example, a path-building
15976 // library might use operator/= to append paths. But it's still reasonable
15977 // to assume that simple assignment is just moving/copying values around
15978 // and so self-assignment is likely a bug.
15979 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15980 [[fallthrough]];
15981 case BO_DivAssign:
15982 case BO_RemAssign:
15983 case BO_SubAssign:
15984 case BO_AndAssign:
15985 case BO_OrAssign:
15986 case BO_XorAssign:
15987 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15988 break;
15989 default:
15990 break;
15991 }
15992
15993 // Find all of the overloaded operators visible from this point.
15994 UnresolvedSet<16> Functions;
15995 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15996
15997 // Build the (potentially-overloaded, potentially-dependent)
15998 // binary operation.
15999 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16000}
16001
16003 BinaryOperatorKind Opc, Expr *LHSExpr,
16004 Expr *RHSExpr, bool ForFoldExpression) {
16005 if (!LHSExpr || !RHSExpr)
16006 return ExprError();
16007
16008 // We want to end up calling one of SemaPseudoObject::checkAssignment
16009 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16010 // both expressions are overloadable or either is type-dependent),
16011 // or CreateBuiltinBinOp (in any other case). We also want to get
16012 // any placeholder types out of the way.
16013
16014 // Handle pseudo-objects in the LHS.
16015 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16016 // Assignments with a pseudo-object l-value need special analysis.
16017 if (pty->getKind() == BuiltinType::PseudoObject &&
16019 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16020
16021 // Don't resolve overloads if the other type is overloadable.
16022 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16023 // We can't actually test that if we still have a placeholder,
16024 // though. Fortunately, none of the exceptions we see in that
16025 // code below are valid when the LHS is an overload set. Note
16026 // that an overload set can be dependently-typed, but it never
16027 // instantiates to having an overloadable type.
16028 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16029 if (resolvedRHS.isInvalid()) return ExprError();
16030 RHSExpr = resolvedRHS.get();
16031
16032 if (RHSExpr->isTypeDependent() ||
16033 RHSExpr->getType()->isOverloadableType())
16034 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16035 }
16036
16037 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16038 // template, diagnose the missing 'template' keyword instead of diagnosing
16039 // an invalid use of a bound member function.
16040 //
16041 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16042 // to C++1z [over.over]/1.4, but we already checked for that case above.
16043 if (Opc == BO_LT && inTemplateInstantiation() &&
16044 (pty->getKind() == BuiltinType::BoundMember ||
16045 pty->getKind() == BuiltinType::Overload)) {
16046 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16047 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16048 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16049 return isa<FunctionTemplateDecl>(ND);
16050 })) {
16051 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16052 : OE->getNameLoc(),
16053 diag::err_template_kw_missing)
16054 << OE->getName().getAsIdentifierInfo();
16055 return ExprError();
16056 }
16057 }
16058
16059 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16060 if (LHS.isInvalid()) return ExprError();
16061 LHSExpr = LHS.get();
16062 }
16063
16064 // Handle pseudo-objects in the RHS.
16065 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16066 // An overload in the RHS can potentially be resolved by the type
16067 // being assigned to.
16068 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16069 if (getLangOpts().CPlusPlus &&
16070 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16071 LHSExpr->getType()->isOverloadableType()))
16072 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16073
16074 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16075 ForFoldExpression);
16076 }
16077
16078 // Don't resolve overloads if the other type is overloadable.
16079 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16080 LHSExpr->getType()->isOverloadableType())
16081 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16082
16083 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16084 if (!resolvedRHS.isUsable()) return ExprError();
16085 RHSExpr = resolvedRHS.get();
16086 }
16087
16088 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16089 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16090 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16091 return ExprError();
16092 }
16093
16094 if (getLangOpts().CPlusPlus) {
16095 // Otherwise, build an overloaded op if either expression is type-dependent
16096 // or has an overloadable type.
16097 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16098 LHSExpr->getType()->isOverloadableType() ||
16099 RHSExpr->getType()->isOverloadableType())
16100 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16101 }
16102
16103 if (getLangOpts().RecoveryAST &&
16104 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16105 assert(!getLangOpts().CPlusPlus);
16106 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16107 "Should only occur in error-recovery path.");
16109 // C [6.15.16] p3:
16110 // An assignment expression has the value of the left operand after the
16111 // assignment, but is not an lvalue.
16113 Context, LHSExpr, RHSExpr, Opc,
16115 OpLoc, CurFPFeatureOverrides());
16116 QualType ResultType;
16117 switch (Opc) {
16118 case BO_Assign:
16119 ResultType = LHSExpr->getType().getUnqualifiedType();
16120 break;
16121 case BO_LT:
16122 case BO_GT:
16123 case BO_LE:
16124 case BO_GE:
16125 case BO_EQ:
16126 case BO_NE:
16127 case BO_LAnd:
16128 case BO_LOr:
16129 // These operators have a fixed result type regardless of operands.
16130 ResultType = Context.IntTy;
16131 break;
16132 case BO_Comma:
16133 ResultType = RHSExpr->getType();
16134 break;
16135 default:
16136 ResultType = Context.DependentTy;
16137 break;
16138 }
16139 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16140 VK_PRValue, OK_Ordinary, OpLoc,
16142 }
16143
16144 // Build a built-in binary operation.
16145 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16146}
16147
16149 if (T.isNull() || T->isDependentType())
16150 return false;
16151
16152 if (!Ctx.isPromotableIntegerType(T))
16153 return true;
16154
16155 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16156}
16157
16159 UnaryOperatorKind Opc, Expr *InputExpr,
16160 bool IsAfterAmp) {
16161 ExprResult Input = InputExpr;
16164 QualType resultType;
16165 bool CanOverflow = false;
16166
16167 bool ConvertHalfVec = false;
16168 if (getLangOpts().OpenCL) {
16169 QualType Ty = InputExpr->getType();
16170 // The only legal unary operation for atomics is '&'.
16171 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16172 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16173 // only with a builtin functions and therefore should be disallowed here.
16174 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16175 || Ty->isBlockPointerType())) {
16176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16177 << InputExpr->getType()
16178 << Input.get()->getSourceRange());
16179 }
16180 }
16181
16182 if (getLangOpts().HLSL && OpLoc.isValid()) {
16183 if (Opc == UO_AddrOf)
16184 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16185 if (Opc == UO_Deref)
16186 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16187 }
16188
16189 if (InputExpr->isTypeDependent() &&
16190 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16191 resultType = Context.DependentTy;
16192 } else {
16193 switch (Opc) {
16194 case UO_PreInc:
16195 case UO_PreDec:
16196 case UO_PostInc:
16197 case UO_PostDec:
16198 resultType =
16199 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16200 Opc == UO_PreInc || Opc == UO_PostInc,
16201 Opc == UO_PreInc || Opc == UO_PreDec);
16202 CanOverflow = isOverflowingIntegerType(Context, resultType);
16203 break;
16204 case UO_AddrOf:
16205 resultType = CheckAddressOfOperand(Input, OpLoc);
16206 CheckAddressOfNoDeref(InputExpr);
16207 RecordModifiableNonNullParam(*this, InputExpr);
16208 break;
16209 case UO_Deref: {
16211 if (Input.isInvalid())
16212 return ExprError();
16213 resultType =
16214 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16215 break;
16216 }
16217 case UO_Plus:
16218 case UO_Minus:
16219 CanOverflow = Opc == UO_Minus &&
16221 Input = UsualUnaryConversions(Input.get());
16222 if (Input.isInvalid())
16223 return ExprError();
16224 // Unary plus and minus require promoting an operand of half vector to a
16225 // float vector and truncating the result back to a half vector. For now,
16226 // we do this only when HalfArgsAndReturns is set (that is, when the
16227 // target is arm or arm64).
16228 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16229
16230 // If the operand is a half vector, promote it to a float vector.
16231 if (ConvertHalfVec)
16232 Input = convertVector(Input.get(), Context.FloatTy, *this);
16233 resultType = Input.get()->getType();
16234 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16235 break;
16236 else if (resultType->isVectorType() &&
16237 // The z vector extensions don't allow + or - with bool vectors.
16238 (!Context.getLangOpts().ZVector ||
16239 resultType->castAs<VectorType>()->getVectorKind() !=
16241 break;
16242 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16243 break;
16244 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16245 Opc == UO_Plus && resultType->isPointerType())
16246 break;
16247
16248 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16249 << resultType << Input.get()->getSourceRange());
16250
16251 case UO_Not: // bitwise complement
16252 Input = UsualUnaryConversions(Input.get());
16253 if (Input.isInvalid())
16254 return ExprError();
16255 resultType = Input.get()->getType();
16256 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16257 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16258 // C99 does not support '~' for complex conjugation.
16259 Diag(OpLoc, diag::ext_integer_complement_complex)
16260 << resultType << Input.get()->getSourceRange();
16261 else if (resultType->hasIntegerRepresentation())
16262 break;
16263 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16264 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16265 // on vector float types.
16266 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16267 if (!T->isIntegerType())
16268 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16269 << resultType << Input.get()->getSourceRange());
16270 } else {
16271 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16272 << resultType << Input.get()->getSourceRange());
16273 }
16274 break;
16275
16276 case UO_LNot: // logical negation
16277 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16279 if (Input.isInvalid())
16280 return ExprError();
16281 resultType = Input.get()->getType();
16282
16283 // Though we still have to promote half FP to float...
16284 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16285 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16286 .get();
16287 resultType = Context.FloatTy;
16288 }
16289
16290 // WebAsembly tables can't be used in unary expressions.
16291 if (resultType->isPointerType() &&
16293 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16294 << resultType << Input.get()->getSourceRange());
16295 }
16296
16297 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16298 // C99 6.5.3.3p1: ok, fallthrough;
16299 if (Context.getLangOpts().CPlusPlus) {
16300 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16301 // operand contextually converted to bool.
16302 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16303 ScalarTypeToBooleanCastKind(resultType));
16304 } else if (Context.getLangOpts().OpenCL &&
16305 Context.getLangOpts().OpenCLVersion < 120) {
16306 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16307 // operate on scalar float types.
16308 if (!resultType->isIntegerType() && !resultType->isPointerType())
16309 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16310 << resultType << Input.get()->getSourceRange());
16311 }
16312 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16313 !resultType->hasBooleanRepresentation()) {
16314 // HLSL unary logical 'not' behaves like C++, which states that the
16315 // operand is converted to bool and the result is bool, however HLSL
16316 // extends this property to vectors.
16317 const VectorType *VTy = resultType->castAs<VectorType>();
16318 resultType =
16319 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16320
16321 Input = ImpCastExprToType(
16322 Input.get(), resultType,
16324 .get();
16325 break;
16326 } else if (resultType->isExtVectorType()) {
16327 if (Context.getLangOpts().OpenCL &&
16328 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16329 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16330 // operate on vector float types.
16331 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16332 if (!T->isIntegerType())
16333 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16334 << resultType << Input.get()->getSourceRange());
16335 }
16336 // Vector logical not returns the signed variant of the operand type.
16337 resultType = GetSignedVectorType(resultType);
16338 break;
16339 } else if (Context.getLangOpts().CPlusPlus &&
16340 resultType->isVectorType()) {
16341 const VectorType *VTy = resultType->castAs<VectorType>();
16342 if (VTy->getVectorKind() != VectorKind::Generic)
16343 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16344 << resultType << Input.get()->getSourceRange());
16345
16346 // Vector logical not returns the signed variant of the operand type.
16347 resultType = GetSignedVectorType(resultType);
16348 break;
16349 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16350 resultType = Context.getLogicalOperationType();
16351 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16352 break;
16353 } else {
16354 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16355 << resultType << Input.get()->getSourceRange());
16356 }
16357
16358 // LNot always has type int. C99 6.5.3.3p5.
16359 // In C++, it's bool. C++ 5.3.1p8
16360 resultType = Context.getLogicalOperationType();
16361 break;
16362 case UO_Real:
16363 case UO_Imag:
16364 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16365 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16366 // ordinary complex l-values to ordinary l-values and all other values to
16367 // r-values.
16368 if (Input.isInvalid())
16369 return ExprError();
16370 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16371 if (Input.get()->isGLValue() &&
16372 Input.get()->getObjectKind() == OK_Ordinary)
16373 VK = Input.get()->getValueKind();
16374 } else if (!getLangOpts().CPlusPlus) {
16375 // In C, a volatile scalar is read by __imag. In C++, it is not.
16376 Input = DefaultLvalueConversion(Input.get());
16377 }
16378 break;
16379 case UO_Extension:
16380 resultType = Input.get()->getType();
16381 VK = Input.get()->getValueKind();
16382 OK = Input.get()->getObjectKind();
16383 break;
16384 case UO_Coawait:
16385 // It's unnecessary to represent the pass-through operator co_await in the
16386 // AST; just return the input expression instead.
16387 assert(!Input.get()->getType()->isDependentType() &&
16388 "the co_await expression must be non-dependant before "
16389 "building operator co_await");
16390 return Input;
16391 }
16392 }
16393 if (resultType.isNull() || Input.isInvalid())
16394 return ExprError();
16395
16396 // Check for array bounds violations in the operand of the UnaryOperator,
16397 // except for the '*' and '&' operators that have to be handled specially
16398 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16399 // that are explicitly defined as valid by the standard).
16400 if (Opc != UO_AddrOf && Opc != UO_Deref)
16401 CheckArrayAccess(Input.get());
16402
16403 auto *UO =
16404 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16405 OpLoc, CanOverflow, CurFPFeatureOverrides());
16406
16407 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16408 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16410 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16411
16412 // Convert the result back to a half vector.
16413 if (ConvertHalfVec)
16414 return convertVector(UO, Context.HalfTy, *this);
16415 return UO;
16416}
16417
16419 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16420 if (!DRE->getQualifier())
16421 return false;
16422
16423 ValueDecl *VD = DRE->getDecl();
16424 if (!VD->isCXXClassMember())
16425 return false;
16426
16428 return true;
16429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16430 return Method->isImplicitObjectMemberFunction();
16431
16432 return false;
16433 }
16434
16435 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16436 if (!ULE->getQualifier())
16437 return false;
16438
16439 for (NamedDecl *D : ULE->decls()) {
16440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16441 if (Method->isImplicitObjectMemberFunction())
16442 return true;
16443 } else {
16444 // Overload set does not contain methods.
16445 break;
16446 }
16447 }
16448
16449 return false;
16450 }
16451
16452 return false;
16453}
16454
16456 UnaryOperatorKind Opc, Expr *Input,
16457 bool IsAfterAmp) {
16458 // First things first: handle placeholders so that the
16459 // overloaded-operator check considers the right type.
16460 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16461 // Increment and decrement of pseudo-object references.
16462 if (pty->getKind() == BuiltinType::PseudoObject &&
16464 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16465
16466 // extension is always a builtin operator.
16467 if (Opc == UO_Extension)
16468 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16469
16470 // & gets special logic for several kinds of placeholder.
16471 // The builtin code knows what to do.
16472 if (Opc == UO_AddrOf &&
16473 (pty->getKind() == BuiltinType::Overload ||
16474 pty->getKind() == BuiltinType::UnknownAny ||
16475 pty->getKind() == BuiltinType::BoundMember))
16476 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16477
16478 // Anything else needs to be handled now.
16480 if (Result.isInvalid()) return ExprError();
16481 Input = Result.get();
16482 }
16483
16484 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16486 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16487 // Find all of the overloaded operators visible from this point.
16488 UnresolvedSet<16> Functions;
16490 if (S && OverOp != OO_None)
16491 LookupOverloadedOperatorName(OverOp, S, Functions);
16492
16493 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16494 }
16495
16496 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16497}
16498
16500 Expr *Input, bool IsAfterAmp) {
16501 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16502 IsAfterAmp);
16503}
16504
16506 LabelDecl *TheDecl) {
16507 TheDecl->markUsed(Context);
16508 // Create the AST node. The address of a label always has type 'void*'.
16509 auto *Res = new (Context) AddrLabelExpr(
16510 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16511
16512 if (getCurFunction())
16513 getCurFunction()->AddrLabels.push_back(Res);
16514
16515 return Res;
16516}
16517
16520 // Make sure we diagnose jumping into a statement expression.
16522}
16523
16525 // Note that function is also called by TreeTransform when leaving a
16526 // StmtExpr scope without rebuilding anything.
16527
16530}
16531
16533 SourceLocation RPLoc) {
16534 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16535}
16536
16538 SourceLocation RPLoc, unsigned TemplateDepth) {
16539 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16540 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16541
16544 assert(!Cleanup.exprNeedsCleanups() &&
16545 "cleanups within StmtExpr not correctly bound!");
16547
16548 // FIXME: there are a variety of strange constraints to enforce here, for
16549 // example, it is not possible to goto into a stmt expression apparently.
16550 // More semantic analysis is needed.
16551
16552 // If there are sub-stmts in the compound stmt, take the type of the last one
16553 // as the type of the stmtexpr.
16554 QualType Ty = Context.VoidTy;
16555 bool StmtExprMayBindToTemp = false;
16556 if (!Compound->body_empty()) {
16557 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16558 if (const Expr *Value = LastStmt->getExprStmt()) {
16559 StmtExprMayBindToTemp = true;
16560 Ty = Value->getType();
16561 }
16562 }
16563 }
16564
16565 // FIXME: Check that expression type is complete/non-abstract; statement
16566 // expressions are not lvalues.
16567 Expr *ResStmtExpr =
16568 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16569 if (StmtExprMayBindToTemp)
16570 return MaybeBindToTemporary(ResStmtExpr);
16571 return ResStmtExpr;
16572}
16573
16575 if (ER.isInvalid())
16576 return ExprError();
16577
16578 // Do function/array conversion on the last expression, but not
16579 // lvalue-to-rvalue. However, initialize an unqualified type.
16581 if (ER.isInvalid())
16582 return ExprError();
16583 Expr *E = ER.get();
16584
16585 if (E->isTypeDependent())
16586 return E;
16587
16588 // In ARC, if the final expression ends in a consume, splice
16589 // the consume out and bind it later. In the alternate case
16590 // (when dealing with a retainable type), the result
16591 // initialization will create a produce. In both cases the
16592 // result will be +1, and we'll need to balance that out with
16593 // a bind.
16594 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16595 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16596 return Cast->getSubExpr();
16597
16598 // FIXME: Provide a better location for the initialization.
16602 SourceLocation(), E);
16603}
16604
16606 TypeSourceInfo *TInfo,
16607 ArrayRef<OffsetOfComponent> Components,
16608 SourceLocation RParenLoc) {
16609 QualType ArgTy = TInfo->getType();
16610 bool Dependent = ArgTy->isDependentType();
16611 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16612
16613 // We must have at least one component that refers to the type, and the first
16614 // one is known to be a field designator. Verify that the ArgTy represents
16615 // a struct/union/class.
16616 if (!Dependent && !ArgTy->isRecordType())
16617 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16618 << ArgTy << TypeRange);
16619
16620 // Type must be complete per C99 7.17p3 because a declaring a variable
16621 // with an incomplete type would be ill-formed.
16622 if (!Dependent
16623 && RequireCompleteType(BuiltinLoc, ArgTy,
16624 diag::err_offsetof_incomplete_type, TypeRange))
16625 return ExprError();
16626
16627 bool DidWarnAboutNonPOD = false;
16628 QualType CurrentType = ArgTy;
16631 for (const OffsetOfComponent &OC : Components) {
16632 if (OC.isBrackets) {
16633 // Offset of an array sub-field. TODO: Should we allow vector elements?
16634 if (!CurrentType->isDependentType()) {
16635 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16636 if(!AT)
16637 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16638 << CurrentType);
16639 CurrentType = AT->getElementType();
16640 } else
16641 CurrentType = Context.DependentTy;
16642
16643 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16644 if (IdxRval.isInvalid())
16645 return ExprError();
16646 Expr *Idx = IdxRval.get();
16647
16648 // The expression must be an integral expression.
16649 // FIXME: An integral constant expression?
16650 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16651 !Idx->getType()->isIntegerType())
16652 return ExprError(
16653 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16654 << Idx->getSourceRange());
16655
16656 // Record this array index.
16657 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16658 Exprs.push_back(Idx);
16659 continue;
16660 }
16661
16662 // Offset of a field.
16663 if (CurrentType->isDependentType()) {
16664 // We have the offset of a field, but we can't look into the dependent
16665 // type. Just record the identifier of the field.
16666 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16667 CurrentType = Context.DependentTy;
16668 continue;
16669 }
16670
16671 // We need to have a complete type to look into.
16672 if (RequireCompleteType(OC.LocStart, CurrentType,
16673 diag::err_offsetof_incomplete_type))
16674 return ExprError();
16675
16676 // Look for the designated field.
16677 auto *RD = CurrentType->getAsRecordDecl();
16678 if (!RD)
16679 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16680 << CurrentType);
16681
16682 // C++ [lib.support.types]p5:
16683 // The macro offsetof accepts a restricted set of type arguments in this
16684 // International Standard. type shall be a POD structure or a POD union
16685 // (clause 9).
16686 // C++11 [support.types]p4:
16687 // If type is not a standard-layout class (Clause 9), the results are
16688 // undefined.
16689 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16690 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16691 unsigned DiagID =
16692 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16693 : diag::ext_offsetof_non_pod_type;
16694
16695 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16696 Diag(BuiltinLoc, DiagID)
16697 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16698 DidWarnAboutNonPOD = true;
16699 }
16700 }
16701
16702 // Look for the field.
16703 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16704 LookupQualifiedName(R, RD);
16705 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16706 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16707 if (!MemberDecl) {
16708 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16709 MemberDecl = IndirectMemberDecl->getAnonField();
16710 }
16711
16712 if (!MemberDecl) {
16713 // Lookup could be ambiguous when looking up a placeholder variable
16714 // __builtin_offsetof(S, _).
16715 // In that case we would already have emitted a diagnostic
16716 if (!R.isAmbiguous())
16717 Diag(BuiltinLoc, diag::err_no_member)
16718 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16719 return ExprError();
16720 }
16721
16722 // C99 7.17p3:
16723 // (If the specified member is a bit-field, the behavior is undefined.)
16724 //
16725 // We diagnose this as an error.
16726 if (MemberDecl->isBitField()) {
16727 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16728 << MemberDecl->getDeclName()
16729 << SourceRange(BuiltinLoc, RParenLoc);
16730 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16731 return ExprError();
16732 }
16733
16734 RecordDecl *Parent = MemberDecl->getParent();
16735 if (IndirectMemberDecl)
16736 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16737
16738 // If the member was found in a base class, introduce OffsetOfNodes for
16739 // the base class indirections.
16740 CXXBasePaths Paths;
16741 if (IsDerivedFrom(OC.LocStart, CurrentType,
16742 Context.getCanonicalTagType(Parent), Paths)) {
16743 if (Paths.getDetectedVirtual()) {
16744 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16745 << MemberDecl->getDeclName()
16746 << SourceRange(BuiltinLoc, RParenLoc);
16747 return ExprError();
16748 }
16749
16750 CXXBasePath &Path = Paths.front();
16751 for (const CXXBasePathElement &B : Path)
16752 Comps.push_back(OffsetOfNode(B.Base));
16753 }
16754
16755 if (IndirectMemberDecl) {
16756 for (auto *FI : IndirectMemberDecl->chain()) {
16757 assert(isa<FieldDecl>(FI));
16758 Comps.push_back(OffsetOfNode(OC.LocStart,
16759 cast<FieldDecl>(FI), OC.LocEnd));
16760 }
16761 } else
16762 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16763
16764 CurrentType = MemberDecl->getType().getNonReferenceType();
16765 }
16766
16767 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16768 Comps, Exprs, RParenLoc);
16769}
16770
16772 SourceLocation BuiltinLoc,
16774 ParsedType ParsedArgTy,
16775 ArrayRef<OffsetOfComponent> Components,
16776 SourceLocation RParenLoc) {
16777
16778 TypeSourceInfo *ArgTInfo;
16779 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16780 if (ArgTy.isNull())
16781 return ExprError();
16782
16783 if (!ArgTInfo)
16784 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16785
16786 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16787}
16788
16789
16791 Expr *CondExpr,
16792 Expr *LHSExpr, Expr *RHSExpr,
16793 SourceLocation RPLoc) {
16794 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16795
16798 QualType resType;
16799 bool CondIsTrue = false;
16800 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16801 resType = Context.DependentTy;
16802 } else {
16803 // The conditional expression is required to be a constant expression.
16804 llvm::APSInt condEval(32);
16806 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16807 if (CondICE.isInvalid())
16808 return ExprError();
16809 CondExpr = CondICE.get();
16810 CondIsTrue = condEval.getZExtValue();
16811
16812 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16813 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16814
16815 resType = ActiveExpr->getType();
16816 VK = ActiveExpr->getValueKind();
16817 OK = ActiveExpr->getObjectKind();
16818 }
16819
16820 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16821 resType, VK, OK, RPLoc, CondIsTrue);
16822}
16823
16824//===----------------------------------------------------------------------===//
16825// Clang Extensions.
16826//===----------------------------------------------------------------------===//
16827
16828void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16830
16831 if (LangOpts.CPlusPlus) {
16833 Decl *ManglingContextDecl;
16834 std::tie(MCtx, ManglingContextDecl) =
16835 getCurrentMangleNumberContext(Block->getDeclContext());
16836 if (MCtx) {
16837 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16838 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16839 }
16840 }
16841
16842 PushBlockScope(CurScope, Block);
16843 CurContext->addDecl(Block);
16844 if (CurScope)
16845 PushDeclContext(CurScope, Block);
16846 else
16847 CurContext = Block;
16848
16850
16851 // Enter a new evaluation context to insulate the block from any
16852 // cleanups from the enclosing full-expression.
16855}
16856
16858 Scope *CurScope) {
16859 assert(ParamInfo.getIdentifier() == nullptr &&
16860 "block-id should have no identifier!");
16861 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16862 BlockScopeInfo *CurBlock = getCurBlock();
16863
16864 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16865 QualType T = Sig->getType();
16867
16868 // GetTypeForDeclarator always produces a function type for a block
16869 // literal signature. Furthermore, it is always a FunctionProtoType
16870 // unless the function was written with a typedef.
16871 assert(T->isFunctionType() &&
16872 "GetTypeForDeclarator made a non-function block signature");
16873
16874 // Look for an explicit signature in that function type.
16875 FunctionProtoTypeLoc ExplicitSignature;
16876
16877 if ((ExplicitSignature = Sig->getTypeLoc()
16879
16880 // Check whether that explicit signature was synthesized by
16881 // GetTypeForDeclarator. If so, don't save that as part of the
16882 // written signature.
16883 if (ExplicitSignature.getLocalRangeBegin() ==
16884 ExplicitSignature.getLocalRangeEnd()) {
16885 // This would be much cheaper if we stored TypeLocs instead of
16886 // TypeSourceInfos.
16887 TypeLoc Result = ExplicitSignature.getReturnLoc();
16888 unsigned Size = Result.getFullDataSize();
16889 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16890 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16891
16892 ExplicitSignature = FunctionProtoTypeLoc();
16893 }
16894 }
16895
16896 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16897 CurBlock->FunctionType = T;
16898
16899 const auto *Fn = T->castAs<FunctionType>();
16900 QualType RetTy = Fn->getReturnType();
16901 bool isVariadic =
16902 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16903
16904 CurBlock->TheDecl->setIsVariadic(isVariadic);
16905
16906 // Context.DependentTy is used as a placeholder for a missing block
16907 // return type. TODO: what should we do with declarators like:
16908 // ^ * { ... }
16909 // If the answer is "apply template argument deduction"....
16910 if (RetTy != Context.DependentTy) {
16911 CurBlock->ReturnType = RetTy;
16912 CurBlock->TheDecl->setBlockMissingReturnType(false);
16913 CurBlock->HasImplicitReturnType = false;
16914 }
16915
16916 // Push block parameters from the declarator if we had them.
16918 if (ExplicitSignature) {
16919 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16920 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16921 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16922 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16923 // Diagnose this as an extension in C17 and earlier.
16924 if (!getLangOpts().C23)
16925 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16926 }
16927 Params.push_back(Param);
16928 }
16929
16930 // Fake up parameter variables if we have a typedef, like
16931 // ^ fntype { ... }
16932 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16933 for (const auto &I : Fn->param_types()) {
16935 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16936 Params.push_back(Param);
16937 }
16938 }
16939
16940 // Set the parameters on the block decl.
16941 if (!Params.empty()) {
16942 CurBlock->TheDecl->setParams(Params);
16944 /*CheckParameterNames=*/false);
16945 }
16946
16947 // Finally we can process decl attributes.
16948 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16949
16950 // Put the parameter variables in scope.
16951 for (auto *AI : CurBlock->TheDecl->parameters()) {
16952 AI->setOwningFunction(CurBlock->TheDecl);
16953
16954 // If this has an identifier, add it to the scope stack.
16955 if (AI->getIdentifier()) {
16956 CheckShadow(CurBlock->TheScope, AI);
16957
16958 PushOnScopeChains(AI, CurBlock->TheScope);
16959 }
16960
16961 if (AI->isInvalidDecl())
16962 CurBlock->TheDecl->setInvalidDecl();
16963 }
16964}
16965
16966void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16967 // Leave the expression-evaluation context.
16970
16971 // Pop off CurBlock, handle nested blocks.
16974}
16975
16977 Stmt *Body, Scope *CurScope) {
16978 // If blocks are disabled, emit an error.
16979 if (!LangOpts.Blocks)
16980 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16981
16982 // Leave the expression-evaluation context.
16985 assert(!Cleanup.exprNeedsCleanups() &&
16986 "cleanups within block not correctly bound!");
16988
16990 BlockDecl *BD = BSI->TheDecl;
16991
16993
16994 if (BSI->HasImplicitReturnType)
16996
16997 QualType RetTy = Context.VoidTy;
16998 if (!BSI->ReturnType.isNull())
16999 RetTy = BSI->ReturnType;
17000
17001 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17002 QualType BlockTy;
17003
17004 // If the user wrote a function type in some form, try to use that.
17005 if (!BSI->FunctionType.isNull()) {
17006 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17007
17008 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17009 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17010
17011 // Turn protoless block types into nullary block types.
17012 if (isa<FunctionNoProtoType>(FTy)) {
17014 EPI.ExtInfo = Ext;
17015 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17016
17017 // Otherwise, if we don't need to change anything about the function type,
17018 // preserve its sugar structure.
17019 } else if (FTy->getReturnType() == RetTy &&
17020 (!NoReturn || FTy->getNoReturnAttr())) {
17021 BlockTy = BSI->FunctionType;
17022
17023 // Otherwise, make the minimal modifications to the function type.
17024 } else {
17027 EPI.TypeQuals = Qualifiers();
17028 EPI.ExtInfo = Ext;
17029 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17030 }
17031
17032 // If we don't have a function type, just build one from nothing.
17033 } else {
17035 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17036 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17037 }
17038
17040 BlockTy = Context.getBlockPointerType(BlockTy);
17041
17042 // If needed, diagnose invalid gotos and switches in the block.
17043 if (getCurFunction()->NeedsScopeChecking() &&
17044 !PP.isCodeCompletionEnabled())
17046
17047 BD->setBody(cast<CompoundStmt>(Body));
17048
17049 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17051
17052 // Try to apply the named return value optimization. We have to check again
17053 // if we can do this, though, because blocks keep return statements around
17054 // to deduce an implicit return type.
17055 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17056 !BD->isDependentContext())
17057 computeNRVO(Body, BSI);
17058
17064
17066
17067 // Set the captured variables on the block.
17069 for (Capture &Cap : BSI->Captures) {
17070 if (Cap.isInvalid() || Cap.isThisCapture())
17071 continue;
17072 // Cap.getVariable() is always a VarDecl because
17073 // blocks cannot capture structured bindings or other ValueDecl kinds.
17074 auto *Var = cast<VarDecl>(Cap.getVariable());
17075 Expr *CopyExpr = nullptr;
17076 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17077 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17078 // The capture logic needs the destructor, so make sure we mark it.
17079 // Usually this is unnecessary because most local variables have
17080 // their destructors marked at declaration time, but parameters are
17081 // an exception because it's technically only the call site that
17082 // actually requires the destructor.
17083 if (isa<ParmVarDecl>(Var))
17085
17086 // Enter a separate potentially-evaluated context while building block
17087 // initializers to isolate their cleanups from those of the block
17088 // itself.
17089 // FIXME: Is this appropriate even when the block itself occurs in an
17090 // unevaluated operand?
17093
17094 SourceLocation Loc = Cap.getLocation();
17095
17097 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17098
17099 // According to the blocks spec, the capture of a variable from
17100 // the stack requires a const copy constructor. This is not true
17101 // of the copy/move done to move a __block variable to the heap.
17102 if (!Result.isInvalid() &&
17103 !Result.get()->getType().isConstQualified()) {
17105 Result.get()->getType().withConst(),
17106 CK_NoOp, VK_LValue);
17107 }
17108
17109 if (!Result.isInvalid()) {
17111 InitializedEntity::InitializeBlock(Var->getLocation(),
17112 Cap.getCaptureType()),
17113 Loc, Result.get());
17114 }
17115
17116 // Build a full-expression copy expression if initialization
17117 // succeeded and used a non-trivial constructor. Recover from
17118 // errors by pretending that the copy isn't necessary.
17119 if (!Result.isInvalid() &&
17120 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17121 ->isTrivial()) {
17123 CopyExpr = Result.get();
17124 }
17125 }
17126 }
17127
17128 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17129 CopyExpr);
17130 Captures.push_back(NewCap);
17131 }
17132 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17133
17134 // Pop the block scope now but keep it alive to the end of this function.
17136 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17137 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17138
17139 BlockExpr *Result = new (Context)
17140 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17141
17142 // If the block isn't obviously global, i.e. it captures anything at
17143 // all, then we need to do a few things in the surrounding context:
17144 if (Result->getBlockDecl()->hasCaptures()) {
17145 // First, this expression has a new cleanup object.
17146 ExprCleanupObjects.push_back(Result->getBlockDecl());
17147 Cleanup.setExprNeedsCleanups(true);
17148
17149 // It also gets a branch-protected scope if any of the captured
17150 // variables needs destruction.
17151 for (const auto &CI : Result->getBlockDecl()->captures()) {
17152 const VarDecl *var = CI.getVariable();
17153 if (var->getType().isDestructedType() != QualType::DK_none) {
17155 break;
17156 }
17157 }
17158 }
17159
17160 if (getCurFunction())
17161 getCurFunction()->addBlock(BD);
17162
17163 // This can happen if the block's return type is deduced, but
17164 // the return expression is invalid.
17165 if (BD->isInvalidDecl())
17166 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17167 {Result}, Result->getType());
17168 return Result;
17169}
17170
17172 SourceLocation RPLoc) {
17173 TypeSourceInfo *TInfo;
17174 GetTypeFromParser(Ty, &TInfo);
17175 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17176}
17177
17179 Expr *E, TypeSourceInfo *TInfo,
17180 SourceLocation RPLoc) {
17181 Expr *OrigExpr = E;
17182 bool IsMS = false;
17183
17184 // CUDA device global function does not support varargs.
17185 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17186 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17189 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17190 }
17191 }
17192
17193 // NVPTX does not support va_arg expression.
17194 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17195 Context.getTargetInfo().getTriple().isNVPTX())
17196 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17197
17198 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17199 // as Microsoft ABI on an actual Microsoft platform, where
17200 // __builtin_ms_va_list and __builtin_va_list are the same.)
17201 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17202 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17203 QualType MSVaListType = Context.getBuiltinMSVaListType();
17204 if (Context.hasSameType(MSVaListType, E->getType())) {
17205 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17206 return ExprError();
17207 IsMS = true;
17208 }
17209 }
17210
17211 // Get the va_list type
17212 QualType VaListType = Context.getBuiltinVaListType();
17213 if (!IsMS) {
17214 if (VaListType->isArrayType()) {
17215 // Deal with implicit array decay; for example, on x86-64,
17216 // va_list is an array, but it's supposed to decay to
17217 // a pointer for va_arg.
17218 VaListType = Context.getArrayDecayedType(VaListType);
17219 // Make sure the input expression also decays appropriately.
17221 if (Result.isInvalid())
17222 return ExprError();
17223 E = Result.get();
17224 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17225 // If va_list is a record type and we are compiling in C++ mode,
17226 // check the argument using reference binding.
17228 Context, Context.getLValueReferenceType(VaListType), false);
17230 if (Init.isInvalid())
17231 return ExprError();
17232 E = Init.getAs<Expr>();
17233 } else {
17234 // Otherwise, the va_list argument must be an l-value because
17235 // it is modified by va_arg.
17236 if (!E->isTypeDependent() &&
17237 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17238 return ExprError();
17239 }
17240 }
17241
17242 if (!IsMS && !E->isTypeDependent() &&
17243 !Context.hasSameType(VaListType, E->getType()))
17244 return ExprError(
17245 Diag(E->getBeginLoc(),
17246 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17247 << OrigExpr->getType() << E->getSourceRange());
17248
17249 if (!TInfo->getType()->isDependentType()) {
17250 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17251 diag::err_second_parameter_to_va_arg_incomplete,
17252 TInfo->getTypeLoc()))
17253 return ExprError();
17254
17256 TInfo->getType(),
17257 diag::err_second_parameter_to_va_arg_abstract,
17258 TInfo->getTypeLoc()))
17259 return ExprError();
17260
17261 if (!TInfo->getType().isPODType(Context)) {
17262 Diag(TInfo->getTypeLoc().getBeginLoc(),
17263 TInfo->getType()->isObjCLifetimeType()
17264 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17265 : diag::warn_second_parameter_to_va_arg_not_pod)
17266 << TInfo->getType()
17267 << TInfo->getTypeLoc().getSourceRange();
17268 }
17269
17270 if (TInfo->getType()->isArrayType()) {
17272 PDiag(diag::warn_second_parameter_to_va_arg_array)
17273 << TInfo->getType()
17274 << TInfo->getTypeLoc().getSourceRange());
17275 }
17276
17277 // Check for va_arg where arguments of the given type will be promoted
17278 // (i.e. this va_arg is guaranteed to have undefined behavior).
17279 QualType PromoteType;
17280 if (Context.isPromotableIntegerType(TInfo->getType())) {
17281 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17282 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17283 // and C23 7.16.1.1p2 says, in part:
17284 // If type is not compatible with the type of the actual next argument
17285 // (as promoted according to the default argument promotions), the
17286 // behavior is undefined, except for the following cases:
17287 // - both types are pointers to qualified or unqualified versions of
17288 // compatible types;
17289 // - one type is compatible with a signed integer type, the other
17290 // type is compatible with the corresponding unsigned integer type,
17291 // and the value is representable in both types;
17292 // - one type is pointer to qualified or unqualified void and the
17293 // other is a pointer to a qualified or unqualified character type;
17294 // - or, the type of the next argument is nullptr_t and type is a
17295 // pointer type that has the same representation and alignment
17296 // requirements as a pointer to a character type.
17297 // Given that type compatibility is the primary requirement (ignoring
17298 // qualifications), you would think we could call typesAreCompatible()
17299 // directly to test this. However, in C++, that checks for *same type*,
17300 // which causes false positives when passing an enumeration type to
17301 // va_arg. Instead, get the underlying type of the enumeration and pass
17302 // that.
17303 QualType UnderlyingType = TInfo->getType();
17304 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17305 UnderlyingType = ED->getIntegerType();
17306 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17307 /*CompareUnqualified*/ true))
17308 PromoteType = QualType();
17309
17310 // If the types are still not compatible, we need to test whether the
17311 // promoted type and the underlying type are the same except for
17312 // signedness. Ask the AST for the correctly corresponding type and see
17313 // if that's compatible.
17314 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17315 PromoteType->isUnsignedIntegerType() !=
17316 UnderlyingType->isUnsignedIntegerType()) {
17317 UnderlyingType =
17318 UnderlyingType->isUnsignedIntegerType()
17319 ? Context.getCorrespondingSignedType(UnderlyingType)
17320 : Context.getCorrespondingUnsignedType(UnderlyingType);
17321 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17322 /*CompareUnqualified*/ true))
17323 PromoteType = QualType();
17324 }
17325 }
17326 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17327 PromoteType = Context.DoubleTy;
17328 if (!PromoteType.isNull())
17330 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17331 << TInfo->getType()
17332 << PromoteType
17333 << TInfo->getTypeLoc().getSourceRange());
17334 }
17335
17337 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17338}
17339
17341 // The type of __null will be int or long, depending on the size of
17342 // pointers on the target.
17343 QualType Ty;
17344 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17345 if (pw == Context.getTargetInfo().getIntWidth())
17346 Ty = Context.IntTy;
17347 else if (pw == Context.getTargetInfo().getLongWidth())
17348 Ty = Context.LongTy;
17349 else if (pw == Context.getTargetInfo().getLongLongWidth())
17350 Ty = Context.LongLongTy;
17351 else {
17352 llvm_unreachable("I don't know size of pointer!");
17353 }
17354
17355 return new (Context) GNUNullExpr(Ty, TokenLoc);
17356}
17357
17359 CXXRecordDecl *ImplDecl = nullptr;
17360
17361 // Fetch the std::source_location::__impl decl.
17362 if (NamespaceDecl *Std = S.getStdNamespace()) {
17363 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17365 if (S.LookupQualifiedName(ResultSL, Std)) {
17366 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17367 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17369 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17370 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17371 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17372 }
17373 }
17374 }
17375 }
17376
17377 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17378 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17379 return nullptr;
17380 }
17381
17382 // Verify that __impl is a trivial struct type, with no base classes, and with
17383 // only the four expected fields.
17384 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17385 ImplDecl->getNumBases() != 0) {
17386 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17387 return nullptr;
17388 }
17389
17390 unsigned Count = 0;
17391 for (FieldDecl *F : ImplDecl->fields()) {
17392 StringRef Name = F->getName();
17393
17394 if (Name == "_M_file_name") {
17395 if (F->getType() !=
17397 break;
17398 Count++;
17399 } else if (Name == "_M_function_name") {
17400 if (F->getType() !=
17402 break;
17403 Count++;
17404 } else if (Name == "_M_line") {
17405 if (!F->getType()->isIntegerType())
17406 break;
17407 Count++;
17408 } else if (Name == "_M_column") {
17409 if (!F->getType()->isIntegerType())
17410 break;
17411 Count++;
17412 } else {
17413 Count = 100; // invalid
17414 break;
17415 }
17416 }
17417 if (Count != 4) {
17418 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17419 return nullptr;
17420 }
17421
17422 return ImplDecl;
17423}
17424
17426 SourceLocation BuiltinLoc,
17427 SourceLocation RPLoc) {
17428 QualType ResultTy;
17429 switch (Kind) {
17434 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17435 ResultTy =
17436 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17437 break;
17438 }
17441 ResultTy = Context.UnsignedIntTy;
17442 break;
17446 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17448 return ExprError();
17449 }
17450 ResultTy = Context.getPointerType(
17451 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17452 break;
17453 }
17454
17455 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17456}
17457
17459 SourceLocation BuiltinLoc,
17460 SourceLocation RPLoc,
17461 DeclContext *ParentContext) {
17462 return new (Context)
17463 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17464}
17465
17467 StringLiteral *BinaryData, StringRef FileName) {
17469 Data->BinaryData = BinaryData;
17470 Data->FileName = FileName;
17471 return new (Context)
17472 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17473 Data->getDataElementCount());
17474}
17475
17477 const Expr *SrcExpr) {
17478 if (!DstType->isFunctionPointerType() ||
17479 !SrcExpr->getType()->isFunctionType())
17480 return false;
17481
17482 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17483 if (!DRE)
17484 return false;
17485
17486 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17487 if (!FD)
17488 return false;
17489
17491 /*Complain=*/true,
17492 SrcExpr->getBeginLoc());
17493}
17494
17496 SourceLocation Loc,
17497 QualType DstType, QualType SrcType,
17498 Expr *SrcExpr, AssignmentAction Action,
17499 bool *Complained) {
17500 if (Complained)
17501 *Complained = false;
17502
17503 // Decode the result (notice that AST's are still created for extensions).
17504 bool CheckInferredResultType = false;
17505 bool isInvalid = false;
17506 unsigned DiagKind = 0;
17507 ConversionFixItGenerator ConvHints;
17508 bool MayHaveConvFixit = false;
17509 bool MayHaveFunctionDiff = false;
17510 const ObjCInterfaceDecl *IFace = nullptr;
17511 const ObjCProtocolDecl *PDecl = nullptr;
17512
17513 switch (ConvTy) {
17515 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17516 return false;
17518 // Still a valid conversion, but we may want to diagnose for C++
17519 // compatibility reasons.
17520 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17521 break;
17523 if (getLangOpts().CPlusPlus) {
17524 DiagKind = diag::err_typecheck_convert_pointer_int;
17525 isInvalid = true;
17526 } else {
17527 DiagKind = diag::ext_typecheck_convert_pointer_int;
17528 }
17529 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17530 MayHaveConvFixit = true;
17531 break;
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_int_pointer;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_int_pointer;
17538 }
17539 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17540 MayHaveConvFixit = true;
17541 break;
17543 DiagKind =
17544 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17545 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17546 MayHaveConvFixit = true;
17547 break;
17549 if (getLangOpts().CPlusPlus) {
17550 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17551 isInvalid = true;
17552 } else {
17553 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17554 }
17555 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17556 MayHaveConvFixit = true;
17557 break;
17560 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17561 } else if (getLangOpts().CPlusPlus) {
17562 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17563 isInvalid = true;
17564 } else {
17565 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17566 }
17567 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17568 SrcType->isObjCObjectPointerType();
17569 if (CheckInferredResultType) {
17570 SrcType = SrcType.getUnqualifiedType();
17571 DstType = DstType.getUnqualifiedType();
17572 } else {
17573 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17574 }
17575 MayHaveConvFixit = true;
17576 break;
17578 if (getLangOpts().CPlusPlus) {
17579 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17580 isInvalid = true;
17581 } else {
17582 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17583 }
17584 break;
17586 if (getLangOpts().CPlusPlus) {
17587 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17588 isInvalid = true;
17589 } else {
17590 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17591 }
17592 break;
17594 // Perform array-to-pointer decay if necessary.
17595 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17596
17597 isInvalid = true;
17598
17599 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17600 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17601 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17602 DiagKind = diag::err_typecheck_incompatible_address_space;
17603 break;
17604 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17605 DiagKind = diag::err_typecheck_incompatible_ownership;
17606 break;
17607 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17608 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17609 break;
17610 }
17611
17612 llvm_unreachable("unknown error case for discarding qualifiers!");
17613 // fallthrough
17614 }
17616 if (SrcType->isArrayType())
17617 SrcType = Context.getArrayDecayedType(SrcType);
17618
17619 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17620 break;
17622 // If the qualifiers lost were because we were applying the
17623 // (deprecated) C++ conversion from a string literal to a char*
17624 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17625 // Ideally, this check would be performed in
17626 // checkPointerTypesForAssignment. However, that would require a
17627 // bit of refactoring (so that the second argument is an
17628 // expression, rather than a type), which should be done as part
17629 // of a larger effort to fix checkPointerTypesForAssignment for
17630 // C++ semantics.
17631 if (getLangOpts().CPlusPlus &&
17633 return false;
17634 if (getLangOpts().CPlusPlus) {
17635 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17636 isInvalid = true;
17637 } else {
17638 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17639 }
17640
17641 break;
17643 if (getLangOpts().CPlusPlus) {
17644 isInvalid = true;
17645 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17646 } else {
17647 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17648 }
17649 break;
17651 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17652 isInvalid = true;
17653 break;
17655 DiagKind = diag::err_int_to_block_pointer;
17656 isInvalid = true;
17657 break;
17659 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17660 isInvalid = true;
17661 break;
17663 if (SrcType->isObjCQualifiedIdType()) {
17664 const ObjCObjectPointerType *srcOPT =
17665 SrcType->castAs<ObjCObjectPointerType>();
17666 for (auto *srcProto : srcOPT->quals()) {
17667 PDecl = srcProto;
17668 break;
17669 }
17670 if (const ObjCInterfaceType *IFaceT =
17672 IFace = IFaceT->getDecl();
17673 }
17674 else if (DstType->isObjCQualifiedIdType()) {
17675 const ObjCObjectPointerType *dstOPT =
17676 DstType->castAs<ObjCObjectPointerType>();
17677 for (auto *dstProto : dstOPT->quals()) {
17678 PDecl = dstProto;
17679 break;
17680 }
17681 if (const ObjCInterfaceType *IFaceT =
17683 IFace = IFaceT->getDecl();
17684 }
17685 if (getLangOpts().CPlusPlus) {
17686 DiagKind = diag::err_incompatible_qualified_id;
17687 isInvalid = true;
17688 } else {
17689 DiagKind = diag::warn_incompatible_qualified_id;
17690 }
17691 break;
17692 }
17694 if (getLangOpts().CPlusPlus) {
17695 DiagKind = diag::err_incompatible_vectors;
17696 isInvalid = true;
17697 } else {
17698 DiagKind = diag::warn_incompatible_vectors;
17699 }
17700 break;
17702 DiagKind = diag::err_arc_weak_unavailable_assign;
17703 isInvalid = true;
17704 break;
17706 return false;
17708 auto getOBTKindName = [](QualType Ty) -> StringRef {
17709 if (Ty->isPointerType())
17710 Ty = Ty->getPointeeType();
17711 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17712 return OBT->getBehaviorKind() ==
17713 OverflowBehaviorType::OverflowBehaviorKind::Trap
17714 ? "__ob_trap"
17715 : "__ob_wrap";
17716 }
17717 llvm_unreachable("OBT kind unhandled");
17718 };
17719
17720 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17721 << DstType << SrcType << getOBTKindName(DstType)
17722 << getOBTKindName(SrcType);
17723 isInvalid = true;
17724 return true;
17725 }
17727 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17728 if (Complained)
17729 *Complained = true;
17730 return true;
17731 }
17732
17733 DiagKind = diag::err_typecheck_convert_incompatible;
17734 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17735 MayHaveConvFixit = true;
17736 isInvalid = true;
17737 MayHaveFunctionDiff = true;
17738 break;
17739 }
17740
17741 QualType FirstType, SecondType;
17742 switch (Action) {
17745 // The destination type comes first.
17746 FirstType = DstType;
17747 SecondType = SrcType;
17748 break;
17749
17756 // The source type comes first.
17757 FirstType = SrcType;
17758 SecondType = DstType;
17759 break;
17760 }
17761
17762 PartialDiagnostic FDiag = PDiag(DiagKind);
17763 AssignmentAction ActionForDiag = Action;
17765 ActionForDiag = AssignmentAction::Passing;
17766
17767 FDiag << FirstType << SecondType << ActionForDiag
17768 << SrcExpr->getSourceRange();
17769
17770 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17771 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17772 auto isPlainChar = [](const clang::Type *Type) {
17773 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17774 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17775 };
17776 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17777 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17778 }
17779
17780 // If we can fix the conversion, suggest the FixIts.
17781 if (!ConvHints.isNull()) {
17782 for (FixItHint &H : ConvHints.Hints)
17783 FDiag << H;
17784 }
17785
17786 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17787
17788 if (MayHaveFunctionDiff)
17789 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17790
17791 Diag(Loc, FDiag);
17792 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17793 DiagKind == diag::err_incompatible_qualified_id) &&
17794 PDecl && IFace && !IFace->hasDefinition())
17795 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17796 << IFace << PDecl;
17797
17798 if (SecondType == Context.OverloadTy)
17800 FirstType, /*TakingAddress=*/true);
17801
17802 if (CheckInferredResultType)
17804
17805 if (Action == AssignmentAction::Returning &&
17808
17809 if (Complained)
17810 *Complained = true;
17811 return isInvalid;
17812}
17813
17815 llvm::APSInt *Result,
17816 AllowFoldKind CanFold) {
17817 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17818 public:
17819 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17820 QualType T) override {
17821 return S.Diag(Loc, diag::err_ice_not_integral)
17822 << T << S.LangOpts.CPlusPlus;
17823 }
17824 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17825 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17826 }
17827 } Diagnoser;
17828
17829 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17830}
17831
17833 llvm::APSInt *Result,
17834 unsigned DiagID,
17835 AllowFoldKind CanFold) {
17836 class IDDiagnoser : public VerifyICEDiagnoser {
17837 unsigned DiagID;
17838
17839 public:
17840 IDDiagnoser(unsigned DiagID)
17841 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17842
17843 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17844 return S.Diag(Loc, DiagID);
17845 }
17846 } Diagnoser(DiagID);
17847
17848 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17849}
17850
17856
17859 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17860}
17861
17864 VerifyICEDiagnoser &Diagnoser,
17865 AllowFoldKind CanFold) {
17866 SourceLocation DiagLoc = E->getBeginLoc();
17867
17868 if (getLangOpts().CPlusPlus11) {
17869 // C++11 [expr.const]p5:
17870 // If an expression of literal class type is used in a context where an
17871 // integral constant expression is required, then that class type shall
17872 // have a single non-explicit conversion function to an integral or
17873 // unscoped enumeration type
17874 ExprResult Converted;
17875 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17876 VerifyICEDiagnoser &BaseDiagnoser;
17877 public:
17878 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17879 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17880 BaseDiagnoser.Suppress, true),
17881 BaseDiagnoser(BaseDiagnoser) {}
17882
17883 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17884 QualType T) override {
17885 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17886 }
17887
17888 SemaDiagnosticBuilder diagnoseIncomplete(
17889 Sema &S, SourceLocation Loc, QualType T) override {
17890 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17891 }
17892
17893 SemaDiagnosticBuilder diagnoseExplicitConv(
17894 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17895 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17896 }
17897
17898 SemaDiagnosticBuilder noteExplicitConv(
17899 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17900 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17901 << ConvTy->isEnumeralType() << ConvTy;
17902 }
17903
17904 SemaDiagnosticBuilder diagnoseAmbiguous(
17905 Sema &S, SourceLocation Loc, QualType T) override {
17906 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17907 }
17908
17909 SemaDiagnosticBuilder noteAmbiguous(
17910 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17911 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17912 << ConvTy->isEnumeralType() << ConvTy;
17913 }
17914
17915 SemaDiagnosticBuilder diagnoseConversion(
17916 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17917 llvm_unreachable("conversion functions are permitted");
17918 }
17919 } ConvertDiagnoser(Diagnoser);
17920
17921 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17922 ConvertDiagnoser);
17923 if (Converted.isInvalid())
17924 return Converted;
17925 E = Converted.get();
17926 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17927 // don't try to evaluate it later. We also don't want to return the
17928 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17929 // this function will attempt to use 'Value'.
17930 if (isa<RecoveryExpr>(E))
17931 return ExprError();
17933 return ExprError();
17934 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17935 // An ICE must be of integral or unscoped enumeration type.
17936 if (!Diagnoser.Suppress)
17937 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17938 << E->getSourceRange();
17939 return ExprError();
17940 }
17941
17942 ExprResult RValueExpr = DefaultLvalueConversion(E);
17943 if (RValueExpr.isInvalid())
17944 return ExprError();
17945
17946 E = RValueExpr.get();
17947
17948 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17949 // in the non-ICE case.
17952 if (Result)
17954 if (!isa<ConstantExpr>(E))
17957
17958 if (Notes.empty())
17959 return E;
17960
17961 // If our only note is the usual "invalid subexpression" note, just point
17962 // the caret at its location rather than producing an essentially
17963 // redundant note.
17964 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17965 diag::note_invalid_subexpr_in_const_expr) {
17966 DiagLoc = Notes[0].first;
17967 Notes.clear();
17968 }
17969
17970 if (getLangOpts().CPlusPlus) {
17971 if (!Diagnoser.Suppress) {
17972 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17973 for (const PartialDiagnosticAt &Note : Notes)
17974 Diag(Note.first, Note.second);
17975 }
17976 return ExprError();
17977 }
17978
17979 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17980 for (const PartialDiagnosticAt &Note : Notes)
17981 Diag(Note.first, Note.second);
17982
17983 return E;
17984 }
17985
17986 Expr::EvalResult EvalResult;
17988 EvalResult.Diag = &Notes;
17989
17990 // Try to evaluate the expression, and produce diagnostics explaining why it's
17991 // not a constant expression as a side-effect.
17992 bool Folded =
17993 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17994 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17995 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17996
17997 if (!isa<ConstantExpr>(E))
17998 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17999
18000 // In C++11, we can rely on diagnostics being produced for any expression
18001 // which is not a constant expression. If no diagnostics were produced, then
18002 // this is a constant expression.
18003 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18004 if (Result)
18005 *Result = EvalResult.Val.getInt();
18006 return E;
18007 }
18008
18009 // If our only note is the usual "invalid subexpression" note, just point
18010 // the caret at its location rather than producing an essentially
18011 // redundant note.
18012 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18013 diag::note_invalid_subexpr_in_const_expr) {
18014 DiagLoc = Notes[0].first;
18015 Notes.clear();
18016 }
18017
18018 if (!Folded || CanFold == AllowFoldKind::No) {
18019 if (!Diagnoser.Suppress) {
18020 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18021 for (const PartialDiagnosticAt &Note : Notes)
18022 Diag(Note.first, Note.second);
18023 }
18024
18025 return ExprError();
18026 }
18027
18028 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18029 for (const PartialDiagnosticAt &Note : Notes)
18030 Diag(Note.first, Note.second);
18031
18032 if (Result)
18033 *Result = EvalResult.Val.getInt();
18034 return E;
18035}
18036
18037namespace {
18038 // Handle the case where we conclude a expression which we speculatively
18039 // considered to be unevaluated is actually evaluated.
18040 class TransformToPE : public TreeTransform<TransformToPE> {
18041 typedef TreeTransform<TransformToPE> BaseTransform;
18042
18043 public:
18044 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18045
18046 // Make sure we redo semantic analysis
18047 bool AlwaysRebuild() { return true; }
18048 bool ReplacingOriginal() { return true; }
18049
18050 // We need to special-case DeclRefExprs referring to FieldDecls which
18051 // are not part of a member pointer formation; normal TreeTransforming
18052 // doesn't catch this case because of the way we represent them in the AST.
18053 // FIXME: This is a bit ugly; is it really the best way to handle this
18054 // case?
18055 //
18056 // Error on DeclRefExprs referring to FieldDecls.
18057 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18058 if (isa<FieldDecl>(E->getDecl()) &&
18059 !SemaRef.isUnevaluatedContext())
18060 return SemaRef.Diag(E->getLocation(),
18061 diag::err_invalid_non_static_member_use)
18062 << E->getDecl() << E->getSourceRange();
18063
18064 return BaseTransform::TransformDeclRefExpr(E);
18065 }
18066
18067 // Exception: filter out member pointer formation
18068 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18069 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18070 return E;
18071
18072 return BaseTransform::TransformUnaryOperator(E);
18073 }
18074
18075 // The body of a lambda-expression is in a separate expression evaluation
18076 // context so never needs to be transformed.
18077 // FIXME: Ideally we wouldn't transform the closure type either, and would
18078 // just recreate the capture expressions and lambda expression.
18079 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18080 return SkipLambdaBody(E, Body);
18081 }
18082 };
18083}
18084
18086 assert(isUnevaluatedContext() &&
18087 "Should only transform unevaluated expressions");
18088 ExprEvalContexts.back().Context =
18089 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18091 return E;
18092 return TransformToPE(*this).TransformExpr(E);
18093}
18094
18096 assert(isUnevaluatedContext() &&
18097 "Should only transform unevaluated expressions");
18100 return TInfo;
18101 return TransformToPE(*this).TransformType(TInfo);
18102}
18103
18104void
18106 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18108 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18109 LambdaContextDecl, ExprContext);
18110
18111 // Discarded statements and immediate contexts nested in other
18112 // discarded statements or immediate context are themselves
18113 // a discarded statement or an immediate context, respectively.
18114 ExprEvalContexts.back().InDiscardedStatement =
18116
18117 // C++23 [expr.const]/p15
18118 // An expression or conversion is in an immediate function context if [...]
18119 // it is a subexpression of a manifestly constant-evaluated expression or
18120 // conversion.
18121 const auto &Prev = parentEvaluationContext();
18122 ExprEvalContexts.back().InImmediateFunctionContext =
18123 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18124
18125 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18126 Prev.InImmediateEscalatingFunctionContext;
18127
18128 Cleanup.reset();
18129 if (!MaybeODRUseExprs.empty())
18130 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18131}
18132
18133void
18137 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18138 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18139}
18140
18142 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18143 // [expr.const]/p14.1
18144 // An expression or conversion is in an immediate function context if it is
18145 // potentially evaluated and either: its innermost enclosing non-block scope
18146 // is a function parameter scope of an immediate function.
18148 FD && FD->isConsteval()
18150 : NewContext);
18154
18155 Current.InDiscardedStatement = false;
18156
18157 if (FD) {
18158
18159 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18160 // context is nested in an immediate function context, so smaller contexts
18161 // that appear inside immediate functions (like variable initializers) are
18162 // considered to be inside an immediate function context even though by
18163 // themselves they are not immediate function contexts. But when a new
18164 // function is entered, we need to reset this tracking, since the entered
18165 // function might be not an immediate function.
18166
18168 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18169
18170 if (isLambdaMethod(FD))
18172 FD->isConsteval() ||
18173 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18174 Parent.isImmediateFunctionContext()));
18175 else
18177 }
18178}
18179
18181 TypeSourceInfo *TSI) {
18182 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18183}
18184
18186 TypeSourceInfo *TSI) {
18187 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18188}
18189
18190namespace {
18191
18192const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18193 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18194 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18195 if (E->getOpcode() == UO_Deref)
18196 return CheckPossibleDeref(S, E->getSubExpr());
18197 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18198 return CheckPossibleDeref(S, E->getBase());
18199 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18200 return CheckPossibleDeref(S, E->getBase());
18201 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18202 QualType Inner;
18203 QualType Ty = E->getType();
18204 if (const auto *Ptr = Ty->getAs<PointerType>())
18205 Inner = Ptr->getPointeeType();
18206 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18207 Inner = Arr->getElementType();
18208 else
18209 return nullptr;
18210
18211 if (Inner->hasAttr(attr::NoDeref))
18212 return E;
18213 }
18214 return nullptr;
18215}
18216
18217} // namespace
18218
18220 for (const Expr *E : Rec.PossibleDerefs) {
18221 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18222 if (DeclRef) {
18223 const ValueDecl *Decl = DeclRef->getDecl();
18224 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18225 << Decl->getName() << E->getSourceRange();
18226 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18227 } else {
18228 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18229 << E->getSourceRange();
18230 }
18231 }
18232 Rec.PossibleDerefs.clear();
18233}
18234
18237 return;
18238
18239 // Note: ignoring parens here is not justified by the standard rules, but
18240 // ignoring parentheses seems like a more reasonable approach, and this only
18241 // drives a deprecation warning so doesn't affect conformance.
18242 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18243 if (BO->getOpcode() == BO_Assign) {
18244 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18245 llvm::erase(LHSs, BO->getLHS());
18246 }
18247 }
18248}
18249
18251 assert(getLangOpts().CPlusPlus20 &&
18252 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18253 "Cannot mark an immediate escalating expression outside of an "
18254 "immediate escalating context");
18255 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18256 Call && Call->getCallee()) {
18257 if (auto *DeclRef =
18258 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18259 DeclRef->setIsImmediateEscalating(true);
18260 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18261 Ctr->setIsImmediateEscalating(true);
18262 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18263 DeclRef->setIsImmediateEscalating(true);
18264 } else {
18265 assert(false && "expected an immediately escalating expression");
18266 }
18268 FI->FoundImmediateEscalatingExpression = true;
18269}
18270
18272 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18273 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18276 return E;
18277
18278 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18279 /// It's OK if this fails; we'll also remove this in
18280 /// HandleImmediateInvocations, but catching it here allows us to avoid
18281 /// walking the AST looking for it in simple cases.
18282 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18283 if (auto *DeclRef =
18284 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18285 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18286
18287 // C++23 [expr.const]/p16
18288 // An expression or conversion is immediate-escalating if it is not initially
18289 // in an immediate function context and it is [...] an immediate invocation
18290 // that is not a constant expression and is not a subexpression of an
18291 // immediate invocation.
18292 APValue Cached;
18293 auto CheckConstantExpressionAndKeepResult = [&]() {
18295 Expr::EvalResult Eval;
18296 Eval.Diag = &Notes;
18297 bool Res = E.get()->EvaluateAsConstantExpr(
18298 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18299 if (Res && Notes.empty()) {
18300 Cached = std::move(Eval.Val);
18301 return true;
18302 }
18303 return false;
18304 };
18305
18306 if (!E.get()->isValueDependent() &&
18307 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18308 !CheckConstantExpressionAndKeepResult()) {
18310 return E;
18311 }
18312
18313 if (Cleanup.exprNeedsCleanups()) {
18314 // Since an immediate invocation is a full expression itself - it requires
18315 // an additional ExprWithCleanups node, but it can participate to a bigger
18316 // full expression which actually requires cleanups to be run after so
18317 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18318 // may discard cleanups for outer expression too early.
18319
18320 // Note that ExprWithCleanups created here must always have empty cleanup
18321 // objects:
18322 // - compound literals do not create cleanup objects in C++ and immediate
18323 // invocations are C++-only.
18324 // - blocks are not allowed inside constant expressions and compiler will
18325 // issue an error if they appear there.
18326 //
18327 // Hence, in correct code any cleanup objects created inside current
18328 // evaluation context must be outside the immediate invocation.
18330 Cleanup.cleanupsHaveSideEffects(), {});
18331 }
18332
18334 getASTContext(), E.get(),
18335 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18336 getASTContext()),
18337 /*IsImmediateInvocation*/ true);
18338 if (Cached.hasValue())
18339 Res->MoveIntoResult(Cached, getASTContext());
18340 /// Value-dependent constant expressions should not be immediately
18341 /// evaluated until they are instantiated.
18342 if (!Res->isValueDependent())
18343 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18344 return Res;
18345}
18346
18350 Expr::EvalResult Eval;
18351 Eval.Diag = &Notes;
18352 ConstantExpr *CE = Candidate.getPointer();
18353 bool Result = CE->EvaluateAsConstantExpr(
18354 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18355 if (!Result || !Notes.empty()) {
18357 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18358 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18359 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18360 FunctionDecl *FD = nullptr;
18361 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18362 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18363 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18364 FD = Call->getConstructor();
18365 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18366 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18367
18368 assert(FD && FD->isImmediateFunction() &&
18369 "could not find an immediate function in this expression");
18370 if (FD->isInvalidDecl())
18371 return;
18372 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18373 << FD << FD->isConsteval();
18374 if (auto Context =
18376 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18377 << Context->Decl;
18378 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18379 }
18380 if (!FD->isConsteval())
18382 for (auto &Note : Notes)
18383 SemaRef.Diag(Note.first, Note.second);
18384 return;
18385 }
18387}
18388
18392 struct ComplexRemove : TreeTransform<ComplexRemove> {
18394 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18397 CurrentII;
18398 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18401 4>::reverse_iterator Current)
18402 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18403 void RemoveImmediateInvocation(ConstantExpr* E) {
18404 auto It = std::find_if(CurrentII, IISet.rend(),
18406 return Elem.getPointer() == E;
18407 });
18408 // It is possible that some subexpression of the current immediate
18409 // invocation was handled from another expression evaluation context. Do
18410 // not handle the current immediate invocation if some of its
18411 // subexpressions failed before.
18412 if (It == IISet.rend()) {
18413 if (SemaRef.FailedImmediateInvocations.contains(E))
18414 CurrentII->setInt(1);
18415 } else {
18416 It->setInt(1); // Mark as deleted
18417 }
18418 }
18419 ExprResult TransformConstantExpr(ConstantExpr *E) {
18420 if (!E->isImmediateInvocation())
18421 return Base::TransformConstantExpr(E);
18422 RemoveImmediateInvocation(E);
18423 return Base::TransformExpr(E->getSubExpr());
18424 }
18425 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18426 /// we need to remove its DeclRefExpr from the DRSet.
18427 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18428 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18429 return Base::TransformCXXOperatorCallExpr(E);
18430 }
18431 /// Base::TransformUserDefinedLiteral doesn't preserve the
18432 /// UserDefinedLiteral node.
18433 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18434 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18435 /// here.
18436 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18437 if (!Init)
18438 return Init;
18439
18440 // We cannot use IgnoreImpCasts because we need to preserve
18441 // full expressions.
18442 while (true) {
18443 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18444 Init = ICE->getSubExpr();
18445 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18446 Init = ICE->getSubExpr();
18447 else
18448 break;
18449 }
18450 /// ConstantExprs are the first layer of implicit node to be removed so if
18451 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18452 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18453 CE && CE->isImmediateInvocation())
18454 RemoveImmediateInvocation(CE);
18455 return Base::TransformInitializer(Init, NotCopyInit);
18456 }
18457 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18458 DRSet.erase(E);
18459 return E;
18460 }
18461 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18462 // Do not rebuild lambdas to avoid creating a new type.
18463 // Lambdas have already been processed inside their eval contexts.
18464 return E;
18465 }
18466 bool AlwaysRebuild() { return false; }
18467 bool ReplacingOriginal() { return true; }
18468 bool AllowSkippingCXXConstructExpr() {
18469 bool Res = AllowSkippingFirstCXXConstructExpr;
18470 AllowSkippingFirstCXXConstructExpr = true;
18471 return Res;
18472 }
18473 bool AllowSkippingFirstCXXConstructExpr = true;
18474 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18476
18477 /// CXXConstructExpr with a single argument are getting skipped by
18478 /// TreeTransform in some situtation because they could be implicit. This
18479 /// can only occur for the top-level CXXConstructExpr because it is used
18480 /// nowhere in the expression being transformed therefore will not be rebuilt.
18481 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18482 /// skipping the first CXXConstructExpr.
18483 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18484 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18485
18486 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18487 // The result may not be usable in case of previous compilation errors.
18488 // In this case evaluation of the expression may result in crash so just
18489 // don't do anything further with the result.
18490 if (Res.isUsable()) {
18492 It->getPointer()->setSubExpr(Res.get());
18493 }
18494}
18495
18496static void
18499 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18500 Rec.ReferenceToConsteval.size() == 0) ||
18502 return;
18503
18504 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18505 // [...]
18506 // - the initializer of a variable that is usable in constant expressions or
18507 // has constant initialization.
18508 if (SemaRef.getLangOpts().CPlusPlus23 &&
18509 Rec.ExprContext ==
18511 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18512 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18513 VD->hasConstantInitialization())) {
18514 // An expression or conversion is in an 'immediate function context' if it
18515 // is potentially evaluated and either:
18516 // [...]
18517 // - it is a subexpression of a manifestly constant-evaluated expression
18518 // or conversion.
18519 return;
18520 }
18521 }
18522
18523 /// When we have more than 1 ImmediateInvocationCandidates or previously
18524 /// failed immediate invocations, we need to check for nested
18525 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18526 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18527 /// invocation.
18528 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18530
18531 /// Prevent sema calls during the tree transform from adding pointers that
18532 /// are already in the sets.
18533 llvm::SaveAndRestore DisableIITracking(
18535
18536 /// Prevent diagnostic during tree transfrom as they are duplicates
18538
18539 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18540 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18541 if (!It->getInt())
18543 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18544 Rec.ReferenceToConsteval.size()) {
18545 struct SimpleRemove : DynamicRecursiveASTVisitor {
18546 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18547 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18548 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18549 DRSet.erase(E);
18550 return DRSet.size();
18551 }
18552 } Visitor(Rec.ReferenceToConsteval);
18553 Visitor.TraverseStmt(
18554 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18555 }
18556 for (auto CE : Rec.ImmediateInvocationCandidates)
18557 if (!CE.getInt())
18559 for (auto *DR : Rec.ReferenceToConsteval) {
18560 // If the expression is immediate escalating, it is not an error;
18561 // The outer context itself becomes immediate and further errors,
18562 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18563 if (DR->isImmediateEscalating())
18564 continue;
18565 auto *FD = cast<FunctionDecl>(DR->getDecl());
18566 const NamedDecl *ND = FD;
18567 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18568 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18569 ND = MD->getParent();
18570
18571 // C++23 [expr.const]/p16
18572 // An expression or conversion is immediate-escalating if it is not
18573 // initially in an immediate function context and it is [...] a
18574 // potentially-evaluated id-expression that denotes an immediate function
18575 // that is not a subexpression of an immediate invocation.
18576 bool ImmediateEscalating = false;
18577 bool IsPotentiallyEvaluated =
18578 Rec.Context ==
18580 Rec.Context ==
18582 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18583 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18584
18586 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18587 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18588 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18589 if (!FD->getBuiltinID())
18590 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18591 if (auto Context =
18593 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18594 << Context->Decl;
18595 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18596 }
18597 if (FD->isImmediateEscalating() && !FD->isConsteval())
18599
18600 } else {
18602 }
18603 }
18604}
18605
18608 if (!Rec.Lambdas.empty()) {
18610 if (!getLangOpts().CPlusPlus20 &&
18611 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18612 Rec.isUnevaluated() ||
18614 unsigned D;
18615 if (Rec.isUnevaluated()) {
18616 // C++11 [expr.prim.lambda]p2:
18617 // A lambda-expression shall not appear in an unevaluated operand
18618 // (Clause 5).
18619 D = diag::err_lambda_unevaluated_operand;
18620 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18621 // C++1y [expr.const]p2:
18622 // A conditional-expression e is a core constant expression unless the
18623 // evaluation of e, following the rules of the abstract machine, would
18624 // evaluate [...] a lambda-expression.
18625 D = diag::err_lambda_in_constant_expression;
18626 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18627 // C++17 [expr.prim.lamda]p2:
18628 // A lambda-expression shall not appear [...] in a template-argument.
18629 D = diag::err_lambda_in_invalid_context;
18630 } else
18631 llvm_unreachable("Couldn't infer lambda error message.");
18632
18633 for (const auto *L : Rec.Lambdas)
18634 Diag(L->getBeginLoc(), D);
18635 }
18636 }
18637
18638 // Append the collected materialized temporaries into previous context before
18639 // exit if the previous also is a lifetime extending context.
18641 parentEvaluationContext().InLifetimeExtendingContext &&
18642 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18645 }
18646
18648 HandleImmediateInvocations(*this, Rec);
18649
18650 // Warn on any volatile-qualified simple-assignments that are not discarded-
18651 // value expressions nor unevaluated operands (those cases get removed from
18652 // this list by CheckUnusedVolatileAssignment).
18653 for (auto *BO : Rec.VolatileAssignmentLHSs)
18654 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18655 << BO->getType();
18656
18657 // When are coming out of an unevaluated context, clear out any
18658 // temporaries that we may have created as part of the evaluation of
18659 // the expression in that context: they aren't relevant because they
18660 // will never be constructed.
18661 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18663 ExprCleanupObjects.end());
18664 Cleanup = Rec.ParentCleanup;
18667 // Otherwise, merge the contexts together.
18668 } else {
18669 Cleanup.mergeFrom(Rec.ParentCleanup);
18670 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18671 }
18672
18674
18675 // Pop the current expression evaluation context off the stack.
18676 ExprEvalContexts.pop_back();
18677}
18678
18680 ExprCleanupObjects.erase(
18681 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18682 ExprCleanupObjects.end());
18683 Cleanup.reset();
18684 MaybeODRUseExprs.clear();
18685}
18686
18689 if (Result.isInvalid())
18690 return ExprError();
18691 E = Result.get();
18692 if (!E->getType()->isVariablyModifiedType())
18693 return E;
18695}
18696
18697/// Are we in a context that is potentially constant evaluated per C++20
18698/// [expr.const]p12?
18700 /// C++2a [expr.const]p12:
18701 // An expression or conversion is potentially constant evaluated if it is
18702 switch (SemaRef.ExprEvalContexts.back().Context) {
18705
18706 // -- a manifestly constant-evaluated expression,
18710 // -- a potentially-evaluated expression,
18712 // -- an immediate subexpression of a braced-init-list,
18713
18714 // -- [FIXME] an expression of the form & cast-expression that occurs
18715 // within a templated entity
18716 // -- a subexpression of one of the above that is not a subexpression of
18717 // a nested unevaluated operand.
18718 return true;
18719
18722 // Expressions in this context are never evaluated.
18723 return false;
18724 }
18725 llvm_unreachable("Invalid context");
18726}
18727
18728/// Return true if this function has a calling convention that requires mangling
18729/// in the size of the parameter pack.
18731 // These manglings are only applicable for targets whcih use Microsoft
18732 // mangling scheme for C.
18734 return false;
18735
18736 // If this is C++ and this isn't an extern "C" function, parameters do not
18737 // need to be complete. In this case, C++ mangling will apply, which doesn't
18738 // use the size of the parameters.
18739 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18740 return false;
18741
18742 // Stdcall, fastcall, and vectorcall need this special treatment.
18743 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18744 switch (CC) {
18745 case CC_X86StdCall:
18746 case CC_X86FastCall:
18747 case CC_X86VectorCall:
18748 return true;
18749 default:
18750 break;
18751 }
18752 return false;
18753}
18754
18755/// Require that all of the parameter types of function be complete. Normally,
18756/// parameter types are only required to be complete when a function is called
18757/// or defined, but to mangle functions with certain calling conventions, the
18758/// mangler needs to know the size of the parameter list. In this situation,
18759/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18760/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18761/// result in a linker error. Clang doesn't implement this behavior, and instead
18762/// attempts to error at compile time.
18764 SourceLocation Loc) {
18765 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18766 FunctionDecl *FD;
18767 ParmVarDecl *Param;
18768
18769 public:
18770 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18771 : FD(FD), Param(Param) {}
18772
18773 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18774 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18775 StringRef CCName;
18776 switch (CC) {
18777 case CC_X86StdCall:
18778 CCName = "stdcall";
18779 break;
18780 case CC_X86FastCall:
18781 CCName = "fastcall";
18782 break;
18783 case CC_X86VectorCall:
18784 CCName = "vectorcall";
18785 break;
18786 default:
18787 llvm_unreachable("CC does not need mangling");
18788 }
18789
18790 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18791 << Param->getDeclName() << FD->getDeclName() << CCName;
18792 }
18793 };
18794
18795 for (ParmVarDecl *Param : FD->parameters()) {
18796 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18797 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18798 }
18799}
18800
18801namespace {
18802enum class OdrUseContext {
18803 /// Declarations in this context are not odr-used.
18804 None,
18805 /// Declarations in this context are formally odr-used, but this is a
18806 /// dependent context.
18807 Dependent,
18808 /// Declarations in this context are odr-used but not actually used (yet).
18809 FormallyOdrUsed,
18810 /// Declarations in this context are used.
18811 Used
18812};
18813}
18814
18815/// Are we within a context in which references to resolved functions or to
18816/// variables result in odr-use?
18817static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18820
18821 if (Context.isUnevaluated())
18822 return OdrUseContext::None;
18823
18825 return OdrUseContext::Dependent;
18826
18827 if (Context.isDiscardedStatementContext())
18828 return OdrUseContext::FormallyOdrUsed;
18829
18830 else if (Context.Context ==
18832 return OdrUseContext::FormallyOdrUsed;
18833
18834 return OdrUseContext::Used;
18835}
18836
18838 if (!Func->isConstexpr())
18839 return false;
18840
18841 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18842 return true;
18843
18844 // Lambda conversion operators are never user provided.
18845 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18846 return isLambdaConversionOperator(Conv);
18847
18848 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18849 return CCD && CCD->getInheritedConstructor();
18850}
18851
18853 bool MightBeOdrUse) {
18854 assert(Func && "No function?");
18855
18856 Func->setReferenced();
18857
18858 // Recursive functions aren't really used until they're used from some other
18859 // context.
18860 bool IsRecursiveCall = CurContext == Func;
18861
18862 // C++11 [basic.def.odr]p3:
18863 // A function whose name appears as a potentially-evaluated expression is
18864 // odr-used if it is the unique lookup result or the selected member of a
18865 // set of overloaded functions [...].
18866 //
18867 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18868 // can just check that here.
18869 OdrUseContext OdrUse =
18870 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18871 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18872 OdrUse = OdrUseContext::FormallyOdrUsed;
18873
18874 // Trivial default constructors and destructors are never actually used.
18875 // FIXME: What about other special members?
18876 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18877 OdrUse == OdrUseContext::Used) {
18878 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18879 if (Constructor->isDefaultConstructor())
18880 OdrUse = OdrUseContext::FormallyOdrUsed;
18882 OdrUse = OdrUseContext::FormallyOdrUsed;
18883 }
18884
18885 // C++20 [expr.const]p12:
18886 // A function [...] is needed for constant evaluation if it is [...] a
18887 // constexpr function that is named by an expression that is potentially
18888 // constant evaluated
18889 bool NeededForConstantEvaluation =
18892
18893 // Determine whether we require a function definition to exist, per
18894 // C++11 [temp.inst]p3:
18895 // Unless a function template specialization has been explicitly
18896 // instantiated or explicitly specialized, the function template
18897 // specialization is implicitly instantiated when the specialization is
18898 // referenced in a context that requires a function definition to exist.
18899 // C++20 [temp.inst]p7:
18900 // The existence of a definition of a [...] function is considered to
18901 // affect the semantics of the program if the [...] function is needed for
18902 // constant evaluation by an expression
18903 // C++20 [basic.def.odr]p10:
18904 // Every program shall contain exactly one definition of every non-inline
18905 // function or variable that is odr-used in that program outside of a
18906 // discarded statement
18907 // C++20 [special]p1:
18908 // The implementation will implicitly define [defaulted special members]
18909 // if they are odr-used or needed for constant evaluation.
18910 //
18911 // Note that we skip the implicit instantiation of templates that are only
18912 // used in unused default arguments or by recursive calls to themselves.
18913 // This is formally non-conforming, but seems reasonable in practice.
18914 bool NeedDefinition =
18915 !IsRecursiveCall &&
18916 (OdrUse == OdrUseContext::Used ||
18917 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18918
18919 // C++14 [temp.expl.spec]p6:
18920 // If a template [...] is explicitly specialized then that specialization
18921 // shall be declared before the first use of that specialization that would
18922 // cause an implicit instantiation to take place, in every translation unit
18923 // in which such a use occurs
18924 if (NeedDefinition &&
18925 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18926 Func->getMemberSpecializationInfo()))
18928
18929 if (getLangOpts().CUDA)
18930 CUDA().CheckCall(Loc, Func);
18931
18932 // If we need a definition, try to create one.
18933 if (NeedDefinition && !Func->getBody()) {
18936 dyn_cast<CXXConstructorDecl>(Func)) {
18938 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18939 if (Constructor->isDefaultConstructor()) {
18940 if (Constructor->isTrivial() &&
18941 !Constructor->hasAttr<DLLExportAttr>())
18942 return;
18944 } else if (Constructor->isCopyConstructor()) {
18946 } else if (Constructor->isMoveConstructor()) {
18948 }
18949 } else if (Constructor->getInheritedConstructor()) {
18951 }
18952 } else if (CXXDestructorDecl *Destructor =
18953 dyn_cast<CXXDestructorDecl>(Func)) {
18955 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18956 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18957 return;
18959 }
18960 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18961 MarkVTableUsed(Loc, Destructor->getParent());
18962 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18963 if (MethodDecl->isOverloadedOperator() &&
18964 MethodDecl->getOverloadedOperator() == OO_Equal) {
18965 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18966 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18967 if (MethodDecl->isCopyAssignmentOperator())
18968 DefineImplicitCopyAssignment(Loc, MethodDecl);
18969 else if (MethodDecl->isMoveAssignmentOperator())
18970 DefineImplicitMoveAssignment(Loc, MethodDecl);
18971 }
18972 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18973 MethodDecl->getParent()->isLambda()) {
18974 CXXConversionDecl *Conversion =
18975 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18976 if (Conversion->isLambdaToBlockPointerConversion())
18978 else
18980 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18981 MarkVTableUsed(Loc, MethodDecl->getParent());
18982 }
18983
18984 if (Func->isDefaulted() && !Func->isDeleted()) {
18988 }
18989
18990 // Implicit instantiation of function templates and member functions of
18991 // class templates.
18992 if (Func->isImplicitlyInstantiable()) {
18994 Func->getTemplateSpecializationKindForInstantiation();
18995 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18996 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18997 if (FirstInstantiation) {
18998 PointOfInstantiation = Loc;
18999 if (auto *MSI = Func->getMemberSpecializationInfo())
19000 MSI->setPointOfInstantiation(Loc);
19001 // FIXME: Notify listener.
19002 else
19003 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19004 } else if (TSK != TSK_ImplicitInstantiation) {
19005 // Use the point of use as the point of instantiation, instead of the
19006 // point of explicit instantiation (which we track as the actual point
19007 // of instantiation). This gives better backtraces in diagnostics.
19008 PointOfInstantiation = Loc;
19009 }
19010
19011 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19012 Func->isConstexpr()) {
19013 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19014 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19015 CodeSynthesisContexts.size())
19017 std::make_pair(Func, PointOfInstantiation));
19018 else if (Func->isConstexpr())
19019 // Do not defer instantiations of constexpr functions, to avoid the
19020 // expression evaluator needing to call back into Sema if it sees a
19021 // call to such a function.
19022 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19023 else {
19024 Func->setInstantiationIsPending(true);
19025 PendingInstantiations.push_back(
19026 std::make_pair(Func, PointOfInstantiation));
19027 if (llvm::isTimeTraceVerbose()) {
19028 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19029 std::string Name;
19030 llvm::raw_string_ostream OS(Name);
19031 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19032 /*Qualified=*/true);
19033 return Name;
19034 });
19035 }
19036 // Notify the consumer that a function was implicitly instantiated.
19037 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19038 }
19039 }
19040 } else {
19041 // Walk redefinitions, as some of them may be instantiable.
19042 for (auto *i : Func->redecls()) {
19043 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19044 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19045 }
19046 }
19047 });
19048 }
19049
19050 // If a constructor was defined in the context of a default parameter
19051 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19052 // context), its initializers may not be referenced yet.
19053 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19055 *this,
19056 Constructor->isImmediateFunction()
19059 Constructor);
19060 for (CXXCtorInitializer *Init : Constructor->inits()) {
19061 if (Init->isInClassMemberInitializer())
19062 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19063 MarkDeclarationsReferencedInExpr(Init->getInit());
19064 });
19065 }
19066 }
19067
19068 // C++14 [except.spec]p17:
19069 // An exception-specification is considered to be needed when:
19070 // - the function is odr-used or, if it appears in an unevaluated operand,
19071 // would be odr-used if the expression were potentially-evaluated;
19072 //
19073 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19074 // function is a pure virtual function we're calling, and in that case the
19075 // function was selected by overload resolution and we need to resolve its
19076 // exception specification for a different reason.
19077 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19079 ResolveExceptionSpec(Loc, FPT);
19080
19081 // A callee could be called by a host function then by a device function.
19082 // If we only try recording once, we will miss recording the use on device
19083 // side. Therefore keep trying until it is recorded.
19084 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19085 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19087
19088 // If this is the first "real" use, act on that.
19089 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19090 // Keep track of used but undefined functions.
19091 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19092 if (mightHaveNonExternalLinkage(Func))
19093 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19094 else if (Func->getMostRecentDecl()->isInlined() &&
19095 !LangOpts.GNUInline &&
19096 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19097 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19099 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19100 }
19101
19102 // Some x86 Windows calling conventions mangle the size of the parameter
19103 // pack into the name. Computing the size of the parameters requires the
19104 // parameter types to be complete. Check that now.
19107
19108 // In the MS C++ ABI, the compiler emits destructor variants where they are
19109 // used. If the destructor is used here but defined elsewhere, mark the
19110 // virtual base destructors referenced. If those virtual base destructors
19111 // are inline, this will ensure they are defined when emitting the complete
19112 // destructor variant. This checking may be redundant if the destructor is
19113 // provided later in this TU.
19114 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19115 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19116 CXXRecordDecl *Parent = Dtor->getParent();
19117 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19119 }
19120 }
19121
19122 Func->markUsed(Context);
19123 }
19124}
19125
19126/// Directly mark a variable odr-used. Given a choice, prefer to use
19127/// MarkVariableReferenced since it does additional checks and then
19128/// calls MarkVarDeclODRUsed.
19129/// If the variable must be captured:
19130/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19131/// - else capture it in the DeclContext that maps to the
19132/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19133static void
19135 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19136 // Keep track of used but undefined variables.
19137 // FIXME: We shouldn't suppress this warning for static data members.
19138 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19139 assert(Var && "expected a capturable variable");
19140
19142 (!Var->isExternallyVisible() || Var->isInline() ||
19144 !(Var->isStaticDataMember() && Var->hasInit())) {
19146 if (old.isInvalid())
19147 old = Loc;
19148 }
19149 QualType CaptureType, DeclRefType;
19150 if (SemaRef.LangOpts.OpenMP)
19153 /*EllipsisLoc*/ SourceLocation(),
19154 /*BuildAndDiagnose*/ true, CaptureType,
19155 DeclRefType, FunctionScopeIndexToStopAt);
19156
19157 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19158 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19159 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19160 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19161 if (VarTarget == SemaCUDA::CVT_Host &&
19162 (UserTarget == CUDAFunctionTarget::Device ||
19163 UserTarget == CUDAFunctionTarget::HostDevice ||
19164 UserTarget == CUDAFunctionTarget::Global)) {
19165 // Diagnose ODR-use of host global variables in device functions.
19166 // Reference of device global variables in host functions is allowed
19167 // through shadow variables therefore it is not diagnosed.
19168 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19169 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19170 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19172 Var->getType().isConstQualified()
19173 ? diag::note_cuda_const_var_unpromoted
19174 : diag::note_cuda_host_var);
19175 }
19176 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19177 // Also capture __device__ const variables, which are classified
19178 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19179 // an explicit CUDADeviceAttr to distinguish them from plain
19180 // const variables (no __device__), which also get CVT_Both but
19181 // only have an implicit CUDADeviceAttr.
19182 (VarTarget == SemaCUDA::CVT_Both &&
19183 Var->hasAttr<CUDADeviceAttr>() &&
19184 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19185 !Var->hasAttr<CUDASharedAttr>() &&
19186 (UserTarget == CUDAFunctionTarget::Host ||
19187 UserTarget == CUDAFunctionTarget::HostDevice)) {
19188 // Record a CUDA/HIP device side variable if it is ODR-used
19189 // by host code. This is done conservatively, when the variable is
19190 // referenced in any of the following contexts:
19191 // - a non-function context
19192 // - a host function
19193 // - a host device function
19194 // This makes the ODR-use of the device side variable by host code to
19195 // be visible in the device compilation for the compiler to be able to
19196 // emit template variables instantiated by host code only and to
19197 // externalize the static device side variable ODR-used by host code.
19198 if (!Var->hasExternalStorage())
19200 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19201 (!FD || (!FD->getDescribedFunctionTemplate() &&
19205 }
19206 }
19207
19208 V->markUsed(SemaRef.Context);
19209}
19210
19212 SourceLocation Loc,
19213 unsigned CapturingScopeIndex) {
19214 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19215}
19216
19218 SourceLocation loc,
19219 ValueDecl *var) {
19220 DeclContext *VarDC = var->getDeclContext();
19221
19222 // If the parameter still belongs to the translation unit, then
19223 // we're actually just using one parameter in the declaration of
19224 // the next.
19225 if (isa<ParmVarDecl>(var) &&
19227 return;
19228
19229 // For C code, don't diagnose about capture if we're not actually in code
19230 // right now; it's impossible to write a non-constant expression outside of
19231 // function context, so we'll get other (more useful) diagnostics later.
19232 //
19233 // For C++, things get a bit more nasty... it would be nice to suppress this
19234 // diagnostic for certain cases like using a local variable in an array bound
19235 // for a member of a local class, but the correct predicate is not obvious.
19236 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19237 return;
19238
19239 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19240 unsigned ContextKind = 3; // unknown
19241 if (isa<CXXMethodDecl>(VarDC) &&
19242 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19243 ContextKind = 2;
19244 } else if (isa<FunctionDecl>(VarDC)) {
19245 ContextKind = 0;
19246 } else if (isa<BlockDecl>(VarDC)) {
19247 ContextKind = 1;
19248 }
19249
19250 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19251 << var << ValueKind << ContextKind << VarDC;
19252 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19253 << var;
19254
19255 // FIXME: Add additional diagnostic info about class etc. which prevents
19256 // capture.
19257}
19258
19260 ValueDecl *Var,
19261 bool &SubCapturesAreNested,
19262 QualType &CaptureType,
19263 QualType &DeclRefType) {
19264 // Check whether we've already captured it.
19265 if (CSI->CaptureMap.count(Var)) {
19266 // If we found a capture, any subcaptures are nested.
19267 SubCapturesAreNested = true;
19268
19269 // Retrieve the capture type for this variable.
19270 CaptureType = CSI->getCapture(Var).getCaptureType();
19271
19272 // Compute the type of an expression that refers to this variable.
19273 DeclRefType = CaptureType.getNonReferenceType();
19274
19275 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19276 // are mutable in the sense that user can change their value - they are
19277 // private instances of the captured declarations.
19278 const Capture &Cap = CSI->getCapture(Var);
19279 // C++ [expr.prim.lambda]p10:
19280 // The type of such a data member is [...] an lvalue reference to the
19281 // referenced function type if the entity is a reference to a function.
19282 // [...]
19283 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19284 !(isa<LambdaScopeInfo>(CSI) &&
19285 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19287 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19288 DeclRefType.addConst();
19289 return true;
19290 }
19291 return false;
19292}
19293
19294// Only block literals, captured statements, and lambda expressions can
19295// capture; other scopes don't work.
19297 ValueDecl *Var,
19298 SourceLocation Loc,
19299 const bool Diagnose,
19300 Sema &S) {
19303
19304 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19305 if (Underlying) {
19306 if (Underlying->hasLocalStorage() && Diagnose)
19308 }
19309 return nullptr;
19310}
19311
19312// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19313// certain types of variables (unnamed, variably modified types etc.)
19314// so check for eligibility.
19316 SourceLocation Loc, const bool Diagnose,
19317 Sema &S) {
19318
19319 assert((isa<VarDecl, BindingDecl>(Var)) &&
19320 "Only variables and structured bindings can be captured");
19321
19322 bool IsBlock = isa<BlockScopeInfo>(CSI);
19323 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19324
19325 // Lambdas are not allowed to capture unnamed variables
19326 // (e.g. anonymous unions).
19327 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19328 // assuming that's the intent.
19329 if (IsLambda && !Var->getDeclName()) {
19330 if (Diagnose) {
19331 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19332 S.Diag(Var->getLocation(), diag::note_declared_at);
19333 }
19334 return false;
19335 }
19336
19337 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19338 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19339 if (Diagnose) {
19340 S.Diag(Loc, diag::err_ref_vm_type);
19341 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19342 }
19343 return false;
19344 }
19345 // Prohibit structs with flexible array members too.
19346 // We cannot capture what is in the tail end of the struct.
19347 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19348 VTD && VTD->hasFlexibleArrayMember()) {
19349 if (Diagnose) {
19350 if (IsBlock)
19351 S.Diag(Loc, diag::err_ref_flexarray_type);
19352 else
19353 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19354 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19355 }
19356 return false;
19357 }
19358 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19359 // Lambdas and captured statements are not allowed to capture __block
19360 // variables; they don't support the expected semantics.
19361 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19362 if (Diagnose) {
19363 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19364 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19365 }
19366 return false;
19367 }
19368 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19369 if (S.getLangOpts().OpenCL && IsBlock &&
19370 Var->getType()->isBlockPointerType()) {
19371 if (Diagnose)
19372 S.Diag(Loc, diag::err_opencl_block_ref_block);
19373 return false;
19374 }
19375
19376 if (isa<BindingDecl>(Var)) {
19377 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19378 if (Diagnose)
19380 return false;
19381 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19382 S.Diag(Loc, S.LangOpts.CPlusPlus20
19383 ? diag::warn_cxx17_compat_capture_binding
19384 : diag::ext_capture_binding)
19385 << Var;
19386 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19387 }
19388 }
19389
19390 return true;
19391}
19392
19393// Returns true if the capture by block was successful.
19395 SourceLocation Loc, const bool BuildAndDiagnose,
19396 QualType &CaptureType, QualType &DeclRefType,
19397 const bool Nested, Sema &S, bool Invalid) {
19398 bool ByRef = false;
19399
19400 // Blocks are not allowed to capture arrays, excepting OpenCL.
19401 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19402 // (decayed to pointers).
19403 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19404 if (BuildAndDiagnose) {
19405 S.Diag(Loc, diag::err_ref_array_type);
19406 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19407 Invalid = true;
19408 } else {
19409 return false;
19410 }
19411 }
19412
19413 // Forbid the block-capture of autoreleasing variables.
19414 if (!Invalid &&
19416 if (BuildAndDiagnose) {
19417 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19418 << /*block*/ 0;
19419 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19420 Invalid = true;
19421 } else {
19422 return false;
19423 }
19424 }
19425
19426 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19427 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19428 QualType PointeeTy = PT->getPointeeType();
19429
19430 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19432 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19433 if (BuildAndDiagnose) {
19434 SourceLocation VarLoc = Var->getLocation();
19435 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19436 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19437 }
19438 }
19439 }
19440
19441 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19442 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19443 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19444 // Block capture by reference does not change the capture or
19445 // declaration reference types.
19446 ByRef = true;
19447 } else {
19448 // Block capture by copy introduces 'const'.
19449 CaptureType = CaptureType.getNonReferenceType().withConst();
19450 DeclRefType = CaptureType;
19451 }
19452
19453 // Actually capture the variable.
19454 if (BuildAndDiagnose)
19455 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19456 CaptureType, Invalid);
19457
19458 return !Invalid;
19459}
19460
19461/// Capture the given variable in the captured region.
19464 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19465 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19466 Sema &S, bool Invalid) {
19467 // By default, capture variables by reference.
19468 bool ByRef = true;
19469 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19470 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19471 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19472 // Using an LValue reference type is consistent with Lambdas (see below).
19473 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19474 bool HasConst = DeclRefType.isConstQualified();
19475 DeclRefType = DeclRefType.getUnqualifiedType();
19476 // Don't lose diagnostics about assignments to const.
19477 if (HasConst)
19478 DeclRefType.addConst();
19479 }
19480 // Do not capture firstprivates in tasks.
19481 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19482 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19483 return true;
19484 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19485 RSI->OpenMPCaptureLevel);
19486 }
19487
19488 if (ByRef)
19489 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19490 else
19491 CaptureType = DeclRefType;
19492
19493 // Actually capture the variable.
19494 if (BuildAndDiagnose)
19495 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19496 Loc, SourceLocation(), CaptureType, Invalid);
19497
19498 return !Invalid;
19499}
19500
19501/// Capture the given variable in the lambda.
19503 SourceLocation Loc, const bool BuildAndDiagnose,
19504 QualType &CaptureType, QualType &DeclRefType,
19505 const bool RefersToCapturedVariable,
19506 const TryCaptureKind Kind,
19507 SourceLocation EllipsisLoc, const bool IsTopScope,
19508 Sema &S, bool Invalid) {
19509 // Determine whether we are capturing by reference or by value.
19510 bool ByRef = false;
19511 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19512 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19513 } else {
19514 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19515 }
19516
19517 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19519 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19520 Invalid = true;
19521 }
19522
19523 // Compute the type of the field that will capture this variable.
19524 if (ByRef) {
19525 // C++11 [expr.prim.lambda]p15:
19526 // An entity is captured by reference if it is implicitly or
19527 // explicitly captured but not captured by copy. It is
19528 // unspecified whether additional unnamed non-static data
19529 // members are declared in the closure type for entities
19530 // captured by reference.
19531 //
19532 // FIXME: It is not clear whether we want to build an lvalue reference
19533 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19534 // to do the former, while EDG does the latter. Core issue 1249 will
19535 // clarify, but for now we follow GCC because it's a more permissive and
19536 // easily defensible position.
19537 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19538 } else {
19539 // C++11 [expr.prim.lambda]p14:
19540 // For each entity captured by copy, an unnamed non-static
19541 // data member is declared in the closure type. The
19542 // declaration order of these members is unspecified. The type
19543 // of such a data member is the type of the corresponding
19544 // captured entity if the entity is not a reference to an
19545 // object, or the referenced type otherwise. [Note: If the
19546 // captured entity is a reference to a function, the
19547 // corresponding data member is also a reference to a
19548 // function. - end note ]
19549 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19550 if (!RefType->getPointeeType()->isFunctionType())
19551 CaptureType = RefType->getPointeeType();
19552 }
19553
19554 // Forbid the lambda copy-capture of autoreleasing variables.
19555 if (!Invalid &&
19557 if (BuildAndDiagnose) {
19558 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19559 S.Diag(Var->getLocation(), diag::note_previous_decl)
19560 << Var->getDeclName();
19561 Invalid = true;
19562 } else {
19563 return false;
19564 }
19565 }
19566
19567 // Make sure that by-copy captures are of a complete and non-abstract type.
19568 if (!Invalid && BuildAndDiagnose) {
19569 if (!CaptureType->isDependentType() &&
19571 Loc, CaptureType,
19572 diag::err_capture_of_incomplete_or_sizeless_type,
19573 Var->getDeclName()))
19574 Invalid = true;
19575 else if (S.RequireNonAbstractType(Loc, CaptureType,
19576 diag::err_capture_of_abstract_type))
19577 Invalid = true;
19578 }
19579 }
19580
19581 // Compute the type of a reference to this captured variable.
19582 if (ByRef)
19583 DeclRefType = CaptureType.getNonReferenceType();
19584 else {
19585 // C++ [expr.prim.lambda]p5:
19586 // The closure type for a lambda-expression has a public inline
19587 // function call operator [...]. This function call operator is
19588 // declared const (9.3.1) if and only if the lambda-expression's
19589 // parameter-declaration-clause is not followed by mutable.
19590 DeclRefType = CaptureType.getNonReferenceType();
19591 bool Const = LSI->lambdaCaptureShouldBeConst();
19592 // C++ [expr.prim.lambda]p10:
19593 // The type of such a data member is [...] an lvalue reference to the
19594 // referenced function type if the entity is a reference to a function.
19595 // [...]
19596 if (Const && !CaptureType->isReferenceType() &&
19597 !DeclRefType->isFunctionType())
19598 DeclRefType.addConst();
19599 }
19600
19601 // Add the capture.
19602 if (BuildAndDiagnose)
19603 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19604 Loc, EllipsisLoc, CaptureType, Invalid);
19605
19606 return !Invalid;
19607}
19608
19610 const ASTContext &Context) {
19611 // Offer a Copy fix even if the type is dependent.
19612 if (Var->getType()->isDependentType())
19613 return true;
19615 if (T.isTriviallyCopyableType(Context))
19616 return true;
19617 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19618
19619 if (!(RD = RD->getDefinition()))
19620 return false;
19621 if (RD->hasSimpleCopyConstructor())
19622 return true;
19623 if (RD->hasUserDeclaredCopyConstructor())
19624 for (CXXConstructorDecl *Ctor : RD->ctors())
19625 if (Ctor->isCopyConstructor())
19626 return !Ctor->isDeleted();
19627 }
19628 return false;
19629}
19630
19631/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19632/// default capture. Fixes may be omitted if they aren't allowed by the
19633/// standard, for example we can't emit a default copy capture fix-it if we
19634/// already explicitly copy capture capture another variable.
19636 ValueDecl *Var) {
19638 // Don't offer Capture by copy of default capture by copy fixes if Var is
19639 // known not to be copy constructible.
19640 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19641
19642 SmallString<32> FixBuffer;
19643 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19644 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19645 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19646 if (ShouldOfferCopyFix) {
19647 // Offer fixes to insert an explicit capture for the variable.
19648 // [] -> [VarName]
19649 // [OtherCapture] -> [OtherCapture, VarName]
19650 FixBuffer.assign({Separator, Var->getName()});
19651 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19652 << Var << /*value*/ 0
19653 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19654 }
19655 // As above but capture by reference.
19656 FixBuffer.assign({Separator, "&", Var->getName()});
19657 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19658 << Var << /*reference*/ 1
19659 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19660 }
19661
19662 // Only try to offer default capture if there are no captures excluding this
19663 // and init captures.
19664 // [this]: OK.
19665 // [X = Y]: OK.
19666 // [&A, &B]: Don't offer.
19667 // [A, B]: Don't offer.
19668 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19669 return !C.isThisCapture() && !C.isInitCapture();
19670 }))
19671 return;
19672
19673 // The default capture specifiers, '=' or '&', must appear first in the
19674 // capture body.
19675 SourceLocation DefaultInsertLoc =
19677
19678 if (ShouldOfferCopyFix) {
19679 bool CanDefaultCopyCapture = true;
19680 // [=, *this] OK since c++17
19681 // [=, this] OK since c++20
19682 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19683 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19685 : false;
19686 // We can't use default capture by copy if any captures already specified
19687 // capture by copy.
19688 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19689 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19690 })) {
19691 FixBuffer.assign({"=", Separator});
19692 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19693 << /*value*/ 0
19694 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19695 }
19696 }
19697
19698 // We can't use default capture by reference if any captures already specified
19699 // capture by reference.
19700 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19701 return !C.isInitCapture() && C.isReferenceCapture() &&
19702 !C.isThisCapture();
19703 })) {
19704 FixBuffer.assign({"&", Separator});
19705 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19706 << /*reference*/ 1
19707 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19708 }
19709}
19710
19712 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19713 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19714 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19715 // An init-capture is notionally from the context surrounding its
19716 // declaration, but its parent DC is the lambda class.
19717 DeclContext *VarDC = Var->getDeclContext();
19718 DeclContext *DC = CurContext;
19719
19720 // Skip past RequiresExprBodys because they don't constitute function scopes.
19721 while (DC->isRequiresExprBody())
19722 DC = DC->getParent();
19723
19724 // tryCaptureVariable is called every time a DeclRef is formed,
19725 // it can therefore have non-negigible impact on performances.
19726 // For local variables and when there is no capturing scope,
19727 // we can bailout early.
19728 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19729 return true;
19730
19731 // Exception: Function parameters are not tied to the function's DeclContext
19732 // until we enter the function definition. Capturing them anyway would result
19733 // in an out-of-bounds error while traversing DC and its parents.
19734 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19735 return true;
19736
19737 const auto *VD = dyn_cast<VarDecl>(Var);
19738 if (VD) {
19739 if (VD->isInitCapture())
19740 VarDC = VarDC->getParent();
19741 } else {
19743 }
19744 assert(VD && "Cannot capture a null variable");
19745
19746 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19747 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19748 // We need to sync up the Declaration Context with the
19749 // FunctionScopeIndexToStopAt
19750 if (FunctionScopeIndexToStopAt) {
19751 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19752 unsigned FSIndex = FunctionScopes.size() - 1;
19753 // When we're parsing the lambda parameter list, the current DeclContext is
19754 // NOT the lambda but its parent. So move away the current LSI before
19755 // aligning DC and FunctionScopeIndexToStopAt.
19756 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19757 FSIndex && LSI && !LSI->AfterParameterList)
19758 --FSIndex;
19759 assert(MaxFunctionScopesIndex <= FSIndex &&
19760 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19761 "FunctionScopes.");
19762 while (FSIndex != MaxFunctionScopesIndex) {
19764 --FSIndex;
19765 }
19766 }
19767
19768 // Capture global variables if it is required to use private copy of this
19769 // variable.
19770 bool IsGlobal = !VD->hasLocalStorage();
19771 if (IsGlobal && !(LangOpts.OpenMP &&
19772 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19773 MaxFunctionScopesIndex)))
19774 return true;
19775
19776 if (isa<VarDecl>(Var))
19777 Var = cast<VarDecl>(Var->getCanonicalDecl());
19778
19779 // Walk up the stack to determine whether we can capture the variable,
19780 // performing the "simple" checks that don't depend on type. We stop when
19781 // we've either hit the declared scope of the variable or find an existing
19782 // capture of that variable. We start from the innermost capturing-entity
19783 // (the DC) and ensure that all intervening capturing-entities
19784 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19785 // declcontext can either capture the variable or have already captured
19786 // the variable.
19787 CaptureType = Var->getType();
19788 DeclRefType = CaptureType.getNonReferenceType();
19789 bool Nested = false;
19790 bool Explicit = (Kind != TryCaptureKind::Implicit);
19791 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19792 do {
19793
19794 LambdaScopeInfo *LSI = nullptr;
19795 if (!FunctionScopes.empty())
19796 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19797 FunctionScopes[FunctionScopesIndex]);
19798
19799 bool IsInScopeDeclarationContext =
19800 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19801
19802 if (LSI && !LSI->AfterParameterList) {
19803 // This allows capturing parameters from a default value which does not
19804 // seems correct
19805 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19806 return true;
19807 }
19808 // If the variable is declared in the current context, there is no need to
19809 // capture it.
19810 if (IsInScopeDeclarationContext &&
19811 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19812 return true;
19813
19814 // Only block literals, captured statements, and lambda expressions can
19815 // capture; other scopes don't work.
19816 DeclContext *ParentDC =
19817 !IsInScopeDeclarationContext
19818 ? DC->getParent()
19819 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19820 BuildAndDiagnose, *this);
19821 // We need to check for the parent *first* because, if we *have*
19822 // private-captured a global variable, we need to recursively capture it in
19823 // intermediate blocks, lambdas, etc.
19824 if (!ParentDC) {
19825 if (IsGlobal) {
19826 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19827 break;
19828 }
19829 return true;
19830 }
19831
19832 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19834
19835 // Check whether we've already captured it.
19836 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19837 DeclRefType)) {
19838 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19839 break;
19840 }
19841
19842 // When evaluating some attributes (like enable_if) we might refer to a
19843 // function parameter appertaining to the same declaration as that
19844 // attribute.
19845 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19846 Parm && Parm->getDeclContext() == DC)
19847 return true;
19848
19849 // If we are instantiating a generic lambda call operator body,
19850 // we do not want to capture new variables. What was captured
19851 // during either a lambdas transformation or initial parsing
19852 // should be used.
19854 if (BuildAndDiagnose) {
19857 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19858 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19859 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19860 buildLambdaCaptureFixit(*this, LSI, Var);
19861 } else
19863 }
19864 return true;
19865 }
19866
19867 // Try to capture variable-length arrays types.
19868 if (Var->getType()->isVariablyModifiedType()) {
19869 // We're going to walk down into the type and look for VLA
19870 // expressions.
19871 QualType QTy = Var->getType();
19872 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19873 QTy = PVD->getOriginalType();
19875 }
19876
19877 if (getLangOpts().OpenMP) {
19878 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19879 // OpenMP private variables should not be captured in outer scope, so
19880 // just break here. Similarly, global variables that are captured in a
19881 // target region should not be captured outside the scope of the region.
19882 if (RSI->CapRegionKind == CR_OpenMP) {
19883 // FIXME: We should support capturing structured bindings in OpenMP.
19884 if (isa<BindingDecl>(Var)) {
19885 if (BuildAndDiagnose) {
19886 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19887 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19888 }
19889 return true;
19890 }
19891 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19892 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19893 // If the variable is private (i.e. not captured) and has variably
19894 // modified type, we still need to capture the type for correct
19895 // codegen in all regions, associated with the construct. Currently,
19896 // it is captured in the innermost captured region only.
19897 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19898 Var->getType()->isVariablyModifiedType()) {
19899 QualType QTy = Var->getType();
19900 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19901 QTy = PVD->getOriginalType();
19902 for (int I = 1,
19903 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19904 I < E; ++I) {
19905 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19906 FunctionScopes[FunctionScopesIndex - I]);
19907 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19908 "Wrong number of captured regions associated with the "
19909 "OpenMP construct.");
19910 captureVariablyModifiedType(Context, QTy, OuterRSI);
19911 }
19912 }
19913 bool IsTargetCap =
19914 IsOpenMPPrivateDecl != OMPC_private &&
19915 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19916 RSI->OpenMPCaptureLevel);
19917 // Do not capture global if it is not privatized in outer regions.
19918 bool IsGlobalCap =
19919 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19920 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19921
19922 // When we detect target captures we are looking from inside the
19923 // target region, therefore we need to propagate the capture from the
19924 // enclosing region. Therefore, the capture is not initially nested.
19925 if (IsTargetCap)
19926 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19927 RSI->OpenMPLevel);
19928
19929 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19930 (IsGlobal && !IsGlobalCap)) {
19931 Nested = !IsTargetCap;
19932 bool HasConst = DeclRefType.isConstQualified();
19933 DeclRefType = DeclRefType.getUnqualifiedType();
19934 // Don't lose diagnostics about assignments to const.
19935 if (HasConst)
19936 DeclRefType.addConst();
19937 CaptureType = Context.getLValueReferenceType(DeclRefType);
19938 break;
19939 }
19940 }
19941 }
19942 }
19944 // No capture-default, and this is not an explicit capture
19945 // so cannot capture this variable.
19946 if (BuildAndDiagnose) {
19947 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19948 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19949 auto *LSI = cast<LambdaScopeInfo>(CSI);
19950 if (LSI->Lambda) {
19951 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19952 buildLambdaCaptureFixit(*this, LSI, Var);
19953 }
19954 // FIXME: If we error out because an outer lambda can not implicitly
19955 // capture a variable that an inner lambda explicitly captures, we
19956 // should have the inner lambda do the explicit capture - because
19957 // it makes for cleaner diagnostics later. This would purely be done
19958 // so that the diagnostic does not misleadingly claim that a variable
19959 // can not be captured by a lambda implicitly even though it is captured
19960 // explicitly. Suggestion:
19961 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19962 // at the function head
19963 // - cache the StartingDeclContext - this must be a lambda
19964 // - captureInLambda in the innermost lambda the variable.
19965 }
19966 return true;
19967 }
19968 Explicit = false;
19969 FunctionScopesIndex--;
19970 if (IsInScopeDeclarationContext)
19971 DC = ParentDC;
19972 } while (!VarDC->Equals(DC));
19973
19974 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19975 // computing the type of the capture at each step, checking type-specific
19976 // requirements, and adding captures if requested.
19977 // If the variable had already been captured previously, we start capturing
19978 // at the lambda nested within that one.
19979 bool Invalid = false;
19980 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19981 ++I) {
19983
19984 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19985 // certain types of variables (unnamed, variably modified types etc.)
19986 // so check for eligibility.
19987 if (!Invalid)
19988 Invalid =
19989 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19990
19991 // After encountering an error, if we're actually supposed to capture, keep
19992 // capturing in nested contexts to suppress any follow-on diagnostics.
19993 if (Invalid && !BuildAndDiagnose)
19994 return true;
19995
19996 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19997 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19998 DeclRefType, Nested, *this, Invalid);
19999 Nested = true;
20000 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20002 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20003 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20004 Nested = true;
20005 } else {
20007 Invalid =
20008 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20009 DeclRefType, Nested, Kind, EllipsisLoc,
20010 /*IsTopScope*/ I == N - 1, *this, Invalid);
20011 Nested = true;
20012 }
20013
20014 if (Invalid && !BuildAndDiagnose)
20015 return true;
20016 }
20017 return Invalid;
20018}
20019
20021 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20022 QualType CaptureType;
20023 QualType DeclRefType;
20024 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20025 /*BuildAndDiagnose=*/true, CaptureType,
20026 DeclRefType, nullptr);
20027}
20028
20030 QualType CaptureType;
20031 QualType DeclRefType;
20032 return !tryCaptureVariable(
20034 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20035}
20036
20038 assert(Var && "Null value cannot be captured");
20039
20040 QualType CaptureType;
20041 QualType DeclRefType;
20042
20043 // Determine whether we can capture this variable.
20045 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20046 nullptr))
20047 return QualType();
20048
20049 return DeclRefType;
20050}
20051
20052namespace {
20053// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20054// The produced TemplateArgumentListInfo* points to data stored within this
20055// object, so should only be used in contexts where the pointer will not be
20056// used after the CopiedTemplateArgs object is destroyed.
20057class CopiedTemplateArgs {
20058 bool HasArgs;
20059 TemplateArgumentListInfo TemplateArgStorage;
20060public:
20061 template<typename RefExpr>
20062 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20063 if (HasArgs)
20064 E->copyTemplateArgumentsInto(TemplateArgStorage);
20065 }
20066 operator TemplateArgumentListInfo*()
20067#ifdef __has_cpp_attribute
20068#if __has_cpp_attribute(clang::lifetimebound)
20069 [[clang::lifetimebound]]
20070#endif
20071#endif
20072 {
20073 return HasArgs ? &TemplateArgStorage : nullptr;
20074 }
20075};
20076}
20077
20078/// Walk the set of potential results of an expression and mark them all as
20079/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20080///
20081/// \return A new expression if we found any potential results, ExprEmpty() if
20082/// not, and ExprError() if we diagnosed an error.
20084 NonOdrUseReason NOUR) {
20085 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20086 // an object that satisfies the requirements for appearing in a
20087 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20088 // is immediately applied." This function handles the lvalue-to-rvalue
20089 // conversion part.
20090 //
20091 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20092 // transform it into the relevant kind of non-odr-use node and rebuild the
20093 // tree of nodes leading to it.
20094 //
20095 // This is a mini-TreeTransform that only transforms a restricted subset of
20096 // nodes (and only certain operands of them).
20097
20098 // Rebuild a subexpression.
20099 auto Rebuild = [&](Expr *Sub) {
20100 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20101 };
20102
20103 // Check whether a potential result satisfies the requirements of NOUR.
20104 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20105 // Any entity other than a VarDecl is always odr-used whenever it's named
20106 // in a potentially-evaluated expression.
20107 auto *VD = dyn_cast<VarDecl>(D);
20108 if (!VD)
20109 return true;
20110
20111 // C++2a [basic.def.odr]p4:
20112 // A variable x whose name appears as a potentially-evalauted expression
20113 // e is odr-used by e unless
20114 // -- x is a reference that is usable in constant expressions, or
20115 // -- x is a variable of non-reference type that is usable in constant
20116 // expressions and has no mutable subobjects, and e is an element of
20117 // the set of potential results of an expression of
20118 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20119 // conversion is applied, or
20120 // -- x is a variable of non-reference type, and e is an element of the
20121 // set of potential results of a discarded-value expression to which
20122 // the lvalue-to-rvalue conversion is not applied
20123 //
20124 // We check the first bullet and the "potentially-evaluated" condition in
20125 // BuildDeclRefExpr. We check the type requirements in the second bullet
20126 // in CheckLValueToRValueConversionOperand below.
20127 switch (NOUR) {
20128 case NOUR_None:
20129 case NOUR_Unevaluated:
20130 llvm_unreachable("unexpected non-odr-use-reason");
20131
20132 case NOUR_Constant:
20133 // Constant references were handled when they were built.
20134 if (VD->getType()->isReferenceType())
20135 return true;
20136 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20137 if (RD->hasDefinition() && RD->hasMutableFields())
20138 return true;
20139 if (!VD->isUsableInConstantExpressions(S.Context))
20140 return true;
20141 break;
20142
20143 case NOUR_Discarded:
20144 if (VD->getType()->isReferenceType())
20145 return true;
20146 break;
20147 }
20148 return false;
20149 };
20150
20151 // Check whether this expression may be odr-used in CUDA/HIP.
20152 auto MaybeCUDAODRUsed = [&]() -> bool {
20153 if (!S.LangOpts.CUDA)
20154 return false;
20155 LambdaScopeInfo *LSI = S.getCurLambda();
20156 if (!LSI)
20157 return false;
20158 auto *DRE = dyn_cast<DeclRefExpr>(E);
20159 if (!DRE)
20160 return false;
20161 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20162 if (!VD)
20163 return false;
20164 return LSI->CUDAPotentialODRUsedVars.count(VD);
20165 };
20166
20167 // Mark that this expression does not constitute an odr-use.
20168 auto MarkNotOdrUsed = [&] {
20169 if (!MaybeCUDAODRUsed()) {
20170 S.MaybeODRUseExprs.remove(E);
20171 if (LambdaScopeInfo *LSI = S.getCurLambda())
20172 LSI->markVariableExprAsNonODRUsed(E);
20173 }
20174 };
20175
20176 // C++2a [basic.def.odr]p2:
20177 // The set of potential results of an expression e is defined as follows:
20178 switch (E->getStmtClass()) {
20179 // -- If e is an id-expression, ...
20180 case Expr::DeclRefExprClass: {
20181 auto *DRE = cast<DeclRefExpr>(E);
20182 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20183 break;
20184
20185 // Rebuild as a non-odr-use DeclRefExpr.
20186 MarkNotOdrUsed();
20187 return DeclRefExpr::Create(
20188 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20189 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20190 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20191 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20192 }
20193
20194 case Expr::FunctionParmPackExprClass: {
20195 auto *FPPE = cast<FunctionParmPackExpr>(E);
20196 // If any of the declarations in the pack is odr-used, then the expression
20197 // as a whole constitutes an odr-use.
20198 for (ValueDecl *D : *FPPE)
20199 if (IsPotentialResultOdrUsed(D))
20200 return ExprEmpty();
20201
20202 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20203 // nothing cares about whether we marked this as an odr-use, but it might
20204 // be useful for non-compiler tools.
20205 MarkNotOdrUsed();
20206 break;
20207 }
20208
20209 // -- If e is a subscripting operation with an array operand...
20210 case Expr::ArraySubscriptExprClass: {
20211 auto *ASE = cast<ArraySubscriptExpr>(E);
20212 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20213 if (!OldBase->getType()->isArrayType())
20214 break;
20215 ExprResult Base = Rebuild(OldBase);
20216 if (!Base.isUsable())
20217 return Base;
20218 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20219 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20220 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20221 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20222 ASE->getRBracketLoc());
20223 }
20224
20225 case Expr::MemberExprClass: {
20226 auto *ME = cast<MemberExpr>(E);
20227 // -- If e is a class member access expression [...] naming a non-static
20228 // data member...
20229 if (isa<FieldDecl>(ME->getMemberDecl())) {
20230 ExprResult Base = Rebuild(ME->getBase());
20231 if (!Base.isUsable())
20232 return Base;
20233 return MemberExpr::Create(
20234 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20235 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20236 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20237 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20238 ME->getObjectKind(), ME->isNonOdrUse());
20239 }
20240
20241 if (ME->getMemberDecl()->isCXXInstanceMember())
20242 break;
20243
20244 // -- If e is a class member access expression naming a static data member,
20245 // ...
20246 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20247 break;
20248
20249 // Rebuild as a non-odr-use MemberExpr.
20250 MarkNotOdrUsed();
20251 return MemberExpr::Create(
20252 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20253 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20254 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20255 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20256 }
20257
20258 case Expr::BinaryOperatorClass: {
20259 auto *BO = cast<BinaryOperator>(E);
20260 Expr *LHS = BO->getLHS();
20261 Expr *RHS = BO->getRHS();
20262 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20263 if (BO->getOpcode() == BO_PtrMemD) {
20264 ExprResult Sub = Rebuild(LHS);
20265 if (!Sub.isUsable())
20266 return Sub;
20267 BO->setLHS(Sub.get());
20268 // -- If e is a comma expression, ...
20269 } else if (BO->getOpcode() == BO_Comma) {
20270 ExprResult Sub = Rebuild(RHS);
20271 if (!Sub.isUsable())
20272 return Sub;
20273 BO->setRHS(Sub.get());
20274 } else {
20275 break;
20276 }
20277 return ExprResult(BO);
20278 }
20279
20280 // -- If e has the form (e1)...
20281 case Expr::ParenExprClass: {
20282 auto *PE = cast<ParenExpr>(E);
20283 ExprResult Sub = Rebuild(PE->getSubExpr());
20284 if (!Sub.isUsable())
20285 return Sub;
20286 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20287 }
20288
20289 // -- If e is a glvalue conditional expression, ...
20290 // We don't apply this to a binary conditional operator. FIXME: Should we?
20291 case Expr::ConditionalOperatorClass: {
20292 auto *CO = cast<ConditionalOperator>(E);
20293 ExprResult LHS = Rebuild(CO->getLHS());
20294 if (LHS.isInvalid())
20295 return ExprError();
20296 ExprResult RHS = Rebuild(CO->getRHS());
20297 if (RHS.isInvalid())
20298 return ExprError();
20299 if (!LHS.isUsable() && !RHS.isUsable())
20300 return ExprEmpty();
20301 if (!LHS.isUsable())
20302 LHS = CO->getLHS();
20303 if (!RHS.isUsable())
20304 RHS = CO->getRHS();
20305 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20306 CO->getCond(), LHS.get(), RHS.get());
20307 }
20308
20309 // [Clang extension]
20310 // -- If e has the form __extension__ e1...
20311 case Expr::UnaryOperatorClass: {
20312 auto *UO = cast<UnaryOperator>(E);
20313 if (UO->getOpcode() != UO_Extension)
20314 break;
20315 ExprResult Sub = Rebuild(UO->getSubExpr());
20316 if (!Sub.isUsable())
20317 return Sub;
20318 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20319 Sub.get());
20320 }
20321
20322 // [Clang extension]
20323 // -- If e has the form _Generic(...), the set of potential results is the
20324 // union of the sets of potential results of the associated expressions.
20325 case Expr::GenericSelectionExprClass: {
20326 auto *GSE = cast<GenericSelectionExpr>(E);
20327
20328 SmallVector<Expr *, 4> AssocExprs;
20329 bool AnyChanged = false;
20330 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20331 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20332 if (AssocExpr.isInvalid())
20333 return ExprError();
20334 if (AssocExpr.isUsable()) {
20335 AssocExprs.push_back(AssocExpr.get());
20336 AnyChanged = true;
20337 } else {
20338 AssocExprs.push_back(OrigAssocExpr);
20339 }
20340 }
20341
20342 void *ExOrTy = nullptr;
20343 bool IsExpr = GSE->isExprPredicate();
20344 if (IsExpr)
20345 ExOrTy = GSE->getControllingExpr();
20346 else
20347 ExOrTy = GSE->getControllingType();
20348 return AnyChanged ? S.CreateGenericSelectionExpr(
20349 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20350 GSE->getRParenLoc(), IsExpr, ExOrTy,
20351 GSE->getAssocTypeSourceInfos(), AssocExprs)
20352 : ExprEmpty();
20353 }
20354
20355 // [Clang extension]
20356 // -- If e has the form __builtin_choose_expr(...), the set of potential
20357 // results is the union of the sets of potential results of the
20358 // second and third subexpressions.
20359 case Expr::ChooseExprClass: {
20360 auto *CE = cast<ChooseExpr>(E);
20361
20362 ExprResult LHS = Rebuild(CE->getLHS());
20363 if (LHS.isInvalid())
20364 return ExprError();
20365
20366 ExprResult RHS = Rebuild(CE->getLHS());
20367 if (RHS.isInvalid())
20368 return ExprError();
20369
20370 if (!LHS.get() && !RHS.get())
20371 return ExprEmpty();
20372 if (!LHS.isUsable())
20373 LHS = CE->getLHS();
20374 if (!RHS.isUsable())
20375 RHS = CE->getRHS();
20376
20377 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20378 RHS.get(), CE->getRParenLoc());
20379 }
20380
20381 // Step through non-syntactic nodes.
20382 case Expr::ConstantExprClass: {
20383 auto *CE = cast<ConstantExpr>(E);
20384 ExprResult Sub = Rebuild(CE->getSubExpr());
20385 if (!Sub.isUsable())
20386 return Sub;
20387 return ConstantExpr::Create(S.Context, Sub.get());
20388 }
20389
20390 // We could mostly rely on the recursive rebuilding to rebuild implicit
20391 // casts, but not at the top level, so rebuild them here.
20392 case Expr::ImplicitCastExprClass: {
20393 auto *ICE = cast<ImplicitCastExpr>(E);
20394 // Only step through the narrow set of cast kinds we expect to encounter.
20395 // Anything else suggests we've left the region in which potential results
20396 // can be found.
20397 switch (ICE->getCastKind()) {
20398 case CK_NoOp:
20399 case CK_DerivedToBase:
20400 case CK_UncheckedDerivedToBase: {
20401 ExprResult Sub = Rebuild(ICE->getSubExpr());
20402 if (!Sub.isUsable())
20403 return Sub;
20404 CXXCastPath Path(ICE->path());
20405 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20406 ICE->getValueKind(), &Path);
20407 }
20408
20409 default:
20410 break;
20411 }
20412 break;
20413 }
20414
20415 default:
20416 break;
20417 }
20418
20419 // Can't traverse through this node. Nothing to do.
20420 return ExprEmpty();
20421}
20422
20424 // Check whether the operand is or contains an object of non-trivial C union
20425 // type.
20426 if (E->getType().isVolatileQualified() &&
20432
20433 // C++2a [basic.def.odr]p4:
20434 // [...] an expression of non-volatile-qualified non-class type to which
20435 // the lvalue-to-rvalue conversion is applied [...]
20436 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20437 return E;
20438
20441 if (Result.isInvalid())
20442 return ExprError();
20443 return Result.get() ? Result : E;
20444}
20445
20447 if (!Res.isUsable())
20448 return Res;
20449
20450 // If a constant-expression is a reference to a variable where we delay
20451 // deciding whether it is an odr-use, just assume we will apply the
20452 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20453 // (a non-type template argument), we have special handling anyway.
20455}
20456
20458 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20459 // call.
20460 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20461 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20462
20463 for (Expr *E : LocalMaybeODRUseExprs) {
20464 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20465 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20466 DRE->getLocation(), *this);
20467 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20468 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20469 *this);
20470 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20471 for (ValueDecl *VD : *FP)
20472 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20473 } else {
20474 llvm_unreachable("Unexpected expression");
20475 }
20476 }
20477
20478 assert(MaybeODRUseExprs.empty() &&
20479 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20480}
20481
20483 ValueDecl *Var, Expr *E) {
20485 if (!VD)
20486 return;
20487
20488 const bool RefersToEnclosingScope =
20489 (SemaRef.CurContext != VD->getDeclContext() &&
20491 if (RefersToEnclosingScope) {
20492 LambdaScopeInfo *const LSI =
20493 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20494 if (LSI && (!LSI->CallOperator ||
20495 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20496 // If a variable could potentially be odr-used, defer marking it so
20497 // until we finish analyzing the full expression for any
20498 // lvalue-to-rvalue
20499 // or discarded value conversions that would obviate odr-use.
20500 // Add it to the list of potential captures that will be analyzed
20501 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20502 // unless the variable is a reference that was initialized by a constant
20503 // expression (this will never need to be captured or odr-used).
20504 //
20505 // FIXME: We can simplify this a lot after implementing P0588R1.
20506 assert(E && "Capture variable should be used in an expression.");
20507 if (!Var->getType()->isReferenceType() ||
20510 }
20511 }
20512}
20513
20515 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20516 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20517 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20519 "Invalid Expr argument to DoMarkVarDeclReferenced");
20520 Var->setReferenced();
20521
20522 if (Var->isInvalidDecl())
20523 return;
20524
20525 auto *MSI = Var->getMemberSpecializationInfo();
20526 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20528
20529 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20530 bool UsableInConstantExpr =
20532
20533 // Only track variables with internal linkage or local scope.
20534 // Use canonical decl so in-class declarations and out-of-class definitions
20535 // of static data members in anonymous namespaces are tracked as a single
20536 // entry.
20537 const VarDecl *CanonVar = Var->getCanonicalDecl();
20538 if ((CanonVar->isLocalVarDeclOrParm() ||
20539 CanonVar->isInternalLinkageFileVar()) &&
20540 !CanonVar->hasExternalStorage()) {
20541 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20542 }
20543
20544 // C++20 [expr.const]p12:
20545 // A variable [...] is needed for constant evaluation if it is [...] a
20546 // variable whose name appears as a potentially constant evaluated
20547 // expression that is either a contexpr variable or is of non-volatile
20548 // const-qualified integral type or of reference type
20549 bool NeededForConstantEvaluation =
20550 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20551
20552 bool NeedDefinition =
20553 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20554 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20555 Var->getType()->isUndeducedType());
20556
20558 "Can't instantiate a partial template specialization.");
20559
20560 // If this might be a member specialization of a static data member, check
20561 // the specialization is visible. We already did the checks for variable
20562 // template specializations when we created them.
20563 if (NeedDefinition && TSK != TSK_Undeclared &&
20566
20567 // Perform implicit instantiation of static data members, static data member
20568 // templates of class templates, and variable template specializations. Delay
20569 // instantiations of variable templates, except for those that could be used
20570 // in a constant expression.
20571 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20572 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20573 // instantiation declaration if a variable is usable in a constant
20574 // expression (among other cases).
20575 bool TryInstantiating =
20577 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20578
20579 if (TryInstantiating) {
20580 SourceLocation PointOfInstantiation =
20581 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20582 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20583 if (FirstInstantiation) {
20584 PointOfInstantiation = Loc;
20585 if (MSI)
20586 MSI->setPointOfInstantiation(PointOfInstantiation);
20587 // FIXME: Notify listener.
20588 else
20589 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20590 }
20591
20592 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20593 // Do not defer instantiations of variables that could be used in a
20594 // constant expression.
20595 // The type deduction also needs a complete initializer.
20596 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20597 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20598 });
20599
20600 // The size of an incomplete array type can be updated by
20601 // instantiating the initializer. The DeclRefExpr's type should be
20602 // updated accordingly too, or users of it would be confused!
20603 if (E)
20605
20606 // Re-set the member to trigger a recomputation of the dependence bits
20607 // for the expression.
20608 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20609 DRE->setDecl(DRE->getDecl());
20610 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20611 ME->setMemberDecl(ME->getMemberDecl());
20612 } else if (FirstInstantiation) {
20614 .push_back(std::make_pair(Var, PointOfInstantiation));
20615 } else {
20616 bool Inserted = false;
20617 for (auto &I : SemaRef.SavedPendingInstantiations) {
20618 auto Iter = llvm::find_if(
20619 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20620 return P.first == Var;
20621 });
20622 if (Iter != I.end()) {
20623 SemaRef.PendingInstantiations.push_back(*Iter);
20624 I.erase(Iter);
20625 Inserted = true;
20626 break;
20627 }
20628 }
20629
20630 // FIXME: For a specialization of a variable template, we don't
20631 // distinguish between "declaration and type implicitly instantiated"
20632 // and "implicit instantiation of definition requested", so we have
20633 // no direct way to avoid enqueueing the pending instantiation
20634 // multiple times.
20635 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20637 .push_back(std::make_pair(Var, PointOfInstantiation));
20638 }
20639 }
20640 }
20641
20642 // C++2a [basic.def.odr]p4:
20643 // A variable x whose name appears as a potentially-evaluated expression e
20644 // is odr-used by e unless
20645 // -- x is a reference that is usable in constant expressions
20646 // -- x is a variable of non-reference type that is usable in constant
20647 // expressions and has no mutable subobjects [FIXME], and e is an
20648 // element of the set of potential results of an expression of
20649 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20650 // conversion is applied
20651 // -- x is a variable of non-reference type, and e is an element of the set
20652 // of potential results of a discarded-value expression to which the
20653 // lvalue-to-rvalue conversion is not applied [FIXME]
20654 //
20655 // We check the first part of the second bullet here, and
20656 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20657 // FIXME: To get the third bullet right, we need to delay this even for
20658 // variables that are not usable in constant expressions.
20659
20660 // If we already know this isn't an odr-use, there's nothing more to do.
20661 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20662 if (DRE->isNonOdrUse())
20663 return;
20664 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20665 if (ME->isNonOdrUse())
20666 return;
20667
20668 switch (OdrUse) {
20669 case OdrUseContext::None:
20670 // In some cases, a variable may not have been marked unevaluated, if it
20671 // appears in a defaukt initializer.
20672 assert((!E || isa<FunctionParmPackExpr>(E) ||
20674 "missing non-odr-use marking for unevaluated decl ref");
20675 break;
20676
20677 case OdrUseContext::FormallyOdrUsed:
20678 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20679 // behavior.
20680 break;
20681
20682 case OdrUseContext::Used:
20683 // If we might later find that this expression isn't actually an odr-use,
20684 // delay the marking.
20686 SemaRef.MaybeODRUseExprs.insert(E);
20687 else
20688 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20689 break;
20690
20691 case OdrUseContext::Dependent:
20692 // If this is a dependent context, we don't need to mark variables as
20693 // odr-used, but we may still need to track them for lambda capture.
20694 // FIXME: Do we also need to do this inside dependent typeid expressions
20695 // (which are modeled as unevaluated at this point)?
20696 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20697 break;
20698 }
20699}
20700
20702 BindingDecl *BD, Expr *E) {
20703 BD->setReferenced();
20704
20705 if (BD->isInvalidDecl())
20706 return;
20707
20708 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20709 if (OdrUse == OdrUseContext::Used) {
20710 QualType CaptureType, DeclRefType;
20712 /*EllipsisLoc*/ SourceLocation(),
20713 /*BuildAndDiagnose*/ true, CaptureType,
20714 DeclRefType,
20715 /*FunctionScopeIndexToStopAt*/ nullptr);
20716 } else if (OdrUse == OdrUseContext::Dependent) {
20717 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20718 }
20719}
20720
20722 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20723}
20724
20725// C++ [temp.dep.expr]p3:
20726// An id-expression is type-dependent if it contains:
20727// - an identifier associated by name lookup with an entity captured by copy
20728// in a lambda-expression that has an explicit object parameter whose type
20729// is dependent ([dcl.fct]),
20731 Sema &SemaRef, ValueDecl *D, Expr *E) {
20732 auto *ID = dyn_cast<DeclRefExpr>(E);
20733 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20734 return;
20735
20736 // If any enclosing lambda with a dependent explicit object parameter either
20737 // explicitly captures the variable by value, or has a capture default of '='
20738 // and does not capture the variable by reference, then the type of the DRE
20739 // is dependent on the type of that lambda's explicit object parameter.
20740 auto IsDependent = [&]() {
20741 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20742 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20743 if (!LSI)
20744 continue;
20745
20746 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20747 LSI->AfterParameterList)
20748 return false;
20749
20750 const auto *MD = LSI->CallOperator;
20751 if (MD->getType().isNull())
20752 continue;
20753
20754 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20755 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20756 !Ty->getParamType(0)->isDependentType())
20757 continue;
20758
20759 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20760 if (C->isCopyCapture())
20761 return true;
20762 continue;
20763 }
20764
20765 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20766 return true;
20767 }
20768 return false;
20769 }();
20770
20771 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20772 IsDependent, SemaRef.getASTContext());
20773}
20774
20775static void
20777 bool MightBeOdrUse,
20778 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20781
20782 if (SemaRef.getLangOpts().OpenACC)
20783 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20784
20785 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20787 if (SemaRef.getLangOpts().CPlusPlus)
20789 Var, E);
20790 return;
20791 }
20792
20793 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20795 if (SemaRef.getLangOpts().CPlusPlus)
20797 Decl, E);
20798 return;
20799 }
20800 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20801
20802 // If this is a call to a method via a cast, also mark the method in the
20803 // derived class used in case codegen can devirtualize the call.
20804 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20805 if (!ME)
20806 return;
20807 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20808 if (!MD)
20809 return;
20810 // Only attempt to devirtualize if this is truly a virtual call.
20811 bool IsVirtualCall = MD->isVirtual() &&
20813 if (!IsVirtualCall)
20814 return;
20815
20816 // If it's possible to devirtualize the call, mark the called function
20817 // referenced.
20819 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20820 if (DM)
20821 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20822}
20823
20825 // [basic.def.odr] (CWG 1614)
20826 // A function is named by an expression or conversion [...]
20827 // unless it is a pure virtual function and either the expression is not an
20828 // id-expression naming the function with an explicitly qualified name or
20829 // the expression forms a pointer to member
20830 bool OdrUse = true;
20831 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20832 if (Method->isVirtual() &&
20833 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20834 OdrUse = false;
20835
20836 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20840 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20841 !FD->isDependentContext())
20842 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20843 }
20844 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20846}
20847
20849 // C++11 [basic.def.odr]p2:
20850 // A non-overloaded function whose name appears as a potentially-evaluated
20851 // expression or a member of a set of candidate functions, if selected by
20852 // overload resolution when referred to from a potentially-evaluated
20853 // expression, is odr-used, unless it is a pure virtual function and its
20854 // name is not explicitly qualified.
20855 bool MightBeOdrUse = true;
20857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20858 if (Method->isPureVirtual())
20859 MightBeOdrUse = false;
20860 }
20861 SourceLocation Loc =
20862 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20863 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20865}
20866
20872
20873/// Perform marking for a reference to an arbitrary declaration. It
20874/// marks the declaration referenced, and performs odr-use checking for
20875/// functions and variables. This method should not be used when building a
20876/// normal expression which refers to a variable.
20878 bool MightBeOdrUse) {
20879 if (MightBeOdrUse) {
20880 if (auto *VD = dyn_cast<VarDecl>(D)) {
20881 MarkVariableReferenced(Loc, VD);
20882 return;
20883 }
20884 }
20885 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20886 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20887 return;
20888 }
20889 D->setReferenced();
20890}
20891
20892namespace {
20893 // Mark all of the declarations used by a type as referenced.
20894 // FIXME: Not fully implemented yet! We need to have a better understanding
20895 // of when we're entering a context we should not recurse into.
20896 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20897 // TreeTransforms rebuilding the type in a new context. Rather than
20898 // duplicating the TreeTransform logic, we should consider reusing it here.
20899 // Currently that causes problems when rebuilding LambdaExprs.
20900class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20901 Sema &S;
20902 SourceLocation Loc;
20903
20904public:
20905 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20906
20907 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20908};
20909}
20910
20911bool MarkReferencedDecls::TraverseTemplateArgument(
20912 const TemplateArgument &Arg) {
20913 {
20914 // A non-type template argument is a constant-evaluated context.
20915 EnterExpressionEvaluationContext Evaluated(
20918 if (Decl *D = Arg.getAsDecl())
20919 S.MarkAnyDeclReferenced(Loc, D, true);
20920 } else if (Arg.getKind() == TemplateArgument::Expression) {
20922 }
20923 }
20924
20926}
20927
20929 MarkReferencedDecls Marker(*this, Loc);
20930 Marker.TraverseType(T);
20931}
20932
20933namespace {
20934/// Helper class that marks all of the declarations referenced by
20935/// potentially-evaluated subexpressions as "referenced".
20936class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20937public:
20938 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20939 bool SkipLocalVariables;
20941
20942 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20944 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20945
20946 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20948 }
20949
20950 void Visit(Expr *E) {
20951 if (llvm::is_contained(StopAt, E))
20952 return;
20953 Inherited::Visit(E);
20954 }
20955
20956 void VisitConstantExpr(ConstantExpr *E) {
20957 // Don't mark declarations within a ConstantExpression, as this expression
20958 // will be evaluated and folded to a value.
20959 }
20960
20961 void VisitDeclRefExpr(DeclRefExpr *E) {
20962 // If we were asked not to visit local variables, don't.
20963 if (SkipLocalVariables) {
20964 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20965 if (VD->hasLocalStorage())
20966 return;
20967 }
20968
20969 // FIXME: This can trigger the instantiation of the initializer of a
20970 // variable, which can cause the expression to become value-dependent
20971 // or error-dependent. Do we need to propagate the new dependence bits?
20973 }
20974
20975 void VisitMemberExpr(MemberExpr *E) {
20977 Visit(E->getBase());
20978 }
20979};
20980} // namespace
20981
20983 bool SkipLocalVariables,
20984 ArrayRef<const Expr*> StopAt) {
20985 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20986}
20987
20988/// Emit a diagnostic when statements are reachable.
20990 const PartialDiagnostic &PD) {
20991 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20992 // The initializer of a constexpr variable or of the first declaration of a
20993 // static data member is not syntactically a constant evaluated constant,
20994 // but nonetheless is always required to be a constant expression, so we
20995 // can skip diagnosing.
20996 if (Decl &&
20997 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20998 Decl->isFirstDecl() && !Decl->isInline())))
20999 return false;
21000
21001 if (Stmts.empty()) {
21002 Diag(Loc, PD);
21003 return true;
21004 }
21005
21006 if (getCurFunction()) {
21007 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21008 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21009 return true;
21010 }
21011
21012 // For non-constexpr file-scope variables with reachability context (non-empty
21013 // Stmts), build a CFG for the initializer and check whether the context in
21014 // question is reachable.
21015 if (Decl && Decl->isFileVarDecl()) {
21016 AnalysisWarnings.registerVarDeclWarning(
21017 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21018 return true;
21019 }
21020
21021 Diag(Loc, PD);
21022 return true;
21023}
21024
21025/// Emit a diagnostic that describes an effect on the run-time behavior
21026/// of the program being compiled.
21027///
21028/// This routine emits the given diagnostic when the code currently being
21029/// type-checked is "potentially evaluated", meaning that there is a
21030/// possibility that the code will actually be executable. Code in sizeof()
21031/// expressions, code used only during overload resolution, etc., are not
21032/// potentially evaluated. This routine will suppress such diagnostics or,
21033/// in the absolutely nutty case of potentially potentially evaluated
21034/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21035/// later.
21036///
21037/// This routine should be used for all diagnostics that describe the run-time
21038/// behavior of a program, such as passing a non-POD value through an ellipsis.
21039/// Failure to do so will likely result in spurious diagnostics or failures
21040/// during overload resolution or within sizeof/alignof/typeof/typeid.
21042 const PartialDiagnostic &PD) {
21043
21044 if (ExprEvalContexts.back().isDiscardedStatementContext())
21045 return false;
21046
21047 switch (ExprEvalContexts.back().Context) {
21052 // The argument will never be evaluated, so don't complain.
21053 break;
21054
21057 // Relevant diagnostics should be produced by constant evaluation.
21058 break;
21059
21062 return DiagIfReachable(Loc, Stmts, PD);
21063 }
21064
21065 return false;
21066}
21067
21069 const PartialDiagnostic &PD) {
21070 return DiagRuntimeBehavior(
21071 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21072 PD);
21073}
21074
21076 CallExpr *CE, FunctionDecl *FD) {
21077 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21078 return false;
21079
21080 // If we're inside a decltype's expression, don't check for a valid return
21081 // type or construct temporaries until we know whether this is the last call.
21082 if (ExprEvalContexts.back().ExprContext ==
21084 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21085 return false;
21086 }
21087
21088 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21089 FunctionDecl *FD;
21090 CallExpr *CE;
21091
21092 public:
21093 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21094 : FD(FD), CE(CE) { }
21095
21096 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21097 if (!FD) {
21098 S.Diag(Loc, diag::err_call_incomplete_return)
21099 << T << CE->getSourceRange();
21100 return;
21101 }
21102
21103 S.Diag(Loc, diag::err_call_function_incomplete_return)
21104 << CE->getSourceRange() << FD << T;
21105 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21106 << FD->getDeclName();
21107 }
21108 } Diagnoser(FD, CE);
21109
21110 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21111 return true;
21112
21113 return false;
21114}
21115
21116// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21117// will prevent this condition from triggering, which is what we want.
21119 SourceLocation Loc;
21120
21121 unsigned diagnostic = diag::warn_condition_is_assignment;
21122 bool IsOrAssign = false;
21123
21124 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21125 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21126 return;
21127
21128 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21129
21130 // Greylist some idioms by putting them into a warning subcategory.
21131 if (ObjCMessageExpr *ME
21132 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21133 Selector Sel = ME->getSelector();
21134
21135 // self = [<foo> init...]
21136 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21137 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21138
21139 // <foo> = [<bar> nextObject]
21140 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21141 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21142 }
21143
21144 Loc = Op->getOperatorLoc();
21145 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21146 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21147 return;
21148
21149 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21150 Loc = Op->getOperatorLoc();
21151 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21152 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21153 else {
21154 // Not an assignment.
21155 return;
21156 }
21157
21158 Diag(Loc, diagnostic) << E->getSourceRange();
21159
21162 Diag(Loc, diag::note_condition_assign_silence)
21164 << FixItHint::CreateInsertion(Close, ")");
21165
21166 if (IsOrAssign)
21167 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21168 << FixItHint::CreateReplacement(Loc, "!=");
21169 else
21170 Diag(Loc, diag::note_condition_assign_to_comparison)
21171 << FixItHint::CreateReplacement(Loc, "==");
21172}
21173
21175 // Don't warn if the parens came from a macro.
21176 SourceLocation parenLoc = ParenE->getBeginLoc();
21177 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21178 return;
21179 // Don't warn for dependent expressions.
21180 if (ParenE->isTypeDependent())
21181 return;
21182
21183 Expr *E = ParenE->IgnoreParens();
21184 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21185 return;
21186
21187 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21188 if (opE->getOpcode() == BO_EQ &&
21189 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21190 == Expr::MLV_Valid) {
21191 SourceLocation Loc = opE->getOperatorLoc();
21192
21193 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21194 SourceRange ParenERange = ParenE->getSourceRange();
21195 Diag(Loc, diag::note_equality_comparison_silence)
21196 << FixItHint::CreateRemoval(ParenERange.getBegin())
21197 << FixItHint::CreateRemoval(ParenERange.getEnd());
21198 Diag(Loc, diag::note_equality_comparison_to_assign)
21199 << FixItHint::CreateReplacement(Loc, "=");
21200 }
21201}
21202
21204 bool IsConstexpr) {
21206 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21208
21209 ExprResult result = CheckPlaceholderExpr(E);
21210 if (result.isInvalid()) return ExprError();
21211 E = result.get();
21212
21213 if (!E->isTypeDependent()) {
21214 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21216
21217 if (getLangOpts().CPlusPlus)
21218 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21219
21221 if (ERes.isInvalid())
21222 return ExprError();
21223 E = ERes.get();
21224
21225 QualType T = E->getType();
21226 if (!T->isScalarType()) { // C99 6.8.4.1p1
21227 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21228 << T << E->getSourceRange();
21229 return ExprError();
21230 }
21231 CheckBoolLikeConversion(E, Loc);
21232 }
21233
21234 return E;
21235}
21236
21238 Expr *SubExpr, ConditionKind CK,
21239 bool MissingOK) {
21240 // MissingOK indicates whether having no condition expression is valid
21241 // (for loop) or invalid (e.g. while loop).
21242 if (!SubExpr)
21243 return MissingOK ? ConditionResult() : ConditionError();
21244
21246 switch (CK) {
21248 Cond = CheckBooleanCondition(Loc, SubExpr);
21249 break;
21250
21252 // Note: this might produce a FullExpr
21253 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21254 break;
21255
21257 Cond = CheckSwitchCondition(Loc, SubExpr);
21258 break;
21259 }
21260 if (Cond.isInvalid()) {
21261 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21262 {SubExpr}, PreferredConditionType(CK));
21263 if (!Cond.get())
21264 return ConditionError();
21265 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21266 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21267
21268 if (!Cond.isUsable())
21269 return ConditionError();
21270
21271 return ConditionResult(*this, nullptr, Cond,
21273}
21274
21275namespace {
21276 /// A visitor for rebuilding a call to an __unknown_any expression
21277 /// to have an appropriate type.
21278 struct RebuildUnknownAnyFunction
21279 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21280
21281 Sema &S;
21282
21283 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21284
21285 ExprResult VisitStmt(Stmt *S) {
21286 llvm_unreachable("unexpected statement!");
21287 }
21288
21289 ExprResult VisitExpr(Expr *E) {
21290 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21291 << E->getSourceRange();
21292 return ExprError();
21293 }
21294
21295 /// Rebuild an expression which simply semantically wraps another
21296 /// expression which it shares the type and value kind of.
21297 template <class T> ExprResult rebuildSugarExpr(T *E) {
21298 ExprResult SubResult = Visit(E->getSubExpr());
21299 if (SubResult.isInvalid()) return ExprError();
21300
21301 Expr *SubExpr = SubResult.get();
21302 E->setSubExpr(SubExpr);
21303 E->setType(SubExpr->getType());
21304 E->setValueKind(SubExpr->getValueKind());
21305 assert(E->getObjectKind() == OK_Ordinary);
21306 return E;
21307 }
21308
21309 ExprResult VisitParenExpr(ParenExpr *E) {
21310 return rebuildSugarExpr(E);
21311 }
21312
21313 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21314 return rebuildSugarExpr(E);
21315 }
21316
21317 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21318 ExprResult SubResult = Visit(E->getSubExpr());
21319 if (SubResult.isInvalid()) return ExprError();
21320
21321 Expr *SubExpr = SubResult.get();
21322 E->setSubExpr(SubExpr);
21323 E->setType(S.Context.getPointerType(SubExpr->getType()));
21324 assert(E->isPRValue());
21325 assert(E->getObjectKind() == OK_Ordinary);
21326 return E;
21327 }
21328
21329 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21330 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21331
21332 E->setType(VD->getType());
21333
21334 assert(E->isPRValue());
21335 if (S.getLangOpts().CPlusPlus &&
21336 !(isa<CXXMethodDecl>(VD) &&
21337 cast<CXXMethodDecl>(VD)->isInstance()))
21339
21340 return E;
21341 }
21342
21343 ExprResult VisitMemberExpr(MemberExpr *E) {
21344 return resolveDecl(E, E->getMemberDecl());
21345 }
21346
21347 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21348 return resolveDecl(E, E->getDecl());
21349 }
21350 };
21351}
21352
21353/// Given a function expression of unknown-any type, try to rebuild it
21354/// to have a function type.
21356 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21357 if (Result.isInvalid()) return ExprError();
21358 return S.DefaultFunctionArrayConversion(Result.get());
21359}
21360
21361namespace {
21362 /// A visitor for rebuilding an expression of type __unknown_anytype
21363 /// into one which resolves the type directly on the referring
21364 /// expression. Strict preservation of the original source
21365 /// structure is not a goal.
21366 struct RebuildUnknownAnyExpr
21367 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21368
21369 Sema &S;
21370
21371 /// The current destination type.
21372 QualType DestType;
21373
21374 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21375 : S(S), DestType(CastType) {}
21376
21377 ExprResult VisitStmt(Stmt *S) {
21378 llvm_unreachable("unexpected statement!");
21379 }
21380
21381 ExprResult VisitExpr(Expr *E) {
21382 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21383 << E->getSourceRange();
21384 return ExprError();
21385 }
21386
21387 ExprResult VisitCallExpr(CallExpr *E);
21388 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21389
21390 /// Rebuild an expression which simply semantically wraps another
21391 /// expression which it shares the type and value kind of.
21392 template <class T> ExprResult rebuildSugarExpr(T *E) {
21393 ExprResult SubResult = Visit(E->getSubExpr());
21394 if (SubResult.isInvalid()) return ExprError();
21395 Expr *SubExpr = SubResult.get();
21396 E->setSubExpr(SubExpr);
21397 E->setType(SubExpr->getType());
21398 E->setValueKind(SubExpr->getValueKind());
21399 assert(E->getObjectKind() == OK_Ordinary);
21400 return E;
21401 }
21402
21403 ExprResult VisitParenExpr(ParenExpr *E) {
21404 return rebuildSugarExpr(E);
21405 }
21406
21407 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21408 return rebuildSugarExpr(E);
21409 }
21410
21411 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21412 const PointerType *Ptr = DestType->getAs<PointerType>();
21413 if (!Ptr) {
21414 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21415 << E->getSourceRange();
21416 return ExprError();
21417 }
21418
21419 if (isa<CallExpr>(E->getSubExpr())) {
21420 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21421 << E->getSourceRange();
21422 return ExprError();
21423 }
21424
21425 assert(E->isPRValue());
21426 assert(E->getObjectKind() == OK_Ordinary);
21427 E->setType(DestType);
21428
21429 // Build the sub-expression as if it were an object of the pointee type.
21430 DestType = Ptr->getPointeeType();
21431 ExprResult SubResult = Visit(E->getSubExpr());
21432 if (SubResult.isInvalid()) return ExprError();
21433 E->setSubExpr(SubResult.get());
21434 return E;
21435 }
21436
21437 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21438
21439 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21440
21441 ExprResult VisitMemberExpr(MemberExpr *E) {
21442 return resolveDecl(E, E->getMemberDecl());
21443 }
21444
21445 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21446 return resolveDecl(E, E->getDecl());
21447 }
21448 };
21449}
21450
21451/// Rebuilds a call expression which yielded __unknown_anytype.
21452ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21453 Expr *CalleeExpr = E->getCallee();
21454
21455 enum FnKind {
21456 FK_MemberFunction,
21457 FK_FunctionPointer,
21458 FK_BlockPointer
21459 };
21460
21461 FnKind Kind;
21462 QualType CalleeType = CalleeExpr->getType();
21463 if (CalleeType == S.Context.BoundMemberTy) {
21465 Kind = FK_MemberFunction;
21466 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21467 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21468 CalleeType = Ptr->getPointeeType();
21469 Kind = FK_FunctionPointer;
21470 } else {
21471 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21472 Kind = FK_BlockPointer;
21473 }
21474 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21475
21476 // Verify that this is a legal result type of a function.
21477 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21478 DestType->isFunctionType()) {
21479 unsigned diagID = diag::err_func_returning_array_function;
21480 if (Kind == FK_BlockPointer)
21481 diagID = diag::err_block_returning_array_function;
21482
21483 S.Diag(E->getExprLoc(), diagID)
21484 << DestType->isFunctionType() << DestType;
21485 return ExprError();
21486 }
21487
21488 // Otherwise, go ahead and set DestType as the call's result.
21489 E->setType(DestType.getNonLValueExprType(S.Context));
21491 assert(E->getObjectKind() == OK_Ordinary);
21492
21493 // Rebuild the function type, replacing the result type with DestType.
21494 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21495 if (Proto) {
21496 // __unknown_anytype(...) is a special case used by the debugger when
21497 // it has no idea what a function's signature is.
21498 //
21499 // We want to build this call essentially under the K&R
21500 // unprototyped rules, but making a FunctionNoProtoType in C++
21501 // would foul up all sorts of assumptions. However, we cannot
21502 // simply pass all arguments as variadic arguments, nor can we
21503 // portably just call the function under a non-variadic type; see
21504 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21505 // However, it turns out that in practice it is generally safe to
21506 // call a function declared as "A foo(B,C,D);" under the prototype
21507 // "A foo(B,C,D,...);". The only known exception is with the
21508 // Windows ABI, where any variadic function is implicitly cdecl
21509 // regardless of its normal CC. Therefore we change the parameter
21510 // types to match the types of the arguments.
21511 //
21512 // This is a hack, but it is far superior to moving the
21513 // corresponding target-specific code from IR-gen to Sema/AST.
21514
21515 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21516 SmallVector<QualType, 8> ArgTypes;
21517 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21518 ArgTypes.reserve(E->getNumArgs());
21519 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21520 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21521 }
21522 ParamTypes = ArgTypes;
21523 }
21524 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21525 Proto->getExtProtoInfo());
21526 } else {
21527 DestType = S.Context.getFunctionNoProtoType(DestType,
21528 FnType->getExtInfo());
21529 }
21530
21531 // Rebuild the appropriate pointer-to-function type.
21532 switch (Kind) {
21533 case FK_MemberFunction:
21534 // Nothing to do.
21535 break;
21536
21537 case FK_FunctionPointer:
21538 DestType = S.Context.getPointerType(DestType);
21539 break;
21540
21541 case FK_BlockPointer:
21542 DestType = S.Context.getBlockPointerType(DestType);
21543 break;
21544 }
21545
21546 // Finally, we can recurse.
21547 ExprResult CalleeResult = Visit(CalleeExpr);
21548 if (!CalleeResult.isUsable()) return ExprError();
21549 E->setCallee(CalleeResult.get());
21550
21551 // Bind a temporary if necessary.
21552 return S.MaybeBindToTemporary(E);
21553}
21554
21555ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21556 // Verify that this is a legal result type of a call.
21557 if (DestType->isArrayType() || DestType->isFunctionType()) {
21558 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21559 << DestType->isFunctionType() << DestType;
21560 return ExprError();
21561 }
21562
21563 // Rewrite the method result type if available.
21564 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21565 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21566 Method->setReturnType(DestType);
21567 }
21568
21569 // Change the type of the message.
21570 E->setType(DestType.getNonReferenceType());
21572
21573 return S.MaybeBindToTemporary(E);
21574}
21575
21576ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21577 // The only case we should ever see here is a function-to-pointer decay.
21578 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21579 assert(E->isPRValue());
21580 assert(E->getObjectKind() == OK_Ordinary);
21581
21582 E->setType(DestType);
21583
21584 // Rebuild the sub-expression as the pointee (function) type.
21585 DestType = DestType->castAs<PointerType>()->getPointeeType();
21586
21587 ExprResult Result = Visit(E->getSubExpr());
21588 if (!Result.isUsable()) return ExprError();
21589
21590 E->setSubExpr(Result.get());
21591 return E;
21592 } else if (E->getCastKind() == CK_LValueToRValue) {
21593 assert(E->isPRValue());
21594 assert(E->getObjectKind() == OK_Ordinary);
21595
21596 assert(isa<BlockPointerType>(E->getType()));
21597
21598 E->setType(DestType);
21599
21600 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21601 DestType = S.Context.getLValueReferenceType(DestType);
21602
21603 ExprResult Result = Visit(E->getSubExpr());
21604 if (!Result.isUsable()) return ExprError();
21605
21606 E->setSubExpr(Result.get());
21607 return E;
21608 } else {
21609 llvm_unreachable("Unhandled cast type!");
21610 }
21611}
21612
21613ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21614 ExprValueKind ValueKind = VK_LValue;
21615 QualType Type = DestType;
21616
21617 // We know how to make this work for certain kinds of decls:
21618
21619 // - functions
21620 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21621 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21622 DestType = Ptr->getPointeeType();
21623 ExprResult Result = resolveDecl(E, VD);
21624 if (Result.isInvalid()) return ExprError();
21625 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21626 VK_PRValue);
21627 }
21628
21629 if (!Type->isFunctionType()) {
21630 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21631 << VD << E->getSourceRange();
21632 return ExprError();
21633 }
21634 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21635 // We must match the FunctionDecl's type to the hack introduced in
21636 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21637 // type. See the lengthy commentary in that routine.
21638 QualType FDT = FD->getType();
21639 const FunctionType *FnType = FDT->castAs<FunctionType>();
21640 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21641 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21642 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21643 SourceLocation Loc = FD->getLocation();
21644 FunctionDecl *NewFD = FunctionDecl::Create(
21645 S.Context, FD->getDeclContext(), Loc, Loc,
21646 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21648 false /*isInlineSpecified*/, FD->hasPrototype(),
21649 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21650
21651 if (FD->getQualifier())
21652 NewFD->setQualifierInfo(FD->getQualifierLoc());
21653
21654 SmallVector<ParmVarDecl*, 16> Params;
21655 for (const auto &AI : FT->param_types()) {
21656 ParmVarDecl *Param =
21657 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21658 Param->setScopeInfo(0, Params.size());
21659 Params.push_back(Param);
21660 }
21661 NewFD->setParams(Params);
21662 DRE->setDecl(NewFD);
21663 VD = DRE->getDecl();
21664 }
21665 }
21666
21667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21668 if (MD->isInstance()) {
21669 ValueKind = VK_PRValue;
21671 }
21672
21673 // Function references aren't l-values in C.
21674 if (!S.getLangOpts().CPlusPlus)
21675 ValueKind = VK_PRValue;
21676
21677 // - variables
21678 } else if (isa<VarDecl>(VD)) {
21679 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21680 Type = RefTy->getPointeeType();
21681 } else if (Type->isFunctionType()) {
21682 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21683 << VD << E->getSourceRange();
21684 return ExprError();
21685 }
21686
21687 // - nothing else
21688 } else {
21689 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21690 << VD << E->getSourceRange();
21691 return ExprError();
21692 }
21693
21694 // Modifying the declaration like this is friendly to IR-gen but
21695 // also really dangerous.
21696 VD->setType(DestType);
21697 E->setType(Type);
21698 E->setValueKind(ValueKind);
21699 return E;
21700}
21701
21704 ExprValueKind &VK, CXXCastPath &Path) {
21705 // The type we're casting to must be either void or complete.
21706 if (!CastType->isVoidType() &&
21708 diag::err_typecheck_cast_to_incomplete))
21709 return ExprError();
21710
21711 // Rewrite the casted expression from scratch.
21712 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21713 if (!result.isUsable()) return ExprError();
21714
21715 CastExpr = result.get();
21717 CastKind = CK_NoOp;
21718
21719 return CastExpr;
21720}
21721
21723 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21724}
21725
21727 Expr *arg, QualType &paramType) {
21728 // If the syntactic form of the argument is not an explicit cast of
21729 // any sort, just do default argument promotion.
21730 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21731 if (!castArg) {
21733 if (result.isInvalid()) return ExprError();
21734 paramType = result.get()->getType();
21735 return result;
21736 }
21737
21738 // Otherwise, use the type that was written in the explicit cast.
21739 assert(!arg->hasPlaceholderType());
21740 paramType = castArg->getTypeAsWritten();
21741
21742 // Copy-initialize a parameter of that type.
21743 InitializedEntity entity =
21745 /*consumed*/ false);
21746 return PerformCopyInitialization(entity, callLoc, arg);
21747}
21748
21750 Expr *orig = E;
21751 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21752 while (true) {
21753 E = E->IgnoreParenImpCasts();
21754 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21755 E = call->getCallee();
21756 diagID = diag::err_uncasted_call_of_unknown_any;
21757 } else {
21758 break;
21759 }
21760 }
21761
21762 SourceLocation loc;
21763 NamedDecl *d;
21764 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21765 loc = ref->getLocation();
21766 d = ref->getDecl();
21767 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21768 loc = mem->getMemberLoc();
21769 d = mem->getMemberDecl();
21770 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21771 diagID = diag::err_uncasted_call_of_unknown_any;
21772 loc = msg->getSelectorStartLoc();
21773 d = msg->getMethodDecl();
21774 if (!d) {
21775 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21776 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21777 << orig->getSourceRange();
21778 return ExprError();
21779 }
21780 } else {
21781 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21782 << E->getSourceRange();
21783 return ExprError();
21784 }
21785
21786 S.Diag(loc, diagID) << d << orig->getSourceRange();
21787
21788 // Never recoverable.
21789 return ExprError();
21790}
21791
21793 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21794 if (!placeholderType) return E;
21795
21796 switch (placeholderType->getKind()) {
21797 case BuiltinType::UnresolvedTemplate: {
21798 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21799 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21800 // There's only one FoundDecl for UnresolvedTemplate type. See
21801 // BuildTemplateIdExpr.
21802 NamedDecl *Temp = *ULE->decls_begin();
21803 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21804
21805 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21806 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21807 // as it models only the unqualified-id case, where this case can clearly be
21808 // qualified. Thus we can't just qualify an assumed template.
21809 TemplateName TN;
21810 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21811 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21812 TemplateName(TD));
21813 else
21814 TN = Context.getAssumedTemplateName(NameInfo.getName());
21815
21816 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21817 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21818 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21819 << IsTypeAliasTemplateDecl;
21820
21821 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21822 bool HasAnyDependentTA = false;
21823 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21824 HasAnyDependentTA |= Arg.getArgument().isDependent();
21825 TAL.addArgument(Arg);
21826 }
21827
21828 QualType TST;
21829 {
21830 SFINAETrap Trap(*this);
21831 TST = CheckTemplateIdType(
21832 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21833 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21834 }
21835 if (TST.isNull())
21836 TST = Context.getTemplateSpecializationType(
21837 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21838 /*CanonicalArgs=*/{},
21839 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21840 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21841 TST);
21842 }
21843
21844 // Overloaded expressions.
21845 case BuiltinType::Overload: {
21846 // Try to resolve a single function template specialization.
21847 // This is obligatory.
21848 ExprResult Result = E;
21850 return Result;
21851
21852 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21853 // leaves Result unchanged on failure.
21854 Result = E;
21856 return Result;
21857
21858 // If that failed, try to recover with a call.
21859 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21860 /*complain*/ true);
21861 return Result;
21862 }
21863
21864 // Bound member functions.
21865 case BuiltinType::BoundMember: {
21866 ExprResult result = E;
21867 const Expr *BME = E->IgnoreParens();
21868 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21869 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21871 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21872 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21873 if (ME->getMemberNameInfo().getName().getNameKind() ==
21875 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21876 }
21877 tryToRecoverWithCall(result, PD,
21878 /*complain*/ true);
21879 return result;
21880 }
21881
21882 // ARC unbridged casts.
21883 case BuiltinType::ARCUnbridgedCast: {
21884 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21885 ObjC().diagnoseARCUnbridgedCast(realCast);
21886 return realCast;
21887 }
21888
21889 // Expressions of unknown type.
21890 case BuiltinType::UnknownAny:
21891 return diagnoseUnknownAnyExpr(*this, E);
21892
21893 // Pseudo-objects.
21894 case BuiltinType::PseudoObject:
21895 return PseudoObject().checkRValue(E);
21896
21897 case BuiltinType::BuiltinFn: {
21898 // Accept __noop without parens by implicitly converting it to a call expr.
21899 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21900 if (DRE) {
21901 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21902 unsigned BuiltinID = FD->getBuiltinID();
21903 if (BuiltinID == Builtin::BI__noop) {
21904 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21905 CK_BuiltinFnToFnPtr)
21906 .get();
21907 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21910 }
21911
21912 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21913 // Any use of these other than a direct call is ill-formed as of C++20,
21914 // because they are not addressable functions. In earlier language
21915 // modes, warn and force an instantiation of the real body.
21916 Diag(E->getBeginLoc(),
21918 ? diag::err_use_of_unaddressable_function
21919 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21920 if (FD->isImplicitlyInstantiable()) {
21921 // Require a definition here because a normal attempt at
21922 // instantiation for a builtin will be ignored, and we won't try
21923 // again later. We assume that the definition of the template
21924 // precedes this use.
21926 /*Recursive=*/false,
21927 /*DefinitionRequired=*/true,
21928 /*AtEndOfTU=*/false);
21929 }
21930 // Produce a properly-typed reference to the function.
21931 CXXScopeSpec SS;
21932 SS.Adopt(DRE->getQualifierLoc());
21933 TemplateArgumentListInfo TemplateArgs;
21934 DRE->copyTemplateArgumentsInto(TemplateArgs);
21935 return BuildDeclRefExpr(
21936 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21937 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21938 DRE->getTemplateKeywordLoc(),
21939 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21940 }
21941 }
21942
21943 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21944 return ExprError();
21945 }
21946
21947 case BuiltinType::IncompleteMatrixIdx: {
21948 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21949 // At this point, we know there was no second [] to complete the operator.
21950 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21951 if (getLangOpts().HLSL) {
21953 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21954 }
21955 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21956 return ExprError();
21957 }
21958
21959 // Expressions of unknown type.
21960 case BuiltinType::ArraySection:
21961 // If we've already diagnosed something on the array section type, we
21962 // shouldn't need to do any further diagnostic here.
21963 if (!E->containsErrors())
21964 Diag(E->getBeginLoc(), diag::err_array_section_use)
21965 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
21966 return ExprError();
21967
21968 // Expressions of unknown type.
21969 case BuiltinType::OMPArrayShaping:
21970 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21971
21972 case BuiltinType::OMPIterator:
21973 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21974
21975 // Everything else should be impossible.
21976#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21977 case BuiltinType::Id:
21978#include "clang/Basic/OpenCLImageTypes.def"
21979#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21980 case BuiltinType::Id:
21981#include "clang/Basic/OpenCLExtensionTypes.def"
21982#define SVE_TYPE(Name, Id, SingletonId) \
21983 case BuiltinType::Id:
21984#include "clang/Basic/AArch64ACLETypes.def"
21985#define PPC_VECTOR_TYPE(Name, Id, Size) \
21986 case BuiltinType::Id:
21987#include "clang/Basic/PPCTypes.def"
21988#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21989#include "clang/Basic/RISCVVTypes.def"
21990#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21991#include "clang/Basic/WebAssemblyReferenceTypes.def"
21992#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21993#include "clang/Basic/AMDGPUTypes.def"
21994#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21995#include "clang/Basic/HLSLIntangibleTypes.def"
21996#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21997#define PLACEHOLDER_TYPE(Id, SingletonId)
21998#include "clang/AST/BuiltinTypes.def"
21999 break;
22000 }
22001
22002 llvm_unreachable("invalid placeholder type!");
22003}
22004
22006 if (E->isTypeDependent())
22007 return true;
22009 return E->getType()->isIntegralOrEnumerationType();
22010 return false;
22011}
22012
22014 ArrayRef<Expr *> SubExprs, QualType T) {
22015 if (!Context.getLangOpts().RecoveryAST)
22016 return ExprError();
22017
22018 if (isSFINAEContext())
22019 return ExprError();
22020
22021 if (T.isNull() || T->isUndeducedType() ||
22022 !Context.getLangOpts().RecoveryASTType)
22023 // We don't know the concrete type, fallback to dependent type.
22024 T = Context.DependentTy;
22025
22026 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22027}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition Decl.cpp:2704
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Token Tok
The Token.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:149
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition SemaExpr.cpp:165
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
static AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, const ExprResult &LHS, const ExprResult &RHS, BinaryOperatorKind Opc)
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:562
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:587
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition SemaExpr.cpp:111
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
static bool isObjCObjectLiteral(ExprResult &E)
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
static bool isScopedEnumerationType(QualType T)
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool hasValue() const
Definition APValue.h:483
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:802
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:798
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:920
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnknownAnyTy
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:917
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4553
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2779
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3784
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6732
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4456
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
StringRef getOpcodeStr() const
Definition Expr.h:4107
bool isRelationalOp() const
Definition Expr.h:4136
SourceLocation getOperatorLoc() const
Definition Expr.h:4083
bool isMultiplicativeOp() const
Definition Expr.h:4126
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
bool isShiftOp() const
Definition Expr.h:4130
Expr * getRHS() const
Definition Expr.h:4093
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5094
bool isBitwiseOp() const
Definition Expr.h:4133
bool isAdditiveOp() const
Definition Expr.h:4128
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition Expr.cpp:2205
Opcode getOpcode() const
Definition Expr.h:4086
bool isAssignmentOp() const
Definition Expr.h:4180
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2142
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4132
BinaryOperatorKind Opcode
Definition Expr.h:4046
A binding in a decomposition declaration.
Definition DeclCXX.h:4201
A class which contains all the information about a particular captured value.
Definition Decl.h:4695
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4689
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5448
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4771
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4828
void setIsVariadic(bool value)
Definition Decl.h:4765
SourceLocation getCaretLocation() const
Definition Decl.h:4762
void setBody(CompoundStmt *B)
Definition Decl.h:4769
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4775
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5459
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5647
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Pointer to a block type.
Definition TypeBase.h:3592
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
bool isSVEBool() const
Definition TypeBase.h:3291
Kind getKind() const
Definition TypeBase.h:3262
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:1972
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2624
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2959
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3289
Represents a C++ base or member initializer.
Definition DeclCXX.h:2389
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1271
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1039
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1378
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1093
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isVirtual() const
Definition DeclCXX.h:2191
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2275
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition DeclCXX.cpp:2526
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:153
SourceRange getSourceRange() const
Definition ExprCXX.h:165
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2003
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2746
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:603
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2085
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1948
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
Expr * getCallee()
Definition Expr.h:3093
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3169
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
void setCallee(Expr *F)
Definition Expr.h:3095
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3723
const char * getCastKindName() const
Definition Expr.h:3727
void setSubExpr(Expr *E)
Definition Expr.h:3731
Expr * getSubExpr()
Definition Expr.h:3729
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1632
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4851
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
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:5116
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1741
bool body_empty() const
Definition Stmt.h:1785
Stmt * body_back()
Definition Stmt.h:1809
ConditionalOperator - The ?
Definition Expr.h:4394
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3886
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1085
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1135
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
bool isImmediateInvocation() const
Definition Expr.h:1157
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4456
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4453
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition TypeLoc.h:1474
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isRequiresExprBody() const
Definition DeclBase.h:2207
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2202
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1384
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1428
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:544
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1432
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1345
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1400
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1362
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1366
ValueDecl * getDecl()
Definition Expr.h:1341
SourceLocation getBeginLoc() const
Definition Expr.h:1352
SourceLocation getLocation() const
Definition Expr.h:1349
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:776
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:591
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1083
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2013
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
DeclaratorContext getContext() const
Definition DeclSpec.h:2093
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
bool isInvalidType() const
Definition DeclSpec.h:2735
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:959
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:728
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5129
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4201
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:300
@ LV_ClassTemporary
Definition Expr.h:299
@ LV_MemberFunction
Definition Expr.h:297
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3117
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3046
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
void setType(QualType t)
Definition Expr.h:145
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3339
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:830
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3688
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3070
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:805
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:817
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:807
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4068
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition Expr.cpp:4320
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
isModifiableLvalueResult
Definition Expr.h:305
@ MLV_DuplicateVectorComponents
Definition Expr.h:309
@ MLV_LValueCast
Definition Expr.h:312
@ MLV_InvalidMessageExpression
Definition Expr.h:321
@ MLV_DuplicateMatrixComponents
Definition Expr.h:310
@ MLV_ConstQualifiedField
Definition Expr.h:315
@ MLV_InvalidExpression
Definition Expr.h:311
@ MLV_IncompleteType
Definition Expr.h:313
@ MLV_Valid
Definition Expr.h:306
@ MLV_ConstQualified
Definition Expr.h:314
@ MLV_NoSetterProperty
Definition Expr.h:318
@ MLV_ArrayTemporary
Definition Expr.h:323
@ MLV_SubObjCPropertySetting
Definition Expr.h:320
@ MLV_ConstAddrSpace
Definition Expr.h:316
@ MLV_MemberFunction
Definition Expr.h:319
@ MLV_NotObjectType
Definition Expr.h:307
@ MLV_ArrayType
Definition Expr.h:317
@ MLV_ClassTemporary
Definition Expr.h:322
@ MLV_IncompleteVoidType
Definition Expr.h:308
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:137
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6609
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3355
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:997
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1076
const Expr * getSubExpr() const
Definition Expr.h:1065
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition Decl.h:2015
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:2204
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3849
bool isImmediateFunction() const
Definition Decl.cpp:3342
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4026
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3764
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3867
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2936
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2458
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3620
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3313
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2948
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4132
bool isConsteval() const
Definition Decl.h:2497
size_t param_size() const
Definition Decl.h:2805
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3201
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4042
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2896
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4842
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4871
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5861
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5664
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5875
unsigned getNumParams() const
Definition TypeBase.h:5635
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5797
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1668
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1660
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4664
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4735
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4592
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4901
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3646
QualType getReturnType() const
Definition TypeBase.h:4893
bool getCmseNSCallAttr() const
Definition TypeBase.h:4907
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4921
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4926
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4716
One of these records is kept for each identifier that is lexed.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1734
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3482
Describes an C or C++ initializer list.
Definition Expr.h:5302
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:975
Represents the declaration of a label.
Definition Decl.h:524
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1969
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1404
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
bool isSignedOverflowDefined() const
bool allowArrayReturnTypes() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1038
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:319
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4414
MS property subscript expression.
Definition ExprCXX.h:1007
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2798
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2868
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4387
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition Expr.cpp:1750
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool isExternallyVisible() const
Definition Decl.h:433
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1453
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7993
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1529
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:626
SourceLocation getLocation() const
Definition ExprObjC.h:623
SourceLocation getOpLoc() const
Definition ExprObjC.h:631
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
bool isArrow() const
Definition ExprObjC.h:618
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:629
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1395
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:418
bool isClassMethod() const
Definition DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1854
qual_range quals() const
Definition TypeBase.h:8168
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition Expr.cpp:1653
Helper class for OffsetOfExpr.
Definition Expr.h:2424
void * getAsOpaquePtr() const
Definition Ownership.h:91
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3129
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2206
const Expr * getSubExpr() const
Definition Expr.h:2202
bool isProducedByFoldExpansion() const
Definition Expr.h:2227
Expr * getExpr(unsigned Init)
Definition Expr.h:6115
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4966
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6113
SourceLocation getLParenLoc() const
Definition Expr.h:6128
SourceLocation getRParenLoc() const
Definition Expr.h:6129
Represents a parameter to a function.
Definition Decl.h:1805
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1838
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:2959
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:633
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:673
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6803
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3630
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2971
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1422
QualType withConst() const
Definition TypeBase.h:1165
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
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:2749
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2990
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1185
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8623
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
bool isCanonical() const
Definition TypeBase.h:8488
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1315
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2741
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:8596
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8463
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:528
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
Represents a struct/union/class.
Definition Decl.h:4342
bool hasFlexibleArrayMember() const
Definition Decl.h:4375
field_iterator field_end() const
Definition Decl.h:4548
field_range fields() const
Definition Decl.h:4545
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5452
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:637
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:448
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1855
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition SemaCUDA.cpp:812
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:988
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:121
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:122
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:855
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition SemaOpenMP.h:377
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:224
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8523
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12542
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12586
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7792
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8276
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13685
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8326
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8244
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:955
bool isAttrContext() const
Definition Sema.h:7022
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8319
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9406
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9445
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9414
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:416
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1533
void ActOnStartStmtExpr()
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1251
SemaCUDA & CUDA()
Definition Sema.h:1473
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7913
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7915
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7914
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8264
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8406
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1244
Preprocessor & getPreprocessor() const
Definition Sema.h:938
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7000
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2400
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8395
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8307
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6829
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
SemaSYCL & SYCL()
Definition Sema.h:1558
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7012
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:838
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
ASTContext & Context
Definition Sema.h:1308
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:8231
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
SemaObjC & ObjC()
Definition Sema.h:1518
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2910
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
bool isImmediateFunctionContext() const
Definition Sema.h:8256
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1081
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:769
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:888
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6147
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6149
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
AssumedTemplateKind
Definition Sema.h:11504
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:511
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8291
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition Sema.h:934
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8389
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Block
Block expression.
Definition Sema.h:14559
const LangOptions & getLangOpts() const
Definition Sema.h:932
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2531
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
SemaOpenACC & OpenACC()
Definition Sema.h:1523
ReuseLambdaContextDecl_t
Definition Sema.h:7091
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1307
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2209
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1306
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2646
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:957
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6573
SemaHLSL & HLSL()
Definition Sema.h:1483
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15783
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:215
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5309
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:77
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7036
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6603
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14107
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:869
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7033
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2383
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:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8260
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8127
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2601
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12613
SemaOpenCL & OpenCL()
Definition Sema.h:1528
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14116
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8252
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6832
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14051
SourceManager & getSourceManager() const
Definition Sema.h:937
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7546
@ NTCUK_Destruct
Definition Sema.h:4138
@ NTCUK_Copy
Definition Sema.h:4139
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8405
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2431
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6830
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13784
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15555
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2586
bool isConstantEvaluatedContext() const
Definition Sema.h:2639
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1309
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4697
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:7040
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1346
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14099
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6774
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6796
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6786
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6801
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6791
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6811
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6780
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6806
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6821
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1267
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8242
void DiscardCleanupsInEvaluationContext()
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8392
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
SourceManager & SourceMgr
Definition Sema.h:1311
@ TemplateNameIsRequired
Definition Sema.h:11481
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:788
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1304
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1588
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6607
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
ExprResult ActOnStmtExprResult(ExprResult E)
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2192
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8050
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9459
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9465
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9457
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9462
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9473
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9469
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6488
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14095
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:7899
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
SemaPseudoObject & PseudoObject()
Definition Sema.h:1543
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2577
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8268
SemaARM & ARM()
Definition Sema.h:1453
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11047
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8734
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5020
SourceLocation getBeginLoc() const
Definition Expr.h:5065
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5061
SourceLocation getEndLoc() const
Definition Expr.h:5066
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5040
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4598
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1494
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1188
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3833
bool isUnion() const
Definition Decl.h:3943
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:736
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
virtual bool useFP16ConversionIntrinsics() const
Check whether conversions to and from __fp16 should go through an integer bitcast with i16.
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3528
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3562
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8402
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8413
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2533
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9102
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isObjCBuiltinType() const
Definition TypeBase.h:8898
bool isMFloat8Type() const
Definition TypeBase.h:9059
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:1965
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9221
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
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:9010
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:726
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
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:9201
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:2084
bool isVoidPointerType() const
Definition Type.cpp:714
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:747
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isArithmeticType() const
Definition Type.cpp:2375
bool isConstantMatrixType() const
Definition TypeBase.h:8835
bool isPointerType() const
Definition TypeBase.h:8668
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2620
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
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:9122
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isScalarType() const
Definition TypeBase.h:9140
bool isVariableArrayType() const
Definition TypeBase.h:8779
bool isSizelessBuiltinType() const
Definition Type.cpp:2576
bool isClkEventT() const
Definition TypeBase.h:8920
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2654
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2121
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8868
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2329
bool isExtVectorType() const
Definition TypeBase.h:8811
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2194
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2693
bool isImageType() const
Definition TypeBase.h:8932
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9028
bool isPipeType() const
Definition TypeBase.h:8939
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2840
bool isBitIntType() const
Definition TypeBase.h:8943
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9003
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isHalfType() const
Definition TypeBase.h:9038
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2453
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2407
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9016
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2275
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2604
bool isQueueT() const
Definition TypeBase.h:8924
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isAtomicType() const
Definition TypeBase.h:8860
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9184
bool isObjCIdType() const
Definition TypeBase.h:8880
bool isMatrixType() const
Definition TypeBase.h:8831
bool isOverflowBehaviorType() const
Definition TypeBase.h:8839
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:2850
bool isComplexIntegerType() const
Definition Type.cpp:732
bool isUnscopedEnumerationType() const
Definition Type.cpp:2151
bool isObjCObjectType() const
Definition TypeBase.h:8851
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5300
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5389
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isHLSLResourceRecord() const
Definition Type.cpp:5449
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9051
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2350
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:9136
bool isVectorType() const
Definition TypeBase.h:8807
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8874
bool isObjCClassType() const
Definition TypeBase.h:8886
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2641
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
@ STK_FloatingComplex
Definition TypeBase.h:2814
@ STK_ObjCObjectPointer
Definition TypeBase.h:2808
@ STK_IntegralComplex
Definition TypeBase.h:2813
@ STK_MemberPointer
Definition TypeBase.h:2809
bool isFloatingType() const
Definition Type.cpp:2342
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:2285
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2978
bool isAnyPointerType() const
Definition TypeBase.h:8676
bool isRealType() const
Definition Type.cpp:2364
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isSubscriptableVectorType() const
Definition TypeBase.h:8827
bool isSamplerT() const
Definition TypeBase.h:8912
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5453
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5100
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:737
bool isUnicodeCharacterType() const
Definition Type.cpp:2214
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2397
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
void setSubExpr(Expr *E)
Definition Expr.h:2289
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2292
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2343
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5151
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4471
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1121
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4127
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1683
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition ExprCXX.cpp:1645
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:641
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4960
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5583
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3687
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool hasInit() const
Definition Decl.cpp:2411
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2270
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1593
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1216
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1298
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1241
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:2499
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:2920
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1566
const Expr * getInit() const
Definition Decl.h:1383
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1232
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
@ TLS_None
Not a TLS variable.
Definition Decl.h:946
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1310
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2388
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:2541
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:2813
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1277
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:2792
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2911
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4016
Expr * getSizeExpr() const
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
VectorKind getVectorKind() const
Definition TypeBase.h:4245
QualType getElementType() const
Definition TypeBase.h:4239
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:794
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:800
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:804
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isBlockCapture() const
Definition ScopeInfo.h:660
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:672
bool isInvalid() const
Definition ScopeInfo.h:665
bool isThisCapture() const
Definition ScopeInfo.h:653
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:699
bool isCopyCapture() const
Definition ScopeInfo.h:658
bool isNested() const
Definition ScopeInfo.h:663
Retains information about a captured region.
Definition ScopeInfo.h:820
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:835
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:749
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:736
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:725
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:722
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:762
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:718
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:741
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:775
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition ScopeInfo.h:1094
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
void addBlock(const BlockDecl *BD)
Definition ScopeInfo.h:497
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:888
bool lambdaCaptureShouldBeConst() const
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition ScopeInfo.h:996
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:1002
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:957
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:896
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:35
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:93
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ GVA_StrongExternal
Definition Linkage.h:76
VariadicCallType
Definition Sema.h:513
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:61
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:653
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:169
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1027
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ AS_none
Definition Specifiers.h:127
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CR_OpenMP
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_None
Definition Specifiers.h:250
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
ExprResult ExprEmpty()
Definition Ownership.h:272
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Unavailable
Definition DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:676
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:216
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
StringLiteralKind
Definition Expr.h:1766
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4195
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4204
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4189
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4192
@ Neon
is ARM Neon vector
Definition TypeBase.h:4198
@ Generic
not a target-specific vector type
Definition TypeBase.h:4186
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4210
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4213
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4207
U cast(CodeGen::Address addr)
Definition Address.h:327
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5007
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1761
PredefinedIdentKind
Definition Expr.h:1992
@ Implicit
An implicit conversion.
Definition Sema.h:440
CharacterLiteralKind
Definition Expr.h:1606
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:180
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5096
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:620
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5442
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13207
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6836
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6871
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6922
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6856
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6876
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:6884
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6880
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6890
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:6851
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6898
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6841
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6838
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6845
Abstract class used to diagnose incomplete types.
Definition Sema.h:8333
Location information for a TemplateArgument.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Describes an entity that is being assigned.