clang 19.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 "TreeTransform.h"
14#include "UsedDeclVisitor.h"
17#include "clang/AST/ASTLambda.h"
20#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
42#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
50#include "clang/Sema/Scope.h"
52#include "clang/Sema/SemaCUDA.h"
56#include "clang/Sema/Template.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/STLForwardCompat.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/ConvertUTF.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/TypeSize.h"
64#include <optional>
65
66using namespace clang;
67using namespace sema;
68
69/// Determine whether the use of this declaration is valid, without
70/// emitting diagnostics.
71bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
72 // See if this is an auto-typed variable whose initializer we are parsing.
73 if (ParsingInitForAutoVars.count(D))
74 return false;
75
76 // See if this is a deleted function.
77 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
78 if (FD->isDeleted())
79 return false;
80
81 // If the function has a deduced return type, and we can't deduce it,
82 // then we can't use it either.
83 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
84 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
85 return false;
86
87 // See if this is an aligned allocation/deallocation function that is
88 // unavailable.
89 if (TreatUnavailableAsInvalid &&
91 return false;
92 }
93
94 // See if this function is unavailable.
95 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
96 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
97 return false;
98
99 if (isa<UnresolvedUsingIfExistsDecl>(D))
100 return false;
101
102 return true;
103}
104
106 // Warn if this is used but marked unused.
107 if (const auto *A = D->getAttr<UnusedAttr>()) {
108 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
109 // should diagnose them.
110 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
111 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
112 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
113 if (DC && !DC->hasAttr<UnusedAttr>())
114 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
115 }
116 }
117}
118
119/// Emit a note explaining that this function is deleted.
121 assert(Decl && Decl->isDeleted());
122
123 if (Decl->isDefaulted()) {
124 // If the method was explicitly defaulted, point at that declaration.
125 if (!Decl->isImplicit())
126 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
127
128 // Try to diagnose why this special member function was implicitly
129 // deleted. This might fail, if that reason no longer applies.
131 return;
132 }
133
134 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
135 if (Ctor && Ctor->isInheritingConstructor())
137
138 Diag(Decl->getLocation(), diag::note_availability_specified_here)
139 << Decl << 1;
140}
141
142/// Determine whether a FunctionDecl was ever declared with an
143/// explicit storage class.
145 for (auto *I : D->redecls()) {
146 if (I->getStorageClass() != SC_None)
147 return true;
148 }
149 return false;
150}
151
152/// Check whether we're in an extern inline function and referring to a
153/// variable or function with internal linkage (C11 6.7.4p3).
154///
155/// This is only a warning because we used to silently accept this code, but
156/// in many cases it will not behave correctly. This is not enabled in C++ mode
157/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
158/// and so while there may still be user mistakes, most of the time we can't
159/// prove that there are errors.
161 const NamedDecl *D,
162 SourceLocation Loc) {
163 // This is disabled under C++; there are too many ways for this to fire in
164 // contexts where the warning is a false positive, or where it is technically
165 // correct but benign.
166 if (S.getLangOpts().CPlusPlus)
167 return;
168
169 // Check if this is an inlined function or method.
170 FunctionDecl *Current = S.getCurFunctionDecl();
171 if (!Current)
172 return;
173 if (!Current->isInlined())
174 return;
175 if (!Current->isExternallyVisible())
176 return;
177
178 // Check if the decl has internal linkage.
180 return;
181
182 // Downgrade from ExtWarn to Extension if
183 // (1) the supposedly external inline function is in the main file,
184 // and probably won't be included anywhere else.
185 // (2) the thing we're referencing is a pure function.
186 // (3) the thing we're referencing is another inline function.
187 // This last can give us false negatives, but it's better than warning on
188 // wrappers for simple C library functions.
189 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
190 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
191 if (!DowngradeWarning && UsedFn)
192 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
193
194 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
195 : diag::ext_internal_in_extern_inline)
196 << /*IsVar=*/!UsedFn << D;
197
199
200 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201 << D;
202}
203
205 const FunctionDecl *First = Cur->getFirstDecl();
206
207 // Suggest "static" on the function, if possible.
209 SourceLocation DeclBegin = First->getSourceRange().getBegin();
210 Diag(DeclBegin, diag::note_convert_inline_to_static)
211 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212 }
213}
214
215/// Determine whether the use of this declaration is valid, and
216/// emit any corresponding diagnostics.
217///
218/// This routine diagnoses various problems with referencing
219/// declarations that can occur when using a declaration. For example,
220/// it might warn if a deprecated or unavailable declaration is being
221/// used, or produce an error (and return true) if a C++0x deleted
222/// function is being used.
223///
224/// \returns true if there was an error (this declaration cannot be
225/// referenced), false otherwise.
226///
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
234 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const PartialDiagnosticAt &Suppressed : Pos->second)
240 Diag(Suppressed.first, Suppressed.second);
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
254 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
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 << D->getDeclName() << cast<VarDecl>(D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
317 return true;
318
319 }
320
321 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
322 // Lambdas are only default-constructible or assignable in C++2a onwards.
323 if (MD->getParent()->isLambda() &&
324 ((isa<CXXConstructorDecl>(MD) &&
325 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
326 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
327 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
328 << !isa<CXXConstructorDecl>(MD);
329 }
330 }
331
332 auto getReferencedObjCProp = [](const NamedDecl *D) ->
333 const ObjCPropertyDecl * {
334 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
335 return MD->findPropertyDecl();
336 return nullptr;
337 };
338 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
339 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
340 return true;
341 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
342 return true;
343 }
344
345 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
346 // Only the variables omp_in and omp_out are allowed in the combiner.
347 // Only the variables omp_priv and omp_orig are allowed in the
348 // initializer-clause.
349 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
350 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
351 isa<VarDecl>(D)) {
352 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
354 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
355 return true;
356 }
357
358 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
359 // List-items in map clauses on this construct may only refer to the declared
360 // variable var and entities that could be referenced by a procedure defined
361 // at the same location.
362 // [OpenMP 5.2] Also allow iterator declared variables.
363 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
364 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
365 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
367 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
368 return true;
369 }
370
371 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
372 Diag(Loc, diag::err_use_of_empty_using_if_exists);
373 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
374 return true;
375 }
376
377 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
378 AvoidPartialAvailabilityChecks, ClassReceiver);
379
380 DiagnoseUnusedOfDecl(*this, D, Loc);
381
383
384 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
385 if (getLangOpts().getFPEvalMethod() !=
388 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
389 Diag(D->getLocation(),
390 diag::err_type_available_only_in_default_eval_method)
391 << D->getName();
392 }
393
394 if (auto *VD = dyn_cast<ValueDecl>(D))
395 checkTypeSupport(VD->getType(), Loc, VD);
396
397 if (LangOpts.SYCLIsDevice ||
398 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
400 if (const auto *VD = dyn_cast<VarDecl>(D))
401 if (VD->getTLSKind() != VarDecl::TLS_None)
402 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
403 }
404
405 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
407 // C++ [expr.prim.req.nested] p3
408 // A local parameter shall only appear as an unevaluated operand
409 // (Clause 8) within the constraint-expression.
410 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
411 << D;
412 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
413 return true;
414 }
415
416 return false;
417}
418
419/// DiagnoseSentinelCalls - This routine checks whether a call or
420/// message-send is to a declaration with the sentinel attribute, and
421/// if so, it checks that the requirements of the sentinel are
422/// satisfied.
424 ArrayRef<Expr *> Args) {
425 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
426 if (!Attr)
427 return;
428
429 // The number of formal parameters of the declaration.
430 unsigned NumFormalParams;
431
432 // The kind of declaration. This is also an index into a %select in
433 // the diagnostic.
434 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
435
436 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
437 NumFormalParams = MD->param_size();
438 CalleeKind = CK_Method;
439 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
440 NumFormalParams = FD->param_size();
441 CalleeKind = CK_Function;
442 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
443 QualType Ty = VD->getType();
444 const FunctionType *Fn = nullptr;
445 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
446 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
447 if (!Fn)
448 return;
449 CalleeKind = CK_Function;
450 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
451 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
452 CalleeKind = CK_Block;
453 } else {
454 return;
455 }
456
457 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
458 NumFormalParams = proto->getNumParams();
459 else
460 NumFormalParams = 0;
461 } else {
462 return;
463 }
464
465 // "NullPos" is the number of formal parameters at the end which
466 // effectively count as part of the variadic arguments. This is
467 // useful if you would prefer to not have *any* formal parameters,
468 // but the language forces you to have at least one.
469 unsigned NullPos = Attr->getNullPos();
470 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
471 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
472
473 // The number of arguments which should follow the sentinel.
474 unsigned NumArgsAfterSentinel = Attr->getSentinel();
475
476 // If there aren't enough arguments for all the formal parameters,
477 // the sentinel, and the args after the sentinel, complain.
478 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
479 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
480 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
481 return;
482 }
483
484 // Otherwise, find the sentinel expression.
485 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
486 if (!SentinelExpr)
487 return;
488 if (SentinelExpr->isValueDependent())
489 return;
490 if (Context.isSentinelNullExpr(SentinelExpr))
491 return;
492
493 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
494 // or 'NULL' if those are actually defined in the context. Only use
495 // 'nil' for ObjC methods, where it's much more likely that the
496 // variadic arguments form a list of object pointers.
497 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
498 std::string NullValue;
499 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
500 NullValue = "nil";
501 else if (getLangOpts().CPlusPlus11)
502 NullValue = "nullptr";
503 else if (PP.isMacroDefined("NULL"))
504 NullValue = "NULL";
505 else
506 NullValue = "(void*) 0";
507
508 if (MissingNilLoc.isInvalid())
509 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
510 else
511 Diag(MissingNilLoc, diag::warn_missing_sentinel)
512 << int(CalleeKind)
513 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
514 Diag(D->getLocation(), diag::note_sentinel_here)
515 << int(CalleeKind) << Attr->getRange();
516}
517
519 return E ? E->getSourceRange() : SourceRange();
520}
521
522//===----------------------------------------------------------------------===//
523// Standard Promotions and Conversions
524//===----------------------------------------------------------------------===//
525
526/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
528 // Handle any placeholder expressions which made it here.
529 if (E->hasPlaceholderType()) {
531 if (result.isInvalid()) return ExprError();
532 E = result.get();
533 }
534
535 QualType Ty = E->getType();
536 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
537
538 if (Ty->isFunctionType()) {
539 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
540 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
542 return ExprError();
543
545 CK_FunctionToPointerDecay).get();
546 } else if (Ty->isArrayType()) {
547 // In C90 mode, arrays only promote to pointers if the array expression is
548 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
549 // type 'array of type' is converted to an expression that has type 'pointer
550 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
551 // that has type 'array of type' ...". The relevant change is "an lvalue"
552 // (C90) to "an expression" (C99).
553 //
554 // C++ 4.2p1:
555 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
556 // T" can be converted to an rvalue of type "pointer to T".
557 //
558 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
560 CK_ArrayToPointerDecay);
561 if (Res.isInvalid())
562 return ExprError();
563 E = Res.get();
564 }
565 }
566 return E;
567}
568
570 // Check to see if we are dereferencing a null pointer. If so,
571 // and if not volatile-qualified, this is undefined behavior that the
572 // optimizer will delete, so warn about it. People sometimes try to use this
573 // to get a deterministic trap and are surprised by clang's behavior. This
574 // only handles the pattern "*null", which is a very syntactic check.
575 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
576 if (UO && UO->getOpcode() == UO_Deref &&
577 UO->getSubExpr()->getType()->isPointerType()) {
578 const LangAS AS =
579 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
580 if ((!isTargetAddressSpace(AS) ||
581 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
582 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
584 !UO->getType().isVolatileQualified()) {
585 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
586 S.PDiag(diag::warn_indirection_through_null)
587 << UO->getSubExpr()->getSourceRange());
588 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
589 S.PDiag(diag::note_indirection_through_null));
590 }
591 }
592}
593
594static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
595 SourceLocation AssignLoc,
596 const Expr* RHS) {
597 const ObjCIvarDecl *IV = OIRE->getDecl();
598 if (!IV)
599 return;
600
601 DeclarationName MemberName = IV->getDeclName();
603 if (!Member || !Member->isStr("isa"))
604 return;
605
606 const Expr *Base = OIRE->getBase();
607 QualType BaseType = Base->getType();
608 if (OIRE->isArrow())
609 BaseType = BaseType->getPointeeType();
610 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
611 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
612 ObjCInterfaceDecl *ClassDeclared = nullptr;
613 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
614 if (!ClassDeclared->getSuperClass()
615 && (*ClassDeclared->ivar_begin()) == IV) {
616 if (RHS) {
617 NamedDecl *ObjectSetClass =
619 &S.Context.Idents.get("object_setClass"),
621 if (ObjectSetClass) {
622 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
623 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
625 "object_setClass(")
627 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
628 << FixItHint::CreateInsertion(RHSLocEnd, ")");
629 }
630 else
631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
632 } else {
633 NamedDecl *ObjectGetClass =
635 &S.Context.Idents.get("object_getClass"),
637 if (ObjectGetClass)
638 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
640 "object_getClass(")
642 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
643 else
644 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
645 }
646 S.Diag(IV->getLocation(), diag::note_ivar_decl);
647 }
648 }
649}
650
652 // Handle any placeholder expressions which made it here.
653 if (E->hasPlaceholderType()) {
655 if (result.isInvalid()) return ExprError();
656 E = result.get();
657 }
658
659 // C++ [conv.lval]p1:
660 // A glvalue of a non-function, non-array type T can be
661 // converted to a prvalue.
662 if (!E->isGLValue()) return E;
663
664 QualType T = E->getType();
665 assert(!T.isNull() && "r-value conversion on typeless expression?");
666
667 // lvalue-to-rvalue conversion cannot be applied to types that decay to
668 // pointers (i.e. function or array types).
670 return E;
671
672 // We don't want to throw lvalue-to-rvalue casts on top of
673 // expressions of certain types in C++.
674 if (getLangOpts().CPlusPlus &&
675 (E->getType() == Context.OverloadTy ||
676 T->isDependentType() ||
677 T->isRecordType()))
678 return E;
679
680 // The C standard is actually really unclear on this point, and
681 // DR106 tells us what the result should be but not why. It's
682 // generally best to say that void types just doesn't undergo
683 // lvalue-to-rvalue at all. Note that expressions of unqualified
684 // 'void' type are never l-values, but qualified void can be.
685 if (T->isVoidType())
686 return E;
687
688 // OpenCL usually rejects direct accesses to values of 'half' type.
689 if (getLangOpts().OpenCL &&
690 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
691 T->isHalfType()) {
692 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
693 << 0 << T;
694 return ExprError();
695 }
696
698 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
699 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
700 &Context.Idents.get("object_getClass"),
702 if (ObjectGetClass)
703 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
704 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
706 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
707 else
708 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
709 }
710 else if (const ObjCIvarRefExpr *OIRE =
711 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
712 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
713
714 // C++ [conv.lval]p1:
715 // [...] If T is a non-class type, the type of the prvalue is the
716 // cv-unqualified version of T. Otherwise, the type of the
717 // rvalue is T.
718 //
719 // C99 6.3.2.1p2:
720 // If the lvalue has qualified type, the value has the unqualified
721 // version of the type of the lvalue; otherwise, the value has the
722 // type of the lvalue.
723 if (T.hasQualifiers())
724 T = T.getUnqualifiedType();
725
726 // Under the MS ABI, lock down the inheritance model now.
727 if (T->isMemberPointerType() &&
729 (void)isCompleteType(E->getExprLoc(), T);
730
732 if (Res.isInvalid())
733 return Res;
734 E = Res.get();
735
736 // Loading a __weak object implicitly retains the value, so we need a cleanup to
737 // balance that.
740
743
744 // C++ [conv.lval]p3:
745 // If T is cv std::nullptr_t, the result is a null pointer constant.
746 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
747 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
749
750 // C11 6.3.2.1p2:
751 // ... if the lvalue has atomic type, the value has the non-atomic version
752 // of the type of the lvalue ...
753 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
754 T = Atomic->getValueType().getUnqualifiedType();
755 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
756 nullptr, VK_PRValue, FPOptionsOverride());
757 }
758
759 return Res;
760}
761
764 if (Res.isInvalid())
765 return ExprError();
766 Res = DefaultLvalueConversion(Res.get());
767 if (Res.isInvalid())
768 return ExprError();
769 return Res;
770}
771
772/// CallExprUnaryConversions - a special case of an unary conversion
773/// performed on a function designator of a call expression.
775 QualType Ty = E->getType();
776 ExprResult Res = E;
777 // Only do implicit cast for a function type, but not for a pointer
778 // to function type.
779 if (Ty->isFunctionType()) {
781 CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(Res.get());
786 if (Res.isInvalid())
787 return ExprError();
788 return Res.get();
789}
790
791/// UsualUnaryConversions - Performs various conversions that are common to most
792/// operators (C99 6.3). The conversions of array and function types are
793/// sometimes suppressed. For example, the array->pointer conversion doesn't
794/// apply if the array is an argument to the sizeof or address (&) operators.
795/// In these instances, this routine should *not* be called.
797 // First, convert to an r-value.
799 if (Res.isInvalid())
800 return ExprError();
801 E = Res.get();
802
803 QualType Ty = E->getType();
804 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
805
806 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
807 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
808 (getLangOpts().getFPEvalMethod() !=
811 switch (EvalMethod) {
812 default:
813 llvm_unreachable("Unrecognized float evaluation method");
814 break;
816 llvm_unreachable("Float evaluation method should be set by now");
817 break;
820 // Widen the expression to double.
821 return Ty->isComplexType()
824 CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
826 break;
829 // Widen the expression to long double.
830 return Ty->isComplexType()
833 CK_FloatingComplexCast)
835 CK_FloatingCast);
836 break;
837 }
838 }
839
840 // Half FP have to be promoted to float unless it is natively supported
841 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
842 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
843
844 // Try to perform integral promotions if the object has a theoretically
845 // promotable type.
847 // C99 6.3.1.1p2:
848 //
849 // The following may be used in an expression wherever an int or
850 // unsigned int may be used:
851 // - an object or expression with an integer type whose integer
852 // conversion rank is less than or equal to the rank of int
853 // and unsigned int.
854 // - A bit-field of type _Bool, int, signed int, or unsigned int.
855 //
856 // If an int can represent all values of the original type, the
857 // value is converted to an int; otherwise, it is converted to an
858 // unsigned int. These are called the integer promotions. All
859 // other types are unchanged by the integer promotions.
860
862 if (!PTy.isNull()) {
863 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
864 return E;
865 }
868 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
869 return E;
870 }
871 }
872 return E;
873}
874
875/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
876/// do not have a prototype. Arguments that have type float or __fp16
877/// are promoted to double. All other argument types are converted by
878/// UsualUnaryConversions().
880 QualType Ty = E->getType();
881 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
882
884 if (Res.isInvalid())
885 return ExprError();
886 E = Res.get();
887
888 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
889 // promote to double.
890 // Note that default argument promotion applies only to float (and
891 // half/fp16); it does not apply to _Float16.
892 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
893 if (BTy && (BTy->getKind() == BuiltinType::Half ||
894 BTy->getKind() == BuiltinType::Float)) {
895 if (getLangOpts().OpenCL &&
896 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
897 if (BTy->getKind() == BuiltinType::Half) {
898 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
899 }
900 } else {
901 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
902 }
903 }
904 if (BTy &&
905 getLangOpts().getExtendIntArgs() ==
910 E = (Ty->isUnsignedIntegerType())
911 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
912 .get()
913 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
915 "Unexpected typesize for LongLongTy");
916 }
917
918 // C++ performs lvalue-to-rvalue conversion as a default argument
919 // promotion, even on class types, but note:
920 // C++11 [conv.lval]p2:
921 // When an lvalue-to-rvalue conversion occurs in an unevaluated
922 // operand or a subexpression thereof the value contained in the
923 // referenced object is not accessed. Otherwise, if the glvalue
924 // has a class type, the conversion copy-initializes a temporary
925 // of type T from the glvalue and the result of the conversion
926 // is a prvalue for the temporary.
927 // FIXME: add some way to gate this entire thing for correctness in
928 // potentially potentially evaluated contexts.
932 E->getExprLoc(), E);
933 if (Temp.isInvalid())
934 return ExprError();
935 E = Temp.get();
936 }
937
938 return E;
939}
940
941/// Determine the degree of POD-ness for an expression.
942/// Incomplete types are considered POD, since this check can be performed
943/// when we're in an unevaluated context.
945 if (Ty->isIncompleteType()) {
946 // C++11 [expr.call]p7:
947 // After these conversions, if the argument does not have arithmetic,
948 // enumeration, pointer, pointer to member, or class type, the program
949 // is ill-formed.
950 //
951 // Since we've already performed array-to-pointer and function-to-pointer
952 // decay, the only such type in C++ is cv void. This also handles
953 // initializer lists as variadic arguments.
954 if (Ty->isVoidType())
955 return VAK_Invalid;
956
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
959 return VAK_Valid;
960 }
961
963 return VAK_Invalid;
964
965 if (Context.getTargetInfo().getTriple().isWasm() &&
967 return VAK_Invalid;
968 }
969
970 if (Ty.isCXX98PODType(Context))
971 return VAK_Valid;
972
973 // C++11 [expr.call]p7:
974 // Passing a potentially-evaluated argument of class type (Clause 9)
975 // having a non-trivial copy constructor, a non-trivial move constructor,
976 // or a non-trivial destructor, with no corresponding parameter,
977 // is conditionally-supported with implementation-defined semantics.
980 if (!Record->hasNonTrivialCopyConstructor() &&
981 !Record->hasNonTrivialMoveConstructor() &&
982 !Record->hasNonTrivialDestructor())
983 return VAK_ValidInCXX11;
984
985 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
986 return VAK_Valid;
987
988 if (Ty->isObjCObjectType())
989 return VAK_Invalid;
990
991 if (getLangOpts().MSVCCompat)
992 return VAK_MSVCUndefined;
993
994 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
995 // permitted to reject them. We should consider doing so.
996 return VAK_Undefined;
997}
998
1000 // Don't allow one to pass an Objective-C interface to a vararg.
1001 const QualType &Ty = E->getType();
1002 VarArgKind VAK = isValidVarArgType(Ty);
1003
1004 // Complain about passing non-POD types through varargs.
1005 switch (VAK) {
1006 case VAK_ValidInCXX11:
1008 E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1010 [[fallthrough]];
1011 case VAK_Valid:
1012 if (Ty->isRecordType()) {
1013 // This is unlikely to be what the user intended. If the class has a
1014 // 'c_str' member function, the user probably meant to call that.
1015 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1016 PDiag(diag::warn_pass_class_arg_to_vararg)
1017 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1018 }
1019 break;
1020
1021 case VAK_Undefined:
1022 case VAK_MSVCUndefined:
1023 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1025 << getLangOpts().CPlusPlus11 << Ty << CT);
1026 break;
1027
1028 case VAK_Invalid:
1030 Diag(E->getBeginLoc(),
1031 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1032 << Ty << CT;
1033 else if (Ty->isObjCObjectType())
1034 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1035 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1036 << Ty << CT);
1037 else
1038 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1039 << isa<InitListExpr>(E) << Ty << CT;
1040 break;
1041 }
1042}
1043
1044/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1045/// will create a trap if the resulting type is not a POD type.
1047 FunctionDecl *FDecl) {
1048 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1049 // Strip the unbridged-cast placeholder expression off, if applicable.
1050 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1051 (CT == VariadicMethod ||
1052 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1053 E = stripARCUnbridgedCast(E);
1054
1055 // Otherwise, do normal placeholder checking.
1056 } else {
1057 ExprResult ExprRes = CheckPlaceholderExpr(E);
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1060 E = ExprRes.get();
1061 }
1062 }
1063
1065 if (ExprRes.isInvalid())
1066 return ExprError();
1067
1068 // Copy blocks to the heap.
1069 if (ExprRes.get()->getType()->isBlockPointerType())
1070 maybeExtendBlockObject(ExprRes);
1071
1072 E = ExprRes.get();
1073
1074 // Diagnostics regarding non-POD argument types are
1075 // emitted along with format string checking in Sema::CheckFunctionCall().
1077 // Turn this into a trap.
1078 CXXScopeSpec SS;
1079 SourceLocation TemplateKWLoc;
1080 UnqualifiedId Name;
1081 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1082 E->getBeginLoc());
1083 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1084 /*HasTrailingLParen=*/true,
1085 /*IsAddressOfOperand=*/false);
1086 if (TrapFn.isInvalid())
1087 return ExprError();
1088
1090 std::nullopt, E->getEndLoc());
1091 if (Call.isInvalid())
1092 return ExprError();
1093
1094 ExprResult Comma =
1095 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1096 if (Comma.isInvalid())
1097 return ExprError();
1098 return Comma.get();
1099 }
1100
1101 if (!getLangOpts().CPlusPlus &&
1103 diag::err_call_incomplete_argument))
1104 return ExprError();
1105
1106 return E;
1107}
1108
1109/// Convert complex integers to complex floats and real integers to
1110/// real floats as required for complex arithmetic. Helper function of
1111/// UsualArithmeticConversions()
1112///
1113/// \return false if the integer expression is an integer type and is
1114/// successfully converted to the (complex) float type.
1116 ExprResult &ComplexExpr,
1117 QualType IntTy,
1118 QualType ComplexTy,
1119 bool SkipCast) {
1120 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1121 if (SkipCast) return false;
1122 if (IntTy->isIntegerType()) {
1123 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1124 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1125 } else {
1126 assert(IntTy->isComplexIntegerType());
1127 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1128 CK_IntegralComplexToFloatingComplex);
1129 }
1130 return false;
1131}
1132
1133// This handles complex/complex, complex/float, or float/complex.
1134// When both operands are complex, the shorter operand is converted to the
1135// type of the longer, and that is the type of the result. This corresponds
1136// to what is done when combining two real floating-point operands.
1137// The fun begins when size promotion occur across type domains.
1138// From H&S 6.3.4: When one operand is complex and the other is a real
1139// floating-point type, the less precise type is converted, within it's
1140// real or complex domain, to the precision of the other type. For example,
1141// when combining a "long double" with a "double _Complex", the
1142// "double _Complex" is promoted to "long double _Complex".
1144 QualType ShorterType,
1145 QualType LongerType,
1146 bool PromotePrecision) {
1147 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1149 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1150
1151 if (PromotePrecision) {
1152 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1153 Shorter =
1154 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1155 } else {
1156 if (LongerIsComplex)
1157 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1158 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1159 }
1160 }
1161 return Result;
1162}
1163
1164/// Handle arithmetic conversion with complex types. Helper function of
1165/// UsualArithmeticConversions()
1167 ExprResult &RHS, QualType LHSType,
1168 QualType RHSType, bool IsCompAssign) {
1169 // Handle (complex) integer types.
1170 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1171 /*SkipCast=*/false))
1172 return LHSType;
1173 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1174 /*SkipCast=*/IsCompAssign))
1175 return RHSType;
1176
1177 // Compute the rank of the two types, regardless of whether they are complex.
1178 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1179 if (Order < 0)
1180 // Promote the precision of the LHS if not an assignment.
1181 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1182 /*PromotePrecision=*/!IsCompAssign);
1183 // Promote the precision of the RHS unless it is already the same as the LHS.
1184 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1185 /*PromotePrecision=*/Order > 0);
1186}
1187
1188/// Handle arithmetic conversion from integer to float. Helper function
1189/// of UsualArithmeticConversions()
1191 ExprResult &IntExpr,
1192 QualType FloatTy, QualType IntTy,
1193 bool ConvertFloat, bool ConvertInt) {
1194 if (IntTy->isIntegerType()) {
1195 if (ConvertInt)
1196 // Convert intExpr to the lhs floating point type.
1197 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1198 CK_IntegralToFloating);
1199 return FloatTy;
1200 }
1201
1202 // Convert both sides to the appropriate complex float.
1203 assert(IntTy->isComplexIntegerType());
1204 QualType result = S.Context.getComplexType(FloatTy);
1205
1206 // _Complex int -> _Complex float
1207 if (ConvertInt)
1208 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1209 CK_IntegralComplexToFloatingComplex);
1210
1211 // float -> _Complex float
1212 if (ConvertFloat)
1213 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1214 CK_FloatingRealToComplex);
1215
1216 return result;
1217}
1218
1219/// Handle arithmethic conversion with floating point types. Helper
1220/// function of UsualArithmeticConversions()
1222 ExprResult &RHS, QualType LHSType,
1223 QualType RHSType, bool IsCompAssign) {
1224 bool LHSFloat = LHSType->isRealFloatingType();
1225 bool RHSFloat = RHSType->isRealFloatingType();
1226
1227 // N1169 4.1.4: If one of the operands has a floating type and the other
1228 // operand has a fixed-point type, the fixed-point operand
1229 // is converted to the floating type [...]
1230 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1231 if (LHSFloat)
1232 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1233 else if (!IsCompAssign)
1234 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1235 return LHSFloat ? LHSType : RHSType;
1236 }
1237
1238 // If we have two real floating types, convert the smaller operand
1239 // to the bigger result.
1240 if (LHSFloat && RHSFloat) {
1241 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1242 if (order > 0) {
1243 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1244 return LHSType;
1245 }
1246
1247 assert(order < 0 && "illegal float comparison");
1248 if (!IsCompAssign)
1249 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1250 return RHSType;
1251 }
1252
1253 if (LHSFloat) {
1254 // Half FP has to be promoted to float unless it is natively supported
1255 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1256 LHSType = S.Context.FloatTy;
1257
1258 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1259 /*ConvertFloat=*/!IsCompAssign,
1260 /*ConvertInt=*/ true);
1261 }
1262 assert(RHSFloat);
1263 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1264 /*ConvertFloat=*/ true,
1265 /*ConvertInt=*/!IsCompAssign);
1266}
1267
1268/// Diagnose attempts to convert between __float128, __ibm128 and
1269/// long double if there is no support for such conversion.
1270/// Helper function of UsualArithmeticConversions().
1271static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1272 QualType RHSType) {
1273 // No issue if either is not a floating point type.
1274 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1275 return false;
1276
1277 // No issue if both have the same 128-bit float semantics.
1278 auto *LHSComplex = LHSType->getAs<ComplexType>();
1279 auto *RHSComplex = RHSType->getAs<ComplexType>();
1280
1281 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1282 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1283
1284 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1285 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1286
1287 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1288 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1289 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1290 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1291 return false;
1292
1293 return true;
1294}
1295
1296typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1297
1298namespace {
1299/// These helper callbacks are placed in an anonymous namespace to
1300/// permit their use as function template parameters.
1301ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1303}
1304
1305ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1306 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1307 CK_IntegralComplexCast);
1308}
1309}
1310
1311/// Handle integer arithmetic conversions. Helper function of
1312/// UsualArithmeticConversions()
1313template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1315 ExprResult &RHS, QualType LHSType,
1316 QualType RHSType, bool IsCompAssign) {
1317 // The rules for this case are in C99 6.3.1.8
1318 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1319 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1320 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1321 if (LHSSigned == RHSSigned) {
1322 // Same signedness; use the higher-ranked type
1323 if (order >= 0) {
1324 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1325 return LHSType;
1326 } else if (!IsCompAssign)
1327 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1328 return RHSType;
1329 } else if (order != (LHSSigned ? 1 : -1)) {
1330 // The unsigned type has greater than or equal rank to the
1331 // signed type, so use the unsigned type
1332 if (RHSSigned) {
1333 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1334 return LHSType;
1335 } else if (!IsCompAssign)
1336 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1337 return RHSType;
1338 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1339 // The two types are different widths; if we are here, that
1340 // means the signed type is larger than the unsigned type, so
1341 // use the signed type.
1342 if (LHSSigned) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else {
1349 // The signed type is higher-ranked than the unsigned type,
1350 // but isn't actually any bigger (like unsigned int and long
1351 // on most 32-bit systems). Use the unsigned type corresponding
1352 // to the signed type.
1353 QualType result =
1354 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1355 RHS = (*doRHSCast)(S, RHS.get(), result);
1356 if (!IsCompAssign)
1357 LHS = (*doLHSCast)(S, LHS.get(), result);
1358 return result;
1359 }
1360}
1361
1362/// Handle conversions with GCC complex int extension. Helper function
1363/// of UsualArithmeticConversions()
1365 ExprResult &RHS, QualType LHSType,
1366 QualType RHSType,
1367 bool IsCompAssign) {
1368 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1369 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1370
1371 if (LHSComplexInt && RHSComplexInt) {
1372 QualType LHSEltType = LHSComplexInt->getElementType();
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1377
1378 return S.Context.getComplexType(ScalarType);
1379 }
1380
1381 if (LHSComplexInt) {
1382 QualType LHSEltType = LHSComplexInt->getElementType();
1383 QualType ScalarType =
1384 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1385 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1387 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1388 CK_IntegralRealToComplex);
1389
1390 return ComplexType;
1391 }
1392
1393 assert(RHSComplexInt);
1394
1395 QualType RHSEltType = RHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1398 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1400
1401 if (!IsCompAssign)
1402 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1403 CK_IntegralRealToComplex);
1404 return ComplexType;
1405}
1406
1407/// Return the rank of a given fixed point or integer type. The value itself
1408/// doesn't matter, but the values must be increasing with proper increasing
1409/// rank as described in N1169 4.1.1.
1410static unsigned GetFixedPointRank(QualType Ty) {
1411 const auto *BTy = Ty->getAs<BuiltinType>();
1412 assert(BTy && "Expected a builtin type.");
1413
1414 switch (BTy->getKind()) {
1415 case BuiltinType::ShortFract:
1416 case BuiltinType::UShortFract:
1417 case BuiltinType::SatShortFract:
1418 case BuiltinType::SatUShortFract:
1419 return 1;
1420 case BuiltinType::Fract:
1421 case BuiltinType::UFract:
1422 case BuiltinType::SatFract:
1423 case BuiltinType::SatUFract:
1424 return 2;
1425 case BuiltinType::LongFract:
1426 case BuiltinType::ULongFract:
1427 case BuiltinType::SatLongFract:
1428 case BuiltinType::SatULongFract:
1429 return 3;
1430 case BuiltinType::ShortAccum:
1431 case BuiltinType::UShortAccum:
1432 case BuiltinType::SatShortAccum:
1433 case BuiltinType::SatUShortAccum:
1434 return 4;
1435 case BuiltinType::Accum:
1436 case BuiltinType::UAccum:
1437 case BuiltinType::SatAccum:
1438 case BuiltinType::SatUAccum:
1439 return 5;
1440 case BuiltinType::LongAccum:
1441 case BuiltinType::ULongAccum:
1442 case BuiltinType::SatLongAccum:
1443 case BuiltinType::SatULongAccum:
1444 return 6;
1445 default:
1446 if (BTy->isInteger())
1447 return 0;
1448 llvm_unreachable("Unexpected fixed point or integer type");
1449 }
1450}
1451
1452/// handleFixedPointConversion - Fixed point operations between fixed
1453/// point types and integers or other fixed point types do not fall under
1454/// usual arithmetic conversion since these conversions could result in loss
1455/// of precsision (N1169 4.1.4). These operations should be calculated with
1456/// the full precision of their result type (N1169 4.1.6.2.1).
1458 QualType RHSTy) {
1459 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1460 "Expected at least one of the operands to be a fixed point type");
1461 assert((LHSTy->isFixedPointOrIntegerType() ||
1462 RHSTy->isFixedPointOrIntegerType()) &&
1463 "Special fixed point arithmetic operation conversions are only "
1464 "applied to ints or other fixed point types");
1465
1466 // If one operand has signed fixed-point type and the other operand has
1467 // unsigned fixed-point type, then the unsigned fixed-point operand is
1468 // converted to its corresponding signed fixed-point type and the resulting
1469 // type is the type of the converted operand.
1470 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1472 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1474
1475 // The result type is the type with the highest rank, whereby a fixed-point
1476 // conversion rank is always greater than an integer conversion rank; if the
1477 // type of either of the operands is a saturating fixedpoint type, the result
1478 // type shall be the saturating fixed-point type corresponding to the type
1479 // with the highest rank; the resulting value is converted (taking into
1480 // account rounding and overflow) to the precision of the resulting type.
1481 // Same ranks between signed and unsigned types are resolved earlier, so both
1482 // types are either signed or both unsigned at this point.
1483 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1484 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1485
1486 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1487
1489 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1490
1491 return ResultTy;
1492}
1493
1494/// Check that the usual arithmetic conversions can be performed on this pair of
1495/// expressions that might be of enumeration type.
1497 SourceLocation Loc,
1498 Sema::ArithConvKind ACK) {
1499 // C++2a [expr.arith.conv]p1:
1500 // If one operand is of enumeration type and the other operand is of a
1501 // different enumeration type or a floating-point type, this behavior is
1502 // deprecated ([depr.arith.conv.enum]).
1503 //
1504 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1505 // Eventually we will presumably reject these cases (in C++23 onwards?).
1507 R = RHS->getEnumCoercedType(S.Context);
1508 bool LEnum = L->isUnscopedEnumerationType(),
1509 REnum = R->isUnscopedEnumerationType();
1510 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1511 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1512 (REnum && L->isFloatingType())) {
1513 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1514 ? diag::err_arith_conv_enum_float_cxx26
1515 : S.getLangOpts().CPlusPlus20
1516 ? diag::warn_arith_conv_enum_float_cxx20
1517 : diag::warn_arith_conv_enum_float)
1518 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1519 << L << R;
1520 } else if (!IsCompAssign && LEnum && REnum &&
1522 unsigned DiagID;
1523 // In C++ 26, usual arithmetic conversions between 2 different enum types
1524 // are ill-formed.
1525 if (S.getLangOpts().CPlusPlus26)
1526 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1527 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1528 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1529 // If either enumeration type is unnamed, it's less likely that the
1530 // user cares about this, but this situation is still deprecated in
1531 // C++2a. Use a different warning group.
1532 DiagID = S.getLangOpts().CPlusPlus20
1533 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1534 : diag::warn_arith_conv_mixed_anon_enum_types;
1535 } else if (ACK == Sema::ACK_Conditional) {
1536 // Conditional expressions are separated out because they have
1537 // historically had a different warning flag.
1538 DiagID = S.getLangOpts().CPlusPlus20
1539 ? diag::warn_conditional_mixed_enum_types_cxx20
1540 : diag::warn_conditional_mixed_enum_types;
1541 } else if (ACK == Sema::ACK_Comparison) {
1542 // Comparison expressions are separated out because they have
1543 // historically had a different warning flag.
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_comparison_mixed_enum_types_cxx20
1546 : diag::warn_comparison_mixed_enum_types;
1547 } else {
1548 DiagID = S.getLangOpts().CPlusPlus20
1549 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1550 : diag::warn_arith_conv_mixed_enum_types;
1551 }
1552 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1553 << (int)ACK << L << R;
1554 }
1555}
1556
1557/// UsualArithmeticConversions - Performs various conversions that are common to
1558/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1559/// routine returns the first non-arithmetic type found. The client is
1560/// responsible for emitting appropriate error diagnostics.
1562 SourceLocation Loc,
1563 ArithConvKind ACK) {
1564 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1565
1566 if (ACK != ACK_CompAssign) {
1567 LHS = UsualUnaryConversions(LHS.get());
1568 if (LHS.isInvalid())
1569 return QualType();
1570 }
1571
1572 RHS = UsualUnaryConversions(RHS.get());
1573 if (RHS.isInvalid())
1574 return QualType();
1575
1576 // For conversion purposes, we ignore any qualifiers.
1577 // For example, "const float" and "float" are equivalent.
1578 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1579 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1580
1581 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1582 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1583 LHSType = AtomicLHS->getValueType();
1584
1585 // If both types are identical, no conversion is needed.
1586 if (Context.hasSameType(LHSType, RHSType))
1587 return Context.getCommonSugaredType(LHSType, RHSType);
1588
1589 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1590 // The caller can deal with this (e.g. pointer + int).
1591 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1592 return QualType();
1593
1594 // Apply unary and bitfield promotions to the LHS's type.
1595 QualType LHSUnpromotedType = LHSType;
1596 if (Context.isPromotableIntegerType(LHSType))
1597 LHSType = Context.getPromotedIntegerType(LHSType);
1598 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1599 if (!LHSBitfieldPromoteTy.isNull())
1600 LHSType = LHSBitfieldPromoteTy;
1601 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1602 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1603
1604 // If both types are identical, no conversion is needed.
1605 if (Context.hasSameType(LHSType, RHSType))
1606 return Context.getCommonSugaredType(LHSType, RHSType);
1607
1608 // At this point, we have two different arithmetic types.
1609
1610 // Diagnose attempts to convert between __ibm128, __float128 and long double
1611 // where such conversions currently can't be handled.
1612 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1613 return QualType();
1614
1615 // Handle complex types first (C99 6.3.1.8p1).
1616 if (LHSType->isComplexType() || RHSType->isComplexType())
1617 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1618 ACK == ACK_CompAssign);
1619
1620 // Now handle "real" floating types (i.e. float, double, long double).
1621 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1622 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1623 ACK == ACK_CompAssign);
1624
1625 // Handle GCC complex int extension.
1626 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1627 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1628 ACK == ACK_CompAssign);
1629
1630 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1631 return handleFixedPointConversion(*this, LHSType, RHSType);
1632
1633 // Finally, we have two differing integer types.
1634 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1635 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Semantic Analysis for various Expression Types
1640//===----------------------------------------------------------------------===//
1641
1642
1644 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1645 bool PredicateIsExpr, void *ControllingExprOrType,
1646 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1647 unsigned NumAssocs = ArgTypes.size();
1648 assert(NumAssocs == ArgExprs.size());
1649
1650 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1651 for (unsigned i = 0; i < NumAssocs; ++i) {
1652 if (ArgTypes[i])
1653 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1654 else
1655 Types[i] = nullptr;
1656 }
1657
1658 // If we have a controlling type, we need to convert it from a parsed type
1659 // into a semantic type and then pass that along.
1660 if (!PredicateIsExpr) {
1661 TypeSourceInfo *ControllingType;
1662 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1663 &ControllingType);
1664 assert(ControllingType && "couldn't get the type out of the parser");
1665 ControllingExprOrType = ControllingType;
1666 }
1667
1669 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1670 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1671 delete [] Types;
1672 return ER;
1673}
1674
1676 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1677 bool PredicateIsExpr, void *ControllingExprOrType,
1679 unsigned NumAssocs = Types.size();
1680 assert(NumAssocs == Exprs.size());
1681 assert(ControllingExprOrType &&
1682 "Must have either a controlling expression or a controlling type");
1683
1684 Expr *ControllingExpr = nullptr;
1685 TypeSourceInfo *ControllingType = nullptr;
1686 if (PredicateIsExpr) {
1687 // Decay and strip qualifiers for the controlling expression type, and
1688 // handle placeholder type replacement. See committee discussion from WG14
1689 // DR423.
1693 reinterpret_cast<Expr *>(ControllingExprOrType));
1694 if (R.isInvalid())
1695 return ExprError();
1696 ControllingExpr = R.get();
1697 } else {
1698 // The extension form uses the type directly rather than converting it.
1699 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1700 if (!ControllingType)
1701 return ExprError();
1702 }
1703
1704 bool TypeErrorFound = false,
1705 IsResultDependent = ControllingExpr
1706 ? ControllingExpr->isTypeDependent()
1707 : ControllingType->getType()->isDependentType(),
1708 ContainsUnexpandedParameterPack =
1709 ControllingExpr
1710 ? ControllingExpr->containsUnexpandedParameterPack()
1711 : ControllingType->getType()->containsUnexpandedParameterPack();
1712
1713 // The controlling expression is an unevaluated operand, so side effects are
1714 // likely unintended.
1715 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1716 ControllingExpr->HasSideEffects(Context, false))
1717 Diag(ControllingExpr->getExprLoc(),
1718 diag::warn_side_effects_unevaluated_context);
1719
1720 for (unsigned i = 0; i < NumAssocs; ++i) {
1721 if (Exprs[i]->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]) {
1725 if (Types[i]->getType()->containsUnexpandedParameterPack())
1726 ContainsUnexpandedParameterPack = true;
1727
1728 if (Types[i]->getType()->isDependentType()) {
1729 IsResultDependent = true;
1730 } else {
1731 // We relax the restriction on use of incomplete types and non-object
1732 // types with the type-based extension of _Generic. Allowing incomplete
1733 // objects means those can be used as "tags" for a type-safe way to map
1734 // to a value. Similarly, matching on function types rather than
1735 // function pointer types can be useful. However, the restriction on VM
1736 // types makes sense to retain as there are open questions about how
1737 // the selection can be made at compile time.
1738 //
1739 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1740 // complete object type other than a variably modified type."
1741 unsigned D = 0;
1742 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1743 D = diag::err_assoc_type_incomplete;
1744 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1745 D = diag::err_assoc_type_nonobject;
1746 else if (Types[i]->getType()->isVariablyModifiedType())
1747 D = diag::err_assoc_type_variably_modified;
1748 else if (ControllingExpr) {
1749 // Because the controlling expression undergoes lvalue conversion,
1750 // array conversion, and function conversion, an association which is
1751 // of array type, function type, or is qualified can never be
1752 // reached. We will warn about this so users are less surprised by
1753 // the unreachable association. However, we don't have to handle
1754 // function types; that's not an object type, so it's handled above.
1755 //
1756 // The logic is somewhat different for C++ because C++ has different
1757 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1758 // If T is a non-class type, the type of the prvalue is the cv-
1759 // unqualified version of T. Otherwise, the type of the prvalue is T.
1760 // The result of these rules is that all qualified types in an
1761 // association in C are unreachable, and in C++, only qualified non-
1762 // class types are unreachable.
1763 //
1764 // NB: this does not apply when the first operand is a type rather
1765 // than an expression, because the type form does not undergo
1766 // conversion.
1767 unsigned Reason = 0;
1768 QualType QT = Types[i]->getType();
1769 if (QT->isArrayType())
1770 Reason = 1;
1771 else if (QT.hasQualifiers() &&
1772 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1773 Reason = 2;
1774
1775 if (Reason)
1776 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1777 diag::warn_unreachable_association)
1778 << QT << (Reason - 1);
1779 }
1780
1781 if (D != 0) {
1782 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1783 << Types[i]->getTypeLoc().getSourceRange()
1784 << Types[i]->getType();
1785 TypeErrorFound = true;
1786 }
1787
1788 // C11 6.5.1.1p2 "No two generic associations in the same generic
1789 // selection shall specify compatible types."
1790 for (unsigned j = i+1; j < NumAssocs; ++j)
1791 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1792 Context.typesAreCompatible(Types[i]->getType(),
1793 Types[j]->getType())) {
1794 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1795 diag::err_assoc_compatible_types)
1796 << Types[j]->getTypeLoc().getSourceRange()
1797 << Types[j]->getType()
1798 << Types[i]->getType();
1799 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1800 diag::note_compat_assoc)
1801 << Types[i]->getTypeLoc().getSourceRange()
1802 << Types[i]->getType();
1803 TypeErrorFound = true;
1804 }
1805 }
1806 }
1807 }
1808 if (TypeErrorFound)
1809 return ExprError();
1810
1811 // If we determined that the generic selection is result-dependent, don't
1812 // try to compute the result expression.
1813 if (IsResultDependent) {
1814 if (ControllingExpr)
1815 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1816 Types, Exprs, DefaultLoc, RParenLoc,
1817 ContainsUnexpandedParameterPack);
1818 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1819 Exprs, DefaultLoc, RParenLoc,
1820 ContainsUnexpandedParameterPack);
1821 }
1822
1823 SmallVector<unsigned, 1> CompatIndices;
1824 unsigned DefaultIndex = -1U;
1825 // Look at the canonical type of the controlling expression in case it was a
1826 // deduced type like __auto_type. However, when issuing diagnostics, use the
1827 // type the user wrote in source rather than the canonical one.
1828 for (unsigned i = 0; i < NumAssocs; ++i) {
1829 if (!Types[i])
1830 DefaultIndex = i;
1831 else if (ControllingExpr &&
1833 ControllingExpr->getType().getCanonicalType(),
1834 Types[i]->getType()))
1835 CompatIndices.push_back(i);
1836 else if (ControllingType &&
1838 ControllingType->getType().getCanonicalType(),
1839 Types[i]->getType()))
1840 CompatIndices.push_back(i);
1841 }
1842
1843 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1844 TypeSourceInfo *ControllingType) {
1845 // We strip parens here because the controlling expression is typically
1846 // parenthesized in macro definitions.
1847 if (ControllingExpr)
1848 ControllingExpr = ControllingExpr->IgnoreParens();
1849
1850 SourceRange SR = ControllingExpr
1851 ? ControllingExpr->getSourceRange()
1852 : ControllingType->getTypeLoc().getSourceRange();
1853 QualType QT = ControllingExpr ? ControllingExpr->getType()
1854 : ControllingType->getType();
1855
1856 return std::make_pair(SR, QT);
1857 };
1858
1859 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1860 // type compatible with at most one of the types named in its generic
1861 // association list."
1862 if (CompatIndices.size() > 1) {
1863 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1864 SourceRange SR = P.first;
1865 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1866 << SR << P.second << (unsigned)CompatIndices.size();
1867 for (unsigned I : CompatIndices) {
1868 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1869 diag::note_compat_assoc)
1870 << Types[I]->getTypeLoc().getSourceRange()
1871 << Types[I]->getType();
1872 }
1873 return ExprError();
1874 }
1875
1876 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1877 // its controlling expression shall have type compatible with exactly one of
1878 // the types named in its generic association list."
1879 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1880 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1881 SourceRange SR = P.first;
1882 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1883 return ExprError();
1884 }
1885
1886 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1887 // type name that is compatible with the type of the controlling expression,
1888 // then the result expression of the generic selection is the expression
1889 // in that generic association. Otherwise, the result expression of the
1890 // generic selection is the expression in the default generic association."
1891 unsigned ResultIndex =
1892 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1893
1894 if (ControllingExpr) {
1896 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898 }
1900 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1901 ContainsUnexpandedParameterPack, ResultIndex);
1902}
1903
1905 switch (Kind) {
1906 default:
1907 llvm_unreachable("unexpected TokenKind");
1908 case tok::kw___func__:
1909 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1910 case tok::kw___FUNCTION__:
1912 case tok::kw___FUNCDNAME__:
1913 return PredefinedIdentKind::FuncDName; // [MS]
1914 case tok::kw___FUNCSIG__:
1915 return PredefinedIdentKind::FuncSig; // [MS]
1916 case tok::kw_L__FUNCTION__:
1917 return PredefinedIdentKind::LFunction; // [MS]
1918 case tok::kw_L__FUNCSIG__:
1919 return PredefinedIdentKind::LFuncSig; // [MS]
1920 case tok::kw___PRETTY_FUNCTION__:
1922 }
1923}
1924
1925/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1926/// to determine the value of a PredefinedExpr. This can be either a
1927/// block, lambda, captured statement, function, otherwise a nullptr.
1929 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1930 DC = DC->getParent();
1931 return cast_or_null<Decl>(DC);
1932}
1933
1934/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1935/// location of the token and the offset of the ud-suffix within it.
1937 unsigned Offset) {
1938 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1939 S.getLangOpts());
1940}
1941
1942/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1943/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1945 IdentifierInfo *UDSuffix,
1946 SourceLocation UDSuffixLoc,
1947 ArrayRef<Expr*> Args,
1948 SourceLocation LitEndLoc) {
1949 assert(Args.size() <= 2 && "too many arguments for literal operator");
1950
1951 QualType ArgTy[2];
1952 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1953 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1954 if (ArgTy[ArgIdx]->isArrayType())
1955 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1956 }
1957
1958 DeclarationName OpName =
1960 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1961 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1962
1963 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1964 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1965 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1966 /*AllowStringTemplatePack*/ false,
1967 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1968 return ExprError();
1969
1970 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1971}
1972
1974 // StringToks needs backing storage as it doesn't hold array elements itself
1975 std::vector<Token> ExpandedToks;
1976 if (getLangOpts().MicrosoftExt)
1977 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1978
1979 StringLiteralParser Literal(StringToks, PP,
1981 if (Literal.hadError)
1982 return ExprError();
1983
1984 SmallVector<SourceLocation, 4> StringTokLocs;
1985 for (const Token &Tok : StringToks)
1986 StringTokLocs.push_back(Tok.getLocation());
1987
1989 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1990 &StringTokLocs[0], StringTokLocs.size());
1991
1992 if (!Literal.getUDSuffix().empty()) {
1993 SourceLocation UDSuffixLoc =
1994 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1995 Literal.getUDSuffixOffset());
1996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1997 }
1998
1999 return Lit;
2000}
2001
2002std::vector<Token>
2004 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2005 // local macros that expand to string literals that may be concatenated.
2006 // These macros are expanded here (in Sema), because StringLiteralParser
2007 // (in Lex) doesn't know the enclosing function (because it hasn't been
2008 // parsed yet).
2009 assert(getLangOpts().MicrosoftExt);
2010
2011 // Note: Although function local macros are defined only inside functions,
2012 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2013 // expansion of macros into empty string literals without additional checks.
2014 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2015 if (!CurrentDecl)
2016 CurrentDecl = Context.getTranslationUnitDecl();
2017
2018 std::vector<Token> ExpandedToks;
2019 ExpandedToks.reserve(Toks.size());
2020 for (const Token &Tok : Toks) {
2021 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2022 assert(tok::isStringLiteral(Tok.getKind()));
2023 ExpandedToks.emplace_back(Tok);
2024 continue;
2025 }
2026 if (isa<TranslationUnitDecl>(CurrentDecl))
2027 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2028 // Stringify predefined expression
2029 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2030 << Tok.getKind();
2031 SmallString<64> Str;
2032 llvm::raw_svector_ostream OS(Str);
2033 Token &Exp = ExpandedToks.emplace_back();
2034 Exp.startToken();
2035 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2036 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2037 OS << 'L';
2038 Exp.setKind(tok::wide_string_literal);
2039 } else {
2040 Exp.setKind(tok::string_literal);
2041 }
2042 OS << '"'
2044 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2045 << '"';
2046 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2047 }
2048 return ExpandedToks;
2049}
2050
2051/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2052/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2053/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2054/// multiple tokens. However, the common case is that StringToks points to one
2055/// string.
2056///
2059 assert(!StringToks.empty() && "Must have at least one string!");
2060
2061 // StringToks needs backing storage as it doesn't hold array elements itself
2062 std::vector<Token> ExpandedToks;
2063 if (getLangOpts().MicrosoftExt)
2064 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2065
2066 StringLiteralParser Literal(StringToks, PP);
2067 if (Literal.hadError)
2068 return ExprError();
2069
2070 SmallVector<SourceLocation, 4> StringTokLocs;
2071 for (const Token &Tok : StringToks)
2072 StringTokLocs.push_back(Tok.getLocation());
2073
2074 QualType CharTy = Context.CharTy;
2076 if (Literal.isWide()) {
2077 CharTy = Context.getWideCharType();
2079 } else if (Literal.isUTF8()) {
2080 if (getLangOpts().Char8)
2081 CharTy = Context.Char8Ty;
2083 } else if (Literal.isUTF16()) {
2084 CharTy = Context.Char16Ty;
2086 } else if (Literal.isUTF32()) {
2087 CharTy = Context.Char32Ty;
2089 } else if (Literal.isPascal()) {
2090 CharTy = Context.UnsignedCharTy;
2091 }
2092
2093 // Warn on initializing an array of char from a u8 string literal; this
2094 // becomes ill-formed in C++2a.
2096 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2097 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2098
2099 // Create removals for all 'u8' prefixes in the string literal(s). This
2100 // ensures C++2a compatibility (but may change the program behavior when
2101 // built by non-Clang compilers for which the execution character set is
2102 // not always UTF-8).
2103 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2104 SourceLocation RemovalDiagLoc;
2105 for (const Token &Tok : StringToks) {
2106 if (Tok.getKind() == tok::utf8_string_literal) {
2107 if (RemovalDiagLoc.isInvalid())
2108 RemovalDiagLoc = Tok.getLocation();
2110 Tok.getLocation(),
2111 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2113 }
2114 }
2115 Diag(RemovalDiagLoc, RemovalDiag);
2116 }
2117
2118 QualType StrTy =
2119 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2120
2121 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2122 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2123 Kind, Literal.Pascal, StrTy,
2124 &StringTokLocs[0],
2125 StringTokLocs.size());
2126 if (Literal.getUDSuffix().empty())
2127 return Lit;
2128
2129 // We're building a user-defined literal.
2130 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2131 SourceLocation UDSuffixLoc =
2132 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2133 Literal.getUDSuffixOffset());
2134
2135 // Make sure we're allowed user-defined literals here.
2136 if (!UDLScope)
2137 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2138
2139 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2140 // operator "" X (str, len)
2141 QualType SizeType = Context.getSizeType();
2142
2143 DeclarationName OpName =
2145 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2146 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2147
2148 QualType ArgTy[] = {
2149 Context.getArrayDecayedType(StrTy), SizeType
2150 };
2151
2152 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2153 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2154 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2155 /*AllowStringTemplatePack*/ true,
2156 /*DiagnoseMissing*/ true, Lit)) {
2157
2158 case LOLR_Cooked: {
2159 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2160 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2161 StringTokLocs[0]);
2162 Expr *Args[] = { Lit, LenArg };
2163
2164 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2165 }
2166
2167 case LOLR_Template: {
2168 TemplateArgumentListInfo ExplicitArgs;
2169 TemplateArgument Arg(Lit);
2170 TemplateArgumentLocInfo ArgInfo(Lit);
2171 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2172 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2173 StringTokLocs.back(), &ExplicitArgs);
2174 }
2175
2177 TemplateArgumentListInfo ExplicitArgs;
2178
2179 unsigned CharBits = Context.getIntWidth(CharTy);
2180 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2181 llvm::APSInt Value(CharBits, CharIsUnsigned);
2182
2183 TemplateArgument TypeArg(CharTy);
2185 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2186
2187 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2188 Value = Lit->getCodeUnit(I);
2189 TemplateArgument Arg(Context, Value, CharTy);
2191 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2192 }
2193 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2194 StringTokLocs.back(), &ExplicitArgs);
2195 }
2196 case LOLR_Raw:
2198 llvm_unreachable("unexpected literal operator lookup result");
2199 case LOLR_Error:
2200 return ExprError();
2201 }
2202 llvm_unreachable("unexpected literal operator lookup result");
2203}
2204
2207 SourceLocation Loc,
2208 const CXXScopeSpec *SS) {
2209 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2210 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2211}
2212
2215 const DeclarationNameInfo &NameInfo,
2216 const CXXScopeSpec *SS, NamedDecl *FoundD,
2217 SourceLocation TemplateKWLoc,
2218 const TemplateArgumentListInfo *TemplateArgs) {
2221 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2222 TemplateArgs);
2223}
2224
2225// CUDA/HIP: Check whether a captured reference variable is referencing a
2226// host variable in a device or host device lambda.
2228 VarDecl *VD) {
2229 if (!S.getLangOpts().CUDA || !VD->hasInit())
2230 return false;
2231 assert(VD->getType()->isReferenceType());
2232
2233 // Check whether the reference variable is referencing a host variable.
2234 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2235 if (!DRE)
2236 return false;
2237 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2238 if (!Referee || !Referee->hasGlobalStorage() ||
2239 Referee->hasAttr<CUDADeviceAttr>())
2240 return false;
2241
2242 // Check whether the current function is a device or host device lambda.
2243 // Check whether the reference variable is a capture by getDeclContext()
2244 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2245 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2246 if (MD && MD->getParent()->isLambda() &&
2247 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2248 VD->getDeclContext() != MD)
2249 return true;
2250
2251 return false;
2252}
2253
2255 // A declaration named in an unevaluated operand never constitutes an odr-use.
2257 return NOUR_Unevaluated;
2258
2259 // C++2a [basic.def.odr]p4:
2260 // A variable x whose name appears as a potentially-evaluated expression e
2261 // is odr-used by e unless [...] x is a reference that is usable in
2262 // constant expressions.
2263 // CUDA/HIP:
2264 // If a reference variable referencing a host variable is captured in a
2265 // device or host device lambda, the value of the referee must be copied
2266 // to the capture and the reference variable must be treated as odr-use
2267 // since the value of the referee is not known at compile time and must
2268 // be loaded from the captured.
2269 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2270 if (VD->getType()->isReferenceType() &&
2271 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2273 VD->isUsableInConstantExpressions(Context))
2274 return NOUR_Constant;
2275 }
2276
2277 // All remaining non-variable cases constitute an odr-use. For variables, we
2278 // need to wait and see how the expression is used.
2279 return NOUR_None;
2280}
2281
2282/// BuildDeclRefExpr - Build an expression that references a
2283/// declaration that does not require a closure capture.
2286 const DeclarationNameInfo &NameInfo,
2287 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2288 SourceLocation TemplateKWLoc,
2289 const TemplateArgumentListInfo *TemplateArgs) {
2290 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2291 NeedToCaptureVariable(D, NameInfo.getLoc());
2292
2294 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2295 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2297
2298 // C++ [except.spec]p17:
2299 // An exception-specification is considered to be needed when:
2300 // - in an expression, the function is the unique lookup result or
2301 // the selected member of a set of overloaded functions.
2302 //
2303 // We delay doing this until after we've built the function reference and
2304 // marked it as used so that:
2305 // a) if the function is defaulted, we get errors from defining it before /
2306 // instead of errors from computing its exception specification, and
2307 // b) if the function is a defaulted comparison, we can use the body we
2308 // build when defining it as input to the exception specification
2309 // computation rather than computing a new body.
2310 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2311 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2312 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2314 }
2315 }
2316
2317 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2319 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2321
2322 const auto *FD = dyn_cast<FieldDecl>(D);
2323 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2324 FD = IFD->getAnonField();
2325 if (FD) {
2326 UnusedPrivateFields.remove(FD);
2327 // Just in case we're building an illegal pointer-to-member.
2328 if (FD->isBitField())
2330 }
2331
2332 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2333 // designates a bit-field.
2334 if (const auto *BD = dyn_cast<BindingDecl>(D))
2335 if (const auto *BE = BD->getBinding())
2336 E->setObjectKind(BE->getObjectKind());
2337
2338 return E;
2339}
2340
2341/// Decomposes the given name into a DeclarationNameInfo, its location, and
2342/// possibly a list of template arguments.
2343///
2344/// If this produces template arguments, it is permitted to call
2345/// DecomposeTemplateName.
2346///
2347/// This actually loses a lot of source location information for
2348/// non-standard name kinds; we should consider preserving that in
2349/// some way.
2350void
2353 DeclarationNameInfo &NameInfo,
2354 const TemplateArgumentListInfo *&TemplateArgs) {
2355 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2356 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2357 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2358
2359 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2360 Id.TemplateId->NumArgs);
2361 translateTemplateArguments(TemplateArgsPtr, Buffer);
2362
2363 TemplateName TName = Id.TemplateId->Template.get();
2364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2365 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2366 TemplateArgs = &Buffer;
2367 } else {
2368 NameInfo = GetNameFromUnqualifiedId(Id);
2369 TemplateArgs = nullptr;
2370 }
2371}
2372
2374 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2376 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2377 DeclContext *Ctx =
2378 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2379 if (!TC) {
2380 // Emit a special diagnostic for failed member lookups.
2381 // FIXME: computing the declaration context might fail here (?)
2382 if (Ctx)
2383 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2384 << SS.getRange();
2385 else
2386 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2387 return;
2388 }
2389
2390 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2391 bool DroppedSpecifier =
2392 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2393 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2394 ? diag::note_implicit_param_decl
2395 : diag::note_previous_decl;
2396 if (!Ctx)
2397 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2398 SemaRef.PDiag(NoteID));
2399 else
2400 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2401 << Typo << Ctx << DroppedSpecifier
2402 << SS.getRange(),
2403 SemaRef.PDiag(NoteID));
2404}
2405
2406/// Diagnose a lookup that found results in an enclosing class during error
2407/// recovery. This usually indicates that the results were found in a dependent
2408/// base class that could not be searched as part of a template definition.
2409/// Always issues a diagnostic (though this may be only a warning in MS
2410/// compatibility mode).
2411///
2412/// Return \c true if the error is unrecoverable, or \c false if the caller
2413/// should attempt to recover using these lookup results.
2415 // During a default argument instantiation the CurContext points
2416 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2417 // function parameter list, hence add an explicit check.
2418 bool isDefaultArgument =
2419 !CodeSynthesisContexts.empty() &&
2420 CodeSynthesisContexts.back().Kind ==
2422 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2423 bool isInstance = CurMethod && CurMethod->isInstance() &&
2424 R.getNamingClass() == CurMethod->getParent() &&
2425 !isDefaultArgument;
2426
2427 // There are two ways we can find a class-scope declaration during template
2428 // instantiation that we did not find in the template definition: if it is a
2429 // member of a dependent base class, or if it is declared after the point of
2430 // use in the same class. Distinguish these by comparing the class in which
2431 // the member was found to the naming class of the lookup.
2432 unsigned DiagID = diag::err_found_in_dependent_base;
2433 unsigned NoteID = diag::note_member_declared_at;
2435 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2436 : diag::err_found_later_in_class;
2437 } else if (getLangOpts().MSVCCompat) {
2438 DiagID = diag::ext_found_in_dependent_base;
2439 NoteID = diag::note_dependent_member_use;
2440 }
2441
2442 if (isInstance) {
2443 // Give a code modification hint to insert 'this->'.
2444 Diag(R.getNameLoc(), DiagID)
2445 << R.getLookupName()
2446 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2448 } else {
2449 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2450 // they're not shadowed).
2451 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2452 }
2453
2454 for (const NamedDecl *D : R)
2455 Diag(D->getLocation(), NoteID);
2456
2457 // Return true if we are inside a default argument instantiation
2458 // and the found name refers to an instance member function, otherwise
2459 // the caller will try to create an implicit member call and this is wrong
2460 // for default arguments.
2461 //
2462 // FIXME: Is this special case necessary? We could allow the caller to
2463 // diagnose this.
2464 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2465 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2466 return true;
2467 }
2468
2469 // Tell the callee to try to recover.
2470 return false;
2471}
2472
2473/// Diagnose an empty lookup.
2474///
2475/// \return false if new lookup candidates were found
2478 TemplateArgumentListInfo *ExplicitTemplateArgs,
2479 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2480 TypoExpr **Out) {
2481 DeclarationName Name = R.getLookupName();
2482
2483 unsigned diagnostic = diag::err_undeclared_var_use;
2484 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2485 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2486 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2487 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2488 diagnostic = diag::err_undeclared_use;
2489 diagnostic_suggest = diag::err_undeclared_use_suggest;
2490 }
2491
2492 // If the original lookup was an unqualified lookup, fake an
2493 // unqualified lookup. This is useful when (for example) the
2494 // original lookup would not have found something because it was a
2495 // dependent name.
2496 DeclContext *DC =
2497 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2498 while (DC) {
2499 if (isa<CXXRecordDecl>(DC)) {
2500 LookupQualifiedName(R, DC);
2501
2502 if (!R.empty()) {
2503 // Don't give errors about ambiguities in this lookup.
2505
2506 // If there's a best viable function among the results, only mention
2507 // that one in the notes.
2508 OverloadCandidateSet Candidates(R.getNameLoc(),
2510 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2512 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2513 OR_Success) {
2514 R.clear();
2515 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2516 R.resolveKind();
2517 }
2518
2520 }
2521
2522 R.clear();
2523 }
2524
2525 DC = DC->getLookupParent();
2526 }
2527
2528 // We didn't find anything, so try to correct for a typo.
2529 TypoCorrection Corrected;
2530 if (S && Out) {
2531 SourceLocation TypoLoc = R.getNameLoc();
2532 assert(!ExplicitTemplateArgs &&
2533 "Diagnosing an empty lookup with explicit template args!");
2534 *Out = CorrectTypoDelayed(
2535 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2536 [=](const TypoCorrection &TC) {
2537 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2538 diagnostic, diagnostic_suggest);
2539 },
2540 nullptr, CTK_ErrorRecovery, LookupCtx);
2541 if (*Out)
2542 return true;
2543 } else if (S && (Corrected =
2545 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2546 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2547 bool DroppedSpecifier =
2548 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2549 R.setLookupName(Corrected.getCorrection());
2550
2551 bool AcceptableWithRecovery = false;
2552 bool AcceptableWithoutRecovery = false;
2553 NamedDecl *ND = Corrected.getFoundDecl();
2554 if (ND) {
2555 if (Corrected.isOverloaded()) {
2559 for (NamedDecl *CD : Corrected) {
2560 if (FunctionTemplateDecl *FTD =
2561 dyn_cast<FunctionTemplateDecl>(CD))
2563 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2564 Args, OCS);
2565 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2566 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2568 Args, OCS);
2569 }
2570 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2571 case OR_Success:
2572 ND = Best->FoundDecl;
2573 Corrected.setCorrectionDecl(ND);
2574 break;
2575 default:
2576 // FIXME: Arbitrarily pick the first declaration for the note.
2577 Corrected.setCorrectionDecl(ND);
2578 break;
2579 }
2580 }
2581 R.addDecl(ND);
2582 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2583 CXXRecordDecl *Record = nullptr;
2584 if (Corrected.getCorrectionSpecifier()) {
2585 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2586 Record = Ty->getAsCXXRecordDecl();
2587 }
2588 if (!Record)
2589 Record = cast<CXXRecordDecl>(
2592 }
2593
2594 auto *UnderlyingND = ND->getUnderlyingDecl();
2595 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2596 isa<FunctionTemplateDecl>(UnderlyingND);
2597 // FIXME: If we ended up with a typo for a type name or
2598 // Objective-C class name, we're in trouble because the parser
2599 // is in the wrong place to recover. Suggest the typo
2600 // correction, but don't make it a fix-it since we're not going
2601 // to recover well anyway.
2602 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2603 getAsTypeTemplateDecl(UnderlyingND) ||
2604 isa<ObjCInterfaceDecl>(UnderlyingND);
2605 } else {
2606 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2607 // because we aren't able to recover.
2608 AcceptableWithoutRecovery = true;
2609 }
2610
2611 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2612 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2613 ? diag::note_implicit_param_decl
2614 : diag::note_previous_decl;
2615 if (SS.isEmpty())
2616 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2617 PDiag(NoteID), AcceptableWithRecovery);
2618 else
2619 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2620 << Name << computeDeclContext(SS, false)
2621 << DroppedSpecifier << SS.getRange(),
2622 PDiag(NoteID), AcceptableWithRecovery);
2623
2624 // Tell the callee whether to try to recover.
2625 return !AcceptableWithRecovery;
2626 }
2627 }
2628 R.clear();
2629
2630 // Emit a special diagnostic for failed member lookups.
2631 // FIXME: computing the declaration context might fail here (?)
2632 if (!SS.isEmpty()) {
2633 Diag(R.getNameLoc(), diag::err_no_member)
2634 << Name << computeDeclContext(SS, false)
2635 << SS.getRange();
2636 return true;
2637 }
2638
2639 // Give up, we can't recover.
2640 Diag(R.getNameLoc(), diagnostic) << Name;
2641 return true;
2642}
2643
2644/// In Microsoft mode, if we are inside a template class whose parent class has
2645/// dependent base classes, and we can't resolve an unqualified identifier, then
2646/// assume the identifier is a member of a dependent base class. We can only
2647/// recover successfully in static methods, instance methods, and other contexts
2648/// where 'this' is available. This doesn't precisely match MSVC's
2649/// instantiation model, but it's close enough.
2650static Expr *
2652 DeclarationNameInfo &NameInfo,
2653 SourceLocation TemplateKWLoc,
2654 const TemplateArgumentListInfo *TemplateArgs) {
2655 // Only try to recover from lookup into dependent bases in static methods or
2656 // contexts where 'this' is available.
2657 QualType ThisType = S.getCurrentThisType();
2658 const CXXRecordDecl *RD = nullptr;
2659 if (!ThisType.isNull())
2660 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2661 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2662 RD = MD->getParent();
2663 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2664 return nullptr;
2665
2666 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2667 // is available, suggest inserting 'this->' as a fixit.
2668 SourceLocation Loc = NameInfo.getLoc();
2669 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2670 DB << NameInfo.getName() << RD;
2671
2672 if (!ThisType.isNull()) {
2673 DB << FixItHint::CreateInsertion(Loc, "this->");
2675 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2676 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2677 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2678 }
2679
2680 // Synthesize a fake NNS that points to the derived class. This will
2681 // perform name lookup during template instantiation.
2682 CXXScopeSpec SS;
2683 auto *NNS =
2684 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2685 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2687 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2688 TemplateArgs);
2689}
2690
2693 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2694 bool HasTrailingLParen, bool IsAddressOfOperand,
2696 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2697 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2698 "cannot be direct & operand and have a trailing lparen");
2699 if (SS.isInvalid())
2700 return ExprError();
2701
2702 TemplateArgumentListInfo TemplateArgsBuffer;
2703
2704 // Decompose the UnqualifiedId into the following data.
2705 DeclarationNameInfo NameInfo;
2706 const TemplateArgumentListInfo *TemplateArgs;
2707 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2708
2709 DeclarationName Name = NameInfo.getName();
2710 IdentifierInfo *II = Name.getAsIdentifierInfo();
2711 SourceLocation NameLoc = NameInfo.getLoc();
2712
2713 if (II && II->isEditorPlaceholder()) {
2714 // FIXME: When typed placeholders are supported we can create a typed
2715 // placeholder expression node.
2716 return ExprError();
2717 }
2718
2719 // C++ [temp.dep.expr]p3:
2720 // An id-expression is type-dependent if it contains:
2721 // -- an identifier that was declared with a dependent type,
2722 // (note: handled after lookup)
2723 // -- a template-id that is dependent,
2724 // (note: handled in BuildTemplateIdExpr)
2725 // -- a conversion-function-id that specifies a dependent type,
2726 // -- a nested-name-specifier that contains a class-name that
2727 // names a dependent type.
2728 // Determine whether this is a member of an unknown specialization;
2729 // we need to handle these differently.
2730 bool DependentID = false;
2731 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2732 Name.getCXXNameType()->isDependentType()) {
2733 DependentID = true;
2734 } else if (SS.isSet()) {
2735 if (DeclContext *DC = computeDeclContext(SS, false)) {
2736 if (RequireCompleteDeclContext(SS, DC))
2737 return ExprError();
2738 } else {
2739 DependentID = true;
2740 }
2741 }
2742
2743 if (DependentID)
2744 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2745 IsAddressOfOperand, TemplateArgs);
2746
2747 // BoundsSafety: This specially handles arguments of bounds attributes
2748 // appertains to a type of C struct field such that the name lookup
2749 // within a struct finds the member name, which is not the case for other
2750 // contexts in C.
2751 if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2752 // See if this is reference to a field of struct.
2753 LookupResult R(*this, NameInfo, LookupMemberName);
2754 // LookupParsedName handles a name lookup from within anonymous struct.
2755 if (LookupParsedName(R, S, &SS)) {
2756 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2757 QualType type = VD->getType().getNonReferenceType();
2758 // This will eventually be translated into MemberExpr upon
2759 // the use of instantiated struct fields.
2760 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2761 }
2762 }
2763 }
2764
2765 // Perform the required lookup.
2766 LookupResult R(*this, NameInfo,
2770 if (TemplateKWLoc.isValid() || TemplateArgs) {
2771 // Lookup the template name again to correctly establish the context in
2772 // which it was found. This is really unfortunate as we already did the
2773 // lookup to determine that it was a template name in the first place. If
2774 // this becomes a performance hit, we can work harder to preserve those
2775 // results until we get here but it's likely not worth it.
2776 bool MemberOfUnknownSpecialization;
2777 AssumedTemplateKind AssumedTemplate;
2778 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2779 MemberOfUnknownSpecialization, TemplateKWLoc,
2780 &AssumedTemplate))
2781 return ExprError();
2782
2783 if (MemberOfUnknownSpecialization ||
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2790
2791 // If the result might be in a dependent base class, this is a dependent
2792 // id-expression.
2794 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2795 IsAddressOfOperand, TemplateArgs);
2796
2797 // If this reference is in an Objective-C method, then we need to do
2798 // some special Objective-C lookup, too.
2799 if (IvarLookupFollowUp) {
2800 ExprResult E(LookupInObjCMethod(R, S, II, true));
2801 if (E.isInvalid())
2802 return ExprError();
2803
2804 if (Expr *Ex = E.getAs<Expr>())
2805 return Ex;
2806 }
2807 }
2808
2809 if (R.isAmbiguous())
2810 return ExprError();
2811
2812 // This could be an implicitly declared function reference if the language
2813 // mode allows it as a feature.
2814 if (R.empty() && HasTrailingLParen && II &&
2815 getLangOpts().implicitFunctionsAllowed()) {
2816 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2817 if (D) R.addDecl(D);
2818 }
2819
2820 // Determine whether this name might be a candidate for
2821 // argument-dependent lookup.
2822 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2823
2824 if (R.empty() && !ADL) {
2825 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2826 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2827 TemplateKWLoc, TemplateArgs))
2828 return E;
2829 }
2830
2831 // Don't diagnose an empty lookup for inline assembly.
2832 if (IsInlineAsmIdentifier)
2833 return ExprError();
2834
2835 // If this name wasn't predeclared and if this is not a function
2836 // call, diagnose the problem.
2837 TypoExpr *TE = nullptr;
2838 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2839 : nullptr);
2840 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2841 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2842 "Typo correction callback misconfigured");
2843 if (CCC) {
2844 // Make sure the callback knows what the typo being diagnosed is.
2845 CCC->setTypoName(II);
2846 if (SS.isValid())
2847 CCC->setTypoNNS(SS.getScopeRep());
2848 }
2849 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2850 // a template name, but we happen to have always already looked up the name
2851 // before we get here if it must be a template name.
2852 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2853 std::nullopt, nullptr, &TE)) {
2854 if (TE && KeywordReplacement) {
2855 auto &State = getTypoExprState(TE);
2856 auto BestTC = State.Consumer->getNextCorrection();
2857 if (BestTC.isKeyword()) {
2858 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2859 if (State.DiagHandler)
2860 State.DiagHandler(BestTC);
2861 KeywordReplacement->startToken();
2862 KeywordReplacement->setKind(II->getTokenID());
2863 KeywordReplacement->setIdentifierInfo(II);
2864 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2865 // Clean up the state associated with the TypoExpr, since it has
2866 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2867 clearDelayedTypo(TE);
2868 // Signal that a correction to a keyword was performed by returning a
2869 // valid-but-null ExprResult.
2870 return (Expr*)nullptr;
2871 }
2872 State.Consumer->resetCorrectionStream();
2873 }
2874 return TE ? TE : ExprError();
2875 }
2876
2877 assert(!R.empty() &&
2878 "DiagnoseEmptyLookup returned false but added no results");
2879
2880 // If we found an Objective-C instance variable, let
2881 // LookupInObjCMethod build the appropriate expression to
2882 // reference the ivar.
2883 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2884 R.clear();
2885 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2886 // In a hopelessly buggy code, Objective-C instance variable
2887 // lookup fails and no expression will be built to reference it.
2888 if (!E.isInvalid() && !E.get())
2889 return ExprError();
2890 return E;
2891 }
2892 }
2893
2894 // This is guaranteed from this point on.
2895 assert(!R.empty() || ADL);
2896
2897 // Check whether this might be a C++ implicit instance member access.
2898 // C++ [class.mfct.non-static]p3:
2899 // When an id-expression that is not part of a class member access
2900 // syntax and not used to form a pointer to member is used in the
2901 // body of a non-static member function of class X, if name lookup
2902 // resolves the name in the id-expression to a non-static non-type
2903 // member of some class C, the id-expression is transformed into a
2904 // class member access expression using (*this) as the
2905 // postfix-expression to the left of the . operator.
2906 //
2907 // But we don't actually need to do this for '&' operands if R
2908 // resolved to a function or overloaded function set, because the
2909 // expression is ill-formed if it actually works out to be a
2910 // non-static member function:
2911 //
2912 // C++ [expr.ref]p4:
2913 // Otherwise, if E1.E2 refers to a non-static member function. . .
2914 // [t]he expression can be used only as the left-hand operand of a
2915 // member function call.
2916 //
2917 // There are other safeguards against such uses, but it's important
2918 // to get this right here so that we don't end up making a
2919 // spuriously dependent expression if we're inside a dependent
2920 // instance method.
2921 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2922 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2923 S);
2924
2925 if (TemplateArgs || TemplateKWLoc.isValid()) {
2926
2927 // In C++1y, if this is a variable template id, then check it
2928 // in BuildTemplateIdExpr().
2929 // The single lookup result must be a variable template declaration.
2930 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2931 Id.TemplateId->Kind == TNK_Var_template) {
2932 assert(R.getAsSingle<VarTemplateDecl>() &&
2933 "There should only be one declaration found.");
2934 }
2935
2936 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2937 }
2938
2939 return BuildDeclarationNameExpr(SS, R, ADL);
2940}
2941
2942/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2943/// declaration name, generally during template instantiation.
2944/// There's a large number of things which don't need to be done along
2945/// this path.
2947 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2948 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2949 if (NameInfo.getName().isDependentName())
2950 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2951 NameInfo, /*TemplateArgs=*/nullptr);
2952
2953 DeclContext *DC = computeDeclContext(SS, false);
2954 if (!DC)
2955 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2956 NameInfo, /*TemplateArgs=*/nullptr);
2957
2958 if (RequireCompleteDeclContext(SS, DC))
2959 return ExprError();
2960
2961 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2962 LookupQualifiedName(R, DC);
2963
2964 if (R.isAmbiguous())
2965 return ExprError();
2966
2968 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2969 NameInfo, /*TemplateArgs=*/nullptr);
2970
2971 if (R.empty()) {
2972 // Don't diagnose problems with invalid record decl, the secondary no_member
2973 // diagnostic during template instantiation is likely bogus, e.g. if a class
2974 // is invalid because it's derived from an invalid base class, then missing
2975 // members were likely supposed to be inherited.
2976 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2977 if (CD->isInvalidDecl())
2978 return ExprError();
2979 Diag(NameInfo.getLoc(), diag::err_no_member)
2980 << NameInfo.getName() << DC << SS.getRange();
2981 return ExprError();
2982 }
2983
2984 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2985 // Diagnose a missing typename if this resolved unambiguously to a type in
2986 // a dependent context. If we can recover with a type, downgrade this to
2987 // a warning in Microsoft compatibility mode.
2988 unsigned DiagID = diag::err_typename_missing;
2989 if (RecoveryTSI && getLangOpts().MSVCCompat)
2990 DiagID = diag::ext_typename_missing;
2991 SourceLocation Loc = SS.getBeginLoc();
2992 auto D = Diag(Loc, DiagID);
2993 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2994 << SourceRange(Loc, NameInfo.getEndLoc());
2995
2996 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2997 // context.
2998 if (!RecoveryTSI)
2999 return ExprError();
3000
3001 // Only issue the fixit if we're prepared to recover.
3002 D << FixItHint::CreateInsertion(Loc, "typename ");
3003
3004 // Recover by pretending this was an elaborated type.
3006 TypeLocBuilder TLB;
3007 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
3008
3013
3014 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3015
3016 return ExprEmpty();
3017 }
3018
3019 // Defend against this resolving to an implicit member access. We usually
3020 // won't get here if this might be a legitimate a class member (we end up in
3021 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3022 // a pointer-to-member or in an unevaluated context in C++11.
3023 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3025 /*TemplateKWLoc=*/SourceLocation(),
3026 R, /*TemplateArgs=*/nullptr, S);
3027
3028 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3029}
3030
3031/// The parser has read a name in, and Sema has detected that we're currently
3032/// inside an ObjC method. Perform some additional checks and determine if we
3033/// should form a reference to an ivar.
3034///
3035/// Ideally, most of this would be done by lookup, but there's
3036/// actually quite a lot of extra work involved.
3038 IdentifierInfo *II) {
3039 SourceLocation Loc = Lookup.getNameLoc();
3040 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3041
3042 // Check for error condition which is already reported.
3043 if (!CurMethod)
3044 return DeclResult(true);
3045
3046 // There are two cases to handle here. 1) scoped lookup could have failed,
3047 // in which case we should look for an ivar. 2) scoped lookup could have
3048 // found a decl, but that decl is outside the current instance method (i.e.
3049 // a global variable). In these two cases, we do a lookup for an ivar with
3050 // this name, if the lookup sucedes, we replace it our current decl.
3051
3052 // If we're in a class method, we don't normally want to look for
3053 // ivars. But if we don't find anything else, and there's an
3054 // ivar, that's an error.
3055 bool IsClassMethod = CurMethod->isClassMethod();
3056
3057 bool LookForIvars;
3058 if (Lookup.empty())
3059 LookForIvars = true;
3060 else if (IsClassMethod)
3061 LookForIvars = false;
3062 else
3063 LookForIvars = (Lookup.isSingleResult() &&
3065 ObjCInterfaceDecl *IFace = nullptr;
3066 if (LookForIvars) {
3067 IFace = CurMethod->getClassInterface();
3068 ObjCInterfaceDecl *ClassDeclared;
3069 ObjCIvarDecl *IV = nullptr;
3070 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3071 // Diagnose using an ivar in a class method.
3072 if (IsClassMethod) {
3073 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3074 return DeclResult(true);
3075 }
3076
3077 // Diagnose the use of an ivar outside of the declaring class.
3079 !declaresSameEntity(ClassDeclared, IFace) &&
3080 !getLangOpts().DebuggerSupport)
3081 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3082
3083 // Success.
3084 return IV;
3085 }
3086 } else if (CurMethod->isInstanceMethod()) {
3087 // We should warn if a local variable hides an ivar.
3088 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3089 ObjCInterfaceDecl *ClassDeclared;
3090 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3091 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3092 declaresSameEntity(IFace, ClassDeclared))
3093 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3094 }
3095 }
3096 } else if (Lookup.isSingleResult() &&
3098 // If accessing a stand-alone ivar in a class method, this is an error.
3099 if (const ObjCIvarDecl *IV =
3100 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3101 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3102 return DeclResult(true);
3103 }
3104 }
3105
3106 // Didn't encounter an error, didn't find an ivar.
3107 return DeclResult(false);
3108}
3109
3111 ObjCIvarDecl *IV) {
3112 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3113 assert(CurMethod && CurMethod->isInstanceMethod() &&
3114 "should not reference ivar from this context");
3115
3116 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3117 assert(IFace && "should not reference ivar from this context");
3118
3119 // If we're referencing an invalid decl, just return this as a silent
3120 // error node. The error diagnostic was already emitted on the decl.
3121 if (IV->isInvalidDecl())
3122 return ExprError();
3123
3124 // Check if referencing a field with __attribute__((deprecated)).
3125 if (DiagnoseUseOfDecl(IV, Loc))
3126 return ExprError();
3127
3128 // FIXME: This should use a new expr for a direct reference, don't
3129 // turn this into Self->ivar, just return a BareIVarExpr or something.
3130 IdentifierInfo &II = Context.Idents.get("self");
3131 UnqualifiedId SelfName;
3132 SelfName.setImplicitSelfParam(&II);
3133 CXXScopeSpec SelfScopeSpec;
3134 SourceLocation TemplateKWLoc;
3135 ExprResult SelfExpr =
3136 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3137 /*HasTrailingLParen=*/false,
3138 /*IsAddressOfOperand=*/false);
3139 if (SelfExpr.isInvalid())
3140 return ExprError();
3141
3142 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3143 if (SelfExpr.isInvalid())
3144 return ExprError();
3145
3146 MarkAnyDeclReferenced(Loc, IV, true);
3147
3148 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3149 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3150 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3151 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3152
3154 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3155 IV->getLocation(), SelfExpr.get(), true, true);
3156
3158 if (!isUnevaluatedContext() &&
3159 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3161 }
3162 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3163 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3164 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3165
3166 return Result;
3167}
3168
3169/// The parser has read a name in, and Sema has detected that we're currently
3170/// inside an ObjC method. Perform some additional checks and determine if we
3171/// should form a reference to an ivar. If so, build an expression referencing
3172/// that ivar.
3175 IdentifierInfo *II, bool AllowBuiltinCreation) {
3176 // FIXME: Integrate this lookup step into LookupParsedName.
3177 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3178 if (Ivar.isInvalid())
3179 return ExprError();
3180 if (Ivar.isUsable())
3181 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3182 cast<ObjCIvarDecl>(Ivar.get()));
3183
3184 if (Lookup.empty() && II && AllowBuiltinCreation)
3185 LookupBuiltin(Lookup);
3186
3187 // Sentinel value saying that we didn't do anything special.
3188 return ExprResult(false);
3189}
3190
3191/// Cast a base object to a member's actual type.
3192///
3193/// There are two relevant checks:
3194///
3195/// C++ [class.access.base]p7:
3196///
3197/// If a class member access operator [...] is used to access a non-static
3198/// data member or non-static member function, the reference is ill-formed if
3199/// the left operand [...] cannot be implicitly converted to a pointer to the
3200/// naming class of the right operand.
3201///
3202/// C++ [expr.ref]p7:
3203///
3204/// If E2 is a non-static data member or a non-static member function, the
3205/// program is ill-formed if the class of which E2 is directly a member is an
3206/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3207///
3208/// Note that the latter check does not consider access; the access of the
3209/// "real" base class is checked as appropriate when checking the access of the
3210/// member name.
3213 NestedNameSpecifier *Qualifier,
3214 NamedDecl *FoundDecl,
3215 NamedDecl *Member) {
3216 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3217 if (!RD)
3218 return From;
3219
3220 QualType DestRecordType;
3221 QualType DestType;
3222 QualType FromRecordType;
3223 QualType FromType = From->getType();
3224 bool PointerConversions = false;
3225 if (isa<FieldDecl>(Member)) {
3226 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3227 auto FromPtrType = FromType->getAs<PointerType>();
3228 DestRecordType = Context.getAddrSpaceQualType(
3229 DestRecordType, FromPtrType
3230 ? FromType->getPointeeType().getAddressSpace()
3231 : FromType.getAddressSpace());
3232
3233 if (FromPtrType) {
3234 DestType = Context.getPointerType(DestRecordType);
3235 FromRecordType = FromPtrType->getPointeeType();
3236 PointerConversions = true;
3237 } else {
3238 DestType = DestRecordType;
3239 FromRecordType = FromType;
3240 }
3241 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3242 if (!Method->isImplicitObjectMemberFunction())
3243 return From;
3244
3245 DestType = Method->getThisType().getNonReferenceType();
3246 DestRecordType = Method->getFunctionObjectParameterType();
3247
3248 if (FromType->getAs<PointerType>()) {
3249 FromRecordType = FromType->getPointeeType();
3250 PointerConversions = true;
3251 } else {
3252 FromRecordType = FromType;
3253 DestType = DestRecordType;
3254 }
3255
3256 LangAS FromAS = FromRecordType.getAddressSpace();
3257 LangAS DestAS = DestRecordType.getAddressSpace();
3258 if (FromAS != DestAS) {
3259 QualType FromRecordTypeWithoutAS =
3260 Context.removeAddrSpaceQualType(FromRecordType);
3261 QualType FromTypeWithDestAS =
3262 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3263 if (PointerConversions)
3264 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3265 From = ImpCastExprToType(From, FromTypeWithDestAS,
3266 CK_AddressSpaceConversion, From->getValueKind())
3267 .get();
3268 }
3269 } else {
3270 // No conversion necessary.
3271 return From;
3272 }
3273
3274 if (DestType->isDependentType() || FromType->isDependentType())
3275 return From;
3276
3277 // If the unqualified types are the same, no conversion is necessary.
3278 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3279 return From;
3280
3281 SourceRange FromRange = From->getSourceRange();
3282 SourceLocation FromLoc = FromRange.getBegin();
3283
3284 ExprValueKind VK = From->getValueKind();
3285
3286 // C++ [class.member.lookup]p8:
3287 // [...] Ambiguities can often be resolved by qualifying a name with its
3288 // class name.
3289 //
3290 // If the member was a qualified name and the qualified referred to a
3291 // specific base subobject type, we'll cast to that intermediate type
3292 // first and then to the object in which the member is declared. That allows
3293 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3294 //
3295 // class Base { public: int x; };
3296 // class Derived1 : public Base { };
3297 // class Derived2 : public Base { };
3298 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3299 //
3300 // void VeryDerived::f() {
3301 // x = 17; // error: ambiguous base subobjects
3302 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3303 // }
3304 if (Qualifier && Qualifier->getAsType()) {
3305 QualType QType = QualType(Qualifier->getAsType(), 0);
3306 assert(QType->isRecordType() && "lookup done with non-record type");
3307
3308 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3309
3310 // In C++98, the qualifier type doesn't actually have to be a base
3311 // type of the object type, in which case we just ignore it.
3312 // Otherwise build the appropriate casts.
3313 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3314 CXXCastPath BasePath;
3315 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3316 FromLoc, FromRange, &BasePath))
3317 return ExprError();
3318
3319 if (PointerConversions)
3320 QType = Context.getPointerType(QType);
3321 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3322 VK, &BasePath).get();
3323
3324 FromType = QType;
3325 FromRecordType = QRecordType;
3326
3327 // If the qualifier type was the same as the destination type,
3328 // we're done.
3329 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3330 return From;
3331 }
3332 }
3333
3334 CXXCastPath BasePath;
3335 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3336 FromLoc, FromRange, &BasePath,
3337 /*IgnoreAccess=*/true))
3338 return ExprError();
3339
3340 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3341 VK, &BasePath);
3342}
3343
3345 const LookupResult &R,
3346 bool HasTrailingLParen) {
3347 // Only when used directly as the postfix-expression of a call.
3348 if (!HasTrailingLParen)
3349 return false;
3350
3351 // Never if a scope specifier was provided.
3352 if (SS.isSet())
3353 return false;
3354
3355 // Only in C++ or ObjC++.
3356 if (!getLangOpts().CPlusPlus)
3357 return false;
3358
3359 // Turn off ADL when we find certain kinds of declarations during
3360 // normal lookup:
3361 for (const NamedDecl *D : R) {
3362 // C++0x [basic.lookup.argdep]p3:
3363 // -- a declaration of a class member
3364 // Since using decls preserve this property, we check this on the
3365 // original decl.
3366 if (D->isCXXClassMember())
3367 return false;
3368
3369 // C++0x [basic.lookup.argdep]p3:
3370 // -- a block-scope function declaration that is not a
3371 // using-declaration
3372 // NOTE: we also trigger this for function templates (in fact, we
3373 // don't check the decl type at all, since all other decl types
3374 // turn off ADL anyway).
3375 if (isa<UsingShadowDecl>(D))
3376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3377 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3378 return false;
3379
3380 // C++0x [basic.lookup.argdep]p3:
3381 // -- a declaration that is neither a function or a function
3382 // template
3383 // And also for builtin functions.
3384 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3385 // But also builtin functions.
3386 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3387 return false;
3388 } else if (!isa<FunctionTemplateDecl>(D))
3389 return false;
3390 }
3391
3392 return true;
3393}
3394
3395
3396/// Diagnoses obvious problems with the use of the given declaration
3397/// as an expression. This is only actually called for lookups that
3398/// were not overloaded, and it doesn't promise that the declaration
3399/// will in fact be used.
3401 bool AcceptInvalid) {
3402 if (D->isInvalidDecl() && !AcceptInvalid)
3403 return true;
3404
3405 if (isa<TypedefNameDecl>(D)) {
3406 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3407 return true;
3408 }
3409
3410 if (isa<ObjCInterfaceDecl>(D)) {
3411 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3412 return true;
3413 }
3414
3415 if (isa<NamespaceDecl>(D)) {
3416 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3417 return true;
3418 }
3419
3420 return false;
3421}
3422
3423// Certain multiversion types should be treated as overloaded even when there is
3424// only one result.
3426 assert(R.isSingleResult() && "Expected only a single result");
3427 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3428 return FD &&
3429 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3430}
3431
3433 LookupResult &R, bool NeedsADL,
3434 bool AcceptInvalidDecl) {
3435 // If this is a single, fully-resolved result and we don't need ADL,
3436 // just build an ordinary singleton decl ref.
3437 if (!NeedsADL && R.isSingleResult() &&
3441 R.getRepresentativeDecl(), nullptr,
3442 AcceptInvalidDecl);
3443
3444 // We only need to check the declaration if there's exactly one
3445 // result, because in the overloaded case the results can only be
3446 // functions and function templates.
3448 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3449 AcceptInvalidDecl))
3450 return ExprError();
3451
3452 // Otherwise, just build an unresolved lookup expression. Suppress
3453 // any lookup-related diagnostics; we'll hash these out later, when
3454 // we've picked a target.
3456
3459 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3460 /*KnownDependent=*/false);
3461
3462 return ULE;
3463}
3464
3466 SourceLocation loc,
3467 ValueDecl *var);
3468
3469/// Complete semantic analysis for a reference to the given declaration.
3471 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3472 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3473 bool AcceptInvalidDecl) {
3474 assert(D && "Cannot refer to a NULL declaration");
3475 assert(!isa<FunctionTemplateDecl>(D) &&
3476 "Cannot refer unambiguously to a function template");
3477
3478 SourceLocation Loc = NameInfo.getLoc();
3479 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3480 // Recovery from invalid cases (e.g. D is an invalid Decl).
3481 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3482 // diagnostics, as invalid decls use int as a fallback type.
3483 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3484 }
3485
3486 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3487 // Specifically diagnose references to class templates that are missing
3488 // a template argument list.
3490 return ExprError();
3491 }
3492
3493 // Make sure that we're referring to a value.
3494 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3495 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3496 Diag(D->getLocation(), diag::note_declared_at);
3497 return ExprError();
3498 }
3499
3500 // Check whether this declaration can be used. Note that we suppress
3501 // this check when we're going to perform argument-dependent lookup
3502 // on this function name, because this might not be the function
3503 // that overload resolution actually selects.
3504 if (DiagnoseUseOfDecl(D, Loc))
3505 return ExprError();
3506
3507 auto *VD = cast<ValueDecl>(D);
3508
3509 // Only create DeclRefExpr's for valid Decl's.
3510 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3511 return ExprError();
3512
3513 // Handle members of anonymous structs and unions. If we got here,
3514 // and the reference is to a class member indirect field, then this
3515 // must be the subject of a pointer-to-member expression.
3516 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3517 IndirectField && !IndirectField->isCXXClassMember())
3519 IndirectField);
3520
3521 QualType type = VD->getType();
3522 if (type.isNull())
3523 return ExprError();
3524 ExprValueKind valueKind = VK_PRValue;
3525
3526 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3527 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3528 // is expanded by some outer '...' in the context of the use.
3529 type = type.getNonPackExpansionType();
3530
3531 switch (D->getKind()) {
3532 // Ignore all the non-ValueDecl kinds.
3533#define ABSTRACT_DECL(kind)
3534#define VALUE(type, base)
3535#define DECL(type, base) case Decl::type:
3536#include "clang/AST/DeclNodes.inc"
3537 llvm_unreachable("invalid value decl kind");
3538
3539 // These shouldn't make it here.
3540 case Decl::ObjCAtDefsField:
3541 llvm_unreachable("forming non-member reference to ivar?");
3542
3543 // Enum constants are always r-values and never references.
3544 // Unresolved using declarations are dependent.
3545 case Decl::EnumConstant:
3546 case Decl::UnresolvedUsingValue:
3547 case Decl::OMPDeclareReduction:
3548 case Decl::OMPDeclareMapper:
3549 valueKind = VK_PRValue;
3550 break;
3551
3552 // Fields and indirect fields that got here must be for
3553 // pointer-to-member expressions; we just call them l-values for
3554 // internal consistency, because this subexpression doesn't really
3555 // exist in the high-level semantics.
3556 case Decl::Field:
3557 case Decl::IndirectField:
3558 case Decl::ObjCIvar:
3559 assert((getLangOpts().CPlusPlus || isBoundsAttrContext()) &&
3560 "building reference to field in C?");
3561
3562 // These can't have reference type in well-formed programs, but
3563 // for internal consistency we do this anyway.
3564 type = type.getNonReferenceType();
3565 valueKind = VK_LValue;
3566 break;
3567
3568 // Non-type template parameters are either l-values or r-values
3569 // depending on the type.
3570 case Decl::NonTypeTemplateParm: {
3571 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3572 type = reftype->getPointeeType();
3573 valueKind = VK_LValue; // even if the parameter is an r-value reference
3574 break;
3575 }
3576
3577 // [expr.prim.id.unqual]p2:
3578 // If the entity is a template parameter object for a template
3579 // parameter of type T, the type of the expression is const T.
3580 // [...] The expression is an lvalue if the entity is a [...] template
3581 // parameter object.
3582 if (type->isRecordType()) {
3583 type = type.getUnqualifiedType().withConst();
3584 valueKind = VK_LValue;
3585 break;
3586 }
3587
3588 // For non-references, we need to strip qualifiers just in case
3589 // the template parameter was declared as 'const int' or whatever.
3590 valueKind = VK_PRValue;
3591 type = type.getUnqualifiedType();
3592 break;
3593 }
3594
3595 case Decl::Var:
3596 case Decl::VarTemplateSpecialization:
3597 case Decl::VarTemplatePartialSpecialization:
3598 case Decl::Decomposition:
3599 case Decl::OMPCapturedExpr:
3600 // In C, "extern void blah;" is valid and is an r-value.
3601 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3602 type->isVoidType()) {
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606 [[fallthrough]];
3607
3608 case Decl::ImplicitParam:
3609 case Decl::ParmVar: {
3610 // These are always l-values.
3611 valueKind = VK_LValue;
3612 type = type.getNonReferenceType();
3613
3614 // FIXME: Does the addition of const really only apply in
3615 // potentially-evaluated contexts? Since the variable isn't actually
3616 // captured in an unevaluated context, it seems that the answer is no.
3617 if (!isUnevaluatedContext()) {
3618 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3619 if (!CapturedType.isNull())
3620 type = CapturedType;
3621 }
3622
3623 break;
3624 }
3625
3626 case Decl::Binding:
3627 // These are always lvalues.
3628 valueKind = VK_LValue;
3629 type = type.getNonReferenceType();
3630 break;
3631
3632 case Decl::Function: {
3633 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3636 valueKind = VK_PRValue;
3637 break;
3638 }
3639 }
3640
3641 const FunctionType *fty = type->castAs<FunctionType>();
3642
3643 // If we're referring to a function with an __unknown_anytype
3644 // result type, make the entire expression __unknown_anytype.
3645 if (fty->getReturnType() == Context.UnknownAnyTy) {
3647 valueKind = VK_PRValue;
3648 break;
3649 }
3650
3651 // Functions are l-values in C++.
3652 if (getLangOpts().CPlusPlus) {
3653 valueKind = VK_LValue;
3654 break;
3655 }
3656
3657 // C99 DR 316 says that, if a function type comes from a
3658 // function definition (without a prototype), that type is only
3659 // used for checking compatibility. Therefore, when referencing
3660 // the function, we pretend that we don't have the full function
3661 // type.
3662 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3664 fty->getExtInfo());
3665
3666 // Functions are r-values in C.
3667 valueKind = VK_PRValue;
3668 break;
3669 }
3670
3671 case Decl::CXXDeductionGuide:
3672 llvm_unreachable("building reference to deduction guide");
3673
3674 case Decl::MSProperty:
3675 case Decl::MSGuid:
3676 case Decl::TemplateParamObject:
3677 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3678 // capture in OpenMP, or duplicated between host and device?
3679 valueKind = VK_LValue;
3680 break;
3681
3682 case Decl::UnnamedGlobalConstant:
3683 valueKind = VK_LValue;
3684 break;
3685
3686 case Decl::CXXMethod:
3687 // If we're referring to a method with an __unknown_anytype
3688 // result type, make the entire expression __unknown_anytype.
3689 // This should only be possible with a type written directly.
3690 if (const FunctionProtoType *proto =
3691 dyn_cast<FunctionProtoType>(VD->getType()))
3692 if (proto->getReturnType() == Context.UnknownAnyTy) {
3694 valueKind = VK_PRValue;
3695 break;
3696 }
3697
3698 // C++ methods are l-values if static, r-values if non-static.
3699 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3700 valueKind = VK_LValue;
3701 break;
3702 }
3703 [[fallthrough]];
3704
3705 case Decl::CXXConversion:
3706 case Decl::CXXDestructor:
3707 case Decl::CXXConstructor:
3708 valueKind = VK_PRValue;
3709 break;
3710 }
3711
3712 auto *E =
3713 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3714 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3715 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3716 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3717 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3718 // diagnostics).
3719 if (VD->isInvalidDecl() && E)
3720 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3721 return E;
3722}
3723
3724static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3726 Target.resize(CharByteWidth * (Source.size() + 1));
3727 char *ResultPtr = &Target[0];
3728 const llvm::UTF8 *ErrorPtr;
3729 bool success =
3730 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3731 (void)success;
3732 assert(success);
3733 Target.resize(ResultPtr - &Target[0]);
3734}
3735
3738 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3739 if (!currentDecl) {
3740 Diag(Loc, diag::ext_predef_outside_function);
3741 currentDecl = Context.getTranslationUnitDecl();
3742 }
3743
3744 QualType ResTy;
3745 StringLiteral *SL = nullptr;
3746 if (cast<DeclContext>(currentDecl)->isDependentContext())
3747 ResTy = Context.DependentTy;
3748 else {
3749 // Pre-defined identifiers are of type char[x], where x is the length of
3750 // the string.
3751 bool ForceElaboratedPrinting =
3752 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3753 auto Str =
3754 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3755 unsigned Length = Str.length();
3756
3757 llvm::APInt LengthI(32, Length + 1);
3760 ResTy =
3762 SmallString<32> RawChars;
3764 Str, RawChars);
3765 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3767 /*IndexTypeQuals*/ 0);
3769 /*Pascal*/ false, ResTy, Loc);
3770 } else {
3772 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3774 /*IndexTypeQuals*/ 0);
3776 /*Pascal*/ false, ResTy, Loc);
3777 }
3778 }
3779
3780 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3781 SL);
3782}
3783
3785 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3786}
3787
3789 SmallString<16> CharBuffer;
3790 bool Invalid = false;
3791 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3792 if (Invalid)
3793 return ExprError();
3794
3795 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3796 PP, Tok.getKind());
3797 if (Literal.hadError())
3798 return ExprError();
3799
3800 QualType Ty;
3801 if (Literal.isWide())
3802 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3803 else if (Literal.isUTF8() && getLangOpts().C23)
3804 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3805 else if (Literal.isUTF8() && getLangOpts().Char8)
3806 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3807 else if (Literal.isUTF16())
3808 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3809 else if (Literal.isUTF32())
3810 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3811 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3812 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3813 else
3814 Ty = Context.CharTy; // 'x' -> char in C++;
3815 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3816
3818 if (Literal.isWide())
3820 else if (Literal.isUTF16())
3822 else if (Literal.isUTF32())
3824 else if (Literal.isUTF8())
3826
3827 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3828 Tok.getLocation());
3829
3830 if (Literal.getUDSuffix().empty())
3831 return Lit;
3832
3833 // We're building a user-defined literal.
3834 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3835 SourceLocation UDSuffixLoc =
3836 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3837
3838 // Make sure we're allowed user-defined literals here.
3839 if (!UDLScope)
3840 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3841
3842 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3843 // operator "" X (ch)
3844 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3845 Lit, Tok.getLocation());
3846}
3847
3849 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3850 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3851 Context.IntTy, Loc);
3852}
3853
3855 QualType Ty, SourceLocation Loc) {
3856 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3857
3858 using llvm::APFloat;
3859 APFloat Val(Format);
3860
3861 APFloat::opStatus result = Literal.GetFloatValue(Val);
3862
3863 // Overflow is always an error, but underflow is only an error if
3864 // we underflowed to zero (APFloat reports denormals as underflow).
3865 if ((result & APFloat::opOverflow) ||
3866 ((result & APFloat::opUnderflow) && Val.isZero())) {
3867 unsigned diagnostic;
3868 SmallString<20> buffer;
3869 if (result & APFloat::opOverflow) {
3870 diagnostic = diag::warn_float_overflow;
3871 APFloat::getLargest(Format).toString(buffer);
3872 } else {
3873 diagnostic = diag::warn_float_underflow;
3874 APFloat::getSmallest(Format).toString(buffer);
3875 }
3876
3877 S.Diag(Loc, diagnostic)
3878 << Ty
3879 << StringRef(buffer.data(), buffer.size());
3880 }
3881
3882 bool isExact = (result == APFloat::opOK);
3883 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3884}
3885
3886bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3887 assert(E && "Invalid expression");
3888
3889 if (E->isValueDependent())
3890 return false;
3891
3892 QualType QT = E->getType();
3893 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3894 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3895 return true;
3896 }
3897
3898 llvm::APSInt ValueAPS;
3900
3901 if (R.isInvalid())
3902 return true;
3903
3904 // GCC allows the value of unroll count to be 0.
3905 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3906 // "The values of 0 and 1 block any unrolling of the loop."
3907 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3908 // '#pragma unroll' cases.
3909 bool ValueIsPositive =
3910 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3911 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3912 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3913 << toString(ValueAPS, 10) << ValueIsPositive;
3914 return true;
3915 }
3916
3917 return false;
3918}
3919
3921 // Fast path for a single digit (which is quite common). A single digit
3922 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3923 if (Tok.getLength() == 1) {
3924 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3925 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3926 }
3927
3928 SmallString<128> SpellingBuffer;
3929 // NumericLiteralParser wants to overread by one character. Add padding to
3930 // the buffer in case the token is copied to the buffer. If getSpelling()
3931 // returns a StringRef to the memory buffer, it should have a null char at
3932 // the EOF, so it is also safe.
3933 SpellingBuffer.resize(Tok.getLength() + 1);
3934
3935 // Get the spelling of the token, which eliminates trigraphs, etc.
3936 bool Invalid = false;
3937 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3938 if (Invalid)
3939 return ExprError();
3940
3941 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3944 if (Literal.hadError)
3945 return ExprError();
3946
3947 if (Literal.hasUDSuffix()) {
3948 // We're building a user-defined literal.
3949 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3950 SourceLocation UDSuffixLoc =
3951 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3952
3953 // Make sure we're allowed user-defined literals here.
3954 if (!UDLScope)
3955 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3956
3957 QualType CookedTy;
3958 if (Literal.isFloatingLiteral()) {
3959 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3960 // long double, the literal is treated as a call of the form
3961 // operator "" X (f L)
3962 CookedTy = Context.LongDoubleTy;
3963 } else {
3964 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3965 // unsigned long long, the literal is treated as a call of the form
3966 // operator "" X (n ULL)
3967 CookedTy = Context.UnsignedLongLongTy;
3968 }
3969
3970 DeclarationName OpName =
3972 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3973 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3974
3975 SourceLocation TokLoc = Tok.getLocation();
3976
3977 // Perform literal operator lookup to determine if we're building a raw
3978 // literal or a cooked one.
3979 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3980 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3981 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3982 /*AllowStringTemplatePack*/ false,
3983 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3985 // Lookup failure for imaginary constants isn't fatal, there's still the
3986 // GNU extension producing _Complex types.
3987 break;
3988 case LOLR_Error:
3989 return ExprError();
3990 case LOLR_Cooked: {
3991 Expr *Lit;
3992 if (Literal.isFloatingLiteral()) {
3993 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3994 } else {
3995 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3996 if (Literal.GetIntegerValue(ResultVal))
3997 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3998 << /* Unsigned */ 1;
3999 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4000 Tok.getLocation());
4001 }
4002 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4003 }
4004
4005 case LOLR_Raw: {
4006 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4007 // literal is treated as a call of the form
4008 // operator "" X ("n")
4009 unsigned Length = Literal.getUDSuffixOffset();
4012 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4013 Expr *Lit =
4014 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4016 /*Pascal*/ false, StrTy, &TokLoc, 1);
4017 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4018 }
4019
4020 case LOLR_Template: {
4021 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4022 // template), L is treated as a call fo the form
4023 // operator "" X <'c1', 'c2', ... 'ck'>()
4024 // where n is the source character sequence c1 c2 ... ck.
4025 TemplateArgumentListInfo ExplicitArgs;
4026 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4027 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4028 llvm::APSInt Value(CharBits, CharIsUnsigned);
4029 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4030 Value = TokSpelling[I];
4033 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4034 }
4035 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4036 &ExplicitArgs);
4037 }
4039 llvm_unreachable("unexpected literal operator lookup result");
4040 }
4041 }
4042
4043 Expr *Res;
4044
4045 if (Literal.isFixedPointLiteral()) {
4046 QualType Ty;
4047
4048 if (Literal.isAccum) {
4049 if (Literal.isHalf) {
4050 Ty = Context.ShortAccumTy;
4051 } else if (Literal.isLong) {
4052 Ty = Context.LongAccumTy;
4053 } else {
4054 Ty = Context.AccumTy;
4055 }
4056 } else if (Literal.isFract) {
4057 if (Literal.isHalf) {
4058 Ty = Context.ShortFractTy;
4059 } else if (Literal.isLong) {
4060 Ty = Context.LongFractTy;
4061 } else {
4062 Ty = Context.FractTy;
4063 }
4064 }
4065
4066 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4067
4068 bool isSigned = !Literal.isUnsigned;
4069 unsigned scale = Context.getFixedPointScale(Ty);
4070 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4071
4072 llvm::APInt Val(bit_width, 0, isSigned);
4073 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4074 bool ValIsZero = Val.isZero() && !Overflowed;
4075
4076 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4077 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4078 // Clause 6.4.4 - The value of a constant shall be in the range of
4079 // representable values for its type, with exception for constants of a
4080 // fract type with a value of exactly 1; such a constant shall denote
4081 // the maximal value for the type.
4082 --Val;
4083 else if (Val.ugt(MaxVal) || Overflowed)
4084 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4085
4087 Tok.getLocation(), scale);
4088 } else if (Literal.isFloatingLiteral()) {
4089 QualType Ty;
4090 if (Literal.isHalf){
4091 if (getLangOpts().HLSL ||
4092 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4093 Ty = Context.HalfTy;
4094 else {
4095 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4096 return ExprError();
4097 }
4098 } else if (Literal.isFloat)
4099 Ty = Context.FloatTy;
4100 else if (Literal.isLong)
4102 else if (Literal.isFloat16)
4103 Ty = Context.Float16Ty;
4104 else if (Literal.isFloat128)
4105 Ty = Context.Float128Ty;
4106 else
4107 Ty = Context.DoubleTy;
4108
4109 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4110
4111 if (Ty == Context.DoubleTy) {
4112 if (getLangOpts().SinglePrecisionConstants) {
4113 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4114 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4115 }
4116 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4117 "cl_khr_fp64", getLangOpts())) {
4118 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4119 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4121 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4122 }
4123 }
4124 } else if (!Literal.isIntegerLiteral()) {
4125 return ExprError();
4126 } else {
4127 QualType Ty;
4128
4129 // 'z/uz' literals are a C++23 feature.
4130 if (Literal.isSizeT)
4133 ? diag::warn_cxx20_compat_size_t_suffix
4134 : diag::ext_cxx23_size_t_suffix
4135 : diag::err_cxx23_size_t_suffix);
4136
4137 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4138 // but we do not currently support the suffix in C++ mode because it's not
4139 // entirely clear whether WG21 will prefer this suffix to return a library
4140 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4141 // literals are a C++ extension.
4142 if (Literal.isBitInt)
4143 PP.Diag(Tok.getLocation(),
4144 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4145 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4146 : diag::ext_c23_bitint_suffix);
4147
4148 // Get the value in the widest-possible width. What is "widest" depends on
4149 // whether the literal is a bit-precise integer or not. For a bit-precise
4150 // integer type, try to scan the source to determine how many bits are
4151 // needed to represent the value. This may seem a bit expensive, but trying
4152 // to get the integer value from an overly-wide APInt is *extremely*
4153 // expensive, so the naive approach of assuming
4154 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4155 unsigned BitsNeeded =
4156 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4157 Literal.getLiteralDigits(), Literal.getRadix())
4159 llvm::APInt ResultVal(BitsNeeded, 0);
4160
4161 if (Literal.GetIntegerValue(ResultVal)) {
4162 // If this value didn't fit into uintmax_t, error and force to ull.
4163 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4164 << /* Unsigned */ 1;
4166 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4167 "long long is not intmax_t?");
4168 } else {
4169 // If this value fits into a ULL, try to figure out what else it fits into
4170 // according to the rules of C99 6.4.4.1p5.
4171
4172 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4173 // be an unsigned int.
4174 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4175
4176 // Check from smallest to largest, picking the smallest type we can.
4177 unsigned Width = 0;
4178
4179 // Microsoft specific integer suffixes are explicitly sized.
4180 if (Literal.MicrosoftInteger) {
4181 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4182 Width = 8;
4183 Ty = Context.CharTy;
4184 } else {
4185 Width = Literal.MicrosoftInteger;
4186 Ty = Context.getIntTypeForBitwidth(Width,
4187 /*Signed=*/!Literal.isUnsigned);
4188 }
4189 }
4190
4191 // Bit-precise integer literals are automagically-sized based on the
4192 // width required by the literal.
4193 if (Literal.isBitInt) {
4194 // The signed version has one more bit for the sign value. There are no
4195 // zero-width bit-precise integers, even if the literal value is 0.
4196 Width = std::max(ResultVal.getActiveBits(), 1u) +
4197 (Literal.isUnsigned ? 0u : 1u);
4198
4199 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4200 // and reset the type to the largest supported width.
4201 unsigned int MaxBitIntWidth =
4203 if (Width > MaxBitIntWidth) {
4204 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4205 << Literal.isUnsigned;
4206 Width = MaxBitIntWidth;
4207 }
4208
4209 // Reset the result value to the smaller APInt and select the correct
4210 // type to be used. Note, we zext even for signed values because the
4211 // literal itself is always an unsigned value (a preceeding - is a
4212 // unary operator, not part of the literal).
4213 ResultVal = ResultVal.zextOrTrunc(Width);
4214 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4215 }
4216
4217 // Check C++23 size_t literals.
4218 if (Literal.isSizeT) {
4219 assert(!Literal.MicrosoftInteger &&
4220 "size_t literals can't be Microsoft literals");
4221 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4223
4224 // Does it fit in size_t?
4225 if (ResultVal.isIntN(SizeTSize)) {
4226 // Does it fit in ssize_t?
4227 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4229 else if (AllowUnsigned)
4230 Ty = Context.getSizeType();
4231 Width = SizeTSize;
4232 }
4233 }
4234
4235 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4236 !Literal.isSizeT) {
4237 // Are int/unsigned possibilities?
4238 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4239
4240 // Does it fit in a unsigned int?
4241 if (ResultVal.isIntN(IntSize)) {
4242 // Does it fit in a signed int?
4243 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4244 Ty = Context.IntTy;
4245 else if (AllowUnsigned)
4247 Width = IntSize;
4248 }
4249 }
4250
4251 // Are long/unsigned long possibilities?
4252 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4253 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4254
4255 // Does it fit in a unsigned long?
4256 if (ResultVal.isIntN(LongSize)) {
4257 // Does it fit in a signed long?
4258 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4259 Ty = Context.LongTy;
4260 else if (AllowUnsigned)
4262 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4263 // is compatible.
4264 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4265 const unsigned LongLongSize =
4267 Diag(Tok.getLocation(),
4269 ? Literal.isLong
4270 ? diag::warn_old_implicitly_unsigned_long_cxx
4271 : /*C++98 UB*/ diag::
4272 ext_old_implicitly_unsigned_long_cxx
4273 : diag::warn_old_implicitly_unsigned_long)
4274 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4275 : /*will be ill-formed*/ 1);
4277 }
4278 Width = LongSize;
4279 }
4280 }
4281
4282 // Check long long if needed.
4283 if (Ty.isNull() && !Literal.isSizeT) {
4284 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4285
4286 // Does it fit in a unsigned long long?
4287 if (ResultVal.isIntN(LongLongSize)) {
4288 // Does it fit in a signed long long?
4289 // To be compatible with MSVC, hex integer literals ending with the
4290 // LL or i64 suffix are always signed in Microsoft mode.
4291 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4292 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4293 Ty = Context.LongLongTy;
4294 else if (AllowUnsigned)
4296 Width = LongLongSize;
4297
4298 // 'long long' is a C99 or C++11 feature, whether the literal
4299 // explicitly specified 'long long' or we needed the extra width.
4300 if (getLangOpts().CPlusPlus)
4301 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4302 ? diag::warn_cxx98_compat_longlong
4303 : diag::ext_cxx11_longlong);
4304 else if (!getLangOpts().C99)
4305 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4306 }
4307 }
4308
4309 // If we still couldn't decide a type, we either have 'size_t' literal
4310 // that is out of range, or a decimal literal that does not fit in a
4311 // signed long long and has no U suffix.
4312 if (Ty.isNull()) {
4313 if (Literal.isSizeT)
4314 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4315 << Literal.isUnsigned;
4316 else
4317 Diag(Tok.getLocation(),
4318 diag::ext_integer_literal_too_large_for_signed);
4321 }
4322
4323 if (ResultVal.getBitWidth() != Width)
4324 ResultVal = ResultVal.trunc(Width);
4325 }
4326 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4327 }
4328
4329 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4330 if (Literal.isImaginary) {
4331 Res = new (Context) ImaginaryLiteral(Res,
4333
4334 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4335 }
4336 return Res;
4337}
4338
4340 assert(E && "ActOnParenExpr() missing expr");
4341 QualType ExprTy = E->getType();
4342 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4343 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4344 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4345 return new (Context) ParenExpr(L, R, E);
4346}
4347
4349 SourceLocation Loc,
4350 SourceRange ArgRange) {
4351 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4352 // scalar or vector data type argument..."
4353 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4354 // type (C99 6.2.5p18) or void.
4355 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4356 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4357 << T << ArgRange;
4358 return true;
4359 }
4360
4361 assert((T->isVoidType() || !T->isIncompleteType()) &&
4362 "Scalar types should always be complete");
4363 return false;
4364}
4365
4367 SourceLocation Loc,
4368 SourceRange ArgRange) {
4369 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4370 if (!T->isVectorType() && !T->isSizelessVectorType())
4371 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4372 << ""
4373 << "__builtin_vectorelements" << T << ArgRange;
4374
4375 return false;
4376}
4377
4379 SourceLocation Loc,
4380 SourceRange ArgRange,
4381 UnaryExprOrTypeTrait TraitKind) {
4382 // Invalid types must be hard errors for SFINAE in C++.
4383 if (S.LangOpts.CPlusPlus)
4384 return true;
4385
4386 // C99 6.5.3.4p1:
4387 if (T->isFunctionType() &&
4388 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4389 TraitKind == UETT_PreferredAlignOf)) {
4390 // sizeof(function)/alignof(function) is allowed as an extension.
4391 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4392 << getTraitSpelling(TraitKind) << ArgRange;
4393 return false;
4394 }
4395
4396 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4397 // this is an error (OpenCL v1.1 s6.3.k)
4398 if (T->isVoidType()) {
4399 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4400 : diag::ext_sizeof_alignof_void_type;
4401 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4402 return false;
4403 }
4404
4405 return true;
4406}
4407
4409 SourceLocation Loc,
4410 SourceRange ArgRange,
4411 UnaryExprOrTypeTrait TraitKind) {
4412 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4413 // runtime doesn't allow it.
4415 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4416 << T << (TraitKind == UETT_SizeOf)
4417 << ArgRange;
4418 return true;
4419 }
4420
4421 return false;
4422}
4423
4424/// Check whether E is a pointer from a decayed array type (the decayed
4425/// pointer type is equal to T) and emit a warning if it is.
4427 const Expr *E) {
4428 // Don't warn if the operation changed the type.
4429 if (T != E->getType())
4430 return;
4431
4432 // Now look for array decays.
4433 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4434 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4435 return;
4436
4437 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4438 << ICE->getType()
4439 << ICE->getSubExpr()->getType();
4440}
4441
4442/// Check the constraints on expression operands to unary type expression
4443/// and type traits.
4444///
4445/// Completes any types necessary and validates the constraints on the operand
4446/// expression. The logic mostly mirrors the type-based overload, but may modify
4447/// the expression as it completes the type for that expression through template
4448/// instantiation, etc.
4450 UnaryExprOrTypeTrait ExprKind) {
4451 QualType ExprTy = E->getType();
4452 assert(!ExprTy->isReferenceType());
4453
4454 bool IsUnevaluatedOperand =
4455 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4456 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4457 ExprKind == UETT_VecStep);
4458 if (IsUnevaluatedOperand) {
4460 if (Result.isInvalid())
4461 return true;
4462 E = Result.get();
4463 }
4464
4465 // The operand for sizeof and alignof is in an unevaluated expression context,
4466 // so side effects could result in unintended consequences.
4467 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4468 // used to build SFINAE gadgets.
4469 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4470 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4472 !E->getType()->isVariableArrayType() &&
4473 E->HasSideEffects(Context, false))
4474 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4475
4476 if (ExprKind == UETT_VecStep)
4477 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4478 E->getSourceRange());
4479
4480 if (ExprKind == UETT_VectorElements)
4481 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4482 E->getSourceRange());
4483
4484 // Explicitly list some types as extensions.
4485 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4486 E->getSourceRange(), ExprKind))
4487 return false;
4488
4489 // WebAssembly tables are always illegal operands to unary expressions and
4490 // type traits.
4491 if (Context.getTargetInfo().getTriple().isWasm() &&
4493 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4494 << getTraitSpelling(ExprKind);
4495 return true;
4496 }
4497
4498 // 'alignof' applied to an expression only requires the base element type of
4499 // the expression to be complete. 'sizeof' requires the expression's type to
4500 // be complete (and will attempt to complete it if it's an array of unknown
4501 // bound).
4502 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4505 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4506 getTraitSpelling(ExprKind), E->getSourceRange()))
4507 return true;
4508 } else {
4510 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4511 getTraitSpelling(ExprKind), E->getSourceRange()))
4512 return true;
4513 }
4514
4515 // Completing the expression's type may have changed it.
4516 ExprTy = E->getType();
4517 assert(!ExprTy->isReferenceType());
4518
4519 if (ExprTy->isFunctionType()) {
4520 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4521 << getTraitSpelling(ExprKind) << E->getSourceRange();
4522 return true;
4523 }
4524
4525 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4526 E->getSourceRange(), ExprKind))
4527 return true;
4528
4529 if (ExprKind == UETT_SizeOf) {
4530 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4531 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4532 QualType OType = PVD->getOriginalType();
4533 QualType Type = PVD->getType();
4534 if (Type->isPointerType() && OType->isArrayType()) {
4535 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4536 << Type << OType;
4537 Diag(PVD->getLocation(), diag::note_declared_at);
4538 }
4539 }
4540 }
4541
4542 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4543 // decays into a pointer and returns an unintended result. This is most
4544 // likely a typo for "sizeof(array) op x".
4545 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4546 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4547 BO->getLHS());
4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549 BO->getRHS());
4550 }
4551 }
4552
4553 return false;
4554}
4555
4556static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4557 // Cannot know anything else if the expression is dependent.
4558 if (E->isTypeDependent())
4559 return false;
4560
4561 if (E->getObjectKind() == OK_BitField) {
4562 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4563 << 1 << E->getSourceRange();
4564 return true;
4565 }
4566
4567 ValueDecl *D = nullptr;
4568 Expr *Inner = E->IgnoreParens();
4569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4570 D = DRE->getDecl();
4571 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4572 D = ME->getMemberDecl();
4573 }
4574
4575 // If it's a field, require the containing struct to have a
4576 // complete definition so that we can compute the layout.
4577 //
4578 // This can happen in C++11 onwards, either by naming the member
4579 // in a way that is not transformed into a member access expression
4580 // (in an unevaluated operand, for instance), or by naming the member
4581 // in a trailing-return-type.
4582 //
4583 // For the record, since __alignof__ on expressions is a GCC
4584 // extension, GCC seems to permit this but always gives the
4585 // nonsensical answer 0.
4586 //
4587 // We don't really need the layout here --- we could instead just
4588 // directly check for all the appropriate alignment-lowing
4589 // attributes --- but that would require duplicating a lot of
4590 // logic that just isn't worth duplicating for such a marginal
4591 // use-case.
4592 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4593 // Fast path this check, since we at least know the record has a
4594 // definition if we can find a member of it.
4595 if (!FD->getParent()->isCompleteDefinition()) {
4596 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4597 << E->getSourceRange();
4598 return true;
4599 }
4600
4601 // Otherwise, if it's a field, and the field doesn't have
4602 // reference type, then it must have a complete type (or be a
4603 // flexible array member, which we explicitly want to
4604 // white-list anyway), which makes the following checks trivial.
4605 if (!FD->getType()->isReferenceType())
4606 return false;
4607 }
4608
4609 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4610}
4611
4613 E = E->IgnoreParens();
4614
4615 // Cannot know anything else if the expression is dependent.
4616 if (E->isTypeDependent())
4617 return false;
4618
4619 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4620}
4621
4623 CapturingScopeInfo *CSI) {
4624 assert(T->isVariablyModifiedType());
4625 assert(CSI != nullptr);
4626
4627 // We're going to walk down into the type and look for VLA expressions.
4628 do {
4629 const Type *Ty = T.getTypePtr();
4630 switch (Ty->getTypeClass()) {
4631#define TYPE(Class, Base)
4632#define ABSTRACT_TYPE(Class, Base)
4633#define NON_CANONICAL_TYPE(Class, Base)
4634#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4635#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4636#include "clang/AST/TypeNodes.inc"
4637 T = QualType();
4638 break;
4639 // These types are never variably-modified.
4640 case Type::Builtin:
4641 case Type::Complex:
4642 case Type::Vector:
4643 case Type::ExtVector:
4644 case Type::ConstantMatrix:
4645 case Type::Record:
4646 case Type::Enum:
4647 case Type::TemplateSpecialization:
4648 case Type::ObjCObject:
4649 case Type::ObjCInterface:
4650 case Type::ObjCObjectPointer:
4651 case Type::ObjCTypeParam:
4652 case Type::Pipe:
4653 case Type::BitInt:
4654 llvm_unreachable("type class is never variably-modified!");
4655 case Type::Elaborated:
4656 T = cast<ElaboratedType>(Ty)->getNamedType();
4657 break;
4658 case Type::Adjusted:
4659 T = cast<AdjustedType>(Ty)->getOriginalType();
4660 break;
4661 case Type::Decayed:
4662 T = cast<DecayedType>(Ty)->getPointeeType();
4663 break;
4664 case Type::ArrayParameter:
4665 T = cast<ArrayParameterType>(Ty)->getElementType();
4666 break;
4667 case Type::Pointer:
4668 T = cast<PointerType>(Ty)->getPointeeType();
4669 break;
4670 case Type::BlockPointer:
4671 T = cast<BlockPointerType>(Ty)->getPointeeType();
4672 break;
4673 case Type::LValueReference:
4674 case Type::RValueReference:
4675 T = cast<ReferenceType>(Ty)->getPointeeType();
4676 break;
4677 case Type::MemberPointer:
4678 T = cast<MemberPointerType>(Ty)->getPointeeType();
4679 break;
4680 case Type::ConstantArray:
4681 case Type::IncompleteArray:
4682 // Losing element qualification here is fine.
4683 T = cast<ArrayType>(Ty)->getElementType();
4684 break;
4685 case Type::VariableArray: {
4686 // Losing element qualification here is fine.
4687 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4688
4689 // Unknown size indication requires no size computation.
4690 // Otherwise, evaluate and record it.
4691 auto Size = VAT->getSizeExpr();
4692 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4693 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4694 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4695
4696 T = VAT->getElementType();
4697 break;
4698 }
4699 case Type::FunctionProto:
4700 case Type::FunctionNoProto:
4701 T = cast<FunctionType>(Ty)->getReturnType();
4702 break;
4703 case Type::Paren:
4704 case Type::TypeOf:
4705 case Type::UnaryTransform:
4706 case Type::Attributed:
4707 case Type::BTFTagAttributed:
4708 case Type::SubstTemplateTypeParm:
4709 case Type::MacroQualified:
4710 case Type::CountAttributed:
4711 // Keep walking after single level desugaring.
4712 T = T.getSingleStepDesugaredType(Context);
4713 break;
4714 case Type::Typedef:
4715 T = cast<TypedefType>(Ty)->desugar();
4716 break;
4717 case Type::Decltype:
4718 T = cast<DecltypeType>(Ty)->desugar();
4719 break;
4720 case Type::PackIndexing:
4721 T = cast<PackIndexingType>(Ty)->desugar();
4722 break;
4723 case Type::Using:
4724 T = cast<UsingType>(Ty)->desugar();
4725 break;
4726 case Type::Auto:
4727 case Type::DeducedTemplateSpecialization:
4728 T = cast<DeducedType>(Ty)->getDeducedType();
4729 break;
4730 case Type::TypeOfExpr:
4731 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4732 break;
4733 case Type::Atomic:
4734 T = cast<AtomicType>(Ty)->getValueType();
4735 break;
4736 }
4737 } while (!T.isNull() && T->isVariablyModifiedType());
4738}
4739
4740/// Check the constraints on operands to unary expression and type
4741/// traits.
4742///
4743/// This will complete any types necessary, and validate the various constraints
4744/// on those operands.
4745///
4746/// The UsualUnaryConversions() function is *not* called by this routine.
4747/// C99 6.3.2.1p[2-4] all state:
4748/// Except when it is the operand of the sizeof operator ...
4749///
4750/// C++ [expr.sizeof]p4
4751/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4752/// standard conversions are not applied to the operand of sizeof.
4753///
4754/// This policy is followed for all of the unary trait expressions.
4756 SourceLocation OpLoc,
4757 SourceRange ExprRange,
4758 UnaryExprOrTypeTrait ExprKind,
4759 StringRef KWName) {
4760 if (ExprType->isDependentType())
4761 return false;
4762
4763 // C++ [expr.sizeof]p2:
4764 // When applied to a reference or a reference type, the result
4765 // is the size of the referenced type.
4766 // C++11 [expr.alignof]p3:
4767 // When alignof is applied to a reference type, the result
4768 // shall be the alignment of the referenced type.
4769 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4770 ExprType = Ref->getPointeeType();
4771
4772 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4773 // When alignof or _Alignof is applied to an array type, the result
4774 // is the alignment of the element type.
4775 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4776 ExprKind == UETT_OpenMPRequiredSimdAlign)
4777 ExprType = Context.getBaseElementType(ExprType);
4778
4779 if (ExprKind == UETT_VecStep)
4780 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4781
4782 if (ExprKind == UETT_VectorElements)
4783 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4784 ExprRange);
4785
4786 // Explicitly list some types as extensions.
4787 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4788 ExprKind))
4789 return false;
4790
4792 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4793 KWName, ExprRange))
4794 return true;
4795
4796 if (ExprType->isFunctionType()) {
4797 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4798 return true;
4799 }
4800
4801 // WebAssembly tables are always illegal operands to unary expressions and
4802 // type traits.
4803 if (Context.getTargetInfo().getTriple().isWasm() &&
4804 ExprType->isWebAssemblyTableType()) {
4805 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4806 << getTraitSpelling(ExprKind);
4807 return true;
4808 }
4809
4810 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4811 ExprKind))
4812 return true;
4813
4814 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4815 if (auto *TT = ExprType->getAs<TypedefType>()) {
4816 for (auto I = FunctionScopes.rbegin(),
4817 E = std::prev(FunctionScopes.rend());
4818 I != E; ++I) {
4819 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4820 if (CSI == nullptr)
4821 break;
4822 DeclContext *DC = nullptr;
4823 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4824 DC = LSI->CallOperator;
4825 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4826 DC = CRSI->TheCapturedDecl;
4827 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4828 DC = BSI->TheDecl;
4829 if (DC) {
4830 if (DC->containsDecl(TT->getDecl()))
4831 break;
4832 captureVariablyModifiedType(Context, ExprType, CSI);
4833 }
4834 }
4835 }
4836 }
4837
4838 return false;
4839}
4840
4841/// Build a sizeof or alignof expression given a type operand.
4843 SourceLocation OpLoc,
4844 UnaryExprOrTypeTrait ExprKind,
4845 SourceRange R) {
4846 if (!TInfo)
4847 return ExprError();
4848
4849 QualType T = TInfo->getType();
4850
4851 if (!T->isDependentType() &&
4852 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4853 getTraitSpelling(ExprKind)))
4854 return ExprError();
4855
4856 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4857 // properly deal with VLAs in nested calls of sizeof and typeof.
4858 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4859 TInfo->getType()->isVariablyModifiedType())
4860 TInfo = TransformToPotentiallyEvaluated(TInfo);
4861
4862 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4863 return new (Context) UnaryExprOrTypeTraitExpr(
4864 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4865}
4866
4867/// Build a sizeof or alignof expression given an expression
4868/// operand.
4871 UnaryExprOrTypeTrait ExprKind) {
4873 if (PE.isInvalid())
4874 return ExprError();
4875
4876 E = PE.get();
4877
4878 // Verify that the operand is valid.
4879 bool isInvalid = false;
4880 if (E->isTypeDependent()) {
4881 // Delay type-checking for type-dependent expressions.
4882 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4883 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4884 } else if (ExprKind == UETT_VecStep) {
4886 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4887 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4888 isInvalid = true;
4889 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4890 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4891 isInvalid = true;
4892 } else if (ExprKind == UETT_VectorElements) {
4893 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4894 } else {
4896 }
4897
4898 if (isInvalid)
4899 return ExprError();
4900
4901 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4903 if (PE.isInvalid()) return ExprError();
4904 E = PE.get();
4905 }
4906
4907 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4908 return new (Context) UnaryExprOrTypeTraitExpr(
4909 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4910}
4911
4912/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4913/// expr and the same for @c alignof and @c __alignof
4914/// Note that the ArgRange is invalid if isType is false.
4917 UnaryExprOrTypeTrait ExprKind, bool IsType,
4918 void *TyOrEx, SourceRange ArgRange) {
4919 // If error parsing type, ignore.
4920 if (!TyOrEx) return ExprError();
4921
4922 if (IsType) {
4923 TypeSourceInfo *TInfo;
4924 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4925 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4926 }
4927
4928 Expr *ArgEx = (Expr *)TyOrEx;
4929 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4930 return Result;
4931}
4932
4934 SourceLocation OpLoc, SourceRange R) {
4935 if (!TInfo)
4936 return true;
4937 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4938 UETT_AlignOf, KWName);
4939}
4940
4941/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4942/// _Alignas(type-name) .
4943/// [dcl.align] An alignment-specifier of the form
4944/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4945///
4946/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4947/// _Alignas(_Alignof(type-name)).
4949 SourceLocation OpLoc, SourceRange R) {
4950 TypeSourceInfo *TInfo;
4952 &TInfo);
4953 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4954}
4955
4957 bool IsReal) {
4958 if (V.get()->isTypeDependent())
4959 return S.Context.DependentTy;
4960
4961 // _Real and _Imag are only l-values for normal l-values.
4962 if (V.get()->getObjectKind() != OK_Ordinary) {
4963 V = S.DefaultLvalueConversion(V.get());
4964 if (V.isInvalid())
4965 return QualType();
4966 }
4967
4968 // These operators return the element type of a complex type.
4969 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4970 return CT->getElementType();
4971
4972 // Otherwise they pass through real integer and floating point types here.
4973 if (V.get()->getType()->isArithmeticType())
4974 return V.get()->getType();
4975
4976 // Test for placeholders.
4977 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4978 if (PR.isInvalid()) return QualType();
4979 if (PR.get() != V.get()) {
4980 V = PR;
4981 return CheckRealImagOperand(S, V, Loc, IsReal);
4982 }
4983
4984 // Reject anything else.
4985 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4986 << (IsReal ? "__real" : "__imag");
4987 return QualType();
4988}
4989
4990
4991
4994 tok::TokenKind Kind, Expr *Input) {
4996 switch (Kind) {
4997 default: llvm_unreachable("Unknown unary op!");
4998 case tok::plusplus: Opc = UO_PostInc; break;
4999 case tok::minusminus: Opc = UO_PostDec; break;
5000 }
5001
5002 // Since this might is a postfix expression, get rid of ParenListExprs.
5004 if (Result.isInvalid()) return ExprError();
5005 Input = Result.get();
5006
5007 return BuildUnaryOp(S, OpLoc, Opc, Input);
5008}
5009
5010/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5011///
5012/// \return true on error
5014 SourceLocation opLoc,
5015 Expr *op) {
5016 assert(op->getType()->isObjCObjectPointerType());
5018 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5019 return false;
5020
5021 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5022 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5023 << op->getSourceRange();
5024 return true;
5025}
5026
5028 auto *BaseNoParens = Base->IgnoreParens();
5029 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5030 return MSProp->getPropertyDecl()->getType()->isArrayType();
5031 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5032}
5033
5034// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5035// Typically this is DependentTy, but can sometimes be more precise.
5036//
5037// There are cases when we could determine a non-dependent type:
5038// - LHS and RHS may have non-dependent types despite being type-dependent
5039// (e.g. unbounded array static members of the current instantiation)
5040// - one may be a dependent-sized array with known element type
5041// - one may be a dependent-typed valid index (enum in current instantiation)
5042//
5043// We *always* return a dependent type, in such cases it is DependentTy.
5044// This avoids creating type-dependent expressions with non-dependent types.
5045// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5047 const ASTContext &Ctx) {
5048 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5049 QualType LTy = LHS->getType(), RTy = RHS->getType();
5051 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5052 if (const PointerType *PT = LTy->getAs<PointerType>())
5053 Result = PT->getPointeeType();
5054 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5055 Result = AT->getElementType();
5056 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5057 if (const PointerType *PT = RTy->getAs<PointerType>())
5058 Result = PT->getPointeeType();
5059 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5060 Result = AT->getElementType();
5061 }
5062 // Ensure we return a dependent type.
5063 return Result->isDependentType() ? Result : Ctx.DependentTy;
5064}
5065
5067 SourceLocation lbLoc,
5068 MultiExprArg ArgExprs,
5069 SourceLocation rbLoc) {
5070
5071 if (base && !base->getType().isNull() &&
5072 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5073 auto *AS = cast<ArraySectionExpr>(base);
5074 if (AS->isOMPArraySection())
5076 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5077 /*Length*/ nullptr,
5078 /*Stride=*/nullptr, rbLoc);
5079
5080 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5081 SourceLocation(), /*Length*/ nullptr,
5082 rbLoc);
5083 }
5084
5085 // Since this might be a postfix expression, get rid of ParenListExprs.
5086 if (isa<ParenListExpr>(base)) {
5088 if (result.isInvalid())
5089 return ExprError();
5090 base = result.get();
5091 }
5092
5093 // Check if base and idx form a MatrixSubscriptExpr.
5094 //
5095 // Helper to check for comma expressions, which are not allowed as indices for
5096 // matrix subscript expressions.
5097 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5098 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5099 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5100 << SourceRange(base->getBeginLoc(), rbLoc);
5101 return true;
5102 }
5103 return false;
5104 };
5105 // The matrix subscript operator ([][])is considered a single operator.
5106 // Separating the index expressions by parenthesis is not allowed.
5107 if (base && !base->getType().isNull() &&
5108 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5109 !isa<MatrixSubscriptExpr>(base)) {
5110 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5111 << SourceRange(base->getBeginLoc(), rbLoc);
5112 return ExprError();
5113 }
5114 // If the base is a MatrixSubscriptExpr, try to create a new
5115 // MatrixSubscriptExpr.
5116 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5117 if (matSubscriptE) {
5118 assert(ArgExprs.size() == 1);
5119 if (CheckAndReportCommaError(ArgExprs.front()))
5120 return ExprError();
5121
5122 assert(matSubscriptE->isIncomplete() &&
5123 "base has to be an incomplete matrix subscript");
5124 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5125 matSubscriptE->getRowIdx(),
5126 ArgExprs.front(), rbLoc);
5127 }
5128 if (base->getType()->isWebAssemblyTableType()) {
5129 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5130 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5131 return ExprError();
5132 }
5133
5134 // Handle any non-overload placeholder types in the base and index
5135 // expressions. We can't handle overloads here because the other
5136 // operand might be an overloadable type, in which case the overload
5137 // resolution for the operator overload should get the first crack
5138 // at the overload.
5139 bool IsMSPropertySubscript = false;
5140 if (base->getType()->isNonOverloadPlaceholderType()) {
5141 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5142 if (!IsMSPropertySubscript) {
5143 ExprResult result = CheckPlaceholderExpr(base);
5144 if (result.isInvalid())
5145 return ExprError();
5146 base = result.get();
5147 }
5148 }
5149
5150 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5151 if (base->getType()->isMatrixType()) {
5152 assert(ArgExprs.size() == 1);
5153 if (CheckAndReportCommaError(ArgExprs.front()))
5154 return ExprError();
5155
5156 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5157 rbLoc);
5158 }
5159
5160 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5161 Expr *idx = ArgExprs[0];
5162 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5163 (isa<CXXOperatorCallExpr>(idx) &&
5164 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5165 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5166 << SourceRange(base->getBeginLoc(), rbLoc);
5167 }
5168 }
5169
5170 if (ArgExprs.size() == 1 &&
5171 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5172 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5173 if (result.isInvalid())
5174 return ExprError();
5175 ArgExprs[0] = result.get();
5176 } else {
5177 if (CheckArgsForPlaceholders(ArgExprs))
5178 return ExprError();
5179 }
5180
5181 // Build an unanalyzed expression if either operand is type-dependent.
5182 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5183 (base->isTypeDependent() ||
5185 !isa<PackExpansionExpr>(ArgExprs[0])) {
5186 return new (Context) ArraySubscriptExpr(
5187 base, ArgExprs.front(),
5188 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5189 VK_LValue, OK_Ordinary, rbLoc);
5190 }
5191
5192 // MSDN, property (C++)
5193 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5194 // This attribute can also be used in the declaration of an empty array in a
5195 // class or structure definition. For example:
5196 // __declspec(property(get=GetX, put=PutX)) int x[];
5197 // The above statement indicates that x[] can be used with one or more array
5198 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5199 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5200 if (IsMSPropertySubscript) {
5201 assert(ArgExprs.size() == 1);
5202 // Build MS property subscript expression if base is MS property reference
5203 // or MS property subscript.
5204 return new (Context)
5205 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5206 VK_LValue, OK_Ordinary, rbLoc);
5207 }
5208
5209 // Use C++ overloaded-operator rules if either operand has record
5210 // type. The spec says to do this if either type is *overloadable*,
5211 // but enum types can't declare subscript operators or conversion
5212 // operators, so there's nothing interesting for overload resolution
5213 // to do if there aren't any record types involved.
5214 //
5215 // ObjC pointers have their own subscripting logic that is not tied
5216 // to overload resolution and so should not take this path.
5217 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5218 ((base->getType()->isRecordType() ||
5219 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5220 ArgExprs[0]->getType()->isRecordType())))) {
5221 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5222 }
5223
5224 ExprResult Res =
5225 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5226
5227 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5228 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5229
5230 return Res;
5231}
5232
5235 InitializationKind Kind =
5237 InitializationSequence InitSeq(*this, Entity, Kind, E);
5238 return InitSeq.Perform(*this, Entity, Kind, E);
5239}
5240
5242 Expr *ColumnIdx,
5243 SourceLocation RBLoc) {
5245 if (BaseR.isInvalid())
5246 return BaseR;
5247 Base = BaseR.get();
5248
5249 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5250 if (RowR.isInvalid())
5251 return RowR;
5252 RowIdx = RowR.get();
5253
5254 if (!ColumnIdx)
5255 return new (Context) MatrixSubscriptExpr(
5256 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5257
5258 // Build an unanalyzed expression if any of the operands is type-dependent.
5259 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5260 ColumnIdx->isTypeDependent())
5261 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5262 Context.DependentTy, RBLoc);
5263
5264 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5265 if (ColumnR.isInvalid())
5266 return ColumnR;
5267 ColumnIdx = ColumnR.get();
5268
5269 // Check that IndexExpr is an integer expression. If it is a constant
5270 // expression, check that it is less than Dim (= the number of elements in the
5271 // corresponding dimension).
5272 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5273 bool IsColumnIdx) -> Expr * {
5274 if (!IndexExpr->getType()->isIntegerType() &&
5275 !IndexExpr->isTypeDependent()) {
5276 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5277 << IsColumnIdx;
5278 return nullptr;
5279 }
5280
5281 if (std::optional<llvm::APSInt> Idx =
5282 IndexExpr->getIntegerConstantExpr(Context)) {
5283 if ((*Idx < 0 || *Idx >= Dim)) {
5284 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5285 << IsColumnIdx << Dim;
5286 return nullptr;
5287 }
5288 }
5289
5290 ExprResult ConvExpr =
5292 assert(!ConvExpr.isInvalid() &&
5293 "should be able to convert any integer type to size type");
5294 return ConvExpr.get();
5295 };
5296
5297 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5298 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5299 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5300 if (!RowIdx || !ColumnIdx)
5301 return ExprError();
5302
5303 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5304 MTy->getElementType(), RBLoc);
5305}
5306
5307void Sema::CheckAddressOfNoDeref(const Expr *E) {
5308 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5309 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5310
5311 // For expressions like `&(*s).b`, the base is recorded and what should be
5312 // checked.
5313 const MemberExpr *Member = nullptr;
5314 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5315 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5316
5317 LastRecord.PossibleDerefs.erase(StrippedExpr);
5318}
5319
5320void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5322 return;
5323
5324 QualType ResultTy = E->getType();
5325 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5326
5327 // Bail if the element is an array since it is not memory access.
5328 if (isa<ArrayType>(ResultTy))
5329 return;
5330
5331 if (ResultTy->hasAttr(attr::NoDeref)) {
5332 LastRecord.PossibleDerefs.insert(E);
5333 return;
5334 }
5335
5336 // Check if the base type is a pointer to a member access of a struct
5337 // marked with noderef.
5338 const Expr *Base = E->getBase();
5339 QualType BaseTy = Base->getType();
5340 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5341 // Not a pointer access
5342 return;
5343
5344 const MemberExpr *Member = nullptr;
5345 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5346 Member->isArrow())
5347 Base = Member->getBase();
5348
5349 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5350 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5351 LastRecord.PossibleDerefs.insert(E);
5352 }
5353}
5354
5357 Expr *Idx, SourceLocation RLoc) {
5358 Expr *LHSExp = Base;
5359 Expr *RHSExp = Idx;
5360
5363
5364 // Per C++ core issue 1213, the result is an xvalue if either operand is
5365 // a non-lvalue array, and an lvalue otherwise.
5366 if (getLangOpts().CPlusPlus11) {
5367 for (auto *Op : {LHSExp, RHSExp}) {
5368 Op = Op->IgnoreImplicit();
5369 if (Op->getType()->isArrayType() && !Op->isLValue())
5370 VK = VK_XValue;
5371 }
5372 }
5373
5374 // Perform default conversions.
5375 if (!LHSExp->getType()->getAs<VectorType>()) {
5377 if (Result.isInvalid())
5378 return ExprError();
5379 LHSExp = Result.get();
5380 }
5382 if (Result.isInvalid())
5383 return ExprError();
5384 RHSExp = Result.get();
5385
5386 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5387
5388 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5389 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5390 // in the subscript position. As a result, we need to derive the array base
5391 // and index from the expression types.
5392 Expr *BaseExpr, *IndexExpr;
5393 QualType ResultType;
5394 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5395 BaseExpr = LHSExp;
5396 IndexExpr = RHSExp;
5397 ResultType =
5399 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5400 BaseExpr = LHSExp;
5401 IndexExpr = RHSExp;
5402 ResultType = PTy->getPointeeType();
5403 } else if (const ObjCObjectPointerType *PTy =
5404 LHSTy->getAs<ObjCObjectPointerType>()) {
5405 BaseExpr = LHSExp;
5406 IndexExpr = RHSExp;
5407
5408 // Use custom logic if this should be the pseudo-object subscript
5409 // expression.
5411 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5412 nullptr);
5413
5414 ResultType = PTy->getPointeeType();
5415 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5416 // Handle the uncommon case of "123[Ptr]".
5417 BaseExpr = RHSExp;
5418 IndexExpr = LHSExp;
5419 ResultType = PTy->getPointeeType();
5420 } else if (const ObjCObjectPointerType *PTy =
5421 RHSTy->getAs<ObjCObjectPointerType>()) {
5422 // Handle the uncommon case of "123[Ptr]".
5423 BaseExpr = RHSExp;
5424 IndexExpr = LHSExp;
5425 ResultType = PTy->getPointeeType();
5427 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5428 << ResultType << BaseExpr->getSourceRange();
5429 return ExprError();
5430 }
5431 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5432 BaseExpr = LHSExp; // vectors: V[123]
5433 IndexExpr = RHSExp;
5434 // We apply C++ DR1213 to vector subscripting too.
5435 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5436 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5437 if (Materialized.isInvalid())
5438 return ExprError();
5439 LHSExp = Materialized.get();
5440 }
5441 VK = LHSExp->getValueKind();
5442 if (VK != VK_PRValue)
5443 OK = OK_VectorComponent;
5444
5445 ResultType = VTy->getElementType();
5446 QualType BaseType = BaseExpr->getType();
5447 Qualifiers BaseQuals = BaseType.getQualifiers();
5448 Qualifiers MemberQuals = ResultType.getQualifiers();
5449 Qualifiers Combined = BaseQuals + MemberQuals;
5450 if (Combined != MemberQuals)
5451 ResultType = Context.getQualifiedType(ResultType, Combined);
5452 } else if (LHSTy->isBuiltinType() &&
5453 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5454 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5455 if (BTy->isSVEBool())
5456 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5457 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5458
5459 BaseExpr = LHSExp;
5460 IndexExpr = RHSExp;
5461 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5462 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5463 if (Materialized.isInvalid())
5464 return ExprError();
5465 LHSExp = Materialized.get();
5466 }
5467 VK = LHSExp->getValueKind();
5468 if (VK != VK_PRValue)
5469 OK = OK_VectorComponent;
5470
5471 ResultType = BTy->getSveEltType(Context);
5472
5473 QualType BaseType = BaseExpr->getType();
5474 Qualifiers BaseQuals = BaseType.getQualifiers();
5475 Qualifiers MemberQuals = ResultType.getQualifiers();
5476 Qualifiers Combined = BaseQuals + MemberQuals;
5477 if (Combined != MemberQuals)
5478 ResultType = Context.getQualifiedType(ResultType, Combined);
5479 } else if (LHSTy->isArrayType()) {
5480 // If we see an array that wasn't promoted by
5481 // DefaultFunctionArrayLvalueConversion, it must be an array that
5482 // wasn't promoted because of the C90 rule that doesn't
5483 // allow promoting non-lvalue arrays. Warn, then
5484 // force the promotion here.
5485 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5486 << LHSExp->getSourceRange();
5487 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5488 CK_ArrayToPointerDecay).get();
5489 LHSTy = LHSExp->getType();
5490
5491 BaseExpr = LHSExp;
5492 IndexExpr = RHSExp;
5493 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5494 } else if (RHSTy->isArrayType()) {
5495 // Same as previous, except for 123[f().a] case
5496 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5497 << RHSExp->getSourceRange();
5498 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5499 CK_ArrayToPointerDecay).get();
5500 RHSTy = RHSExp->getType();
5501
5502 BaseExpr = RHSExp;
5503 IndexExpr = LHSExp;
5504 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5505 } else {
5506 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5507 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5508 }
5509 // C99 6.5.2.1p1
5510 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5511 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5512 << IndexExpr->getSourceRange());
5513
5514 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5515 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5516 !IndexExpr->isTypeDependent()) {
5517 std::optional<llvm::APSInt> IntegerContantExpr =
5519 if (!IntegerContantExpr.has_value() ||
5520 IntegerContantExpr.value().isNegative())
5521 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5522 }
5523
5524 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5525 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5526 // type. Note that Functions are not objects, and that (in C99 parlance)
5527 // incomplete types are not object types.
5528 if (ResultType->isFunctionType()) {
5529 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5530 << ResultType << BaseExpr->getSourceRange();
5531 return ExprError();
5532 }
5533
5534 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5535 // GNU extension: subscripting on pointer to void
5536 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5537 << BaseExpr->getSourceRange();
5538
5539 // C forbids expressions of unqualified void type from being l-values.
5540 // See IsCForbiddenLValueType.
5541 if (!ResultType.hasQualifiers())
5542 VK = VK_PRValue;
5543 } else if (!ResultType->isDependentType() &&
5544 !ResultType.isWebAssemblyReferenceType() &&
5546 LLoc, ResultType,
5547 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5548 return ExprError();
5549
5550 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5551 !ResultType.isCForbiddenLValueType());
5552
5554 FunctionScopes.size() > 1) {
5555 if (auto *TT =
5556 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5557 for (auto I = FunctionScopes.rbegin(),
5558 E = std::prev(FunctionScopes.rend());
5559 I != E; ++I) {
5560 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5561 if (CSI == nullptr)
5562 break;
5563 DeclContext *DC = nullptr;
5564 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5565 DC = LSI->CallOperator;
5566 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5567 DC = CRSI->TheCapturedDecl;
5568 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5569 DC = BSI->TheDecl;
5570 if (DC) {
5571 if (DC->containsDecl(TT->getDecl()))
5572 break;
5574 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5575 }
5576 }
5577 }
5578 }
5579
5580 return new (Context)
5581 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5582}
5583
5585 ParmVarDecl *Param, Expr *RewrittenInit,
5586 bool SkipImmediateInvocations) {
5587 if (Param->hasUnparsedDefaultArg()) {
5588 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5589 // If we've already cleared out the location for the default argument,
5590 // that means we're parsing it right now.
5591 if (!UnparsedDefaultArgLocs.count(Param)) {
5592 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5593 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5594 Param->setInvalidDecl();
5595 return true;
5596 }
5597
5598 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5599 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5601 diag::note_default_argument_declared_here);
5602 return true;
5603 }
5604
5605 if (Param->hasUninstantiatedDefaultArg()) {
5606 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5607 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5608 return true;
5609 }
5610
5611 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5612 assert(Init && "default argument but no initializer?");
5613
5614 // If the default expression creates temporaries, we need to
5615 // push them to the current stack of expression temporaries so they'll
5616 // be properly destroyed.
5617 // FIXME: We should really be rebuilding the default argument with new
5618 // bound temporaries; see the comment in PR5810.
5619 // We don't need to do that with block decls, though, because
5620 // blocks in default argument expression can never capture anything.
5621 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5622 // Set the "needs cleanups" bit regardless of whether there are
5623 // any explicit objects.
5624 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5625 // Append all the objects to the cleanup list. Right now, this
5626 // should always be a no-op, because blocks in default argument
5627 // expressions should never be able to capture anything.
5628 assert(!InitWithCleanup->getNumObjects() &&
5629 "default argument expression has capturing blocks?");
5630 }
5631 // C++ [expr.const]p15.1:
5632 // An expression or conversion is in an immediate function context if it is
5633 // potentially evaluated and [...] its innermost enclosing non-block scope
5634 // is a function parameter scope of an immediate function.
5636 *this,
5640 Param);
5641 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5642 SkipImmediateInvocations;
5643 runWithSufficientStackSpace(CallLoc, [&] {
5644 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5645 });
5646 return false;
5647}
5648
5649struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5651 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5652
5653 bool HasImmediateCalls = false;
5654 bool shouldVisitImplicitCode() const { return true; }
5655
5657 if (const FunctionDecl *FD = E->getDirectCallee())
5658 HasImmediateCalls |= FD->isImmediateFunction();
5660 }
5661
5663 if (const FunctionDecl *FD = E->getConstructor())
5664 HasImmediateCalls |= FD->isImmediateFunction();
5666 }
5667
5668 // SourceLocExpr are not immediate invocations
5669 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5670 // need to be rebuilt so that they refer to the correct SourceLocation and
5671 // DeclContext.
5673 HasImmediateCalls = true;
5675 }
5676
5677 // A nested lambda might have parameters with immediate invocations
5678 // in their default arguments.
5679 // The compound statement is not visited (as it does not constitute a
5680 // subexpression).
5681 // FIXME: We should consider visiting and transforming captures
5682 // with init expressions.
5684 return VisitCXXMethodDecl(E->getCallOperator());
5685 }
5686
5688 return TraverseStmt(E->getExpr());
5689 }
5690
5692 return TraverseStmt(E->getExpr());
5693 }
5694};
5695
5697 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5699 : TreeTransform(SemaRef) {}
5700
5701 // Lambda can only have immediate invocations in the default
5702 // args of their parameters, which is transformed upon calling the closure.
5703 // The body is not a subexpression, so we have nothing to do.
5704 // FIXME: Immediate calls in capture initializers should be transformed.
5707
5708 // Make sure we don't rebuild the this pointer as it would
5709 // cause it to incorrectly point it to the outermost class
5710 // in the case of nested struct initialization.
5712};
5713
5715 FunctionDecl *FD, ParmVarDecl *Param,
5716 Expr *Init) {
5717 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5718
5719 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5720 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5721 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5722 InitializationContext =
5724 if (!InitializationContext.has_value())
5725 InitializationContext.emplace(CallLoc, Param, CurContext);
5726
5727 if (!Init && !Param->hasUnparsedDefaultArg()) {
5728 // Mark that we are replacing a default argument first.
5729 // If we are instantiating a template we won't have to
5730 // retransform immediate calls.
5731 // C++ [expr.const]p15.1:
5732 // An expression or conversion is in an immediate function context if it
5733 // is potentially evaluated and [...] its innermost enclosing non-block
5734 // scope is a function parameter scope of an immediate function.
5736 *this,
5740 Param);
5741
5742 if (Param->hasUninstantiatedDefaultArg()) {
5743 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5744 return ExprError();
5745 }
5746 // CWG2631
5747 // An immediate invocation that is not evaluated where it appears is
5748 // evaluated and checked for whether it is a constant expression at the
5749 // point where the enclosing initializer is used in a function call.
5751 if (!NestedDefaultChecking)
5752 V.TraverseDecl(Param);
5753
5754 // Rewrite the call argument that was created from the corresponding
5755 // parameter's default argument.
5756 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5757 if (V.HasImmediateCalls)
5758 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5759 CallLoc, Param, CurContext};
5760 // Pass down lifetime extending flag, and collect temporaries in
5761 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5764 ExprResult Res;
5765 runWithSufficientStackSpace(CallLoc, [&] {
5766 Res = Immediate.TransformInitializer(Param->getInit(),
5767 /*NotCopy=*/false);
5768 });
5769 if (Res.isInvalid())
5770 return ExprError();
5771 Res = ConvertParamDefaultArgument(Param, Res.get(),
5772 Res.get()->getBeginLoc());
5773 if (Res.isInvalid())
5774 return ExprError();
5775 Init = Res.get();
5776 }
5777 }
5778
5780 CallLoc, FD, Param, Init,
5781 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5782 return ExprError();
5783
5784 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5785 Init, InitializationContext->Context);
5786}
5787
5789 assert(Field->hasInClassInitializer());
5790
5791 // If we might have already tried and failed to instantiate, don't try again.
5792 if (Field->isInvalidDecl())
5793 return ExprError();
5794
5795 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5796
5797 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5798
5799 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5800 InitializationContext =
5802 if (!InitializationContext.has_value())
5803 InitializationContext.emplace(Loc, Field, CurContext);
5804
5805 Expr *Init = nullptr;
5806
5807 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5808
5811
5812 if (!Field->getInClassInitializer()) {
5813 // Maybe we haven't instantiated the in-class initializer. Go check the
5814 // pattern FieldDecl to see if it has one.
5815 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5816 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5818 ClassPattern->lookup(Field->getDeclName());
5819
5820 FieldDecl *Pattern = nullptr;
5821 for (auto *L : Lookup) {
5822 if ((Pattern = dyn_cast<FieldDecl>(L)))
5823 break;
5824 }
5825 assert(Pattern && "We must have set the Pattern!");
5826 if (!Pattern->hasInClassInitializer() ||
5827 InstantiateInClassInitializer(Loc, Field, Pattern,
5829 Field->setInvalidDecl();
5830 return ExprError();
5831 }
5832 }
5833 }
5834
5835 // CWG2631
5836 // An immediate invocation that is not evaluated where it appears is
5837 // evaluated and checked for whether it is a constant expression at the
5838 // point where the enclosing initializer is used in a [...] a constructor
5839 // definition, or an aggregate initialization.
5841 if (!NestedDefaultChecking)
5842 V.TraverseDecl(Field);
5843 if (V.HasImmediateCalls) {
5844 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5845 CurContext};
5846 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5847 NestedDefaultChecking;
5848
5850 ExprResult Res;
5852 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5853 /*CXXDirectInit=*/false);
5854 });
5855 if (!Res.isInvalid())
5856 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5857 if (Res.isInvalid()) {
5858 Field->setInvalidDecl();
5859 return ExprError();
5860 }
5861 Init = Res.get();
5862 }
5863
5864 if (Field->getInClassInitializer()) {
5865 Expr *E = Init ? Init : Field->getInClassInitializer();
5866 if (!NestedDefaultChecking)
5868 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5869 });
5870 // C++11 [class.base.init]p7:
5871 // The initialization of each base and member constitutes a
5872 // full-expression.
5873 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5874 if (Res.isInvalid()) {
5875 Field->setInvalidDecl();
5876 return ExprError();
5877 }
5878 Init = Res.get();
5879
5880 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5881 Field, InitializationContext->Context,
5882 Init);
5883 }
5884
5885 // DR1351:
5886 // If the brace-or-equal-initializer of a non-static data member
5887 // invokes a defaulted default constructor of its class or of an
5888 // enclosing class in a potentially evaluated subexpression, the
5889 // program is ill-formed.
5890 //
5891 // This resolution is unworkable: the exception specification of the
5892 // default constructor can be needed in an unevaluated context, in
5893 // particular, in the operand of a noexcept-expression, and we can be
5894 // unable to compute an exception specification for an enclosed class.
5895 //
5896 // Any attempt to resolve the exception specification of a defaulted default
5897 // constructor before the initializer is lexically complete will ultimately
5898 // come here at which point we can diagnose it.
5899 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5900 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5901 << OutermostClass << Field;
5902 Diag(Field->getEndLoc(),
5903 diag::note_default_member_initializer_not_yet_parsed);
5904 // Recover by marking the field invalid, unless we're in a SFINAE context.
5905 if (!isSFINAEContext())
5906 Field->setInvalidDecl();
5907 return ExprError();
5908}
5909
5912 Expr *Fn) {
5913 if (Proto && Proto->isVariadic()) {
5914 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5915 return VariadicConstructor;
5916 else if (Fn && Fn->getType()->isBlockPointerType())
5917 return VariadicBlock;
5918 else if (FDecl) {
5919 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5920 if (Method->isInstance())
5921 return VariadicMethod;
5922 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5923 return VariadicMethod;
5924 return VariadicFunction;
5925 }
5926 return VariadicDoesNotApply;
5927}
5928
5929namespace {
5930class FunctionCallCCC final : public FunctionCallFilterCCC {
5931public:
5932 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5933 unsigned NumArgs, MemberExpr *ME)
5934 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5935 FunctionName(FuncName) {}
5936
5937 bool ValidateCandidate(const TypoCorrection &candidate) override {
5938 if (!candidate.getCorrectionSpecifier() ||
5939 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5940 return false;
5941 }
5942
5944 }
5945
5946 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5947 return std::make_unique<FunctionCallCCC>(*this);
5948 }
5949
5950private:
5951 const IdentifierInfo *const FunctionName;
5952};
5953}
5954
5956 FunctionDecl *FDecl,
5957 ArrayRef<Expr *> Args) {
5958 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5959 DeclarationName FuncName = FDecl->getDeclName();
5960 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5961
5962 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5963 if (TypoCorrection Corrected = S.CorrectTypo(
5965 S.getScopeForContext(S.CurContext), nullptr, CCC,
5967 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5968 if (Corrected.isOverloaded()) {
5971 for (NamedDecl *CD : Corrected) {
5972 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5974 OCS);
5975 }
5976 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5977 case OR_Success:
5978 ND = Best->FoundDecl;
5979 Corrected.setCorrectionDecl(ND);
5980 break;
5981 default:
5982 break;
5983 }
5984 }
5985 ND = ND->getUnderlyingDecl();
5986 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5987 return Corrected;
5988 }
5989 }
5990 return TypoCorrection();
5991}
5992
5993/// ConvertArgumentsForCall - Converts the arguments specified in
5994/// Args/NumArgs to the parameter types of the function FDecl with
5995/// function prototype Proto. Call is the call expression itself, and
5996/// Fn is the function expression. For a C++ member function, this
5997/// routine does not attempt to convert the object argument. Returns
5998/// true if the call is ill-formed.
5999bool
6001 FunctionDecl *FDecl,
6002 const FunctionProtoType *Proto,
6003 ArrayRef<Expr *> Args,
6004 SourceLocation RParenLoc,
6005 bool IsExecConfig) {
6006 // Bail out early if calling a builtin with custom typechecking.
6007 if (FDecl)
6008 if (unsigned ID = FDecl->getBuiltinID())
6010 return false;
6011
6012 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6013 // assignment, to the types of the corresponding parameter, ...
6014 bool HasExplicitObjectParameter =
6015 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6016 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6017 unsigned NumParams = Proto->getNumParams();
6018 bool Invalid = false;
6019 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6020 unsigned FnKind = Fn->getType()->isBlockPointerType()
6021 ? 1 /* block */
6022 : (IsExecConfig ? 3 /* kernel function (exec config) */
6023 : 0 /* function */);
6024
6025 // If too few arguments are available (and we don't have default
6026 // arguments for the remaining parameters), don't make the call.
6027 if (Args.size() < NumParams) {
6028 if (Args.size() < MinArgs) {
6029 TypoCorrection TC;
6030 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6031 unsigned diag_id =
6032 MinArgs == NumParams && !Proto->isVariadic()
6033 ? diag::err_typecheck_call_too_few_args_suggest
6034 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6036 TC, PDiag(diag_id)
6037 << FnKind << MinArgs - ExplicitObjectParameterOffset
6038 << static_cast<unsigned>(Args.size()) -
6039 ExplicitObjectParameterOffset
6040 << HasExplicitObjectParameter << TC.getCorrectionRange());
6041 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6042 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6043 ->getDeclName())
6044 Diag(RParenLoc,
6045 MinArgs == NumParams && !Proto->isVariadic()
6046 ? diag::err_typecheck_call_too_few_args_one
6047 : diag::err_typecheck_call_too_few_args_at_least_one)
6048 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6049 << HasExplicitObjectParameter << Fn->getSourceRange();
6050 else
6051 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6052 ? diag::err_typecheck_call_too_few_args
6053 : diag::err_typecheck_call_too_few_args_at_least)
6054 << FnKind << MinArgs - ExplicitObjectParameterOffset
6055 << static_cast<unsigned>(Args.size()) -
6056 ExplicitObjectParameterOffset
6057 << HasExplicitObjectParameter << Fn->getSourceRange();
6058
6059 // Emit the location of the prototype.
6060 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6061 Diag(FDecl->getLocation(), diag::note_callee_decl)
6062 << FDecl << FDecl->getParametersSourceRange();
6063
6064 return true;
6065 }
6066 // We reserve space for the default arguments when we create
6067 // the call expression, before calling ConvertArgumentsForCall.
6068 assert((Call->getNumArgs() == NumParams) &&
6069 "We should have reserved space for the default arguments before!");
6070 }
6071
6072 // If too many are passed and not variadic, error on the extras and drop
6073 // them.
6074 if (Args.size() > NumParams) {
6075 if (!Proto->isVariadic()) {
6076 TypoCorrection TC;
6077 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6078 unsigned diag_id =
6079 MinArgs == NumParams && !Proto->isVariadic()
6080 ? diag::err_typecheck_call_too_many_args_suggest
6081 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6083 TC, PDiag(diag_id)
6084 << FnKind << NumParams - ExplicitObjectParameterOffset
6085 << static_cast<unsigned>(Args.size()) -
6086 ExplicitObjectParameterOffset
6087 << HasExplicitObjectParameter << TC.getCorrectionRange());
6088 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6089 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6090 ->getDeclName())
6091 Diag(Args[NumParams]->getBeginLoc(),
6092 MinArgs == NumParams
6093 ? diag::err_typecheck_call_too_many_args_one
6094 : diag::err_typecheck_call_too_many_args_at_most_one)
6095 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6096 << static_cast<unsigned>(Args.size()) -
6097 ExplicitObjectParameterOffset
6098 << HasExplicitObjectParameter << Fn->getSourceRange()
6099 << SourceRange(Args[NumParams]->getBeginLoc(),
6100 Args.back()->getEndLoc());
6101 else
6102 Diag(Args[NumParams]->getBeginLoc(),
6103 MinArgs == NumParams
6104 ? diag::err_typecheck_call_too_many_args
6105 : diag::err_typecheck_call_too_many_args_at_most)
6106 << FnKind << NumParams - ExplicitObjectParameterOffset
6107 << static_cast<unsigned>(Args.size()) -
6108 ExplicitObjectParameterOffset
6109 << HasExplicitObjectParameter << Fn->getSourceRange()
6110 << SourceRange(Args[NumParams]->getBeginLoc(),
6111 Args.back()->getEndLoc());
6112
6113 // Emit the location of the prototype.
6114 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6115 Diag(FDecl->getLocation(), diag::note_callee_decl)
6116 << FDecl << FDecl->getParametersSourceRange();
6117
6118 // This deletes the extra arguments.
6119 Call->shrinkNumArgs(NumParams);
6120 return true;
6121 }
6122 }
6123 SmallVector<Expr *, 8> AllArgs;
6124 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6125
6126 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6127 AllArgs, CallType);
6128 if (Invalid)
6129 return true;
6130 unsigned TotalNumArgs = AllArgs.size();
6131 for (unsigned i = 0; i < TotalNumArgs; ++i)
6132 Call->setArg(i, AllArgs[i]);
6133
6134 Call->computeDependence();
6135 return false;
6136}
6137
6139 const FunctionProtoType *Proto,
6140 unsigned FirstParam, ArrayRef<Expr *> Args,
6141 SmallVectorImpl<Expr *> &AllArgs,
6142 VariadicCallType CallType, bool AllowExplicit,
6143 bool IsListInitialization) {
6144 unsigned NumParams = Proto->getNumParams();
6145 bool Invalid = false;
6146 size_t ArgIx = 0;
6147 // Continue to check argument types (even if we have too few/many args).
6148 for (unsigned i = FirstParam; i < NumParams; i++) {
6149 QualType ProtoArgType = Proto->getParamType(i);
6150
6151 Expr *Arg;
6152 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6153 if (ArgIx < Args.size()) {
6154 Arg = Args[ArgIx++];
6155
6156 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6157 diag::err_call_incomplete_argument, Arg))
6158 return true;
6159
6160 // Strip the unbridged-cast placeholder expression off, if applicable.
6161 bool CFAudited = false;
6162 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6163 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6164 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6165 Arg = stripARCUnbridgedCast(Arg);
6166 else if (getLangOpts().ObjCAutoRefCount &&
6167 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6168 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6169 CFAudited = true;
6170
6171 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6172 ProtoArgType->isBlockPointerType())
6173 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6174 BE->getBlockDecl()->setDoesNotEscape();
6175
6176 InitializedEntity Entity =
6178 ProtoArgType)
6180 Context, ProtoArgType, Proto->isParamConsumed(i));
6181
6182 // Remember that parameter belongs to a CF audited API.
6183 if (CFAudited)
6184 Entity.setParameterCFAudited();
6185
6187 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6188 if (ArgE.isInvalid())
6189 return true;
6190
6191 Arg = ArgE.getAs<Expr>();
6192 } else {
6193 assert(Param && "can't use default arguments without a known callee");
6194
6195 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6196 if (ArgExpr.isInvalid())
6197 return true;
6198
6199 Arg = ArgExpr.getAs<Expr>();
6200 }
6201
6202 // Check for array bounds violations for each argument to the call. This
6203 // check only triggers warnings when the argument isn't a more complex Expr
6204 // with its own checking, such as a BinaryOperator.
6205 CheckArrayAccess(Arg);
6206
6207 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6208 CheckStaticArrayArgument(CallLoc, Param, Arg);
6209
6210 AllArgs.push_back(Arg);
6211 }
6212
6213 // If this is a variadic call, handle args passed through "...".
6214 if (CallType != VariadicDoesNotApply) {
6215 // Assume that extern "C" functions with variadic arguments that
6216 // return __unknown_anytype aren't *really* variadic.
6217 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6218 FDecl->isExternC()) {
6219 for (Expr *A : Args.slice(ArgIx)) {
6220 QualType paramType; // ignored
6221 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6222 Invalid |= arg.isInvalid();
6223 AllArgs.push_back(arg.get());
6224 }
6225
6226 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6227 } else {
6228 for (Expr *A : Args.slice(ArgIx)) {
6229 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6230 Invalid |= Arg.isInvalid();
6231 AllArgs.push_back(Arg.get());
6232 }
6233 }
6234
6235 // Check for array bounds violations.
6236 for (Expr *A : Args.slice(ArgIx))
6237 CheckArrayAccess(A);
6238 }
6239 return Invalid;
6240}
6241
6243 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6244 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6245 TL = DTL.getOriginalLoc();
6246 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6247 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6248 << ATL.getLocalSourceRange();
6249}
6250
6251/// CheckStaticArrayArgument - If the given argument corresponds to a static
6252/// array parameter, check that it is non-null, and that if it is formed by
6253/// array-to-pointer decay, the underlying array is sufficiently large.
6254///
6255/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6256/// array type derivation, then for each call to the function, the value of the
6257/// corresponding actual argument shall provide access to the first element of
6258/// an array with at least as many elements as specified by the size expression.
6259void
6261 ParmVarDecl *Param,
6262 const Expr *ArgExpr) {
6263 // Static array parameters are not supported in C++.
6264 if (!Param || getLangOpts().CPlusPlus)
6265 return;
6266
6267 QualType OrigTy = Param->getOriginalType();
6268
6269 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6270 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6271 return;
6272
6273 if (ArgExpr->isNullPointerConstant(Context,
6275 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6276 DiagnoseCalleeStaticArrayParam(*this, Param);
6277 return;
6278 }
6279
6280 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6281 if (!CAT)
6282 return;
6283
6284 const ConstantArrayType *ArgCAT =
6286 if (!ArgCAT)
6287 return;
6288
6289 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6290 ArgCAT->getElementType())) {
6291 if (ArgCAT->getSize().ult(CAT->getSize())) {
6292 Diag(CallLoc, diag::warn_static_array_too_small)
6293 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6294 << (unsigned)CAT->getZExtSize() << 0;
6295 DiagnoseCalleeStaticArrayParam(*this, Param);
6296 }
6297 return;
6298 }
6299
6300 std::optional<CharUnits> ArgSize =
6302 std::optional<CharUnits> ParmSize =
6304 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6305 Diag(CallLoc, diag::warn_static_array_too_small)
6306 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6307 << (unsigned)ParmSize->getQuantity() << 1;
6308 DiagnoseCalleeStaticArrayParam(*this, Param);
6309 }
6310}
6311
6312/// Given a function expression of unknown-any type, try to rebuild it
6313/// to have a function type.
6315
6316/// Is the given type a placeholder that we need to lower out
6317/// immediately during argument processing?
6319 // Placeholders are never sugared.
6320 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6321 if (!placeholder) return false;
6322
6323 switch (placeholder->getKind()) {
6324 // Ignore all the non-placeholder types.
6325#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6326 case BuiltinType::Id:
6327#include "clang/Basic/OpenCLImageTypes.def"
6328#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6329 case BuiltinType::Id:
6330#include "clang/Basic/OpenCLExtensionTypes.def"
6331 // In practice we'll never use this, since all SVE types are sugared
6332 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6333#define SVE_TYPE(Name, Id, SingletonId) \
6334 case BuiltinType::Id:
6335#include "clang/Basic/AArch64SVEACLETypes.def"
6336#define PPC_VECTOR_TYPE(Name, Id, Size) \
6337 case BuiltinType::Id:
6338#include "clang/Basic/PPCTypes.def"
6339#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6340#include "clang/Basic/RISCVVTypes.def"
6341#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6342#include "clang/Basic/WebAssemblyReferenceTypes.def"
6343#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6344#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6345#include "clang/AST/BuiltinTypes.def"
6346 return false;
6347
6348 // We cannot lower out overload sets; they might validly be resolved
6349 // by the call machinery.
6350 case BuiltinType::Overload:
6351 return false;
6352
6353 // Unbridged casts in ARC can be handled in some call positions and
6354 // should be left in place.
6355 case BuiltinType::ARCUnbridgedCast:
6356 return false;
6357
6358 // Pseudo-objects should be converted as soon as possible.
6359 case BuiltinType::PseudoObject:
6360 return true;
6361
6362 // The debugger mode could theoretically but currently does not try
6363 // to resolve unknown-typed arguments based on known parameter types.
6364 case BuiltinType::UnknownAny:
6365 return true;
6366
6367 // These are always invalid as call arguments and should be reported.
6368 case BuiltinType::BoundMember:
6369 case BuiltinType::BuiltinFn:
6370 case BuiltinType::IncompleteMatrixIdx:
6371 case BuiltinType::ArraySection:
6372 case BuiltinType::OMPArrayShaping:
6373 case BuiltinType::OMPIterator:
6374 return true;
6375
6376 }
6377 llvm_unreachable("bad builtin type kind");
6378}
6379
6381 // Apply this processing to all the arguments at once instead of
6382 // dying at the first failure.
6383 bool hasInvalid = false;
6384 for (size_t i = 0, e = args.size(); i != e; i++) {
6385 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6386 ExprResult result = CheckPlaceholderExpr(args[i]);
6387 if (result.isInvalid()) hasInvalid = true;
6388 else args[i] = result.get();
6389 }
6390 }
6391 return hasInvalid;
6392}
6393
6394/// If a builtin function has a pointer argument with no explicit address
6395/// space, then it should be able to accept a pointer to any address
6396/// space as input. In order to do this, we need to replace the
6397/// standard builtin declaration with one that uses the same address space
6398/// as the call.
6399///
6400/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6401/// it does not contain any pointer arguments without
6402/// an address space qualifer. Otherwise the rewritten
6403/// FunctionDecl is returned.
6404/// TODO: Handle pointer return types.
6406 FunctionDecl *FDecl,
6407 MultiExprArg ArgExprs) {
6408
6409 QualType DeclType = FDecl->getType();
6410 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6411
6412 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6413 ArgExprs.size() < FT->getNumParams())
6414 return nullptr;
6415
6416 bool NeedsNewDecl = false;
6417 unsigned i = 0;
6418 SmallVector<QualType, 8> OverloadParams;
6419
6420 for (QualType ParamType : FT->param_types()) {
6421
6422 // Convert array arguments to pointer to simplify type lookup.
6423 ExprResult ArgRes =
6425 if (ArgRes.isInvalid())
6426 return nullptr;
6427 Expr *Arg = ArgRes.get();
6428 QualType ArgType = Arg->getType();
6429 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6430 !ArgType->isPointerType() ||
6431 !ArgType->getPointeeType().hasAddressSpace() ||
6433 OverloadParams.push_back(ParamType);
6434 continue;
6435 }
6436
6437 QualType PointeeType = ParamType->getPointeeType();
6438 if (PointeeType.hasAddressSpace())
6439 continue;
6440
6441 NeedsNewDecl = true;
6442 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6443
6444 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6445 OverloadParams.push_back(Context.getPointerType(PointeeType));
6446 }
6447
6448 if (!NeedsNewDecl)
6449 return nullptr;
6450
6452 EPI.Variadic = FT->isVariadic();
6453 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6454 OverloadParams, EPI);
6455 DeclContext *Parent = FDecl->getParent();
6456 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6457 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6458 FDecl->getIdentifier(), OverloadTy,
6459 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6460 false,
6461 /*hasPrototype=*/true);
6463 FT = cast<FunctionProtoType>(OverloadTy);
6464 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6465 QualType ParamType = FT->getParamType(i);
6466 ParmVarDecl *Parm =
6467 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6468 SourceLocation(), nullptr, ParamType,
6469 /*TInfo=*/nullptr, SC_None, nullptr);
6470 Parm->setScopeInfo(0, i);
6471 Params.push_back(Parm);
6472 }
6473 OverloadDecl->setParams(Params);
6474 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6475 return OverloadDecl;
6476}
6477
6478static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6479 FunctionDecl *Callee,
6480 MultiExprArg ArgExprs) {
6481 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6482 // similar attributes) really don't like it when functions are called with an
6483 // invalid number of args.
6484 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6485 /*PartialOverloading=*/false) &&
6486 !Callee->isVariadic())
6487 return;
6488 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6489 return;
6490
6491 if (const EnableIfAttr *Attr =
6492 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6493 S.Diag(Fn->getBeginLoc(),
6494 isa<CXXMethodDecl>(Callee)
6495 ? diag::err_ovl_no_viable_member_function_in_call
6496 : diag::err_ovl_no_viable_function_in_call)
6497 << Callee << Callee->getSourceRange();
6498 S.Diag(Callee->getLocation(),
6499 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6500 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6501 return;
6502 }
6503}
6504
6506 const UnresolvedMemberExpr *const UME, Sema &S) {
6507
6508 const auto GetFunctionLevelDCIfCXXClass =
6509 [](Sema &S) -> const CXXRecordDecl * {
6510 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6511 if (!DC || !DC->getParent())
6512 return nullptr;
6513
6514 // If the call to some member function was made from within a member
6515 // function body 'M' return return 'M's parent.
6516 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6517 return MD->getParent()->getCanonicalDecl();
6518 // else the call was made from within a default member initializer of a
6519 // class, so return the class.
6520 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6521 return RD->getCanonicalDecl();
6522 return nullptr;
6523 };
6524 // If our DeclContext is neither a member function nor a class (in the
6525 // case of a lambda in a default member initializer), we can't have an
6526 // enclosing 'this'.
6527
6528 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6529 if (!CurParentClass)
6530 return false;
6531
6532 // The naming class for implicit member functions call is the class in which
6533 // name lookup starts.
6534 const CXXRecordDecl *const NamingClass =
6536 assert(NamingClass && "Must have naming class even for implicit access");
6537
6538 // If the unresolved member functions were found in a 'naming class' that is
6539 // related (either the same or derived from) to the class that contains the
6540 // member function that itself contained the implicit member access.
6541
6542 return CurParentClass == NamingClass ||
6543 CurParentClass->isDerivedFrom(NamingClass);
6544}
6545
6546static void
6548 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6549
6550 if (!UME)
6551 return;
6552
6553 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6554 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6555 // already been captured, or if this is an implicit member function call (if
6556 // it isn't, an attempt to capture 'this' should already have been made).
6557 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6558 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6559 return;
6560
6561 // Check if the naming class in which the unresolved members were found is
6562 // related (same as or is a base of) to the enclosing class.
6563
6565 return;
6566
6567
6568 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6569 // If the enclosing function is not dependent, then this lambda is
6570 // capture ready, so if we can capture this, do so.
6571 if (!EnclosingFunctionCtx->isDependentContext()) {
6572 // If the current lambda and all enclosing lambdas can capture 'this' -
6573 // then go ahead and capture 'this' (since our unresolved overload set
6574 // contains at least one non-static member function).
6575 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6576 S.CheckCXXThisCapture(CallLoc);
6577 } else if (S.CurContext->isDependentContext()) {
6578 // ... since this is an implicit member reference, that might potentially
6579 // involve a 'this' capture, mark 'this' for potential capture in
6580 // enclosing lambdas.
6581 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6582 CurLSI->addPotentialThisCapture(CallLoc);
6583 }
6584}
6585
6586// Once a call is fully resolved, warn for unqualified calls to specific
6587// C++ standard functions, like move and forward.
6589 const CallExpr *Call) {
6590 // We are only checking unary move and forward so exit early here.
6591 if (Call->getNumArgs() != 1)
6592 return;
6593
6594 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6595 if (!E || isa<UnresolvedLookupExpr>(E))
6596 return;
6597 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6598 if (!DRE || !DRE->getLocation().isValid())
6599 return;
6600
6601 if (DRE->getQualifier())
6602 return;
6603
6604 const FunctionDecl *FD = Call->getDirectCallee();
6605 if (!FD)
6606 return;
6607
6608 // Only warn for some functions deemed more frequent or problematic.
6609 unsigned BuiltinID = FD->getBuiltinID();
6610 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6611 return;
6612
6613 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6615 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6616}
6617
6619 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6620 Expr *ExecConfig) {
6622 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6623 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6624 if (Call.isInvalid())
6625 return Call;
6626
6627 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6628 // language modes.
6629 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6630 ULE && ULE->hasExplicitTemplateArgs() &&
6631 ULE->decls_begin() == ULE->decls_end()) {
6633 ? diag::warn_cxx17_compat_adl_only_template_id
6634 : diag::ext_adl_only_template_id)
6635 << ULE->getName();
6636 }
6637
6638 if (LangOpts.OpenMP)
6639 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6640 ExecConfig);
6641 if (LangOpts.CPlusPlus) {
6642 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6644 }
6645 return Call;
6646}
6647
6648/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6649/// This provides the location of the left/right parens and a list of comma
6650/// locations.
6652 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6653 Expr *ExecConfig, bool IsExecConfig,
6654 bool AllowRecovery) {
6655 // Since this might be a postfix expression, get rid of ParenListExprs.
6657 if (Result.isInvalid()) return ExprError();
6658 Fn = Result.get();
6659
6660 if (CheckArgsForPlaceholders(ArgExprs))
6661 return ExprError();
6662
6663 if (getLangOpts().CPlusPlus) {
6664 // If this is a pseudo-destructor expression, build the call immediately.
6665 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6666 if (!ArgExprs.empty()) {
6667 // Pseudo-destructor calls should not have any arguments.
6668 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6670 SourceRange(ArgExprs.front()->getBeginLoc(),
6671 ArgExprs.back()->getEndLoc()));
6672 }
6673
6674 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6675 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6676 }
6677 if (Fn->getType() == Context.PseudoObjectTy) {
6678 ExprResult result = CheckPlaceholderExpr(Fn);
6679 if (result.isInvalid()) return ExprError();
6680 Fn = result.get();
6681 }
6682
6683 // Determine whether this is a dependent call inside a C++ template,
6684 // in which case we won't do any semantic analysis now.
6685 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6686 if (ExecConfig) {
6688 cast<CallExpr>(ExecConfig), ArgExprs,
6690 RParenLoc, CurFPFeatureOverrides());
6691 } else {
6692
6694 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6695 Fn->getBeginLoc());
6696
6697 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6698 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6699 }
6700 }
6701
6702 // Determine whether this is a call to an object (C++ [over.call.object]).
6703 if (Fn->getType()->isRecordType())
6704 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6705 RParenLoc);
6706
6707 if (Fn->getType() == Context.UnknownAnyTy) {
6708 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6709 if (result.isInvalid()) return ExprError();
6710 Fn = result.get();
6711 }
6712
6713 if (Fn->getType() == Context.BoundMemberTy) {
6714 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6715 RParenLoc, ExecConfig, IsExecConfig,
6716 AllowRecovery);
6717 }
6718 }
6719
6720 // Check for overloaded calls. This can happen even in C due to extensions.
6721 if (Fn->getType() == Context.OverloadTy) {
6723
6724 // We aren't supposed to apply this logic if there's an '&' involved.
6725 if (!find.HasFormOfMemberPointer) {
6727 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6728 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6729 OverloadExpr *ovl = find.Expression;
6730 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6732 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6733 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6734 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6735 RParenLoc, ExecConfig, IsExecConfig,
6736 AllowRecovery);
6737 }
6738 }
6739
6740 // If we're directly calling a function, get the appropriate declaration.
6741 if (Fn->getType() == Context.UnknownAnyTy) {
6742 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6743 if (result.isInvalid()) return ExprError();
6744 Fn = result.get();
6745 }
6746
6747 Expr *NakedFn = Fn->IgnoreParens();
6748
6749 bool CallingNDeclIndirectly = false;
6750 NamedDecl *NDecl = nullptr;
6751 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6752 if (UnOp->getOpcode() == UO_AddrOf) {
6753 CallingNDeclIndirectly = true;
6754 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6755 }
6756 }
6757
6758 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6759 NDecl = DRE->getDecl();
6760
6761 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6762 if (FDecl && FDecl->getBuiltinID()) {
6763 // Rewrite the function decl for this builtin by replacing parameters
6764 // with no explicit address space with the address space of the arguments
6765 // in ArgExprs.
6766 if ((FDecl =
6767 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6768 NDecl = FDecl;
6770 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6771 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6772 nullptr, DRE->isNonOdrUse());
6773 }
6774 }
6775 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6776 NDecl = ME->getMemberDecl();
6777
6778 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6779 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6780 FD, /*Complain=*/true, Fn->getBeginLoc()))
6781 return ExprError();
6782
6783 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6784
6785 // If this expression is a call to a builtin function in HIP device
6786 // compilation, allow a pointer-type argument to default address space to be
6787 // passed as a pointer-type parameter to a non-default address space.
6788 // If Arg is declared in the default address space and Param is declared
6789 // in a non-default address space, perform an implicit address space cast to
6790 // the parameter type.
6791 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6792 FD->getBuiltinID()) {
6793 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6794 ParmVarDecl *Param = FD->getParamDecl(Idx);
6795 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6796 !ArgExprs[Idx]->getType()->isPointerType())
6797 continue;
6798
6799 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6800 auto ArgTy = ArgExprs[Idx]->getType();
6801 auto ArgPtTy = ArgTy->getPointeeType();
6802 auto ArgAS = ArgPtTy.getAddressSpace();
6803
6804 // Add address space cast if target address spaces are different
6805 bool NeedImplicitASC =
6806 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6807 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6808 // or from specific AS which has target AS matching that of Param.
6810 if (!NeedImplicitASC)
6811 continue;
6812
6813 // First, ensure that the Arg is an RValue.
6814 if (ArgExprs[Idx]->isGLValue()) {
6815 ArgExprs[Idx] = ImplicitCastExpr::Create(
6816 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6817 nullptr, VK_PRValue, FPOptionsOverride());
6818 }
6819
6820 // Construct a new arg type with address space of Param
6821 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6822 ArgPtQuals.setAddressSpace(ParamAS);
6823 auto NewArgPtTy =
6824 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6825 auto NewArgTy =
6827 ArgTy.getQualifiers());
6828
6829 // Finally perform an implicit address space cast
6830 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6831 CK_AddressSpaceConversion)
6832 .get();
6833 }
6834 }
6835 }
6836
6839 assert(!getLangOpts().CPlusPlus);
6840 assert((Fn->containsErrors() ||
6841 llvm::any_of(ArgExprs,
6842 [](clang::Expr *E) { return E->containsErrors(); })) &&
6843 "should only occur in error-recovery path.");
6844 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6845 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6846 }
6847 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6848 ExecConfig, IsExecConfig);
6849}
6850
6851/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6852// with the specified CallArgs
6854 MultiExprArg CallArgs) {
6855 StringRef Name = Context.BuiltinInfo.getName(Id);
6856 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6858 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6859
6860 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6861 assert(BuiltInDecl && "failed to find builtin declaration");
6862
6863 ExprResult DeclRef =
6864 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6865 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6866
6868 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6869
6870 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6871 return Call.get();
6872}
6873
6874/// Parse a __builtin_astype expression.
6875///
6876/// __builtin_astype( value, dst type )
6877///
6879 SourceLocation BuiltinLoc,
6880 SourceLocation RParenLoc) {
6881 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6882 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6883}
6884
6885/// Create a new AsTypeExpr node (bitcast) from the arguments.
6887 SourceLocation BuiltinLoc,
6888 SourceLocation RParenLoc) {
6891 QualType SrcTy = E->getType();
6892 if (!SrcTy->isDependentType() &&
6893 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6894 return ExprError(
6895 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6896 << DestTy << SrcTy << E->getSourceRange());
6897 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6898}
6899
6900/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6901/// provided arguments.
6902///
6903/// __builtin_convertvector( value, dst type )
6904///
6906 SourceLocation BuiltinLoc,
6907 SourceLocation RParenLoc) {
6908 TypeSourceInfo *TInfo;
6909 GetTypeFromParser(ParsedDestTy, &TInfo);
6910 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6911}
6912
6913/// BuildResolvedCallExpr - Build a call to a resolved expression,
6914/// i.e. an expression not of \p OverloadTy. The expression should
6915/// unary-convert to an expression of function-pointer or
6916/// block-pointer type.
6917///
6918/// \param NDecl the declaration being called, if available
6920 SourceLocation LParenLoc,
6921 ArrayRef<Expr *> Args,
6922 SourceLocation RParenLoc, Expr *Config,
6923 bool IsExecConfig, ADLCallKind UsesADL) {
6924 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6925 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6926
6927 // Functions with 'interrupt' attribute cannot be called directly.
6928 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6929 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6930 return ExprError();
6931 }
6932
6933 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6934 // so there's some risk when calling out to non-interrupt handler functions
6935 // that the callee might not preserve them. This is easy to diagnose here,
6936 // but can be very challenging to debug.
6937 // Likewise, X86 interrupt handlers may only call routines with attribute
6938 // no_caller_saved_registers since there is no efficient way to
6939 // save and restore the non-GPR state.
6940 if (auto *Caller = getCurFunctionDecl()) {
6941 if (Caller->hasAttr<ARMInterruptAttr>()) {
6942 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6943 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6944 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6945 if (FDecl)
6946 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6947 }
6948 }
6949 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6950 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6951 const TargetInfo &TI = Context.getTargetInfo();
6952 bool HasNonGPRRegisters =
6953 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6954 if (HasNonGPRRegisters &&
6955 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6956 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6957 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6958 if (FDecl)
6959 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6960 }
6961 }
6962 }
6963
6964 // Promote the function operand.
6965 // We special-case function promotion here because we only allow promoting
6966 // builtin functions to function pointers in the callee of a call.
6968 QualType ResultTy;
6969 if (BuiltinID &&
6970 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6971 // Extract the return type from the (builtin) function pointer type.
6972 // FIXME Several builtins still have setType in
6973 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6974 // Builtins.td to ensure they are correct before removing setType calls.
6975 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6976 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6977 ResultTy = FDecl->getCallResultType();
6978 } else {
6980 ResultTy = Context.BoolTy;
6981 }
6982 if (Result.isInvalid())
6983 return ExprError();
6984 Fn = Result.get();
6985
6986 // Check for a valid function type, but only if it is not a builtin which
6987 // requires custom type checking. These will be handled by
6988 // CheckBuiltinFunctionCall below just after creation of the call expression.
6989 const FunctionType *FuncT = nullptr;
6990 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6991 retry:
6992 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6993 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6994 // have type pointer to function".
6995 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6996 if (!FuncT)
6997 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6998 << Fn->getType() << Fn->getSourceRange());
6999 } else if (const BlockPointerType *BPT =
7000 Fn->getType()->getAs<BlockPointerType>()) {
7001 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7002 } else {
7003 // Handle calls to expressions of unknown-any type.
7004 if (Fn->getType() == Context.UnknownAnyTy) {
7005 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7006 if (rewrite.isInvalid())
7007 return ExprError();
7008 Fn = rewrite.get();
7009 goto retry;
7010 }
7011
7012 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7013 << Fn->getType() << Fn->getSourceRange());
7014 }
7015 }
7016
7017 // Get the number of parameters in the function prototype, if any.
7018 // We will allocate space for max(Args.size(), NumParams) arguments
7019 // in the call expression.
7020 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7021 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7022
7023 CallExpr *TheCall;
7024 if (Config) {
7025 assert(UsesADL == ADLCallKind::NotADL &&
7026 "CUDAKernelCallExpr should not use ADL");
7027 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7028 Args, ResultTy, VK_PRValue, RParenLoc,
7029 CurFPFeatureOverrides(), NumParams);
7030 } else {
7031 TheCall =
7032 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7033 CurFPFeatureOverrides(), NumParams, UsesADL);
7034 }
7035
7037 // Forget about the nulled arguments since typo correction
7038 // do not handle them well.
7039 TheCall->shrinkNumArgs(Args.size());
7040 // C cannot always handle TypoExpr nodes in builtin calls and direct
7041 // function calls as their argument checking don't necessarily handle
7042 // dependent types properly, so make sure any TypoExprs have been
7043 // dealt with.
7045 if (!Result.isUsable()) return ExprError();
7046 CallExpr *TheOldCall = TheCall;
7047 TheCall = dyn_cast<CallExpr>(Result.get());
7048 bool CorrectedTypos = TheCall != TheOldCall;
7049 if (!TheCall) return Result;
7050 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7051
7052 // A new call expression node was created if some typos were corrected.
7053 // However it may not have been constructed with enough storage. In this
7054 // case, rebuild the node with enough storage. The waste of space is
7055 // immaterial since this only happens when some typos were corrected.
7056 if (CorrectedTypos && Args.size() < NumParams) {
7057 if (Config)
7059 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7060 RParenLoc, CurFPFeatureOverrides(), NumParams);
7061 else
7062 TheCall =
7063 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7064 CurFPFeatureOverrides(), NumParams, UsesADL);
7065 }
7066 // We can now handle the nulled arguments for the default arguments.
7067 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7068 }
7069
7070 // Bail out early if calling a builtin with custom type checking.
7071 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7072 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7073
7074 if (getLangOpts().CUDA) {
7075 if (Config) {
7076 // CUDA: Kernel calls must be to global functions
7077 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7078 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7079 << FDecl << Fn->getSourceRange());
7080
7081 // CUDA: Kernel function must have 'void' return type
7082 if (!FuncT->getReturnType()->isVoidType() &&
7083 !FuncT->getReturnType()->getAs<AutoType>() &&
7085 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7086 << Fn->getType() << Fn->getSourceRange());
7087 } else {
7088 // CUDA: Calls to global functions must be configured
7089 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7090 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7091 << FDecl << Fn->getSourceRange());
7092 }
7093 }
7094
7095 // Check for a valid return type
7096 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7097 FDecl))
7098 return ExprError();
7099
7100 // We know the result type of the call, set it.
7101 TheCall->setType(FuncT->getCallResultType(Context));
7103
7104 // WebAssembly tables can't be used as arguments.
7105 if (Context.getTargetInfo().getTriple().isWasm()) {
7106 for (const Expr *Arg : Args) {
7107 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7108 return ExprError(Diag(Arg->getExprLoc(),
7109 diag::err_wasm_table_as_function_parameter));
7110 }
7111 }
7112 }
7113
7114 if (Proto) {
7115 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7116 IsExecConfig))
7117 return ExprError();
7118 } else {
7119 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7120
7121 if (FDecl) {
7122 // Check if we have too few/too many template arguments, based
7123 // on our knowledge of the function definition.
7124 const FunctionDecl *Def = nullptr;
7125 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7126 Proto = Def->getType()->getAs<FunctionProtoType>();
7127 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7128 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7129 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7130 }
7131
7132 // If the function we're calling isn't a function prototype, but we have
7133 // a function prototype from a prior declaratiom, use that prototype.
7134 if (!FDecl->hasPrototype())
7135 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7136 }
7137
7138 // If we still haven't found a prototype to use but there are arguments to
7139 // the call, diagnose this as calling a function without a prototype.
7140 // However, if we found a function declaration, check to see if
7141 // -Wdeprecated-non-prototype was disabled where the function was declared.
7142 // If so, we will silence the diagnostic here on the assumption that this
7143 // interface is intentional and the user knows what they're doing. We will
7144 // also silence the diagnostic if there is a function declaration but it
7145 // was implicitly defined (the user already gets diagnostics about the
7146 // creation of the implicit function declaration, so the additional warning
7147 // is not helpful).
7148 if (!Proto && !Args.empty() &&
7149 (!FDecl || (!FDecl->isImplicit() &&
7150 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7151 FDecl->getLocation()))))
7152 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7153 << (FDecl != nullptr) << FDecl;
7154
7155 // Promote the arguments (C99 6.5.2.2p6).
7156 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7157 Expr *Arg = Args[i];
7158
7159 if (Proto && i < Proto->getNumParams()) {
7161 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7162 ExprResult ArgE =
7164 if (ArgE.isInvalid())
7165 return true;
7166
7167 Arg = ArgE.getAs<Expr>();
7168
7169 } else {
7171
7172 if (ArgE.isInvalid())
7173 return true;
7174
7175 Arg = ArgE.getAs<Expr>();
7176 }
7177
7178 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7179 diag::err_call_incomplete_argument, Arg))
7180 return ExprError();
7181
7182 TheCall->setArg(i, Arg);
7183 }
7184 TheCall->computeDependence();
7185 }
7186
7187 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7188 if (!isa<RequiresExprBodyDecl>(CurContext) &&
7189 Method->isImplicitObjectMemberFunction())
7190 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7191 << Fn->getSourceRange() << 0);
7192
7193 // Check for sentinels
7194 if (NDecl)
7195 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7196
7197 // Warn for unions passing across security boundary (CMSE).
7198 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7199 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7200 if (const auto *RT =
7201 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7202 if (RT->getDecl()->isOrContainsUnion())
7203 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7204 << 0 << i;
7205 }
7206 }
7207 }
7208
7209 // Do special checking on direct calls to functions.
7210 if (FDecl) {
7211 if (CheckFunctionCall(FDecl, TheCall, Proto))
7212 return ExprError();
7213
7214 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7215
7216 if (BuiltinID)
7217 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7218 } else if (NDecl) {
7219 if (CheckPointerCall(NDecl, TheCall, Proto))
7220 return ExprError();
7221 } else {
7222 if (CheckOtherCall(TheCall, Proto))
7223 return ExprError();
7224 }
7225
7226 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7227}
7228
7231 SourceLocation RParenLoc, Expr *InitExpr) {
7232 assert(Ty && "ActOnCompoundLiteral(): missing type");
7233 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7234
7235 TypeSourceInfo *TInfo;
7236 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7237 if (!TInfo)
7238 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7239
7240 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7241}
7242
7245 SourceLocation RParenLoc, Expr *LiteralExpr) {
7246 QualType literalType = TInfo->getType();
7247
7248 if (literalType->isArrayType()) {
7250 LParenLoc, Context.getBaseElementType(literalType),
7251 diag::err_array_incomplete_or_sizeless_type,
7252 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7253 return ExprError();
7254 if (literalType->isVariableArrayType()) {
7255 // C23 6.7.10p4: An entity of variable length array type shall not be
7256 // initialized except by an empty initializer.
7257 //
7258 // The C extension warnings are issued from ParseBraceInitializer() and
7259 // do not need to be issued here. However, we continue to issue an error
7260 // in the case there are initializers or we are compiling C++. We allow
7261 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7262 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7263 // FIXME: should we allow this construct in C++ when it makes sense to do
7264 // so?
7265 std::optional<unsigned> NumInits;
7266 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7267 NumInits = ILE->getNumInits();
7268 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7269 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7270 diag::err_variable_object_no_init))
7271 return ExprError();
7272 }
7273 } else if (!literalType->isDependentType() &&
7274 RequireCompleteType(LParenLoc, literalType,
7275 diag::err_typecheck_decl_incomplete_type,
7276 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7277 return ExprError();
7278
7279 InitializedEntity Entity
7283 SourceRange(LParenLoc, RParenLoc),
7284 /*InitList=*/true);
7285 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7286 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7287 &literalType);
7288 if (Result.isInvalid())
7289 return ExprError();
7290 LiteralExpr = Result.get();
7291
7292 bool isFileScope = !CurContext->isFunctionOrMethod();
7293
7294 // In C, compound literals are l-values for some reason.
7295 // For GCC compatibility, in C++, file-scope array compound literals with
7296 // constant initializers are also l-values, and compound literals are
7297 // otherwise prvalues.
7298 //
7299 // (GCC also treats C++ list-initialized file-scope array prvalues with
7300 // constant initializers as l-values, but that's non-conforming, so we don't
7301 // follow it there.)
7302 //
7303 // FIXME: It would be better to handle the lvalue cases as materializing and
7304 // lifetime-extending a temporary object, but our materialized temporaries
7305 // representation only supports lifetime extension from a variable, not "out
7306 // of thin air".
7307 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7308 // is bound to the result of applying array-to-pointer decay to the compound
7309 // literal.
7310 // FIXME: GCC supports compound literals of reference type, which should
7311 // obviously have a value kind derived from the kind of reference involved.
7312 ExprValueKind VK =
7313 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7314 ? VK_PRValue
7315 : VK_LValue;
7316
7317 if (isFileScope)
7318 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7319 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7320 Expr *Init = ILE->getInit(i);
7321 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7322 }
7323
7324 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7325 VK, LiteralExpr, isFileScope);
7326 if (isFileScope) {
7327 if (!LiteralExpr->isTypeDependent() &&
7328 !LiteralExpr->isValueDependent() &&
7329 !literalType->isDependentType()) // C99 6.5.2.5p3
7330 if (CheckForConstantInitializer(LiteralExpr))
7331 return ExprError();
7332 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7333 literalType.getAddressSpace() != LangAS::Default) {
7334 // Embedded-C extensions to C99 6.5.2.5:
7335 // "If the compound literal occurs inside the body of a function, the
7336 // type name shall not be qualified by an address-space qualifier."
7337 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7338 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7339 return ExprError();
7340 }
7341
7342 if (!isFileScope && !getLangOpts().CPlusPlus) {
7343 // Compound literals that have automatic storage duration are destroyed at
7344 // the end of the scope in C; in C++, they're just temporaries.
7345
7346 // Emit diagnostics if it is or contains a C union type that is non-trivial
7347 // to destruct.
7351
7352 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7353 if (literalType.isDestructedType()) {
7355 ExprCleanupObjects.push_back(E);
7357 }
7358 }
7359
7362 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7363 E->getInitializer()->getExprLoc());
7364
7365 return MaybeBindToTemporary(E);
7366}
7367
7370 SourceLocation RBraceLoc) {
7371 // Only produce each kind of designated initialization diagnostic once.
7372 SourceLocation FirstDesignator;
7373 bool DiagnosedArrayDesignator = false;
7374 bool DiagnosedNestedDesignator = false;
7375 bool DiagnosedMixedDesignator = false;
7376
7377 // Check that any designated initializers are syntactically valid in the
7378 // current language mode.
7379 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7380 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7381 if (FirstDesignator.isInvalid())
7382 FirstDesignator = DIE->getBeginLoc();
7383
7384 if (!getLangOpts().CPlusPlus)
7385 break;
7386
7387 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7388 DiagnosedNestedDesignator = true;
7389 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7390 << DIE->getDesignatorsSourceRange();
7391 }
7392
7393 for (auto &Desig : DIE->designators()) {
7394 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7395 DiagnosedArrayDesignator = true;
7396 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7397 << Desig.getSourceRange();
7398 }
7399 }
7400
7401 if (!DiagnosedMixedDesignator &&
7402 !isa<DesignatedInitExpr>(InitArgList[0])) {
7403 DiagnosedMixedDesignator = true;
7404 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7405 << DIE->getSourceRange();
7406 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7407 << InitArgList[0]->getSourceRange();
7408 }
7409 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7410 isa<DesignatedInitExpr>(InitArgList[0])) {
7411 DiagnosedMixedDesignator = true;
7412 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7413 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7414 << DIE->getSourceRange();
7415 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7416 << InitArgList[I]->getSourceRange();
7417 }
7418 }
7419
7420 if (FirstDesignator.isValid()) {
7421 // Only diagnose designated initiaization as a C++20 extension if we didn't
7422 // already diagnose use of (non-C++20) C99 designator syntax.
7423 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7424 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7425 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7426 ? diag::warn_cxx17_compat_designated_init
7427 : diag::ext_cxx_designated_init);
7428 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7429 Diag(FirstDesignator, diag::ext_designated_init);
7430 }
7431 }
7432
7433 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7434}
7435
7438 SourceLocation RBraceLoc) {
7439 // Semantic analysis for initializers is done by ActOnDeclarator() and
7440 // CheckInitializer() - it requires knowledge of the object being initialized.
7441
7442 // Immediately handle non-overload placeholders. Overloads can be
7443 // resolved contextually, but everything else here can't.
7444 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7445 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7446 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7447
7448 // Ignore failures; dropping the entire initializer list because
7449 // of one failure would be terrible for indexing/etc.
7450 if (result.isInvalid()) continue;
7451
7452 InitArgList[I] = result.get();
7453 }
7454 }
7455
7456 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7457 RBraceLoc);
7458 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7459 return E;
7460}
7461
7462/// Do an explicit extend of the given block pointer if we're in ARC.
7464 assert(E.get()->getType()->isBlockPointerType());
7465 assert(E.get()->isPRValue());
7466
7467 // Only do this in an r-value context.
7468 if (!getLangOpts().ObjCAutoRefCount) return;
7469
7471 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7472 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7474}
7475
7476/// Prepare a conversion of the given expression to an ObjC object
7477/// pointer type.
7479 QualType type = E.get()->getType();
7480 if (type->isObjCObjectPointerType()) {
7481 return CK_BitCast;
7482 } else if (type->isBlockPointerType()) {
7484 return CK_BlockPointerToObjCPointerCast;
7485 } else {
7486 assert(type->isPointerType());
7487 return CK_CPointerToObjCPointerCast;
7488 }
7489}
7490
7491/// Prepares for a scalar cast, performing all the necessary stages
7492/// except the final cast and returning the kind required.
7494 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7495 // Also, callers should have filtered out the invalid cases with
7496 // pointers. Everything else should be possible.
7497
7498 QualType SrcTy = Src.get()->getType();
7499 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7500 return CK_NoOp;
7501
7502 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7504 llvm_unreachable("member pointer type in C");
7505
7506 case Type::STK_CPointer:
7509 switch (DestTy->getScalarTypeKind()) {
7510 case Type::STK_CPointer: {
7511 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7512 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7513 if (SrcAS != DestAS)
7514 return CK_AddressSpaceConversion;
7515 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7516 return CK_NoOp;
7517 return CK_BitCast;
7518 }
7520 return (SrcKind == Type::STK_BlockPointer
7521 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7523 if (SrcKind == Type::STK_ObjCObjectPointer)
7524 return CK_BitCast;
7525 if (SrcKind == Type::STK_CPointer)
7526 return CK_CPointerToObjCPointerCast;
7528 return CK_BlockPointerToObjCPointerCast;
7529 case Type::STK_Bool:
7530 return CK_PointerToBoolean;
7531 case Type::STK_Integral:
7532 return CK_PointerToIntegral;
7533 case Type::STK_Floating:
7538 llvm_unreachable("illegal cast from pointer");
7539 }
7540 llvm_unreachable("Should have returned before this");
7541
7543 switch (DestTy->getScalarTypeKind()) {
7545 return CK_FixedPointCast;
7546 case Type::STK_Bool:
7547 return CK_FixedPointToBoolean;
7548 case Type::STK_Integral:
7549 return CK_FixedPointToIntegral;
7550 case Type::STK_Floating:
7551 return CK_FixedPointToFloating;
7554 Diag(Src.get()->getExprLoc(),
7555 diag::err_unimplemented_conversion_with_fixed_point_type)
7556 << DestTy;
7557 return CK_IntegralCast;
7558 case Type::STK_CPointer:
7562 llvm_unreachable("illegal cast to pointer type");
7563 }
7564 llvm_unreachable("Should have returned before this");
7565
7566 case Type::STK_Bool: // casting from bool is like casting from an integer
7567 case Type::STK_Integral:
7568 switch (DestTy->getScalarTypeKind()) {
7569 case Type::STK_CPointer:
7574 return CK_NullToPointer;
7575 return CK_IntegralToPointer;
7576 case Type::STK_Bool:
7577 return CK_IntegralToBoolean;
7578 case Type::STK_Integral:
7579 return CK_IntegralCast;
7580 case Type::STK_Floating:
7581 return CK_IntegralToFloating;
7583 Src = ImpCastExprToType(Src.get(),
7584 DestTy->castAs<ComplexType>()->getElementType(),
7585 CK_IntegralCast);
7586 return CK_IntegralRealToComplex;
7588 Src = ImpCastExprToType(Src.get(),
7589 DestTy->castAs<ComplexType>()->getElementType(),
7590 CK_IntegralToFloating);
7591 return CK_FloatingRealToComplex;
7593 llvm_unreachable("member pointer type in C");
7595 return CK_IntegralToFixedPoint;
7596 }
7597 llvm_unreachable("Should have returned before this");
7598
7599 case Type::STK_Floating:
7600 switch (DestTy->getScalarTypeKind()) {
7601 case Type::STK_Floating:
7602 return CK_FloatingCast;
7603 case Type::STK_Bool:
7604 return CK_FloatingToBoolean;
7605 case Type::STK_Integral:
7606 return CK_FloatingToIntegral;
7608 Src = ImpCastExprToType(Src.get(),
7609 DestTy->castAs<ComplexType>()->getElementType(),
7610 CK_FloatingCast);
7611 return CK_FloatingRealToComplex;
7613 Src = ImpCastExprToType(Src.get(),
7614 DestTy->castAs<ComplexType>()->getElementType(),
7615 CK_FloatingToIntegral);
7616 return CK_IntegralRealToComplex;
7617 case Type::STK_CPointer:
7620 llvm_unreachable("valid float->pointer cast?");
7622 llvm_unreachable("member pointer type in C");
7624 return CK_FloatingToFixedPoint;
7625 }
7626 llvm_unreachable("Should have returned before this");
7627
7629 switch (DestTy->getScalarTypeKind()) {
7631 return CK_FloatingComplexCast;
7633 return CK_FloatingComplexToIntegralComplex;
7634 case Type::STK_Floating: {
7635 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7636 if (Context.hasSameType(ET, DestTy))
7637 return CK_FloatingComplexToReal;
7638 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7639 return CK_FloatingCast;
7640 }
7641 case Type::STK_Bool:
7642 return CK_FloatingComplexToBoolean;
7643 case Type::STK_Integral:
7644 Src = ImpCastExprToType(Src.get(),
7645 SrcTy->castAs<ComplexType>()->getElementType(),
7646 CK_FloatingComplexToReal);
7647 return CK_FloatingToIntegral;
7648 case Type::STK_CPointer:
7651 llvm_unreachable("valid complex float->pointer cast?");
7653 llvm_unreachable("member pointer type in C");
7655 Diag(Src.get()->getExprLoc(),
7656 diag::err_unimplemented_conversion_with_fixed_point_type)
7657 << SrcTy;
7658 return CK_IntegralCast;
7659 }
7660 llvm_unreachable("Should have returned before this");
7661
7663 switch (DestTy->getScalarTypeKind()) {
7665 return CK_IntegralComplexToFloatingComplex;
7667 return CK_IntegralComplexCast;
7668 case Type::STK_Integral: {
7669 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7670 if (Context.hasSameType(ET, DestTy))
7671 return CK_IntegralComplexToReal;
7672 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7673 return CK_IntegralCast;
7674 }
7675 case Type::STK_Bool:
7676 return CK_IntegralComplexToBoolean;
7677 case Type::STK_Floating:
7678 Src = ImpCastExprToType(Src.get(),
7679 SrcTy->castAs<ComplexType>()->getElementType(),
7680 CK_IntegralComplexToReal);
7681 return CK_IntegralToFloating;
7682 case Type::STK_CPointer:
7685 llvm_unreachable("valid complex int->pointer cast?");
7687 llvm_unreachable("member pointer type in C");
7689 Diag(Src.get()->getExprLoc(),
7690 diag::err_unimplemented_conversion_with_fixed_point_type)
7691 << SrcTy;
7692 return CK_IntegralCast;
7693 }
7694 llvm_unreachable("Should have returned before this");
7695 }
7696
7697 llvm_unreachable("Unhandled scalar cast");
7698}
7699
7700static bool breakDownVectorType(QualType type, uint64_t &len,
7701 QualType &eltType) {
7702 // Vectors are simple.
7703 if (const VectorType *vecType = type->getAs<VectorType>()) {
7704 len = vecType->getNumElements();
7705 eltType = vecType->getElementType();
7706 assert(eltType->isScalarType());
7707 return true;
7708 }
7709
7710 // We allow lax conversion to and from non-vector types, but only if
7711 // they're real types (i.e. non-complex, non-pointer scalar types).
7712 if (!type->isRealType()) return false;
7713
7714 len = 1;
7715 eltType = type;
7716 return true;
7717}
7718
7719/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7720/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7721/// allowed?
7722///
7723/// This will also return false if the two given types do not make sense from
7724/// the perspective of SVE bitcasts.
7726 assert(srcTy->isVectorType() || destTy->isVectorType());
7727
7728 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7729 if (!FirstType->isSVESizelessBuiltinType())
7730 return false;
7731
7732 const auto *VecTy = SecondType->getAs<VectorType>();
7733 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7734 };
7735
7736 return ValidScalableConversion(srcTy, destTy) ||
7737 ValidScalableConversion(destTy, srcTy);
7738}
7739
7740/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
7741/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
7742/// VLS type) allowed?
7743///
7744/// This will also return false if the two given types do not make sense from
7745/// the perspective of RVV bitcasts.
7747 assert(srcTy->isVectorType() || destTy->isVectorType());
7748
7749 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7750 if (!FirstType->isRVVSizelessBuiltinType())
7751 return false;
7752
7753 const auto *VecTy = SecondType->getAs<VectorType>();
7754 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
7755 };
7756
7757 return ValidScalableConversion(srcTy, destTy) ||
7758 ValidScalableConversion(destTy, srcTy);
7759}
7760
7761/// Are the two types matrix types and do they have the same dimensions i.e.
7762/// do they have the same number of rows and the same number of columns?
7764 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7765 return false;
7766
7767 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7768 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7769
7770 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7771 matSrcType->getNumColumns() == matDestType->getNumColumns();
7772}
7773
7775 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7776
7777 uint64_t SrcLen, DestLen;
7778 QualType SrcEltTy, DestEltTy;
7779 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7780 return false;
7781 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7782 return false;
7783
7784 // ASTContext::getTypeSize will return the size rounded up to a
7785 // power of 2, so instead of using that, we need to use the raw
7786 // element size multiplied by the element count.
7787 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7788 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7789
7790 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7791}
7792
7793// This returns true if at least one of the types is an altivec vector.
7795 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7796 "expected at least one type to be a vector here");
7797
7798 bool IsSrcTyAltivec =
7799 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7801 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7803 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7805
7806 bool IsDestTyAltivec = DestTy->isVectorType() &&
7807 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7809 (DestTy->castAs<VectorType>()->getVectorKind() ==
7811 (DestTy->castAs<VectorType>()->getVectorKind() ==
7813
7814 return (IsSrcTyAltivec || IsDestTyAltivec);
7815}
7816
7817/// Are the two types lax-compatible vector types? That is, given
7818/// that one of them is a vector, do they have equal storage sizes,
7819/// where the storage size is the number of elements times the element
7820/// size?
7821///
7822/// This will also return false if either of the types is neither a
7823/// vector nor a real type.
7825 assert(destTy->isVectorType() || srcTy->isVectorType());
7826
7827 // Disallow lax conversions between scalars and ExtVectors (these
7828 // conversions are allowed for other vector types because common headers
7829 // depend on them). Most scalar OP ExtVector cases are handled by the
7830 // splat path anyway, which does what we want (convert, not bitcast).
7831 // What this rules out for ExtVectors is crazy things like char4*float.
7832 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7833 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7834
7835 return areVectorTypesSameSize(srcTy, destTy);
7836}
7837
7838/// Is this a legal conversion between two types, one of which is
7839/// known to be a vector type?
7841 assert(destTy->isVectorType() || srcTy->isVectorType());
7842
7843 switch (Context.getLangOpts().getLaxVectorConversions()) {
7845 return false;
7846
7848 if (!srcTy->isIntegralOrEnumerationType()) {
7849 auto *Vec = srcTy->getAs<VectorType>();
7850 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7851 return false;
7852 }
7853 if (!destTy->isIntegralOrEnumerationType()) {
7854 auto *Vec = destTy->getAs<VectorType>();
7855 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7856 return false;
7857 }
7858 // OK, integer (vector) -> integer (vector) bitcast.
7859 break;
7860
7862 break;
7863 }
7864
7865 return areLaxCompatibleVectorTypes(srcTy, destTy);
7866}
7867
7869 CastKind &Kind) {
7870 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7871 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7872 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7873 << DestTy << SrcTy << R;
7874 }
7875 } else if (SrcTy->isMatrixType()) {
7876 return Diag(R.getBegin(),
7877 diag::err_invalid_conversion_between_matrix_and_type)
7878 << SrcTy << DestTy << R;
7879 } else if (DestTy->isMatrixType()) {
7880 return Diag(R.getBegin(),
7881 diag::err_invalid_conversion_between_matrix_and_type)
7882 << DestTy << SrcTy << R;
7883 }
7884
7885 Kind = CK_MatrixCast;
7886 return false;
7887}
7888
7890 CastKind &Kind) {
7891 assert(VectorTy->isVectorType() && "Not a vector type!");
7892
7893 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7894 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7895 return Diag(R.getBegin(),
7896 Ty->isVectorType() ?
7897 diag::err_invalid_conversion_between_vectors :
7898 diag::err_invalid_conversion_between_vector_and_integer)
7899 << VectorTy << Ty << R;
7900 } else
7901 return Diag(R.getBegin(),
7902 diag::err_invalid_conversion_between_vector_and_scalar)
7903 << VectorTy << Ty << R;
7904
7905 Kind = CK_BitCast;
7906 return false;
7907}
7908
7910 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7911
7912 if (DestElemTy == SplattedExpr->getType())
7913 return SplattedExpr;
7914
7915 assert(DestElemTy->isFloatingType() ||
7916 DestElemTy->isIntegralOrEnumerationType());
7917
7918 CastKind CK;
7919 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7920 // OpenCL requires that we convert `true` boolean expressions to -1, but
7921 // only when splatting vectors.
7922 if (DestElemTy->isFloatingType()) {
7923 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7924 // in two steps: boolean to signed integral, then to floating.
7925 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7926 CK_BooleanToSignedIntegral);
7927 SplattedExpr = CastExprRes.get();
7928 CK = CK_IntegralToFloating;
7929 } else {
7930 CK = CK_BooleanToSignedIntegral;
7931 }
7932 } else {
7933 ExprResult CastExprRes = SplattedExpr;
7934 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7935 if (CastExprRes.isInvalid())
7936 return ExprError();
7937 SplattedExpr = CastExprRes.get();
7938 }
7939 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7940}
7941
7943 Expr *CastExpr, CastKind &Kind) {
7944 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7945
7946 QualType SrcTy = CastExpr->getType();
7947
7948 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7949 // an ExtVectorType.
7950 // In OpenCL, casts between vectors of different types are not allowed.
7951 // (See OpenCL 6.2).
7952 if (SrcTy->isVectorType()) {
7953 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7954 (getLangOpts().OpenCL &&
7955 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7956 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7957 << DestTy << SrcTy << R;
7958 return ExprError();
7959 }
7960 Kind = CK_BitCast;
7961 return CastExpr;
7962 }
7963
7964 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7965 // conversion will take place first from scalar to elt type, and then
7966 // splat from elt type to vector.
7967 if (SrcTy->isPointerType())
7968 return Diag(R.getBegin(),
7969 diag::err_invalid_conversion_between_vector_and_scalar)
7970 << DestTy << SrcTy << R;
7971
7972 Kind = CK_VectorSplat;
7973 return prepareVectorSplat(DestTy, CastExpr);
7974}
7975
7978 Declarator &D, ParsedType &Ty,
7979 SourceLocation RParenLoc, Expr *CastExpr) {
7980 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7981 "ActOnCastExpr(): missing type or expr");
7982
7984 if (D.isInvalidType())
7985 return ExprError();
7986
7987 if (getLangOpts().CPlusPlus) {
7988 // Check that there are no default arguments (C++ only).
7990 } else {
7991 // Make sure any TypoExprs have been dealt with.
7993 if (!Res.isUsable())
7994 return ExprError();
7995 CastExpr = Res.get();
7996 }
7997
7999
8000 QualType castType = castTInfo->getType();
8001 Ty = CreateParsedType(castType, castTInfo);
8002
8003 bool isVectorLiteral = false;
8004
8005 // Check for an altivec or OpenCL literal,
8006 // i.e. all the elements are integer constants.
8007 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8008 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8009 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8010 && castType->isVectorType() && (PE || PLE)) {
8011 if (PLE && PLE->getNumExprs() == 0) {
8012 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8013 return ExprError();
8014 }
8015 if (PE || PLE->getNumExprs() == 1) {
8016 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8017 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8018 isVectorLiteral = true;
8019 }
8020 else
8021 isVectorLiteral = true;
8022 }
8023
8024 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8025 // then handle it as such.
8026 if (isVectorLiteral)
8027 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8028
8029 // If the Expr being casted is a ParenListExpr, handle it specially.
8030 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8031 // sequence of BinOp comma operators.
8032 if (isa<ParenListExpr>(CastExpr)) {
8034 if (Result.isInvalid()) return ExprError();
8035 CastExpr = Result.get();
8036 }
8037
8038 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8039 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8040
8042
8044
8046
8047 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8048}
8049
8051 SourceLocation RParenLoc, Expr *E,
8052 TypeSourceInfo *TInfo) {
8053 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8054 "Expected paren or paren list expression");
8055
8056 Expr **exprs;
8057 unsigned numExprs;
8058 Expr *subExpr;
8059 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8060 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8061 LiteralLParenLoc = PE->getLParenLoc();
8062 LiteralRParenLoc = PE->getRParenLoc();
8063 exprs = PE->getExprs();
8064 numExprs = PE->getNumExprs();
8065 } else { // isa<ParenExpr> by assertion at function entrance
8066 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8067 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8068 subExpr = cast<ParenExpr>(E)->getSubExpr();
8069 exprs = &subExpr;
8070 numExprs = 1;
8071 }
8072
8073 QualType Ty = TInfo->getType();
8074 assert(Ty->isVectorType() && "Expected vector type");
8075
8076 SmallVector<Expr *, 8> initExprs;
8077 const VectorType *VTy = Ty->castAs<VectorType>();
8078 unsigned numElems = VTy->getNumElements();
8079
8080 // '(...)' form of vector initialization in AltiVec: the number of
8081 // initializers must be one or must match the size of the vector.
8082 // If a single value is specified in the initializer then it will be
8083 // replicated to all the components of the vector
8085 VTy->getElementType()))
8086 return ExprError();
8088 // The number of initializers must be one or must match the size of the
8089 // vector. If a single value is specified in the initializer then it will
8090 // be replicated to all the components of the vector
8091 if (numExprs == 1) {
8092 QualType ElemTy = VTy->getElementType();
8093 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8094 if (Literal.isInvalid())
8095 return ExprError();
8096 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8097 PrepareScalarCast(Literal, ElemTy));
8098 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8099 }
8100 else if (numExprs < numElems) {
8101 Diag(E->getExprLoc(),
8102 diag::err_incorrect_number_of_vector_initializers);
8103 return ExprError();
8104 }
8105 else
8106 initExprs.append(exprs, exprs + numExprs);
8107 }
8108 else {
8109 // For OpenCL, when the number of initializers is a single value,
8110 // it will be replicated to all components of the vector.
8112 numExprs == 1) {
8113 QualType ElemTy = VTy->getElementType();
8114 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8115 if (Literal.isInvalid())
8116 return ExprError();
8117 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8118 PrepareScalarCast(Literal, ElemTy));
8119 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8120 }
8121
8122 initExprs.append(exprs, exprs + numExprs);
8123 }
8124 // FIXME: This means that pretty-printing the final AST will produce curly
8125 // braces instead of the original commas.
8126 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8127 initExprs, LiteralRParenLoc);
8128 initE->setType(Ty);
8129 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8130}
8131
8132/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8133/// the ParenListExpr into a sequence of comma binary operators.
8136 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8137 if (!E)
8138 return OrigExpr;
8139
8140 ExprResult Result(E->getExpr(0));
8141
8142 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8143 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8144 E->getExpr(i));
8145
8146 if (Result.isInvalid()) return ExprError();
8147
8148 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8149}
8150
8153 MultiExprArg Val) {
8154 return ParenListExpr::Create(Context, L, Val, R);
8155}
8156
8157/// Emit a specialized diagnostic when one expression is a null pointer
8158/// constant and the other is not a pointer. Returns true if a diagnostic is
8159/// emitted.
8160bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8161 SourceLocation QuestionLoc) {
8162 const Expr *NullExpr = LHSExpr;
8163 const Expr *NonPointerExpr = RHSExpr;
8167
8168 if (NullKind == Expr::NPCK_NotNull) {
8169 NullExpr = RHSExpr;
8170 NonPointerExpr = LHSExpr;
8171 NullKind =
8174 }
8175
8176 if (NullKind == Expr::NPCK_NotNull)
8177 return false;
8178
8179 if (NullKind == Expr::NPCK_ZeroExpression)
8180 return false;
8181
8182 if (NullKind == Expr::NPCK_ZeroLiteral) {
8183 // In this case, check to make sure that we got here from a "NULL"
8184 // string in the source code.
8185 NullExpr = NullExpr->IgnoreParenImpCasts();
8186 SourceLocation loc = NullExpr->getExprLoc();
8187 if (!findMacroSpelling(loc, "NULL"))
8188 return false;
8189 }
8190
8191 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8192 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8193 << NonPointerExpr->getType() << DiagType
8194 << NonPointerExpr->getSourceRange();
8195 return true;
8196}
8197
8198/// Return false if the condition expression is valid, true otherwise.
8199static bool checkCondition(Sema &S, const Expr *Cond,
8200 SourceLocation QuestionLoc) {
8201 QualType CondTy = Cond->getType();
8202
8203 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8204 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8205 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8206 << CondTy << Cond->getSourceRange();
8207 return true;
8208 }
8209
8210 // C99 6.5.15p2
8211 if (CondTy->isScalarType()) return false;
8212
8213 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8214 << CondTy << Cond->getSourceRange();
8215 return true;
8216}
8217
8218/// Return false if the NullExpr can be promoted to PointerTy,
8219/// true otherwise.
8221 QualType PointerTy) {
8222 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8223 !NullExpr.get()->isNullPointerConstant(S.Context,
8225 return true;
8226
8227 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8228 return false;
8229}
8230
8231/// Checks compatibility between two pointers and return the resulting
8232/// type.
8234 ExprResult &RHS,
8235 SourceLocation Loc) {
8236 QualType LHSTy = LHS.get()->getType();
8237 QualType RHSTy = RHS.get()->getType();
8238
8239 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8240 // Two identical pointers types are always compatible.
8241 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8242 }
8243
8244 QualType lhptee, rhptee;
8245
8246 // Get the pointee types.
8247 bool IsBlockPointer = false;
8248 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8249 lhptee = LHSBTy->getPointeeType();
8250 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8251 IsBlockPointer = true;
8252 } else {
8253 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8254 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8255 }
8256
8257 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8258 // differently qualified versions of compatible types, the result type is
8259 // a pointer to an appropriately qualified version of the composite
8260 // type.
8261
8262 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8263 // clause doesn't make sense for our extensions. E.g. address space 2 should
8264 // be incompatible with address space 3: they may live on different devices or
8265 // anything.
8266 Qualifiers lhQual = lhptee.getQualifiers();
8267 Qualifiers rhQual = rhptee.getQualifiers();
8268
8269 LangAS ResultAddrSpace = LangAS::Default;
8270 LangAS LAddrSpace = lhQual.getAddressSpace();
8271 LangAS RAddrSpace = rhQual.getAddressSpace();
8272
8273 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8274 // spaces is disallowed.
8275 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8276 ResultAddrSpace = LAddrSpace;
8277 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8278 ResultAddrSpace = RAddrSpace;
8279 else {
8280 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8281 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8282 << RHS.get()->getSourceRange();
8283 return QualType();
8284 }
8285
8286 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8287 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8288 lhQual.removeCVRQualifiers();
8289 rhQual.removeCVRQualifiers();
8290
8291 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8292 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8293 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8294 // qual types are compatible iff
8295 // * corresponded types are compatible
8296 // * CVR qualifiers are equal
8297 // * address spaces are equal
8298 // Thus for conditional operator we merge CVR and address space unqualified
8299 // pointees and if there is a composite type we return a pointer to it with
8300 // merged qualifiers.
8301 LHSCastKind =
8302 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8303 RHSCastKind =
8304 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8305 lhQual.removeAddressSpace();
8306 rhQual.removeAddressSpace();
8307
8308 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8309 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8310
8311 QualType CompositeTy = S.Context.mergeTypes(
8312 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8313 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8314
8315 if (CompositeTy.isNull()) {
8316 // In this situation, we assume void* type. No especially good
8317 // reason, but this is what gcc does, and we do have to pick
8318 // to get a consistent AST.
8319 QualType incompatTy;
8320 incompatTy = S.Context.getPointerType(
8321 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8322 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8323 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8324
8325 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8326 // for casts between types with incompatible address space qualifiers.
8327 // For the following code the compiler produces casts between global and
8328 // local address spaces of the corresponded innermost pointees:
8329 // local int *global *a;
8330 // global int *global *b;
8331 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8332 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8333 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8334 << RHS.get()->getSourceRange();
8335
8336 return incompatTy;
8337 }
8338
8339 // The pointer types are compatible.
8340 // In case of OpenCL ResultTy should have the address space qualifier
8341 // which is a superset of address spaces of both the 2nd and the 3rd
8342 // operands of the conditional operator.
8343 QualType ResultTy = [&, ResultAddrSpace]() {
8344 if (S.getLangOpts().OpenCL) {
8345 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8346 CompositeQuals.setAddressSpace(ResultAddrSpace);
8347 return S.Context
8348 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8349 .withCVRQualifiers(MergedCVRQual);
8350 }
8351 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8352 }();
8353 if (IsBlockPointer)
8354 ResultTy = S.Context.getBlockPointerType(ResultTy);
8355 else
8356 ResultTy = S.Context.getPointerType(ResultTy);
8357
8358 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8359 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8360 return ResultTy;
8361}
8362
8363/// Return the resulting type when the operands are both block pointers.
8365 ExprResult &LHS,
8366 ExprResult &RHS,
8367 SourceLocation Loc) {
8368 QualType LHSTy = LHS.get()->getType();
8369 QualType RHSTy = RHS.get()->getType();
8370
8371 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8372 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8374 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8375 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8376 return destType;
8377 }
8378 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8379 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8380 << RHS.get()->getSourceRange();
8381 return QualType();
8382 }
8383
8384 // We have 2 block pointer types.
8385 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8386}
8387
8388/// Return the resulting type when the operands are both pointers.
8389static QualType
8391 ExprResult &RHS,
8392 SourceLocation Loc) {
8393 // get the pointer types
8394 QualType LHSTy = LHS.get()->getType();
8395 QualType RHSTy = RHS.get()->getType();
8396
8397 // get the "pointed to" types
8398 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8399 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8400
8401 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8402 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8403 // Figure out necessary qualifiers (C99 6.5.15p6)
8404 QualType destPointee
8405 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8406 QualType destType = S.Context.getPointerType(destPointee);
8407 // Add qualifiers if necessary.
8408 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8409 // Promote to void*.
8410 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8411 return destType;
8412 }
8413 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8414 QualType destPointee
8415 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8416 QualType destType = S.Context.getPointerType(destPointee);
8417 // Add qualifiers if necessary.
8418 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8419 // Promote to void*.
8420 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8421 return destType;
8422 }
8423
8424 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8425}
8426
8427/// Return false if the first expression is not an integer and the second
8428/// expression is not a pointer, true otherwise.
8430 Expr* PointerExpr, SourceLocation Loc,
8431 bool IsIntFirstExpr) {
8432 if (!PointerExpr->getType()->isPointerType() ||
8433 !Int.get()->getType()->isIntegerType())
8434 return false;
8435
8436 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8437 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8438
8439 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8440 << Expr1->getType() << Expr2->getType()
8441 << Expr1->getSourceRange() << Expr2->getSourceRange();
8442 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8443 CK_IntegralToPointer);
8444 return true;
8445}
8446
8447/// Simple conversion between integer and floating point types.
8448///
8449/// Used when handling the OpenCL conditional operator where the
8450/// condition is a vector while the other operands are scalar.
8451///
8452/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8453/// types are either integer or floating type. Between the two
8454/// operands, the type with the higher rank is defined as the "result
8455/// type". The other operand needs to be promoted to the same type. No
8456/// other type promotion is allowed. We cannot use
8457/// UsualArithmeticConversions() for this purpose, since it always
8458/// promotes promotable types.
8460 ExprResult &RHS,
8461 SourceLocation QuestionLoc) {
8463 if (LHS.isInvalid())
8464 return QualType();
8466 if (RHS.isInvalid())
8467 return QualType();
8468
8469 // For conversion purposes, we ignore any qualifiers.
8470 // For example, "const float" and "float" are equivalent.
8471 QualType LHSType =
8473 QualType RHSType =
8475
8476 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8477 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8478 << LHSType << LHS.get()->getSourceRange();
8479 return QualType();
8480 }
8481
8482 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8483 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8484 << RHSType << RHS.get()->getSourceRange();
8485 return QualType();
8486 }
8487
8488 // If both types are identical, no conversion is needed.
8489 if (LHSType == RHSType)
8490 return LHSType;
8491
8492 // Now handle "real" floating types (i.e. float, double, long double).
8493 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8494 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8495 /*IsCompAssign = */ false);
8496
8497 // Finally, we have two differing integer types.
8498 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8499 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8500}
8501
8502/// Convert scalar operands to a vector that matches the
8503/// condition in length.
8504///
8505/// Used when handling the OpenCL conditional operator where the
8506/// condition is a vector while the other operands are scalar.
8507///
8508/// We first compute the "result type" for the scalar operands
8509/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8510/// into a vector of that type where the length matches the condition
8511/// vector type. s6.11.6 requires that the element types of the result
8512/// and the condition must have the same number of bits.
8513static QualType
8515 QualType CondTy, SourceLocation QuestionLoc) {
8516 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8517 if (ResTy.isNull()) return QualType();
8518
8519 const VectorType *CV = CondTy->getAs<VectorType>();
8520 assert(CV);
8521
8522 // Determine the vector result type
8523 unsigned NumElements = CV->getNumElements();
8524 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8525
8526 // Ensure that all types have the same number of bits
8528 != S.Context.getTypeSize(ResTy)) {
8529 // Since VectorTy is created internally, it does not pretty print
8530 // with an OpenCL name. Instead, we just print a description.
8531 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8532 SmallString<64> Str;
8533 llvm::raw_svector_ostream OS(Str);
8534 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8535 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8536 << CondTy << OS.str();
8537 return QualType();
8538 }
8539
8540 // Convert operands to the vector result type
8541 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8542 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8543
8544 return VectorTy;
8545}
8546
8547/// Return false if this is a valid OpenCL condition vector
8549 SourceLocation QuestionLoc) {
8550 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8551 // integral type.
8552 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8553 assert(CondTy);
8554 QualType EleTy = CondTy->getElementType();
8555 if (EleTy->isIntegerType()) return false;
8556
8557 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8558 << Cond->getType() << Cond->getSourceRange();
8559 return true;
8560}
8561
8562/// Return false if the vector condition type and the vector
8563/// result type are compatible.
8564///
8565/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8566/// number of elements, and their element types have the same number
8567/// of bits.
8568static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8569 SourceLocation QuestionLoc) {
8570 const VectorType *CV = CondTy->getAs<VectorType>();
8571 const VectorType *RV = VecResTy->getAs<VectorType>();
8572 assert(CV && RV);
8573
8574 if (CV->getNumElements() != RV->getNumElements()) {
8575 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8576 << CondTy << VecResTy;
8577 return true;
8578 }
8579
8580 QualType CVE = CV->getElementType();
8581 QualType RVE = RV->getElementType();
8582
8583 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8584 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8585 << CondTy << VecResTy;
8586 return true;
8587 }
8588
8589 return false;
8590}
8591
8592/// Return the resulting type for the conditional operator in
8593/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8594/// s6.3.i) when the condition is a vector type.
8595static QualType
8597 ExprResult &LHS, ExprResult &RHS,
8598 SourceLocation QuestionLoc) {
8600 if (Cond.isInvalid())
8601 return QualType();
8602 QualType CondTy = Cond.get()->getType();
8603
8604 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8605 return QualType();
8606
8607 // If either operand is a vector then find the vector type of the
8608 // result as specified in OpenCL v1.1 s6.3.i.
8609 if (LHS.get()->getType()->isVectorType() ||
8610 RHS.get()->getType()->isVectorType()) {
8611 bool IsBoolVecLang =
8612 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8613 QualType VecResTy =
8614 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8615 /*isCompAssign*/ false,
8616 /*AllowBothBool*/ true,
8617 /*AllowBoolConversions*/ false,
8618 /*AllowBooleanOperation*/ IsBoolVecLang,
8619 /*ReportInvalid*/ true);
8620 if (VecResTy.isNull())
8621 return QualType();
8622 // The result type must match the condition type as specified in
8623 // OpenCL v1.1 s6.11.6.
8624 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8625 return QualType();
8626 return VecResTy;
8627 }
8628
8629 // Both operands are scalar.
8630 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8631}
8632
8633/// Return true if the Expr is block type
8634static bool checkBlockType(Sema &S, const Expr *E) {
8635 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8636 QualType Ty = CE->getCallee()->getType();
8637 if (Ty->isBlockPointerType()) {
8638 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8639 return true;
8640 }
8641 }
8642 return false;
8643}
8644
8645/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8646/// In that case, LHS = cond.
8647/// C99 6.5.15
8649 ExprResult &RHS, ExprValueKind &VK,
8650 ExprObjectKind &OK,
8651 SourceLocation QuestionLoc) {
8652
8653 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8654 if (!LHSResult.isUsable()) return QualType();
8655 LHS = LHSResult;
8656
8657 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8658 if (!RHSResult.isUsable()) return QualType();
8659 RHS = RHSResult;
8660
8661 // C++ is sufficiently different to merit its own checker.
8662 if (getLangOpts().CPlusPlus)
8663 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8664
8665 VK = VK_PRValue;
8666 OK = OK_Ordinary;
8667
8669 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8670 RHS.get()->isTypeDependent())) {
8671 assert(!getLangOpts().CPlusPlus);
8672 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8673 RHS.get()->containsErrors()) &&
8674 "should only occur in error-recovery path.");
8675 return Context.DependentTy;
8676 }
8677
8678 // The OpenCL operator with a vector condition is sufficiently
8679 // different to merit its own checker.
8680 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8681 Cond.get()->getType()->isExtVectorType())
8682 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8683
8684 // First, check the condition.
8685 Cond = UsualUnaryConversions(Cond.get());
8686 if (Cond.isInvalid())
8687 return QualType();
8688 if (checkCondition(*this, Cond.get(), QuestionLoc))
8689 return QualType();
8690
8691 // Handle vectors.
8692 if (LHS.get()->getType()->isVectorType() ||
8693 RHS.get()->getType()->isVectorType())
8694 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8695 /*AllowBothBool*/ true,
8696 /*AllowBoolConversions*/ false,
8697 /*AllowBooleanOperation*/ false,
8698 /*ReportInvalid*/ true);
8699
8700 QualType ResTy =
8701 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8702 if (LHS.isInvalid() || RHS.isInvalid())
8703 return QualType();
8704
8705 // WebAssembly tables are not allowed as conditional LHS or RHS.
8706 QualType LHSTy = LHS.get()->getType();
8707 QualType RHSTy = RHS.get()->getType();
8708 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8709 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8711 return QualType();
8712 }
8713
8714 // Diagnose attempts to convert between __ibm128, __float128 and long double
8715 // where such conversions currently can't be handled.
8716 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8717 Diag(QuestionLoc,
8718 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8720 return QualType();
8721 }
8722
8723 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8724 // selection operator (?:).
8725 if (getLangOpts().OpenCL &&
8726 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8727 return QualType();
8728 }
8729
8730 // If both operands have arithmetic type, do the usual arithmetic conversions
8731 // to find a common type: C99 6.5.15p3,5.
8732 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8733 // Disallow invalid arithmetic conversions, such as those between bit-
8734 // precise integers types of different sizes, or between a bit-precise
8735 // integer and another type.
8736 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8737 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8738 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8739 << RHS.get()->getSourceRange();
8740 return QualType();
8741 }
8742
8743 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8744 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8745
8746 return ResTy;
8747 }
8748
8749 // If both operands are the same structure or union type, the result is that
8750 // type.
8751 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8752 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8753 if (LHSRT->getDecl() == RHSRT->getDecl())
8754 // "If both the operands have structure or union type, the result has
8755 // that type." This implies that CV qualifiers are dropped.
8757 RHSTy.getUnqualifiedType());
8758 // FIXME: Type of conditional expression must be complete in C mode.
8759 }
8760
8761 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8762 // The following || allows only one side to be void (a GCC-ism).
8763 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8764 QualType ResTy;
8765 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8766 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8767 } else if (RHSTy->isVoidType()) {
8768 ResTy = RHSTy;
8769 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8770 << RHS.get()->getSourceRange();
8771 } else {
8772 ResTy = LHSTy;
8773 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8774 << LHS.get()->getSourceRange();
8775 }
8776 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8777 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8778 return ResTy;
8779 }
8780
8781 // C23 6.5.15p7:
8782 // ... if both the second and third operands have nullptr_t type, the
8783 // result also has that type.
8784 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8785 return ResTy;
8786
8787 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8788 // the type of the other operand."
8789 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8790 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8791
8792 // All objective-c pointer type analysis is done here.
8793 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8794 QuestionLoc);
8795 if (LHS.isInvalid() || RHS.isInvalid())
8796 return QualType();
8797 if (!compositeType.isNull())
8798 return compositeType;
8799
8800
8801 // Handle block pointer types.
8802 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8803 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8804 QuestionLoc);
8805
8806 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8807 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8808 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8809 QuestionLoc);
8810
8811 // GCC compatibility: soften pointer/integer mismatch. Note that
8812 // null pointers have been filtered out by this point.
8813 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8814 /*IsIntFirstExpr=*/true))
8815 return RHSTy;
8816 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8817 /*IsIntFirstExpr=*/false))
8818 return LHSTy;
8819
8820 // Emit a better diagnostic if one of the expressions is a null pointer
8821 // constant and the other is not a pointer type. In this case, the user most
8822 // likely forgot to take the address of the other expression.
8823 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8824 return QualType();
8825
8826 // Finally, if the LHS and RHS types are canonically the same type, we can
8827 // use the common sugared type.
8828 if (Context.hasSameType(LHSTy, RHSTy))
8829 return Context.getCommonSugaredType(LHSTy, RHSTy);
8830
8831 // Otherwise, the operands are not compatible.
8832 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8833 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8834 << RHS.get()->getSourceRange();
8835 return QualType();
8836}
8837
8838/// FindCompositeObjCPointerType - Helper method to find composite type of
8839/// two objective-c pointer types of the two input expressions.
8841 SourceLocation QuestionLoc) {
8842 QualType LHSTy = LHS.get()->getType();
8843 QualType RHSTy = RHS.get()->getType();
8844
8845 // Handle things like Class and struct objc_class*. Here we case the result
8846 // to the pseudo-builtin, because that will be implicitly cast back to the
8847 // redefinition type if an attempt is made to access its fields.
8848 if (LHSTy->isObjCClassType() &&
8850 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8851 return LHSTy;
8852 }
8853 if (RHSTy->isObjCClassType() &&
8855 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8856 return RHSTy;
8857 }
8858 // And the same for struct objc_object* / id
8859 if (LHSTy->isObjCIdType() &&
8861 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8862 return LHSTy;
8863 }
8864 if (RHSTy->isObjCIdType() &&
8866 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8867 return RHSTy;
8868 }
8869 // And the same for struct objc_selector* / SEL
8870 if (Context.isObjCSelType(LHSTy) &&
8872 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8873 return LHSTy;
8874 }
8875 if (Context.isObjCSelType(RHSTy) &&
8877 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8878 return RHSTy;
8879 }
8880 // Check constraints for Objective-C object pointers types.
8881 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8882
8883 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8884 // Two identical object pointer types are always compatible.
8885 return LHSTy;
8886 }
8887 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8888 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8889 QualType compositeType = LHSTy;
8890
8891 // If both operands are interfaces and either operand can be
8892 // assigned to the other, use that type as the composite
8893 // type. This allows
8894 // xxx ? (A*) a : (B*) b
8895 // where B is a subclass of A.
8896 //
8897 // Additionally, as for assignment, if either type is 'id'
8898 // allow silent coercion. Finally, if the types are
8899 // incompatible then make sure to use 'id' as the composite
8900 // type so the result is acceptable for sending messages to.
8901
8902 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8903 // It could return the composite type.
8904 if (!(compositeType =
8905 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8906 // Nothing more to do.
8907 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8908 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8909 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8910 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8911 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8912 RHSOPT->isObjCQualifiedIdType()) &&
8914 true)) {
8915 // Need to handle "id<xx>" explicitly.
8916 // GCC allows qualified id and any Objective-C type to devolve to
8917 // id. Currently localizing to here until clear this should be
8918 // part of ObjCQualifiedIdTypesAreCompatible.
8919 compositeType = Context.getObjCIdType();
8920 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8921 compositeType = Context.getObjCIdType();
8922 } else {
8923 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8924 << LHSTy << RHSTy
8925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8926 QualType incompatTy = Context.getObjCIdType();
8927 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8928 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8929 return incompatTy;
8930 }
8931 // The object pointer types are compatible.
8932 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8933 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8934 return compositeType;
8935 }
8936 // Check Objective-C object pointer types and 'void *'
8937 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8938 if (getLangOpts().ObjCAutoRefCount) {
8939 // ARC forbids the implicit conversion of object pointers to 'void *',
8940 // so these types are not compatible.
8941 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8942 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8943 LHS = RHS = true;
8944 return QualType();
8945 }
8946 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8947 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8948 QualType destPointee
8949 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8950 QualType destType = Context.getPointerType(destPointee);
8951 // Add qualifiers if necessary.
8952 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8953 // Promote to void*.
8954 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8955 return destType;
8956 }
8957 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8958 if (getLangOpts().ObjCAutoRefCount) {
8959 // ARC forbids the implicit conversion of object pointers to 'void *',
8960 // so these types are not compatible.
8961 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8963 LHS = RHS = true;
8964 return QualType();
8965 }
8966 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8967 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8968 QualType destPointee
8969 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8970 QualType destType = Context.getPointerType(destPointee);
8971 // Add qualifiers if necessary.
8972 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8973 // Promote to void*.
8974 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8975 return destType;
8976 }
8977 return QualType();
8978}
8979
8980/// SuggestParentheses - Emit a note with a fixit hint that wraps
8981/// ParenRange in parentheses.
8983 const PartialDiagnostic &Note,
8984 SourceRange ParenRange) {
8985 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8986 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8987 EndLoc.isValid()) {
8988 Self.Diag(Loc, Note)
8989 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8990 << FixItHint::CreateInsertion(EndLoc, ")");
8991 } else {
8992 // We can't display the parentheses, so just show the bare note.
8993 Self.Diag(Loc, Note) << ParenRange;
8994 }
8995}
8996
8998 return BinaryOperator::isAdditiveOp(Opc) ||
9000 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9001 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9002 // not any of the logical operators. Bitwise-xor is commonly used as a
9003 // logical-xor because there is no logical-xor operator. The logical
9004 // operators, including uses of xor, have a high false positive rate for
9005 // precedence warnings.
9006}
9007
9008/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9009/// expression, either using a built-in or overloaded operator,
9010/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9011/// expression.
9012static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9013 const Expr **RHSExprs) {
9014 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9015 E = E->IgnoreImpCasts();
9017 E = E->IgnoreImpCasts();
9018 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9019 E = MTE->getSubExpr();
9020 E = E->IgnoreImpCasts();
9021 }
9022
9023 // Built-in binary operator.
9024 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9025 OP && IsArithmeticOp(OP->getOpcode())) {
9026 *Opcode = OP->getOpcode();
9027 *RHSExprs = OP->getRHS();
9028 return true;
9029 }
9030
9031 // Overloaded operator.
9032 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9033 if (Call->getNumArgs() != 2)
9034 return false;
9035
9036 // Make sure this is really a binary operator that is safe to pass into
9037 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9038 OverloadedOperatorKind OO = Call->getOperator();
9039 if (OO < OO_Plus || OO > OO_Arrow ||
9040 OO == OO_PlusPlus || OO == OO_MinusMinus)
9041 return false;
9042
9044 if (IsArithmeticOp(OpKind)) {
9045 *Opcode = OpKind;
9046 *RHSExprs = Call->getArg(1);
9047 return true;
9048 }
9049 }
9050
9051 return false;
9052}
9053
9054/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9055/// or is a logical expression such as (x==y) which has int type, but is
9056/// commonly interpreted as boolean.
9057static bool ExprLooksBoolean(const Expr *E) {
9058 E = E->IgnoreParenImpCasts();
9059
9060 if (E->getType()->isBooleanType())
9061 return true;
9062 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9063 return OP->isComparisonOp() || OP->isLogicalOp();
9064 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9065 return OP->getOpcode() == UO_LNot;
9066 if (E->getType()->isPointerType())
9067 return true;
9068 // FIXME: What about overloaded operator calls returning "unspecified boolean
9069 // type"s (commonly pointer-to-members)?
9070
9071 return false;
9072}
9073
9074/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9075/// and binary operator are mixed in a way that suggests the programmer assumed
9076/// the conditional operator has higher precedence, for example:
9077/// "int x = a + someBinaryCondition ? 1 : 2".
9079 Expr *Condition, const Expr *LHSExpr,
9080 const Expr *RHSExpr) {
9081 BinaryOperatorKind CondOpcode;
9082 const Expr *CondRHS;
9083
9084 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9085 return;
9086 if (!ExprLooksBoolean(CondRHS))
9087 return;
9088
9089 // The condition is an arithmetic binary expression, with a right-
9090 // hand side that looks boolean, so warn.
9091
9092 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9093 ? diag::warn_precedence_bitwise_conditional
9094 : diag::warn_precedence_conditional;
9095
9096 Self.Diag(OpLoc, DiagID)
9097 << Condition->getSourceRange()
9098 << BinaryOperator::getOpcodeStr(CondOpcode);
9099
9101 Self, OpLoc,
9102 Self.PDiag(diag::note_precedence_silence)
9103 << BinaryOperator::getOpcodeStr(CondOpcode),
9104 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9105
9106 SuggestParentheses(Self, OpLoc,
9107 Self.PDiag(diag::note_precedence_conditional_first),
9108 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9109}
9110
9111/// Compute the nullability of a conditional expression.
9113 QualType LHSTy, QualType RHSTy,
9114 ASTContext &Ctx) {
9115 if (!ResTy->isAnyPointerType())
9116 return ResTy;
9117
9118 auto GetNullability = [](QualType Ty) {
9119 std::optional<NullabilityKind> Kind = Ty->getNullability();
9120 if (Kind) {
9121 // For our purposes, treat _Nullable_result as _Nullable.
9124 return *Kind;
9125 }
9127 };
9128
9129 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9130 NullabilityKind MergedKind;
9131
9132 // Compute nullability of a binary conditional expression.
9133 if (IsBin) {
9134 if (LHSKind == NullabilityKind::NonNull)
9135 MergedKind = NullabilityKind::NonNull;
9136 else
9137 MergedKind = RHSKind;
9138 // Compute nullability of a normal conditional expression.
9139 } else {
9140 if (LHSKind == NullabilityKind::Nullable ||
9141 RHSKind == NullabilityKind::Nullable)
9142 MergedKind = NullabilityKind::Nullable;
9143 else if (LHSKind == NullabilityKind::NonNull)
9144 MergedKind = RHSKind;
9145 else if (RHSKind == NullabilityKind::NonNull)
9146 MergedKind = LHSKind;
9147 else
9148 MergedKind = NullabilityKind::Unspecified;
9149 }
9150
9151 // Return if ResTy already has the correct nullability.
9152 if (GetNullability(ResTy) == MergedKind)
9153 return ResTy;
9154
9155 // Strip all nullability from ResTy.
9156 while (ResTy->getNullability())
9157 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9158
9159 // Create a new AttributedType with the new nullability kind.
9160 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9161 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9162}
9163
9164/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9165/// in the case of a the GNU conditional expr extension.
9167 SourceLocation ColonLoc,
9168 Expr *CondExpr, Expr *LHSExpr,
9169 Expr *RHSExpr) {
9171 // C cannot handle TypoExpr nodes in the condition because it
9172 // doesn't handle dependent types properly, so make sure any TypoExprs have
9173 // been dealt with before checking the operands.
9174 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9175 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9176 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9177
9178 if (!CondResult.isUsable())
9179 return ExprError();
9180
9181 if (LHSExpr) {
9182 if (!LHSResult.isUsable())
9183 return ExprError();
9184 }
9185
9186 if (!RHSResult.isUsable())
9187 return ExprError();
9188
9189 CondExpr = CondResult.get();
9190 LHSExpr = LHSResult.get();
9191 RHSExpr = RHSResult.get();
9192 }
9193
9194 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9195 // was the condition.
9196 OpaqueValueExpr *opaqueValue = nullptr;
9197 Expr *commonExpr = nullptr;
9198 if (!LHSExpr) {
9199 commonExpr = CondExpr;
9200 // Lower out placeholder types first. This is important so that we don't
9201 // try to capture a placeholder. This happens in few cases in C++; such
9202 // as Objective-C++'s dictionary subscripting syntax.
9203 if (commonExpr->hasPlaceholderType()) {
9204 ExprResult result = CheckPlaceholderExpr(commonExpr);
9205 if (!result.isUsable()) return ExprError();
9206 commonExpr = result.get();
9207 }
9208 // We usually want to apply unary conversions *before* saving, except
9209 // in the special case of a C++ l-value conditional.
9210 if (!(getLangOpts().CPlusPlus
9211 && !commonExpr->isTypeDependent()
9212 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9213 && commonExpr->isGLValue()
9214 && commonExpr->isOrdinaryOrBitFieldObject()
9215 && RHSExpr->isOrdinaryOrBitFieldObject()
9216 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9217 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9218 if (commonRes.isInvalid())
9219 return ExprError();
9220 commonExpr = commonRes.get();
9221 }
9222
9223 // If the common expression is a class or array prvalue, materialize it
9224 // so that we can safely refer to it multiple times.
9225 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9226 commonExpr->getType()->isArrayType())) {
9227 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9228 if (MatExpr.isInvalid())
9229 return ExprError();
9230 commonExpr = MatExpr.get();
9231 }
9232
9233 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9234 commonExpr->getType(),
9235 commonExpr->getValueKind(),
9236 commonExpr->getObjectKind(),
9237 commonExpr);
9238 LHSExpr = CondExpr = opaqueValue;
9239 }
9240
9241 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9244 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9245 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9246 VK, OK, QuestionLoc);
9247 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9248 RHS.isInvalid())
9249 return ExprError();
9250
9251 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9252 RHS.get());
9253
9254 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9255
9256 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9257 Context);
9258
9259 if (!commonExpr)
9260 return new (Context)
9261 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9262 RHS.get(), result, VK, OK);
9263
9265 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9266 ColonLoc, result, VK, OK);
9267}
9268
9269// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9271 unsigned FromAttributes = 0, ToAttributes = 0;
9272 if (const auto *FromFn =
9273 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9274 FromAttributes =
9275 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9276 if (const auto *ToFn =
9277 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9278 ToAttributes =
9279 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9280
9281 return FromAttributes != ToAttributes;
9282}
9283
9284// Check if we have a conversion between incompatible cmse function pointer
9285// types, that is, a conversion between a function pointer with the
9286// cmse_nonsecure_call attribute and one without.
9288 QualType ToType) {
9289 if (const auto *ToFn =
9290 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9291 if (const auto *FromFn =
9292 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9293 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9294 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9295
9296 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9297 }
9298 }
9299 return false;
9300}
9301
9302// checkPointerTypesForAssignment - This is a very tricky routine (despite
9303// being closely modeled after the C99 spec:-). The odd characteristic of this
9304// routine is it effectively iqnores the qualifiers on the top level pointee.
9305// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9306// FIXME: add a couple examples in this comment.
9309 SourceLocation Loc) {
9310 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9311 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9312
9313 // get the "pointed to" type (ignoring qualifiers at the top level)
9314 const Type *lhptee, *rhptee;
9315 Qualifiers lhq, rhq;
9316 std::tie(lhptee, lhq) =
9317 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9318 std::tie(rhptee, rhq) =
9319 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9320
9322
9323 // C99 6.5.16.1p1: This following citation is common to constraints
9324 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9325 // qualifiers of the type *pointed to* by the right;
9326
9327 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9328 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9330 // Ignore lifetime for further calculation.
9331 lhq.removeObjCLifetime();
9332 rhq.removeObjCLifetime();
9333 }
9334
9335 if (!lhq.compatiblyIncludes(rhq)) {
9336 // Treat address-space mismatches as fatal.
9337 if (!lhq.isAddressSpaceSupersetOf(rhq))
9339
9340 // It's okay to add or remove GC or lifetime qualifiers when converting to
9341 // and from void*.
9342 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9345 && (lhptee->isVoidType() || rhptee->isVoidType()))
9346 ; // keep old
9347
9348 // Treat lifetime mismatches as fatal.
9349 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9351
9352 // For GCC/MS compatibility, other qualifier mismatches are treated
9353 // as still compatible in C.
9355 }
9356
9357 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9358 // incomplete type and the other is a pointer to a qualified or unqualified
9359 // version of void...
9360 if (lhptee->isVoidType()) {
9361 if (rhptee->isIncompleteOrObjectType())
9362 return ConvTy;
9363
9364 // As an extension, we allow cast to/from void* to function pointer.
9365 assert(rhptee->isFunctionType());
9367 }
9368
9369 if (rhptee->isVoidType()) {
9370 if (lhptee->isIncompleteOrObjectType())
9371 return ConvTy;
9372
9373 // As an extension, we allow cast to/from void* to function pointer.
9374 assert(lhptee->isFunctionType());
9376 }
9377
9378 if (!S.Diags.isIgnored(
9379 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9380 Loc) &&
9381 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9382 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9384
9385 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9386 // unqualified versions of compatible types, ...
9387 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9388 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9389 // Check if the pointee types are compatible ignoring the sign.
9390 // We explicitly check for char so that we catch "char" vs
9391 // "unsigned char" on systems where "char" is unsigned.
9392 if (lhptee->isCharType())
9393 ltrans = S.Context.UnsignedCharTy;
9394 else if (lhptee->hasSignedIntegerRepresentation())
9395 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9396
9397 if (rhptee->isCharType())
9398 rtrans = S.Context.UnsignedCharTy;
9399 else if (rhptee->hasSignedIntegerRepresentation())
9400 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9401
9402 if (ltrans == rtrans) {
9403 // Types are compatible ignoring the sign. Qualifier incompatibility
9404 // takes priority over sign incompatibility because the sign
9405 // warning can be disabled.
9406 if (ConvTy != Sema::Compatible)
9407 return ConvTy;
9408
9410 }
9411
9412 // If we are a multi-level pointer, it's possible that our issue is simply
9413 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9414 // the eventual target type is the same and the pointers have the same
9415 // level of indirection, this must be the issue.
9416 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9417 do {
9418 std::tie(lhptee, lhq) =
9419 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9420 std::tie(rhptee, rhq) =
9421 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9422
9423 // Inconsistent address spaces at this point is invalid, even if the
9424 // address spaces would be compatible.
9425 // FIXME: This doesn't catch address space mismatches for pointers of
9426 // different nesting levels, like:
9427 // __local int *** a;
9428 // int ** b = a;
9429 // It's not clear how to actually determine when such pointers are
9430 // invalidly incompatible.
9431 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9433
9434 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9435
9436 if (lhptee == rhptee)
9438 }
9439
9440 // General pointer incompatibility takes priority over qualifiers.
9441 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9444 }
9445 if (!S.getLangOpts().CPlusPlus &&
9446 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9448 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9450 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9452 return ConvTy;
9453}
9454
9455/// checkBlockPointerTypesForAssignment - This routine determines whether two
9456/// block pointer types are compatible or whether a block and normal pointer
9457/// are compatible. It is more restrict than comparing two function pointer
9458// types.
9461 QualType RHSType) {
9462 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9463 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9464
9465 QualType lhptee, rhptee;
9466
9467 // get the "pointed to" type (ignoring qualifiers at the top level)
9468 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9469 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9470
9471 // In C++, the types have to match exactly.
9472 if (S.getLangOpts().CPlusPlus)
9474
9476
9477 // For blocks we enforce that qualifiers are identical.
9478 Qualifiers LQuals = lhptee.getLocalQualifiers();
9479 Qualifiers RQuals = rhptee.getLocalQualifiers();
9480 if (S.getLangOpts().OpenCL) {
9481 LQuals.removeAddressSpace();
9482 RQuals.removeAddressSpace();
9483 }
9484 if (LQuals != RQuals)
9486
9487 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9488 // assignment.
9489 // The current behavior is similar to C++ lambdas. A block might be
9490 // assigned to a variable iff its return type and parameters are compatible
9491 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9492 // an assignment. Presumably it should behave in way that a function pointer
9493 // assignment does in C, so for each parameter and return type:
9494 // * CVR and address space of LHS should be a superset of CVR and address
9495 // space of RHS.
9496 // * unqualified types should be compatible.
9497 if (S.getLangOpts().OpenCL) {
9499 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9500 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9502 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9504
9505 return ConvTy;
9506}
9507
9508/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9509/// for assignment compatibility.
9512 QualType RHSType) {
9513 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9514 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9515
9516 if (LHSType->isObjCBuiltinType()) {
9517 // Class is not compatible with ObjC object pointers.
9518 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9519 !RHSType->isObjCQualifiedClassType())
9521 return Sema::Compatible;
9522 }
9523 if (RHSType->isObjCBuiltinType()) {
9524 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9525 !LHSType->isObjCQualifiedClassType())
9527 return Sema::Compatible;
9528 }
9529 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9530 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9531
9532 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9533 // make an exception for id<P>
9534 !LHSType->isObjCQualifiedIdType())
9536
9537 if (S.Context.typesAreCompatible(LHSType, RHSType))
9538 return Sema::Compatible;
9539 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9542}
9543
9546 QualType LHSType, QualType RHSType) {
9547 // Fake up an opaque expression. We don't actually care about what
9548 // cast operations are required, so if CheckAssignmentConstraints
9549 // adds casts to this they'll be wasted, but fortunately that doesn't
9550 // usually happen on valid code.
9551 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9552 ExprResult RHSPtr = &RHSExpr;
9553 CastKind K;
9554
9555 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9556}
9557
9558/// This helper function returns true if QT is a vector type that has element
9559/// type ElementType.
9560static bool isVector(QualType QT, QualType ElementType) {
9561 if (const VectorType *VT = QT->getAs<VectorType>())
9562 return VT->getElementType().getCanonicalType() == ElementType;
9563 return false;
9564}
9565
9566/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9567/// has code to accommodate several GCC extensions when type checking
9568/// pointers. Here are some objectionable examples that GCC considers warnings:
9569///
9570/// int a, *pint;
9571/// short *pshort;
9572/// struct foo *pfoo;
9573///
9574/// pint = pshort; // warning: assignment from incompatible pointer type
9575/// a = pint; // warning: assignment makes integer from pointer without a cast
9576/// pint = a; // warning: assignment makes pointer from integer without a cast
9577/// pint = pfoo; // warning: assignment from incompatible pointer type
9578///
9579/// As a result, the code for dealing with pointers is more complex than the
9580/// C99 spec dictates.
9581///
9582/// Sets 'Kind' for any result kind except Incompatible.
9585 CastKind &Kind, bool ConvertRHS) {
9586 QualType RHSType = RHS.get()->getType();
9587 QualType OrigLHSType = LHSType;
9588
9589 // Get canonical types. We're not formatting these types, just comparing
9590 // them.
9591 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9592 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9593
9594 // Common case: no conversion required.
9595 if (LHSType == RHSType) {
9596 Kind = CK_NoOp;
9597 return Compatible;
9598 }
9599
9600 // If the LHS has an __auto_type, there are no additional type constraints
9601 // to be worried about.
9602 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9603 if (AT->isGNUAutoType()) {
9604 Kind = CK_NoOp;
9605 return Compatible;
9606 }
9607 }
9608
9609 // If we have an atomic type, try a non-atomic assignment, then just add an
9610 // atomic qualification step.
9611 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9613 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9614 if (result != Compatible)
9615 return result;
9616 if (Kind != CK_NoOp && ConvertRHS)
9617 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9618 Kind = CK_NonAtomicToAtomic;
9619 return Compatible;
9620 }
9621
9622 // If the left-hand side is a reference type, then we are in a
9623 // (rare!) case where we've allowed the use of references in C,
9624 // e.g., as a parameter type in a built-in function. In this case,
9625 // just make sure that the type referenced is compatible with the
9626 // right-hand side type. The caller is responsible for adjusting
9627 // LHSType so that the resulting expression does not have reference
9628 // type.
9629 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9630 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9631 Kind = CK_LValueBitCast;
9632 return Compatible;
9633 }
9634 return Incompatible;
9635 }
9636
9637 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9638 // to the same ExtVector type.
9639 if (LHSType->isExtVectorType()) {
9640 if (RHSType->isExtVectorType())
9641 return Incompatible;
9642 if (RHSType->isArithmeticType()) {
9643 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9644 if (ConvertRHS)
9645 RHS = prepareVectorSplat(LHSType, RHS.get());
9646 Kind = CK_VectorSplat;
9647 return Compatible;
9648 }
9649 }
9650
9651 // Conversions to or from vector type.
9652 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9653 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9654 // Allow assignments of an AltiVec vector type to an equivalent GCC
9655 // vector type and vice versa
9656 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9657 Kind = CK_BitCast;
9658 return Compatible;
9659 }
9660
9661 // If we are allowing lax vector conversions, and LHS and RHS are both
9662 // vectors, the total size only needs to be the same. This is a bitcast;
9663 // no bits are changed but the result type is different.
9664 if (isLaxVectorConversion(RHSType, LHSType)) {
9665 // The default for lax vector conversions with Altivec vectors will
9666 // change, so if we are converting between vector types where
9667 // at least one is an Altivec vector, emit a warning.
9668 if (Context.getTargetInfo().getTriple().isPPC() &&
9669 anyAltivecTypes(RHSType, LHSType) &&
9670 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9671 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9672 << RHSType << LHSType;
9673 Kind = CK_BitCast;
9674 return IncompatibleVectors;
9675 }
9676 }
9677
9678 // When the RHS comes from another lax conversion (e.g. binops between
9679 // scalars and vectors) the result is canonicalized as a vector. When the
9680 // LHS is also a vector, the lax is allowed by the condition above. Handle
9681 // the case where LHS is a scalar.
9682 if (LHSType->isScalarType()) {
9683 const VectorType *VecType = RHSType->getAs<VectorType>();
9684 if (VecType && VecType->getNumElements() == 1 &&
9685 isLaxVectorConversion(RHSType, LHSType)) {
9686 if (Context.getTargetInfo().getTriple().isPPC() &&
9688 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9690 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9691 << RHSType << LHSType;
9692 ExprResult *VecExpr = &RHS;
9693 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9694 Kind = CK_BitCast;
9695 return Compatible;
9696 }
9697 }
9698
9699 // Allow assignments between fixed-length and sizeless SVE vectors.
9700 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9701 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9702 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9703 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9704 Kind = CK_BitCast;
9705 return Compatible;
9706 }
9707
9708 // Allow assignments between fixed-length and sizeless RVV vectors.
9709 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9710 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9711 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9712 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9713 Kind = CK_BitCast;
9714 return Compatible;
9715 }
9716 }
9717
9718 return Incompatible;
9719 }
9720
9721 // Diagnose attempts to convert between __ibm128, __float128 and long double
9722 // where such conversions currently can't be handled.
9723 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9724 return Incompatible;
9725
9726 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9727 // discards the imaginary part.
9728 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9729 !LHSType->getAs<ComplexType>())
9730 return Incompatible;
9731
9732 // Arithmetic conversions.
9733 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9734 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9735 if (ConvertRHS)
9736 Kind = PrepareScalarCast(RHS, LHSType);
9737 return Compatible;
9738 }
9739
9740 // Conversions to normal pointers.
9741 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9742 // U* -> T*
9743 if (isa<PointerType>(RHSType)) {
9744 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9745 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9746 if (AddrSpaceL != AddrSpaceR)
9747 Kind = CK_AddressSpaceConversion;
9748 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9749 Kind = CK_NoOp;
9750 else
9751 Kind = CK_BitCast;
9752 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9753 RHS.get()->getBeginLoc());
9754 }
9755
9756 // int -> T*
9757 if (RHSType->isIntegerType()) {
9758 Kind = CK_IntegralToPointer; // FIXME: null?
9759 return IntToPointer;
9760 }
9761
9762 // C pointers are not compatible with ObjC object pointers,
9763 // with two exceptions:
9764 if (isa<ObjCObjectPointerType>(RHSType)) {
9765 // - conversions to void*
9766 if (LHSPointer->getPointeeType()->isVoidType()) {
9767 Kind = CK_BitCast;
9768 return Compatible;
9769 }
9770
9771 // - conversions from 'Class' to the redefinition type
9772 if (RHSType->isObjCClassType() &&
9773 Context.hasSameType(LHSType,
9775 Kind = CK_BitCast;
9776 return Compatible;
9777 }
9778
9779 Kind = CK_BitCast;
9780 return IncompatiblePointer;
9781 }
9782
9783 // U^ -> void*
9784 if (RHSType->getAs<BlockPointerType>()) {
9785 if (LHSPointer->getPointeeType()->isVoidType()) {
9786 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9787 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9788 ->getPointeeType()
9789 .getAddressSpace();
9790 Kind =
9791 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9792 return Compatible;
9793 }
9794 }
9795
9796 return Incompatible;
9797 }
9798
9799 // Conversions to block pointers.
9800 if (isa<BlockPointerType>(LHSType)) {
9801 // U^ -> T^
9802 if (RHSType->isBlockPointerType()) {
9803 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9804 ->getPointeeType()
9805 .getAddressSpace();
9806 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9807 ->getPointeeType()
9808 .getAddressSpace();
9809 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9810 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9811 }
9812
9813 // int or null -> T^
9814 if (RHSType->isIntegerType()) {
9815 Kind = CK_IntegralToPointer; // FIXME: null
9816 return IntToBlockPointer;
9817 }
9818
9819 // id -> T^
9820 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9821 Kind = CK_AnyPointerToBlockPointerCast;
9822 return Compatible;
9823 }
9824
9825 // void* -> T^
9826 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9827 if (RHSPT->getPointeeType()->isVoidType()) {
9828 Kind = CK_AnyPointerToBlockPointerCast;
9829 return Compatible;
9830 }
9831
9832 return Incompatible;
9833 }
9834
9835 // Conversions to Objective-C pointers.
9836 if (isa<ObjCObjectPointerType>(LHSType)) {
9837 // A* -> B*
9838 if (RHSType->isObjCObjectPointerType()) {
9839 Kind = CK_BitCast;
9841 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9842 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9843 result == Compatible &&
9844 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9845 result = IncompatibleObjCWeakRef;
9846 return result;
9847 }
9848
9849 // int or null -> A*
9850 if (RHSType->isIntegerType()) {
9851 Kind = CK_IntegralToPointer; // FIXME: null
9852 return IntToPointer;
9853 }
9854
9855 // In general, C pointers are not compatible with ObjC object pointers,
9856 // with two exceptions:
9857 if (isa<PointerType>(RHSType)) {
9858 Kind = CK_CPointerToObjCPointerCast;
9859
9860 // - conversions from 'void*'
9861 if (RHSType->isVoidPointerType()) {
9862 return Compatible;
9863 }
9864
9865 // - conversions to 'Class' from its redefinition type
9866 if (LHSType->isObjCClassType() &&
9867 Context.hasSameType(RHSType,
9869 return Compatible;
9870 }
9871
9872 return IncompatiblePointer;
9873 }
9874
9875 // Only under strict condition T^ is compatible with an Objective-C pointer.
9876 if (RHSType->isBlockPointerType() &&
9878 if (ConvertRHS)
9880 Kind = CK_BlockPointerToObjCPointerCast;
9881 return Compatible;
9882 }
9883
9884 return Incompatible;
9885 }
9886
9887 // Conversion to nullptr_t (C23 only)
9888 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9891 // null -> nullptr_t
9892 Kind = CK_NullToPointer;
9893 return Compatible;
9894 }
9895
9896 // Conversions from pointers that are not covered by the above.
9897 if (isa<PointerType>(RHSType)) {
9898 // T* -> _Bool
9899 if (LHSType == Context.BoolTy) {
9900 Kind = CK_PointerToBoolean;
9901 return Compatible;
9902 }
9903
9904 // T* -> int
9905 if (LHSType->isIntegerType()) {
9906 Kind = CK_PointerToIntegral;
9907 return PointerToInt;
9908 }
9909
9910 return Incompatible;
9911 }
9912
9913 // Conversions from Objective-C pointers that are not covered by the above.
9914 if (isa<ObjCObjectPointerType>(RHSType)) {
9915 // T* -> _Bool
9916 if (LHSType == Context.BoolTy) {
9917 Kind = CK_PointerToBoolean;
9918 return Compatible;
9919 }
9920
9921 // T* -> int
9922 if (LHSType->isIntegerType()) {
9923 Kind = CK_PointerToIntegral;
9924 return PointerToInt;
9925 }
9926
9927 return Incompatible;
9928 }
9929
9930 // struct A -> struct B
9931 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9932 if (Context.typesAreCompatible(LHSType, RHSType)) {
9933 Kind = CK_NoOp;
9934 return Compatible;
9935 }
9936 }
9937
9938 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9939 Kind = CK_IntToOCLSampler;
9940 return Compatible;
9941 }
9942
9943 return Incompatible;
9944}
9945
9946/// Constructs a transparent union from an expression that is
9947/// used to initialize the transparent union.
9949 ExprResult &EResult, QualType UnionType,
9950 FieldDecl *Field) {
9951 // Build an initializer list that designates the appropriate member
9952 // of the transparent union.
9953 Expr *E = EResult.get();
9955 E, SourceLocation());
9956 Initializer->setType(UnionType);
9957 Initializer->setInitializedFieldInUnion(Field);
9958
9959 // Build a compound literal constructing a value of the transparent
9960 // union type from this initializer list.
9961 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9962 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9963 VK_PRValue, Initializer, false);
9964}
9965
9968 ExprResult &RHS) {
9969 QualType RHSType = RHS.get()->getType();
9970
9971 // If the ArgType is a Union type, we want to handle a potential
9972 // transparent_union GCC extension.
9973 const RecordType *UT = ArgType->getAsUnionType();
9974 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9975 return Incompatible;
9976
9977 // The field to initialize within the transparent union.
9978 RecordDecl *UD = UT->getDecl();
9979 FieldDecl *InitField = nullptr;
9980 // It's compatible if the expression matches any of the fields.
9981 for (auto *it : UD->fields()) {
9982 if (it->getType()->isPointerType()) {
9983 // If the transparent union contains a pointer type, we allow:
9984 // 1) void pointer
9985 // 2) null pointer constant
9986 if (RHSType->isPointerType())
9987 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9988 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9989 InitField = it;
9990 break;
9991 }
9992
9995 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9996 CK_NullToPointer);
9997 InitField = it;
9998 break;
9999 }
10000 }
10001
10002 CastKind Kind;
10003 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10004 == Compatible) {
10005 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10006 InitField = it;
10007 break;
10008 }
10009 }
10010
10011 if (!InitField)
10012 return Incompatible;
10013
10014 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10015 return Compatible;
10016}
10017
10020 bool Diagnose,
10021 bool DiagnoseCFAudited,
10022 bool ConvertRHS) {
10023 // We need to be able to tell the caller whether we diagnosed a problem, if
10024 // they ask us to issue diagnostics.
10025 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10026
10027 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10028 // we can't avoid *all* modifications at the moment, so we need some somewhere
10029 // to put the updated value.
10030 ExprResult LocalRHS = CallerRHS;
10031 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10032
10033 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10034 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10035 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10036 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10037 Diag(RHS.get()->getExprLoc(),
10038 diag::warn_noderef_to_dereferenceable_pointer)
10039 << RHS.get()->getSourceRange();
10040 }
10041 }
10042 }
10043
10044 if (getLangOpts().CPlusPlus) {
10045 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10046 // C++ 5.17p3: If the left operand is not of class type, the
10047 // expression is implicitly converted (C++ 4) to the
10048 // cv-unqualified type of the left operand.
10049 QualType RHSType = RHS.get()->getType();
10050 if (Diagnose) {
10051 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10052 AA_Assigning);
10053 } else {
10056 /*SuppressUserConversions=*/false,
10057 AllowedExplicit::None,
10058 /*InOverloadResolution=*/false,
10059 /*CStyle=*/false,
10060 /*AllowObjCWritebackConversion=*/false);
10061 if (ICS.isFailure())
10062 return Incompatible;
10063 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10064 ICS, AA_Assigning);
10065 }
10066 if (RHS.isInvalid())
10067 return Incompatible;
10069 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10070 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10071 result = IncompatibleObjCWeakRef;
10072 return result;
10073 }
10074
10075 // FIXME: Currently, we fall through and treat C++ classes like C
10076 // structures.
10077 // FIXME: We also fall through for atomics; not sure what should
10078 // happen there, though.
10079 } else if (RHS.get()->getType() == Context.OverloadTy) {
10080 // As a set of extensions to C, we support overloading on functions. These
10081 // functions need to be resolved here.
10082 DeclAccessPair DAP;
10084 RHS.get(), LHSType, /*Complain=*/false, DAP))
10085 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10086 else
10087 return Incompatible;
10088 }
10089
10090 // This check seems unnatural, however it is necessary to ensure the proper
10091 // conversion of functions/arrays. If the conversion were done for all
10092 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10093 // expressions that suppress this implicit conversion (&, sizeof). This needs
10094 // to happen before we check for null pointer conversions because C does not
10095 // undergo the same implicit conversions as C++ does above (by the calls to
10096 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10097 // lvalue to rvalue cast before checking for null pointer constraints. This
10098 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10099 //
10100 // Suppress this for references: C++ 8.5.3p5.
10101 if (!LHSType->isReferenceType()) {
10102 // FIXME: We potentially allocate here even if ConvertRHS is false.
10104 if (RHS.isInvalid())
10105 return Incompatible;
10106 }
10107
10108 // The constraints are expressed in terms of the atomic, qualified, or
10109 // unqualified type of the LHS.
10110 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10111
10112 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10113 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10114 if ((LHSTypeAfterConversion->isPointerType() ||
10115 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10116 LHSTypeAfterConversion->isBlockPointerType()) &&
10117 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10120 if (Diagnose || ConvertRHS) {
10121 CastKind Kind;
10122 CXXCastPath Path;
10123 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10124 /*IgnoreBaseAccess=*/false, Diagnose);
10125 if (ConvertRHS)
10126 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10127 }
10128 return Compatible;
10129 }
10130 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10131 // unqualified bool, and the right operand is a pointer or its type is
10132 // nullptr_t.
10133 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10134 RHS.get()->getType()->isNullPtrType()) {
10135 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10136 // only handles nullptr -> _Bool due to needing an extra conversion
10137 // step.
10138 // We model this by converting from nullptr -> void * and then let the
10139 // conversion from void * -> _Bool happen naturally.
10140 if (Diagnose || ConvertRHS) {
10141 CastKind Kind;
10142 CXXCastPath Path;
10143 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10144 /*IgnoreBaseAccess=*/false, Diagnose);
10145 if (ConvertRHS)
10146 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10147 &Path);
10148 }
10149 }
10150
10151 // OpenCL queue_t type assignment.
10152 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10154 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10155 return Compatible;
10156 }
10157
10158 CastKind Kind;
10160 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10161
10162 // C99 6.5.16.1p2: The value of the right operand is converted to the
10163 // type of the assignment expression.
10164 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10165 // so that we can use references in built-in functions even in C.
10166 // The getNonReferenceType() call makes sure that the resulting expression
10167 // does not have reference type.
10168 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10170 Expr *E = RHS.get();
10171
10172 // Check for various Objective-C errors. If we are not reporting
10173 // diagnostics and just checking for errors, e.g., during overload
10174 // resolution, return Incompatible to indicate the failure.
10175 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10178 DiagnoseCFAudited) != ACR_okay) {
10179 if (!Diagnose)
10180 return Incompatible;
10181 }
10182 if (getLangOpts().ObjC &&
10184 E->getType(), E, Diagnose) ||
10185 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10186 if (!Diagnose)
10187 return Incompatible;
10188 // Replace the expression with a corrected version and continue so we
10189 // can find further errors.
10190 RHS = E;
10191 return Compatible;
10192 }
10193
10194 if (ConvertRHS)
10195 RHS = ImpCastExprToType(E, Ty, Kind);
10196 }
10197
10198 return result;
10199}
10200
10201namespace {
10202/// The original operand to an operator, prior to the application of the usual
10203/// arithmetic conversions and converting the arguments of a builtin operator
10204/// candidate.
10205struct OriginalOperand {
10206 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10207 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10208 Op = MTE->getSubExpr();
10209 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10210 Op = BTE->getSubExpr();
10211 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10212 Orig = ICE->getSubExprAsWritten();
10213 Conversion = ICE->getConversionFunction();
10214 }
10215 }
10216
10217 QualType getType() const { return Orig->getType(); }
10218
10219 Expr *Orig;
10220 NamedDecl *Conversion;
10221};
10222}
10223
10225 ExprResult &RHS) {
10226 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10227
10228 Diag(Loc, diag::err_typecheck_invalid_operands)
10229 << OrigLHS.getType() << OrigRHS.getType()
10230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10231
10232 // If a user-defined conversion was applied to either of the operands prior
10233 // to applying the built-in operator rules, tell the user about it.
10234 if (OrigLHS.Conversion) {
10235 Diag(OrigLHS.Conversion->getLocation(),
10236 diag::note_typecheck_invalid_operands_converted)
10237 << 0 << LHS.get()->getType();
10238 }
10239 if (OrigRHS.Conversion) {
10240 Diag(OrigRHS.Conversion->getLocation(),
10241 diag::note_typecheck_invalid_operands_converted)
10242 << 1 << RHS.get()->getType();
10243 }
10244
10245 return QualType();
10246}
10247
10248// Diagnose cases where a scalar was implicitly converted to a vector and
10249// diagnose the underlying types. Otherwise, diagnose the error
10250// as invalid vector logical operands for non-C++ cases.
10252 ExprResult &RHS) {
10253 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10254 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10255
10256 bool LHSNatVec = LHSType->isVectorType();
10257 bool RHSNatVec = RHSType->isVectorType();
10258
10259 if (!(LHSNatVec && RHSNatVec)) {
10260 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10261 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10262 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10263 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10264 << Vector->getSourceRange();
10265 return QualType();
10266 }
10267
10268 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10269 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10270 << RHS.get()->getSourceRange();
10271
10272 return QualType();
10273}
10274
10275/// Try to convert a value of non-vector type to a vector type by converting
10276/// the type to the element type of the vector and then performing a splat.
10277/// If the language is OpenCL, we only use conversions that promote scalar
10278/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10279/// for float->int.
10280///
10281/// OpenCL V2.0 6.2.6.p2:
10282/// An error shall occur if any scalar operand type has greater rank
10283/// than the type of the vector element.
10284///
10285/// \param scalar - if non-null, actually perform the conversions
10286/// \return true if the operation fails (but without diagnosing the failure)
10288 QualType scalarTy,
10289 QualType vectorEltTy,
10290 QualType vectorTy,
10291 unsigned &DiagID) {
10292 // The conversion to apply to the scalar before splatting it,
10293 // if necessary.
10294 CastKind scalarCast = CK_NoOp;
10295
10296 if (vectorEltTy->isIntegralType(S.Context)) {
10297 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10298 (scalarTy->isIntegerType() &&
10299 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10300 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10301 return true;
10302 }
10303 if (!scalarTy->isIntegralType(S.Context))
10304 return true;
10305 scalarCast = CK_IntegralCast;
10306 } else if (vectorEltTy->isRealFloatingType()) {
10307 if (scalarTy->isRealFloatingType()) {
10308 if (S.getLangOpts().OpenCL &&
10309 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10310 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10311 return true;
10312 }
10313 scalarCast = CK_FloatingCast;
10314 }
10315 else if (scalarTy->isIntegralType(S.Context))
10316 scalarCast = CK_IntegralToFloating;
10317 else
10318 return true;
10319 } else {
10320 return true;
10321 }
10322
10323 // Adjust scalar if desired.
10324 if (scalar) {
10325 if (scalarCast != CK_NoOp)
10326 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10327 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10328 }
10329 return false;
10330}
10331
10332/// Convert vector E to a vector with the same number of elements but different
10333/// element type.
10334static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10335 const auto *VecTy = E->getType()->getAs<VectorType>();
10336 assert(VecTy && "Expression E must be a vector");
10337 QualType NewVecTy =
10338 VecTy->isExtVectorType()
10339 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10340 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10341 VecTy->getVectorKind());
10342
10343 // Look through the implicit cast. Return the subexpression if its type is
10344 // NewVecTy.
10345 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10346 if (ICE->getSubExpr()->getType() == NewVecTy)
10347 return ICE->getSubExpr();
10348
10349 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10350 return S.ImpCastExprToType(E, NewVecTy, Cast);
10351}
10352
10353/// Test if a (constant) integer Int can be casted to another integer type
10354/// IntTy without losing precision.
10356 QualType OtherIntTy) {
10357 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10358
10359 // Reject cases where the value of the Int is unknown as that would
10360 // possibly cause truncation, but accept cases where the scalar can be
10361 // demoted without loss of precision.
10362 Expr::EvalResult EVResult;
10363 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10364 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10365 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10366 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10367
10368 if (CstInt) {
10369 // If the scalar is constant and is of a higher order and has more active
10370 // bits that the vector element type, reject it.
10371 llvm::APSInt Result = EVResult.Val.getInt();
10372 unsigned NumBits = IntSigned
10373 ? (Result.isNegative() ? Result.getSignificantBits()
10374 : Result.getActiveBits())
10375 : Result.getActiveBits();
10376 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10377 return true;
10378
10379 // If the signedness of the scalar type and the vector element type
10380 // differs and the number of bits is greater than that of the vector
10381 // element reject it.
10382 return (IntSigned != OtherIntSigned &&
10383 NumBits > S.Context.getIntWidth(OtherIntTy));
10384 }
10385
10386 // Reject cases where the value of the scalar is not constant and it's
10387 // order is greater than that of the vector element type.
10388 return (Order < 0);
10389}
10390
10391/// Test if a (constant) integer Int can be casted to floating point type
10392/// FloatTy without losing precision.
10394 QualType FloatTy) {
10395 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10396
10397 // Determine if the integer constant can be expressed as a floating point
10398 // number of the appropriate type.
10399 Expr::EvalResult EVResult;
10400 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10401
10402 uint64_t Bits = 0;
10403 if (CstInt) {
10404 // Reject constants that would be truncated if they were converted to
10405 // the floating point type. Test by simple to/from conversion.
10406 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10407 // could be avoided if there was a convertFromAPInt method
10408 // which could signal back if implicit truncation occurred.
10409 llvm::APSInt Result = EVResult.Val.getInt();
10410 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10411 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10412 llvm::APFloat::rmTowardZero);
10413 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10415 bool Ignored = false;
10416 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10417 &Ignored);
10418 if (Result != ConvertBack)
10419 return true;
10420 } else {
10421 // Reject types that cannot be fully encoded into the mantissa of
10422 // the float.
10423 Bits = S.Context.getTypeSize(IntTy);
10424 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10425 S.Context.getFloatTypeSemantics(FloatTy));
10426 if (Bits > FloatPrec)
10427 return true;
10428 }
10429
10430 return false;
10431}
10432
10433/// Attempt to convert and splat Scalar into a vector whose types matches
10434/// Vector following GCC conversion rules. The rule is that implicit
10435/// conversion can occur when Scalar can be casted to match Vector's element
10436/// type without causing truncation of Scalar.
10438 ExprResult *Vector) {
10439 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10440 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10441 QualType VectorEltTy;
10442
10443 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10444 assert(!isa<ExtVectorType>(VT) &&
10445 "ExtVectorTypes should not be handled here!");
10446 VectorEltTy = VT->getElementType();
10447 } else if (VectorTy->isSveVLSBuiltinType()) {
10448 VectorEltTy =
10449 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10450 } else {
10451 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10452 }
10453
10454 // Reject cases where the vector element type or the scalar element type are
10455 // not integral or floating point types.
10456 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10457 return true;
10458
10459 // The conversion to apply to the scalar before splatting it,
10460 // if necessary.
10461 CastKind ScalarCast = CK_NoOp;
10462
10463 // Accept cases where the vector elements are integers and the scalar is
10464 // an integer.
10465 // FIXME: Notionally if the scalar was a floating point value with a precise
10466 // integral representation, we could cast it to an appropriate integer
10467 // type and then perform the rest of the checks here. GCC will perform
10468 // this conversion in some cases as determined by the input language.
10469 // We should accept it on a language independent basis.
10470 if (VectorEltTy->isIntegralType(S.Context) &&
10471 ScalarTy->isIntegralType(S.Context) &&
10472 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10473
10474 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10475 return true;
10476
10477 ScalarCast = CK_IntegralCast;
10478 } else if (VectorEltTy->isIntegralType(S.Context) &&
10479 ScalarTy->isRealFloatingType()) {
10480 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10481 ScalarCast = CK_FloatingToIntegral;
10482 else
10483 return true;
10484 } else if (VectorEltTy->isRealFloatingType()) {
10485 if (ScalarTy->isRealFloatingType()) {
10486
10487 // Reject cases where the scalar type is not a constant and has a higher
10488 // Order than the vector element type.
10489 llvm::APFloat Result(0.0);
10490
10491 // Determine whether this is a constant scalar. In the event that the
10492 // value is dependent (and thus cannot be evaluated by the constant
10493 // evaluator), skip the evaluation. This will then diagnose once the
10494 // expression is instantiated.
10495 bool CstScalar = Scalar->get()->isValueDependent() ||
10496 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10497 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10498 if (!CstScalar && Order < 0)
10499 return true;
10500
10501 // If the scalar cannot be safely casted to the vector element type,
10502 // reject it.
10503 if (CstScalar) {
10504 bool Truncated = false;
10505 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10506 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10507 if (Truncated)
10508 return true;
10509 }
10510
10511 ScalarCast = CK_FloatingCast;
10512 } else if (ScalarTy->isIntegralType(S.Context)) {
10513 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10514 return true;
10515
10516 ScalarCast = CK_IntegralToFloating;
10517 } else
10518 return true;
10519 } else if (ScalarTy->isEnumeralType())
10520 return true;
10521
10522 // Adjust scalar if desired.
10523 if (ScalarCast != CK_NoOp)
10524 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10525 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10526 return false;
10527}
10528
10530 SourceLocation Loc, bool IsCompAssign,
10531 bool AllowBothBool,
10532 bool AllowBoolConversions,
10533 bool AllowBoolOperation,
10534 bool ReportInvalid) {
10535 if (!IsCompAssign) {
10537 if (LHS.isInvalid())
10538 return QualType();
10539 }
10541 if (RHS.isInvalid())
10542 return QualType();
10543
10544 // For conversion purposes, we ignore any qualifiers.
10545 // For example, "const float" and "float" are equivalent.
10546 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10547 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10548
10549 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10550 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10551 assert(LHSVecType || RHSVecType);
10552
10553 // AltiVec-style "vector bool op vector bool" combinations are allowed
10554 // for some operators but not others.
10555 if (!AllowBothBool && LHSVecType &&
10556 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10557 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10558 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10559
10560 // This operation may not be performed on boolean vectors.
10561 if (!AllowBoolOperation &&
10562 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10563 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10564
10565 // If the vector types are identical, return.
10566 if (Context.hasSameType(LHSType, RHSType))
10567 return Context.getCommonSugaredType(LHSType, RHSType);
10568
10569 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10570 if (LHSVecType && RHSVecType &&
10571 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10572 if (isa<ExtVectorType>(LHSVecType)) {
10573 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10574 return LHSType;
10575 }
10576
10577 if (!IsCompAssign)
10578 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10579 return RHSType;
10580 }
10581
10582 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10583 // can be mixed, with the result being the non-bool type. The non-bool
10584 // operand must have integer element type.
10585 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10586 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10587 (Context.getTypeSize(LHSVecType->getElementType()) ==
10588 Context.getTypeSize(RHSVecType->getElementType()))) {
10589 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10590 LHSVecType->getElementType()->isIntegerType() &&
10591 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10592 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10593 return LHSType;
10594 }
10595 if (!IsCompAssign &&
10596 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10597 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10598 RHSVecType->getElementType()->isIntegerType()) {
10599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10600 return RHSType;
10601 }
10602 }
10603
10604 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10605 // invalid since the ambiguity can affect the ABI.
10606 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10607 unsigned &SVEorRVV) {
10608 const VectorType *VecType = SecondType->getAs<VectorType>();
10609 SVEorRVV = 0;
10610 if (FirstType->isSizelessBuiltinType() && VecType) {
10613 return true;
10616 SVEorRVV = 1;
10617 return true;
10618 }
10619 }
10620
10621 return false;
10622 };
10623
10624 unsigned SVEorRVV;
10625 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10626 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10627 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10628 << SVEorRVV << LHSType << RHSType;
10629 return QualType();
10630 }
10631
10632 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10633 // invalid since the ambiguity can affect the ABI.
10634 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10635 unsigned &SVEorRVV) {
10636 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10637 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10638
10639 SVEorRVV = 0;
10640 if (FirstVecType && SecondVecType) {
10641 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10642 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10643 SecondVecType->getVectorKind() ==
10645 return true;
10646 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10647 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10648 SVEorRVV = 1;
10649 return true;
10650 }
10651 }
10652 return false;
10653 }
10654
10655 if (SecondVecType &&
10656 SecondVecType->getVectorKind() == VectorKind::Generic) {
10657 if (FirstType->isSVESizelessBuiltinType())
10658 return true;
10659 if (FirstType->isRVVSizelessBuiltinType()) {
10660 SVEorRVV = 1;
10661 return true;
10662 }
10663 }
10664
10665 return false;
10666 };
10667
10668 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10669 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10670 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10671 << SVEorRVV << LHSType << RHSType;
10672 return QualType();
10673 }
10674
10675 // If there's a vector type and a scalar, try to convert the scalar to
10676 // the vector element type and splat.
10677 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10678 if (!RHSVecType) {
10679 if (isa<ExtVectorType>(LHSVecType)) {
10680 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10681 LHSVecType->getElementType(), LHSType,
10682 DiagID))
10683 return LHSType;
10684 } else {
10685 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10686 return LHSType;
10687 }
10688 }
10689 if (!LHSVecType) {
10690 if (isa<ExtVectorType>(RHSVecType)) {
10691 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10692 LHSType, RHSVecType->getElementType(),
10693 RHSType, DiagID))
10694 return RHSType;
10695 } else {
10696 if (LHS.get()->isLValue() ||
10697 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10698 return RHSType;
10699 }
10700 }
10701
10702 // FIXME: The code below also handles conversion between vectors and
10703 // non-scalars, we should break this down into fine grained specific checks
10704 // and emit proper diagnostics.
10705 QualType VecType = LHSVecType ? LHSType : RHSType;
10706 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10707 QualType OtherType = LHSVecType ? RHSType : LHSType;
10708 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10709 if (isLaxVectorConversion(OtherType, VecType)) {
10710 if (Context.getTargetInfo().getTriple().isPPC() &&
10711 anyAltivecTypes(RHSType, LHSType) &&
10712 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10713 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10714 // If we're allowing lax vector conversions, only the total (data) size
10715 // needs to be the same. For non compound assignment, if one of the types is
10716 // scalar, the result is always the vector type.
10717 if (!IsCompAssign) {
10718 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10719 return VecType;
10720 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10721 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10722 // type. Note that this is already done by non-compound assignments in
10723 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10724 // <1 x T> -> T. The result is also a vector type.
10725 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10726 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10727 ExprResult *RHSExpr = &RHS;
10728 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10729 return VecType;
10730 }
10731 }
10732
10733 // Okay, the expression is invalid.
10734
10735 // If there's a non-vector, non-real operand, diagnose that.
10736 if ((!RHSVecType && !RHSType->isRealType()) ||
10737 (!LHSVecType && !LHSType->isRealType())) {
10738 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10739 << LHSType << RHSType
10740 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10741 return QualType();
10742 }
10743
10744 // OpenCL V1.1 6.2.6.p1:
10745 // If the operands are of more than one vector type, then an error shall
10746 // occur. Implicit conversions between vector types are not permitted, per
10747 // section 6.2.1.
10748 if (getLangOpts().OpenCL &&
10749 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10750 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10751 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10752 << RHSType;
10753 return QualType();
10754 }
10755
10756
10757 // If there is a vector type that is not a ExtVector and a scalar, we reach
10758 // this point if scalar could not be converted to the vector's element type
10759 // without truncation.
10760 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10761 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10762 QualType Scalar = LHSVecType ? RHSType : LHSType;
10763 QualType Vector = LHSVecType ? LHSType : RHSType;
10764 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10765 Diag(Loc,
10766 diag::err_typecheck_vector_not_convertable_implict_truncation)
10767 << ScalarOrVector << Scalar << Vector;
10768
10769 return QualType();
10770 }
10771
10772 // Otherwise, use the generic diagnostic.
10773 Diag(Loc, DiagID)
10774 << LHSType << RHSType
10775 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10776 return QualType();
10777}
10778
10780 SourceLocation Loc,
10781 bool IsCompAssign,
10782 ArithConvKind OperationKind) {
10783 if (!IsCompAssign) {
10785 if (LHS.isInvalid())
10786 return QualType();
10787 }
10789 if (RHS.isInvalid())
10790 return QualType();
10791
10792 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10793 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10794
10795 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10796 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10797
10798 unsigned DiagID = diag::err_typecheck_invalid_operands;
10799 if ((OperationKind == ACK_Arithmetic) &&
10800 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10801 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10802 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10803 << RHS.get()->getSourceRange();
10804 return QualType();
10805 }
10806
10807 if (Context.hasSameType(LHSType, RHSType))
10808 return LHSType;
10809
10810 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10811 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10812 return LHSType;
10813 }
10814 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10815 if (LHS.get()->isLValue() ||
10816 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10817 return RHSType;
10818 }
10819
10820 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10821 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10822 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10823 << LHSType << RHSType << LHS.get()->getSourceRange()
10824 << RHS.get()->getSourceRange();
10825 return QualType();
10826 }
10827
10828 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10829 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10830 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10831 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10832 << LHSType << RHSType << LHS.get()->getSourceRange()
10833 << RHS.get()->getSourceRange();
10834 return QualType();
10835 }
10836
10837 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10838 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10839 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10840 bool ScalarOrVector =
10841 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10842
10843 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10844 << ScalarOrVector << Scalar << Vector;
10845
10846 return QualType();
10847 }
10848
10849 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10850 << RHS.get()->getSourceRange();
10851 return QualType();
10852}
10853
10854// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10855// expression. These are mainly cases where the null pointer is used as an
10856// integer instead of a pointer.
10858 SourceLocation Loc, bool IsCompare) {
10859 // The canonical way to check for a GNU null is with isNullPointerConstant,
10860 // but we use a bit of a hack here for speed; this is a relatively
10861 // hot path, and isNullPointerConstant is slow.
10862 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10863 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10864
10865 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10866
10867 // Avoid analyzing cases where the result will either be invalid (and
10868 // diagnosed as such) or entirely valid and not something to warn about.
10869 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10870 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10871 return;
10872
10873 // Comparison operations would not make sense with a null pointer no matter
10874 // what the other expression is.
10875 if (!IsCompare) {
10876 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10877 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10878 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10879 return;
10880 }
10881
10882 // The rest of the operations only make sense with a null pointer
10883 // if the other expression is a pointer.
10884 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10885 NonNullType->canDecayToPointerType())
10886 return;
10887
10888 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10889 << LHSNull /* LHS is NULL */ << NonNullType
10890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10891}
10892
10894 SourceLocation Loc) {
10895 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10896 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10897 if (!LUE || !RUE)
10898 return;
10899 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10900 RUE->getKind() != UETT_SizeOf)
10901 return;
10902
10903 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10904 QualType LHSTy = LHSArg->getType();
10905 QualType RHSTy;
10906
10907 if (RUE->isArgumentType())
10908 RHSTy = RUE->getArgumentType().getNonReferenceType();
10909 else
10910 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10911
10912 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10913 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10914 return;
10915
10916 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10917 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10918 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10919 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10920 << LHSArgDecl;
10921 }
10922 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10923 QualType ArrayElemTy = ArrayTy->getElementType();
10924 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10925 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10926 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10927 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10928 return;
10929 S.Diag(Loc, diag::warn_division_sizeof_array)
10930 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10931 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10932 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10933 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10934 << LHSArgDecl;
10935 }
10936
10937 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10938 }
10939}
10940
10942 ExprResult &RHS,
10943 SourceLocation Loc, bool IsDiv) {
10944 // Check for division/remainder by zero.
10945 Expr::EvalResult RHSValue;
10946 if (!RHS.get()->isValueDependent() &&
10947 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10948 RHSValue.Val.getInt() == 0)
10949 S.DiagRuntimeBehavior(Loc, RHS.get(),
10950 S.PDiag(diag::warn_remainder_division_by_zero)
10951 << IsDiv << RHS.get()->getSourceRange());
10952}
10953
10955 SourceLocation Loc,
10956 bool IsCompAssign, bool IsDiv) {
10957 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10958
10959 QualType LHSTy = LHS.get()->getType();
10960 QualType RHSTy = RHS.get()->getType();
10961 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10962 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10963 /*AllowBothBool*/ getLangOpts().AltiVec,
10964 /*AllowBoolConversions*/ false,
10965 /*AllowBooleanOperation*/ false,
10966 /*ReportInvalid*/ true);
10967 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10968 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10970 if (!IsDiv &&
10971 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10972 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10973 // For division, only matrix-by-scalar is supported. Other combinations with
10974 // matrix types are invalid.
10975 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10976 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10977
10979 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10980 if (LHS.isInvalid() || RHS.isInvalid())
10981 return QualType();
10982
10983
10984 if (compType.isNull() || !compType->isArithmeticType())
10985 return InvalidOperands(Loc, LHS, RHS);
10986 if (IsDiv) {
10987 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10988 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10989 }
10990 return compType;
10991}
10992
10994 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10995 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10996
10997 if (LHS.get()->getType()->isVectorType() ||
10998 RHS.get()->getType()->isVectorType()) {
10999 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11001 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11002 /*AllowBothBool*/ getLangOpts().AltiVec,
11003 /*AllowBoolConversions*/ false,
11004 /*AllowBooleanOperation*/ false,
11005 /*ReportInvalid*/ true);
11006 return InvalidOperands(Loc, LHS, RHS);
11007 }
11008
11009 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11010 RHS.get()->getType()->isSveVLSBuiltinType()) {
11011 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11013 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11015
11016 return InvalidOperands(Loc, LHS, RHS);
11017 }
11018
11020 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11021 if (LHS.isInvalid() || RHS.isInvalid())
11022 return QualType();
11023
11024 if (compType.isNull() || !compType->isIntegerType())
11025 return InvalidOperands(Loc, LHS, RHS);
11026 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11027 return compType;
11028}
11029
11030/// Diagnose invalid arithmetic on two void pointers.
11032 Expr *LHSExpr, Expr *RHSExpr) {
11033 S.Diag(Loc, S.getLangOpts().CPlusPlus
11034 ? diag::err_typecheck_pointer_arith_void_type
11035 : diag::ext_gnu_void_ptr)
11036 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11037 << RHSExpr->getSourceRange();
11038}
11039
11040/// Diagnose invalid arithmetic on a void pointer.
11042 Expr *Pointer) {
11043 S.Diag(Loc, S.getLangOpts().CPlusPlus
11044 ? diag::err_typecheck_pointer_arith_void_type
11045 : diag::ext_gnu_void_ptr)
11046 << 0 /* one pointer */ << Pointer->getSourceRange();
11047}
11048
11049/// Diagnose invalid arithmetic on a null pointer.
11050///
11051/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11052/// idiom, which we recognize as a GNU extension.
11053///
11055 Expr *Pointer, bool IsGNUIdiom) {
11056 if (IsGNUIdiom)
11057 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11058 << Pointer->getSourceRange();
11059 else
11060 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11061 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11062}
11063
11064/// Diagnose invalid subraction on a null pointer.
11065///
11067 Expr *Pointer, bool BothNull) {
11068 // Null - null is valid in C++ [expr.add]p7
11069 if (BothNull && S.getLangOpts().CPlusPlus)
11070 return;
11071
11072 // Is this s a macro from a system header?
11074 return;
11075
11077 S.PDiag(diag::warn_pointer_sub_null_ptr)
11078 << S.getLangOpts().CPlusPlus
11079 << Pointer->getSourceRange());
11080}
11081
11082/// Diagnose invalid arithmetic on two function pointers.
11084 Expr *LHS, Expr *RHS) {
11085 assert(LHS->getType()->isAnyPointerType());
11086 assert(RHS->getType()->isAnyPointerType());
11087 S.Diag(Loc, S.getLangOpts().CPlusPlus
11088 ? diag::err_typecheck_pointer_arith_function_type
11089 : diag::ext_gnu_ptr_func_arith)
11090 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11091 // We only show the second type if it differs from the first.
11093 RHS->getType())
11094 << RHS->getType()->getPointeeType()
11095 << LHS->getSourceRange() << RHS->getSourceRange();
11096}
11097
11098/// Diagnose invalid arithmetic on a function pointer.
11100 Expr *Pointer) {
11101 assert(Pointer->getType()->isAnyPointerType());
11102 S.Diag(Loc, S.getLangOpts().CPlusPlus
11103 ? diag::err_typecheck_pointer_arith_function_type
11104 : diag::ext_gnu_ptr_func_arith)
11105 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11106 << 0 /* one pointer, so only one type */
11107 << Pointer->getSourceRange();
11108}
11109
11110/// Emit error if Operand is incomplete pointer type
11111///
11112/// \returns True if pointer has incomplete type
11114 Expr *Operand) {
11115 QualType ResType = Operand->getType();
11116 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11117 ResType = ResAtomicType->getValueType();
11118
11119 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11120 QualType PointeeTy = ResType->getPointeeType();
11121 return S.RequireCompleteSizedType(
11122 Loc, PointeeTy,
11123 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11124 Operand->getSourceRange());
11125}
11126
11127/// Check the validity of an arithmetic pointer operand.
11128///
11129/// If the operand has pointer type, this code will check for pointer types
11130/// which are invalid in arithmetic operations. These will be diagnosed
11131/// appropriately, including whether or not the use is supported as an
11132/// extension.
11133///
11134/// \returns True when the operand is valid to use (even if as an extension).
11136 Expr *Operand) {
11137 QualType ResType = Operand->getType();
11138 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11139 ResType = ResAtomicType->getValueType();
11140
11141 if (!ResType->isAnyPointerType()) return true;
11142
11143 QualType PointeeTy = ResType->getPointeeType();
11144 if (PointeeTy->isVoidType()) {
11145 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11146 return !S.getLangOpts().CPlusPlus;
11147 }
11148 if (PointeeTy->isFunctionType()) {
11149 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11150 return !S.getLangOpts().CPlusPlus;
11151 }
11152
11153 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11154
11155 return true;
11156}
11157
11158/// Check the validity of a binary arithmetic operation w.r.t. pointer
11159/// operands.
11160///
11161/// This routine will diagnose any invalid arithmetic on pointer operands much
11162/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11163/// for emitting a single diagnostic even for operations where both LHS and RHS
11164/// are (potentially problematic) pointers.
11165///
11166/// \returns True when the operand is valid to use (even if as an extension).
11168 Expr *LHSExpr, Expr *RHSExpr) {
11169 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11170 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11171 if (!isLHSPointer && !isRHSPointer) return true;
11172
11173 QualType LHSPointeeTy, RHSPointeeTy;
11174 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11175 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11176
11177 // if both are pointers check if operation is valid wrt address spaces
11178 if (isLHSPointer && isRHSPointer) {
11179 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11180 S.Diag(Loc,
11181 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11182 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11183 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11184 return false;
11185 }
11186 }
11187
11188 // Check for arithmetic on pointers to incomplete types.
11189 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11190 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11191 if (isLHSVoidPtr || isRHSVoidPtr) {
11192 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11193 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11194 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11195
11196 return !S.getLangOpts().CPlusPlus;
11197 }
11198
11199 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11200 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11201 if (isLHSFuncPtr || isRHSFuncPtr) {
11202 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11203 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11204 RHSExpr);
11205 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11206
11207 return !S.getLangOpts().CPlusPlus;
11208 }
11209
11210 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11211 return false;
11212 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11213 return false;
11214
11215 return true;
11216}
11217
11218/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11219/// literal.
11221 Expr *LHSExpr, Expr *RHSExpr) {
11222 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11223 Expr* IndexExpr = RHSExpr;
11224 if (!StrExpr) {
11225 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11226 IndexExpr = LHSExpr;
11227 }
11228
11229 bool IsStringPlusInt = StrExpr &&
11231 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11232 return;
11233
11234 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11235 Self.Diag(OpLoc, diag::warn_string_plus_int)
11236 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11237
11238 // Only print a fixit for "str" + int, not for int + "str".
11239 if (IndexExpr == RHSExpr) {
11240 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11241 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11242 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11244 << FixItHint::CreateInsertion(EndLoc, "]");
11245 } else
11246 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11247}
11248
11249/// Emit a warning when adding a char literal to a string.
11251 Expr *LHSExpr, Expr *RHSExpr) {
11252 const Expr *StringRefExpr = LHSExpr;
11253 const CharacterLiteral *CharExpr =
11254 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11255
11256 if (!CharExpr) {
11257 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11258 StringRefExpr = RHSExpr;
11259 }
11260
11261 if (!CharExpr || !StringRefExpr)
11262 return;
11263
11264 const QualType StringType = StringRefExpr->getType();
11265
11266 // Return if not a PointerType.
11267 if (!StringType->isAnyPointerType())
11268 return;
11269
11270 // Return if not a CharacterType.
11271 if (!StringType->getPointeeType()->isAnyCharacterType())
11272 return;
11273
11274 ASTContext &Ctx = Self.getASTContext();
11275 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11276
11277 const QualType CharType = CharExpr->getType();
11278 if (!CharType->isAnyCharacterType() &&
11279 CharType->isIntegerType() &&
11280 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11281 Self.Diag(OpLoc, diag::warn_string_plus_char)
11282 << DiagRange << Ctx.CharTy;
11283 } else {
11284 Self.Diag(OpLoc, diag::warn_string_plus_char)
11285 << DiagRange << CharExpr->getType();
11286 }
11287
11288 // Only print a fixit for str + char, not for char + str.
11289 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11290 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11291 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11292 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11294 << FixItHint::CreateInsertion(EndLoc, "]");
11295 } else {
11296 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11297 }
11298}
11299
11300/// Emit error when two pointers are incompatible.
11302 Expr *LHSExpr, Expr *RHSExpr) {
11303 assert(LHSExpr->getType()->isAnyPointerType());
11304 assert(RHSExpr->getType()->isAnyPointerType());
11305 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11306 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11307 << RHSExpr->getSourceRange();
11308}
11309
11310// C99 6.5.6
11313 QualType* CompLHSTy) {
11314 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11315
11316 if (LHS.get()->getType()->isVectorType() ||
11317 RHS.get()->getType()->isVectorType()) {
11318 QualType compType =
11319 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11320 /*AllowBothBool*/ getLangOpts().AltiVec,
11321 /*AllowBoolConversions*/ getLangOpts().ZVector,
11322 /*AllowBooleanOperation*/ false,
11323 /*ReportInvalid*/ true);
11324 if (CompLHSTy) *CompLHSTy = compType;
11325 return compType;
11326 }
11327
11328 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11329 RHS.get()->getType()->isSveVLSBuiltinType()) {
11330 QualType compType =
11331 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11332 if (CompLHSTy)
11333 *CompLHSTy = compType;
11334 return compType;
11335 }
11336
11337 if (LHS.get()->getType()->isConstantMatrixType() ||
11338 RHS.get()->getType()->isConstantMatrixType()) {
11339 QualType compType =
11340 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11341 if (CompLHSTy)
11342 *CompLHSTy = compType;
11343 return compType;
11344 }
11345
11347 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11348 if (LHS.isInvalid() || RHS.isInvalid())
11349 return QualType();
11350
11351 // Diagnose "string literal" '+' int and string '+' "char literal".
11352 if (Opc == BO_Add) {
11353 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11354 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11355 }
11356
11357 // handle the common case first (both operands are arithmetic).
11358 if (!compType.isNull() && compType->isArithmeticType()) {
11359 if (CompLHSTy) *CompLHSTy = compType;
11360 return compType;
11361 }
11362
11363 // Type-checking. Ultimately the pointer's going to be in PExp;
11364 // note that we bias towards the LHS being the pointer.
11365 Expr *PExp = LHS.get(), *IExp = RHS.get();
11366
11367 bool isObjCPointer;
11368 if (PExp->getType()->isPointerType()) {
11369 isObjCPointer = false;
11370 } else if (PExp->getType()->isObjCObjectPointerType()) {
11371 isObjCPointer = true;
11372 } else {
11373 std::swap(PExp, IExp);
11374 if (PExp->getType()->isPointerType()) {
11375 isObjCPointer = false;
11376 } else if (PExp->getType()->isObjCObjectPointerType()) {
11377 isObjCPointer = true;
11378 } else {
11379 return InvalidOperands(Loc, LHS, RHS);
11380 }
11381 }
11382 assert(PExp->getType()->isAnyPointerType());
11383
11384 if (!IExp->getType()->isIntegerType())
11385 return InvalidOperands(Loc, LHS, RHS);
11386
11387 // Adding to a null pointer results in undefined behavior.
11390 // In C++ adding zero to a null pointer is defined.
11391 Expr::EvalResult KnownVal;
11392 if (!getLangOpts().CPlusPlus ||
11393 (!IExp->isValueDependent() &&
11394 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11395 KnownVal.Val.getInt() != 0))) {
11396 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11398 Context, BO_Add, PExp, IExp);
11399 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11400 }
11401 }
11402
11403 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11404 return QualType();
11405
11406 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11407 return QualType();
11408
11409 // Check array bounds for pointer arithemtic
11410 CheckArrayAccess(PExp, IExp);
11411
11412 if (CompLHSTy) {
11414 if (LHSTy.isNull()) {
11415 LHSTy = LHS.get()->getType();
11417 LHSTy = Context.getPromotedIntegerType(LHSTy);
11418 }
11419 *CompLHSTy = LHSTy;
11420 }
11421
11422 return PExp->getType();
11423}
11424
11425// C99 6.5.6
11427 SourceLocation Loc,
11428 QualType* CompLHSTy) {
11429 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11430
11431 if (LHS.get()->getType()->isVectorType() ||
11432 RHS.get()->getType()->isVectorType()) {
11433 QualType compType =
11434 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11435 /*AllowBothBool*/ getLangOpts().AltiVec,
11436 /*AllowBoolConversions*/ getLangOpts().ZVector,
11437 /*AllowBooleanOperation*/ false,
11438 /*ReportInvalid*/ true);
11439 if (CompLHSTy) *CompLHSTy = compType;
11440 return compType;
11441 }
11442
11443 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11444 RHS.get()->getType()->isSveVLSBuiltinType()) {
11445 QualType compType =
11446 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11447 if (CompLHSTy)
11448 *CompLHSTy = compType;
11449 return compType;
11450 }
11451
11452 if (LHS.get()->getType()->isConstantMatrixType() ||
11453 RHS.get()->getType()->isConstantMatrixType()) {
11454 QualType compType =
11455 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11456 if (CompLHSTy)
11457 *CompLHSTy = compType;
11458 return compType;
11459 }
11460
11462 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11463 if (LHS.isInvalid() || RHS.isInvalid())
11464 return QualType();
11465
11466 // Enforce type constraints: C99 6.5.6p3.
11467
11468 // Handle the common case first (both operands are arithmetic).
11469 if (!compType.isNull() && compType->isArithmeticType()) {
11470 if (CompLHSTy) *CompLHSTy = compType;
11471 return compType;
11472 }
11473
11474 // Either ptr - int or ptr - ptr.
11475 if (LHS.get()->getType()->isAnyPointerType()) {
11476 QualType lpointee = LHS.get()->getType()->getPointeeType();
11477
11478 // Diagnose bad cases where we step over interface counts.
11479 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11480 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11481 return QualType();
11482
11483 // The result type of a pointer-int computation is the pointer type.
11484 if (RHS.get()->getType()->isIntegerType()) {
11485 // Subtracting from a null pointer should produce a warning.
11486 // The last argument to the diagnose call says this doesn't match the
11487 // GNU int-to-pointer idiom.
11490 // In C++ adding zero to a null pointer is defined.
11491 Expr::EvalResult KnownVal;
11492 if (!getLangOpts().CPlusPlus ||
11493 (!RHS.get()->isValueDependent() &&
11494 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11495 KnownVal.Val.getInt() != 0))) {
11496 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11497 }
11498 }
11499
11500 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11501 return QualType();
11502
11503 // Check array bounds for pointer arithemtic
11504 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11505 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11506
11507 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11508 return LHS.get()->getType();
11509 }
11510
11511 // Handle pointer-pointer subtractions.
11512 if (const PointerType *RHSPTy
11513 = RHS.get()->getType()->getAs<PointerType>()) {
11514 QualType rpointee = RHSPTy->getPointeeType();
11515
11516 if (getLangOpts().CPlusPlus) {
11517 // Pointee types must be the same: C++ [expr.add]
11518 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11519 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11520 }
11521 } else {
11522 // Pointee types must be compatible C99 6.5.6p3
11526 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11527 return QualType();
11528 }
11529 }
11530
11532 LHS.get(), RHS.get()))
11533 return QualType();
11534
11535 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11537 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11539
11540 // Subtracting nullptr or from nullptr is suspect
11541 if (LHSIsNullPtr)
11542 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11543 if (RHSIsNullPtr)
11544 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11545
11546 // The pointee type may have zero size. As an extension, a structure or
11547 // union may have zero size or an array may have zero length. In this
11548 // case subtraction does not make sense.
11549 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11550 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11551 if (ElementSize.isZero()) {
11552 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11553 << rpointee.getUnqualifiedType()
11554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11555 }
11556 }
11557
11558 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11559 return Context.getPointerDiffType();
11560 }
11561 }
11562
11563 return InvalidOperands(Loc, LHS, RHS);
11564}
11565
11567 if (const EnumType *ET = T->getAs<EnumType>())
11568 return ET->getDecl()->isScoped();
11569 return false;
11570}
11571
11574 QualType LHSType) {
11575 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11576 // so skip remaining warnings as we don't want to modify values within Sema.
11577 if (S.getLangOpts().OpenCL)
11578 return;
11579
11580 // Check right/shifter operand
11581 Expr::EvalResult RHSResult;
11582 if (RHS.get()->isValueDependent() ||
11583 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11584 return;
11585 llvm::APSInt Right = RHSResult.Val.getInt();
11586
11587 if (Right.isNegative()) {
11588 S.DiagRuntimeBehavior(Loc, RHS.get(),
11589 S.PDiag(diag::warn_shift_negative)
11590 << RHS.get()->getSourceRange());
11591 return;
11592 }
11593
11594 QualType LHSExprType = LHS.get()->getType();
11595 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11596 if (LHSExprType->isBitIntType())
11597 LeftSize = S.Context.getIntWidth(LHSExprType);
11598 else if (LHSExprType->isFixedPointType()) {
11599 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11600 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11601 }
11602 if (Right.uge(LeftSize)) {
11603 S.DiagRuntimeBehavior(Loc, RHS.get(),
11604 S.PDiag(diag::warn_shift_gt_typewidth)
11605 << RHS.get()->getSourceRange());
11606 return;
11607 }
11608
11609 // FIXME: We probably need to handle fixed point types specially here.
11610 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11611 return;
11612
11613 // When left shifting an ICE which is signed, we can check for overflow which
11614 // according to C++ standards prior to C++2a has undefined behavior
11615 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11616 // more than the maximum value representable in the result type, so never
11617 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11618 // expression is still probably a bug.)
11619 Expr::EvalResult LHSResult;
11620 if (LHS.get()->isValueDependent() ||
11622 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11623 return;
11624 llvm::APSInt Left = LHSResult.Val.getInt();
11625
11626 // Don't warn if signed overflow is defined, then all the rest of the
11627 // diagnostics will not be triggered because the behavior is defined.
11628 // Also don't warn in C++20 mode (and newer), as signed left shifts
11629 // always wrap and never overflow.
11630 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11631 return;
11632
11633 // If LHS does not have a non-negative value then, the
11634 // behavior is undefined before C++2a. Warn about it.
11635 if (Left.isNegative()) {
11636 S.DiagRuntimeBehavior(Loc, LHS.get(),
11637 S.PDiag(diag::warn_shift_lhs_negative)
11638 << LHS.get()->getSourceRange());
11639 return;
11640 }
11641
11642 llvm::APInt ResultBits =
11643 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11644 if (ResultBits.ule(LeftSize))
11645 return;
11646 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11647 Result = Result.shl(Right);
11648
11649 // Print the bit representation of the signed integer as an unsigned
11650 // hexadecimal number.
11651 SmallString<40> HexResult;
11652 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11653
11654 // If we are only missing a sign bit, this is less likely to result in actual
11655 // bugs -- if the result is cast back to an unsigned type, it will have the
11656 // expected value. Thus we place this behind a different warning that can be
11657 // turned off separately if needed.
11658 if (ResultBits - 1 == LeftSize) {
11659 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11660 << HexResult << LHSType
11661 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11662 return;
11663 }
11664
11665 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11666 << HexResult.str() << Result.getSignificantBits() << LHSType
11667 << Left.getBitWidth() << LHS.get()->getSourceRange()
11668 << RHS.get()->getSourceRange();
11669}
11670
11671/// Return the resulting type when a vector is shifted
11672/// by a scalar or vector shift amount.
11674 SourceLocation Loc, bool IsCompAssign) {
11675 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11676 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11677 !LHS.get()->getType()->isVectorType()) {
11678 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11679 << RHS.get()->getType() << LHS.get()->getType()
11680 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11681 return QualType();
11682 }
11683
11684 if (!IsCompAssign) {
11685 LHS = S.UsualUnaryConversions(LHS.get());
11686 if (LHS.isInvalid()) return QualType();
11687 }
11688
11689 RHS = S.UsualUnaryConversions(RHS.get());
11690 if (RHS.isInvalid()) return QualType();
11691
11692 QualType LHSType = LHS.get()->getType();
11693 // Note that LHS might be a scalar because the routine calls not only in
11694 // OpenCL case.
11695 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11696 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11697
11698 // Note that RHS might not be a vector.
11699 QualType RHSType = RHS.get()->getType();
11700 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11701 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11702
11703 // Do not allow shifts for boolean vectors.
11704 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11705 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11706 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11707 << LHS.get()->getType() << RHS.get()->getType()
11708 << LHS.get()->getSourceRange();
11709 return QualType();
11710 }
11711
11712 // The operands need to be integers.
11713 if (!LHSEleType->isIntegerType()) {
11714 S.Diag(Loc, diag::err_typecheck_expect_int)
11715 << LHS.get()->getType() << LHS.get()->getSourceRange();
11716 return QualType();
11717 }
11718
11719 if (!RHSEleType->isIntegerType()) {
11720 S.Diag(Loc, diag::err_typecheck_expect_int)
11721 << RHS.get()->getType() << RHS.get()->getSourceRange();
11722 return QualType();
11723 }
11724
11725 if (!LHSVecTy) {
11726 assert(RHSVecTy);
11727 if (IsCompAssign)
11728 return RHSType;
11729 if (LHSEleType != RHSEleType) {
11730 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11731 LHSEleType = RHSEleType;
11732 }
11733 QualType VecTy =
11734 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11735 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11736 LHSType = VecTy;
11737 } else if (RHSVecTy) {
11738 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11739 // are applied component-wise. So if RHS is a vector, then ensure
11740 // that the number of elements is the same as LHS...
11741 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11742 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11743 << LHS.get()->getType() << RHS.get()->getType()
11744 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11745 return QualType();
11746 }
11747 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11748 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11749 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11750 if (LHSBT != RHSBT &&
11751 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11752 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11753 << LHS.get()->getType() << RHS.get()->getType()
11754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11755 }
11756 }
11757 } else {
11758 // ...else expand RHS to match the number of elements in LHS.
11759 QualType VecTy =
11760 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11761 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11762 }
11763
11764 return LHSType;
11765}
11766
11768 ExprResult &RHS, SourceLocation Loc,
11769 bool IsCompAssign) {
11770 if (!IsCompAssign) {
11771 LHS = S.UsualUnaryConversions(LHS.get());
11772 if (LHS.isInvalid())
11773 return QualType();
11774 }
11775
11776 RHS = S.UsualUnaryConversions(RHS.get());
11777 if (RHS.isInvalid())
11778 return QualType();
11779
11780 QualType LHSType = LHS.get()->getType();
11781 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11782 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11783 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11784 : LHSType;
11785
11786 // Note that RHS might not be a vector
11787 QualType RHSType = RHS.get()->getType();
11788 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11789 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11790 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11791 : RHSType;
11792
11793 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11794 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11795 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11796 << LHSType << RHSType << LHS.get()->getSourceRange();
11797 return QualType();
11798 }
11799
11800 if (!LHSEleType->isIntegerType()) {
11801 S.Diag(Loc, diag::err_typecheck_expect_int)
11802 << LHS.get()->getType() << LHS.get()->getSourceRange();
11803 return QualType();
11804 }
11805
11806 if (!RHSEleType->isIntegerType()) {
11807 S.Diag(Loc, diag::err_typecheck_expect_int)
11808 << RHS.get()->getType() << RHS.get()->getSourceRange();
11809 return QualType();
11810 }
11811
11812 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11813 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11814 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11815 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11816 << LHSType << RHSType << LHS.get()->getSourceRange()
11817 << RHS.get()->getSourceRange();
11818 return QualType();
11819 }
11820
11821 if (!LHSType->isSveVLSBuiltinType()) {
11822 assert(RHSType->isSveVLSBuiltinType());
11823 if (IsCompAssign)
11824 return RHSType;
11825 if (LHSEleType != RHSEleType) {
11826 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11827 LHSEleType = RHSEleType;
11828 }
11829 const llvm::ElementCount VecSize =
11830 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11831 QualType VecTy =
11832 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11833 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11834 LHSType = VecTy;
11835 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11836 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11837 S.Context.getTypeSize(LHSBuiltinTy)) {
11838 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11839 << LHSType << RHSType << LHS.get()->getSourceRange()
11840 << RHS.get()->getSourceRange();
11841 return QualType();
11842 }
11843 } else {
11844 const llvm::ElementCount VecSize =
11845 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11846 if (LHSEleType != RHSEleType) {
11847 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11848 RHSEleType = LHSEleType;
11849 }
11850 QualType VecTy =
11851 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11852 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11853 }
11854
11855 return LHSType;
11856}
11857
11858// C99 6.5.7
11861 bool IsCompAssign) {
11862 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11863
11864 // Vector shifts promote their scalar inputs to vector type.
11865 if (LHS.get()->getType()->isVectorType() ||
11866 RHS.get()->getType()->isVectorType()) {
11867 if (LangOpts.ZVector) {
11868 // The shift operators for the z vector extensions work basically
11869 // like general shifts, except that neither the LHS nor the RHS is
11870 // allowed to be a "vector bool".
11871 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11872 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11873 return InvalidOperands(Loc, LHS, RHS);
11874 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11875 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11876 return InvalidOperands(Loc, LHS, RHS);
11877 }
11878 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11879 }
11880
11881 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11882 RHS.get()->getType()->isSveVLSBuiltinType())
11883 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11884
11885 // Shifts don't perform usual arithmetic conversions, they just do integer
11886 // promotions on each operand. C99 6.5.7p3
11887
11888 // For the LHS, do usual unary conversions, but then reset them away
11889 // if this is a compound assignment.
11890 ExprResult OldLHS = LHS;
11891 LHS = UsualUnaryConversions(LHS.get());
11892 if (LHS.isInvalid())
11893 return QualType();
11894 QualType LHSType = LHS.get()->getType();
11895 if (IsCompAssign) LHS = OldLHS;
11896
11897 // The RHS is simpler.
11898 RHS = UsualUnaryConversions(RHS.get());
11899 if (RHS.isInvalid())
11900 return QualType();
11901 QualType RHSType = RHS.get()->getType();
11902
11903 // C99 6.5.7p2: Each of the operands shall have integer type.
11904 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11905 if ((!LHSType->isFixedPointOrIntegerType() &&
11906 !LHSType->hasIntegerRepresentation()) ||
11907 !RHSType->hasIntegerRepresentation())
11908 return InvalidOperands(Loc, LHS, RHS);
11909
11910 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11911 // hasIntegerRepresentation() above instead of this.
11912 if (isScopedEnumerationType(LHSType) ||
11913 isScopedEnumerationType(RHSType)) {
11914 return InvalidOperands(Loc, LHS, RHS);
11915 }
11916 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11917
11918 // "The type of the result is that of the promoted left operand."
11919 return LHSType;
11920}
11921
11922/// Diagnose bad pointer comparisons.
11924 ExprResult &LHS, ExprResult &RHS,
11925 bool IsError) {
11926 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11927 : diag::ext_typecheck_comparison_of_distinct_pointers)
11928 << LHS.get()->getType() << RHS.get()->getType()
11929 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11930}
11931
11932/// Returns false if the pointers are converted to a composite type,
11933/// true otherwise.
11935 ExprResult &LHS, ExprResult &RHS) {
11936 // C++ [expr.rel]p2:
11937 // [...] Pointer conversions (4.10) and qualification
11938 // conversions (4.4) are performed on pointer operands (or on
11939 // a pointer operand and a null pointer constant) to bring
11940 // them to their composite pointer type. [...]
11941 //
11942 // C++ [expr.eq]p1 uses the same notion for (in)equality
11943 // comparisons of pointers.
11944
11945 QualType LHSType = LHS.get()->getType();
11946 QualType RHSType = RHS.get()->getType();
11947 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11948 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11949
11950 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11951 if (T.isNull()) {
11952 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11953 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11954 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11955 else
11956 S.InvalidOperands(Loc, LHS, RHS);
11957 return true;
11958 }
11959
11960 return false;
11961}
11962
11964 ExprResult &LHS,
11965 ExprResult &RHS,
11966 bool IsError) {
11967 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11968 : diag::ext_typecheck_comparison_of_fptr_to_void)
11969 << LHS.get()->getType() << RHS.get()->getType()
11970 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11971}
11972
11974 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11975 case Stmt::ObjCArrayLiteralClass:
11976 case Stmt::ObjCDictionaryLiteralClass:
11977 case Stmt::ObjCStringLiteralClass:
11978 case Stmt::ObjCBoxedExprClass:
11979 return true;
11980 default:
11981 // Note that ObjCBoolLiteral is NOT an object literal!
11982 return false;
11983 }
11984}
11985
11986static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11989
11990 // If this is not actually an Objective-C object, bail out.
11991 if (!Type)
11992 return false;
11993
11994 // Get the LHS object's interface type.
11995 QualType InterfaceType = Type->getPointeeType();
11996
11997 // If the RHS isn't an Objective-C object, bail out.
11998 if (!RHS->getType()->isObjCObjectPointerType())
11999 return false;
12000
12001 // Try to find the -isEqual: method.
12002 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12003 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12004 InterfaceType,
12005 /*IsInstance=*/true);
12006 if (!Method) {
12007 if (Type->isObjCIdType()) {
12008 // For 'id', just check the global pool.
12009 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12010 /*receiverId=*/true);
12011 } else {
12012 // Check protocols.
12013 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12014 /*IsInstance=*/true);
12015 }
12016 }
12017
12018 if (!Method)
12019 return false;
12020
12021 QualType T = Method->parameters()[0]->getType();
12022 if (!T->isObjCObjectPointerType())
12023 return false;
12024
12025 QualType R = Method->getReturnType();
12026 if (!R->isScalarType())
12027 return false;
12028
12029 return true;
12030}
12031
12033 FromE = FromE->IgnoreParenImpCasts();
12034 switch (FromE->getStmtClass()) {
12035 default:
12036 break;
12037 case Stmt::ObjCStringLiteralClass:
12038 // "string literal"
12039 return LK_String;
12040 case Stmt::ObjCArrayLiteralClass:
12041 // "array literal"
12042 return LK_Array;
12043 case Stmt::ObjCDictionaryLiteralClass:
12044 // "dictionary literal"
12045 return LK_Dictionary;
12046 case Stmt::BlockExprClass:
12047 return LK_Block;
12048 case Stmt::ObjCBoxedExprClass: {
12049 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12050 switch (Inner->getStmtClass()) {
12051 case Stmt::IntegerLiteralClass:
12052 case Stmt::FloatingLiteralClass:
12053 case Stmt::CharacterLiteralClass:
12054 case Stmt::ObjCBoolLiteralExprClass:
12055 case Stmt::CXXBoolLiteralExprClass:
12056 // "numeric literal"
12057 return LK_Numeric;
12058 case Stmt::ImplicitCastExprClass: {
12059 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12060 // Boolean literals can be represented by implicit casts.
12061 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12062 return LK_Numeric;
12063 break;
12064 }
12065 default:
12066 break;
12067 }
12068 return LK_Boxed;
12069 }
12070 }
12071 return LK_None;
12072}
12073
12075 ExprResult &LHS, ExprResult &RHS,
12077 Expr *Literal;
12078 Expr *Other;
12079 if (isObjCObjectLiteral(LHS)) {
12080 Literal = LHS.get();
12081 Other = RHS.get();
12082 } else {
12083 Literal = RHS.get();
12084 Other = LHS.get();
12085 }
12086
12087 // Don't warn on comparisons against nil.
12088 Other = Other->IgnoreParenCasts();
12089 if (Other->isNullPointerConstant(S.getASTContext(),
12091 return;
12092
12093 // This should be kept in sync with warn_objc_literal_comparison.
12094 // LK_String should always be after the other literals, since it has its own
12095 // warning flag.
12096 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12097 assert(LiteralKind != Sema::LK_Block);
12098 if (LiteralKind == Sema::LK_None) {
12099 llvm_unreachable("Unknown Objective-C object literal kind");
12100 }
12101
12102 if (LiteralKind == Sema::LK_String)
12103 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12104 << Literal->getSourceRange();
12105 else
12106 S.Diag(Loc, diag::warn_objc_literal_comparison)
12107 << LiteralKind << Literal->getSourceRange();
12108
12110 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12111 SourceLocation Start = LHS.get()->getBeginLoc();
12113 CharSourceRange OpRange =
12115
12116 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12117 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12118 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12119 << FixItHint::CreateInsertion(End, "]");
12120 }
12121}
12122
12123/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12125 ExprResult &RHS, SourceLocation Loc,
12126 BinaryOperatorKind Opc) {
12127 // Check that left hand side is !something.
12128 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12129 if (!UO || UO->getOpcode() != UO_LNot) return;
12130
12131 // Only check if the right hand side is non-bool arithmetic type.
12132 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12133
12134 // Make sure that the something in !something is not bool.
12135 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12136 if (SubExpr->isKnownToHaveBooleanValue()) return;
12137
12138 // Emit warning.
12139 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12140 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12141 << Loc << IsBitwiseOp;
12142
12143 // First note suggest !(x < y)
12144 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12145 SourceLocation FirstClose = RHS.get()->getEndLoc();
12146 FirstClose = S.getLocForEndOfToken(FirstClose);
12147 if (FirstClose.isInvalid())
12148 FirstOpen = SourceLocation();
12149 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12150 << IsBitwiseOp
12151 << FixItHint::CreateInsertion(FirstOpen, "(")
12152 << FixItHint::CreateInsertion(FirstClose, ")");
12153
12154 // Second note suggests (!x) < y
12155 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12156 SourceLocation SecondClose = LHS.get()->getEndLoc();
12157 SecondClose = S.getLocForEndOfToken(SecondClose);
12158 if (SecondClose.isInvalid())
12159 SecondOpen = SourceLocation();
12160 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12161 << FixItHint::CreateInsertion(SecondOpen, "(")
12162 << FixItHint::CreateInsertion(SecondClose, ")");
12163}
12164
12165// Returns true if E refers to a non-weak array.
12166static bool checkForArray(const Expr *E) {
12167 const ValueDecl *D = nullptr;
12168 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12169 D = DR->getDecl();
12170 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12171 if (Mem->isImplicitAccess())
12172 D = Mem->getMemberDecl();
12173 }
12174 if (!D)
12175 return false;
12176 return D->getType()->isArrayType() && !D->isWeak();
12177}
12178
12179/// Diagnose some forms of syntactically-obvious tautological comparison.
12181 Expr *LHS, Expr *RHS,
12182 BinaryOperatorKind Opc) {
12183 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12184 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12185
12186 QualType LHSType = LHS->getType();
12187 QualType RHSType = RHS->getType();
12188 if (LHSType->hasFloatingRepresentation() ||
12189 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12191 return;
12192
12193 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12194 // Tautological diagnostics.
12195 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12196 return;
12197
12198 // Comparisons between two array types are ill-formed for operator<=>, so
12199 // we shouldn't emit any additional warnings about it.
12200 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12201 return;
12202
12203 // For non-floating point types, check for self-comparisons of the form
12204 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12205 // often indicate logic errors in the program.
12206 //
12207 // NOTE: Don't warn about comparison expressions resulting from macro
12208 // expansion. Also don't warn about comparisons which are only self
12209 // comparisons within a template instantiation. The warnings should catch
12210 // obvious cases in the definition of the template anyways. The idea is to
12211 // warn when the typed comparison operator will always evaluate to the same
12212 // result.
12213
12214 // Used for indexing into %select in warn_comparison_always
12215 enum {
12216 AlwaysConstant,
12217 AlwaysTrue,
12218 AlwaysFalse,
12219 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12220 };
12221
12222 // C++2a [depr.array.comp]:
12223 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12224 // operands of array type are deprecated.
12225 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12226 RHSStripped->getType()->isArrayType()) {
12227 S.Diag(Loc, diag::warn_depr_array_comparison)
12228 << LHS->getSourceRange() << RHS->getSourceRange()
12229 << LHSStripped->getType() << RHSStripped->getType();
12230 // Carry on to produce the tautological comparison warning, if this
12231 // expression is potentially-evaluated, we can resolve the array to a
12232 // non-weak declaration, and so on.
12233 }
12234
12235 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12236 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12237 unsigned Result;
12238 switch (Opc) {
12239 case BO_EQ:
12240 case BO_LE:
12241 case BO_GE:
12242 Result = AlwaysTrue;
12243 break;
12244 case BO_NE:
12245 case BO_LT:
12246 case BO_GT:
12247 Result = AlwaysFalse;
12248 break;
12249 case BO_Cmp:
12250 Result = AlwaysEqual;
12251 break;
12252 default:
12253 Result = AlwaysConstant;
12254 break;
12255 }
12256 S.DiagRuntimeBehavior(Loc, nullptr,
12257 S.PDiag(diag::warn_comparison_always)
12258 << 0 /*self-comparison*/
12259 << Result);
12260 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12261 // What is it always going to evaluate to?
12262 unsigned Result;
12263 switch (Opc) {
12264 case BO_EQ: // e.g. array1 == array2
12265 Result = AlwaysFalse;
12266 break;
12267 case BO_NE: // e.g. array1 != array2
12268 Result = AlwaysTrue;
12269 break;
12270 default: // e.g. array1 <= array2
12271 // The best we can say is 'a constant'
12272 Result = AlwaysConstant;
12273 break;
12274 }
12275 S.DiagRuntimeBehavior(Loc, nullptr,
12276 S.PDiag(diag::warn_comparison_always)
12277 << 1 /*array comparison*/
12278 << Result);
12279 }
12280 }
12281
12282 if (isa<CastExpr>(LHSStripped))
12283 LHSStripped = LHSStripped->IgnoreParenCasts();
12284 if (isa<CastExpr>(RHSStripped))
12285 RHSStripped = RHSStripped->IgnoreParenCasts();
12286
12287 // Warn about comparisons against a string constant (unless the other
12288 // operand is null); the user probably wants string comparison function.
12289 Expr *LiteralString = nullptr;
12290 Expr *LiteralStringStripped = nullptr;
12291 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12292 !RHSStripped->isNullPointerConstant(S.Context,
12294 LiteralString = LHS;
12295 LiteralStringStripped = LHSStripped;
12296 } else if ((isa<StringLiteral>(RHSStripped) ||
12297 isa<ObjCEncodeExpr>(RHSStripped)) &&
12298 !LHSStripped->isNullPointerConstant(S.Context,
12300 LiteralString = RHS;
12301 LiteralStringStripped = RHSStripped;
12302 }
12303
12304 if (LiteralString) {
12305 S.DiagRuntimeBehavior(Loc, nullptr,
12306 S.PDiag(diag::warn_stringcompare)
12307 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12308 << LiteralString->getSourceRange());
12309 }
12310}
12311
12313 switch (CK) {
12314 default: {
12315#ifndef NDEBUG
12316 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12317 << "\n";
12318#endif
12319 llvm_unreachable("unhandled cast kind");
12320 }
12321 case CK_UserDefinedConversion:
12322 return ICK_Identity;
12323 case CK_LValueToRValue:
12324 return ICK_Lvalue_To_Rvalue;
12325 case CK_ArrayToPointerDecay:
12326 return ICK_Array_To_Pointer;
12327 case CK_FunctionToPointerDecay:
12329 case CK_IntegralCast:
12331 case CK_FloatingCast:
12333 case CK_IntegralToFloating:
12334 case CK_FloatingToIntegral:
12335 return ICK_Floating_Integral;
12336 case CK_IntegralComplexCast:
12337 case CK_FloatingComplexCast:
12338 case CK_FloatingComplexToIntegralComplex:
12339 case CK_IntegralComplexToFloatingComplex:
12341 case CK_FloatingComplexToReal:
12342 case CK_FloatingRealToComplex:
12343 case CK_IntegralComplexToReal:
12344 case CK_IntegralRealToComplex:
12345 return ICK_Complex_Real;
12346 case CK_HLSLArrayRValue:
12347 return ICK_HLSL_Array_RValue;
12348 }
12349}
12350
12352 QualType FromType,
12353 SourceLocation Loc) {
12354 // Check for a narrowing implicit conversion.
12357 SCS.setToType(0, FromType);
12358 SCS.setToType(1, ToType);
12359 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12360 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12361
12362 APValue PreNarrowingValue;
12363 QualType PreNarrowingType;
12364 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12365 PreNarrowingType,
12366 /*IgnoreFloatToIntegralConversion*/ true)) {
12368 // Implicit conversion to a narrower type, but the expression is
12369 // value-dependent so we can't tell whether it's actually narrowing.
12370 case NK_Not_Narrowing:
12371 return false;
12372
12374 // Implicit conversion to a narrower type, and the value is not a constant
12375 // expression.
12376 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12377 << /*Constant*/ 1
12378 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12379 return true;
12380
12382 // Implicit conversion to a narrower type, and the value is not a constant
12383 // expression.
12384 case NK_Type_Narrowing:
12385 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12386 << /*Constant*/ 0 << FromType << ToType;
12387 // TODO: It's not a constant expression, but what if the user intended it
12388 // to be? Can we produce notes to help them figure out why it isn't?
12389 return true;
12390 }
12391 llvm_unreachable("unhandled case in switch");
12392}
12393
12395 ExprResult &LHS,
12396 ExprResult &RHS,
12397 SourceLocation Loc) {
12398 QualType LHSType = LHS.get()->getType();
12399 QualType RHSType = RHS.get()->getType();
12400 // Dig out the original argument type and expression before implicit casts
12401 // were applied. These are the types/expressions we need to check the
12402 // [expr.spaceship] requirements against.
12403 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12404 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12405 QualType LHSStrippedType = LHSStripped.get()->getType();
12406 QualType RHSStrippedType = RHSStripped.get()->getType();
12407
12408 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12409 // other is not, the program is ill-formed.
12410 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12411 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12412 return QualType();
12413 }
12414
12415 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12416 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12417 RHSStrippedType->isEnumeralType();
12418 if (NumEnumArgs == 1) {
12419 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12420 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12421 if (OtherTy->hasFloatingRepresentation()) {
12422 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12423 return QualType();
12424 }
12425 }
12426 if (NumEnumArgs == 2) {
12427 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12428 // type E, the operator yields the result of converting the operands
12429 // to the underlying type of E and applying <=> to the converted operands.
12430 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12431 S.InvalidOperands(Loc, LHS, RHS);
12432 return QualType();
12433 }
12434 QualType IntType =
12435 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12436 assert(IntType->isArithmeticType());
12437
12438 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12439 // promote the boolean type, and all other promotable integer types, to
12440 // avoid this.
12441 if (S.Context.isPromotableIntegerType(IntType))
12442 IntType = S.Context.getPromotedIntegerType(IntType);
12443
12444 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12445 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12446 LHSType = RHSType = IntType;
12447 }
12448
12449 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12450 // usual arithmetic conversions are applied to the operands.
12451 QualType Type =
12453 if (LHS.isInvalid() || RHS.isInvalid())
12454 return QualType();
12455 if (Type.isNull())
12456 return S.InvalidOperands(Loc, LHS, RHS);
12457
12458 std::optional<ComparisonCategoryType> CCT =
12460 if (!CCT)
12461 return S.InvalidOperands(Loc, LHS, RHS);
12462
12463 bool HasNarrowing = checkThreeWayNarrowingConversion(
12464 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12465 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12466 RHS.get()->getBeginLoc());
12467 if (HasNarrowing)
12468 return QualType();
12469
12470 assert(!Type.isNull() && "composite type for <=> has not been set");
12471
12474}
12475
12477 ExprResult &RHS,
12478 SourceLocation Loc,
12479 BinaryOperatorKind Opc) {
12480 if (Opc == BO_Cmp)
12481 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12482
12483 // C99 6.5.8p3 / C99 6.5.9p4
12484 QualType Type =
12486 if (LHS.isInvalid() || RHS.isInvalid())
12487 return QualType();
12488 if (Type.isNull())
12489 return S.InvalidOperands(Loc, LHS, RHS);
12490 assert(Type->isArithmeticType() || Type->isEnumeralType());
12491
12493 return S.InvalidOperands(Loc, LHS, RHS);
12494
12495 // Check for comparisons of floating point operands using != and ==.
12497 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12498
12499 // The result of comparisons is 'bool' in C++, 'int' in C.
12501}
12502
12504 if (!NullE.get()->getType()->isAnyPointerType())
12505 return;
12506 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12507 if (!E.get()->getType()->isAnyPointerType() &&
12511 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12512 if (CL->getValue() == 0)
12513 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12514 << NullValue
12516 NullValue ? "NULL" : "(void *)0");
12517 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12518 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12520 if (T == Context.CharTy)
12521 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12522 << NullValue
12524 NullValue ? "NULL" : "(void *)0");
12525 }
12526 }
12527}
12528
12529// C99 6.5.8, C++ [expr.rel]
12531 SourceLocation Loc,
12532 BinaryOperatorKind Opc) {
12533 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12534 bool IsThreeWay = Opc == BO_Cmp;
12535 bool IsOrdered = IsRelational || IsThreeWay;
12536 auto IsAnyPointerType = [](ExprResult E) {
12537 QualType Ty = E.get()->getType();
12538 return Ty->isPointerType() || Ty->isMemberPointerType();
12539 };
12540
12541 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12542 // type, array-to-pointer, ..., conversions are performed on both operands to
12543 // bring them to their composite type.
12544 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12545 // any type-related checks.
12546 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12548 if (LHS.isInvalid())
12549 return QualType();
12551 if (RHS.isInvalid())
12552 return QualType();
12553 } else {
12554 LHS = DefaultLvalueConversion(LHS.get());
12555 if (LHS.isInvalid())
12556 return QualType();
12557 RHS = DefaultLvalueConversion(RHS.get());
12558 if (RHS.isInvalid())
12559 return QualType();
12560 }
12561
12562 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12566 }
12567
12568 // Handle vector comparisons separately.
12569 if (LHS.get()->getType()->isVectorType() ||
12570 RHS.get()->getType()->isVectorType())
12571 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12572
12573 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12574 RHS.get()->getType()->isSveVLSBuiltinType())
12575 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12576
12577 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12578 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12579
12580 QualType LHSType = LHS.get()->getType();
12581 QualType RHSType = RHS.get()->getType();
12582 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12583 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12584 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12585
12586 if ((LHSType->isPointerType() &&
12588 (RHSType->isPointerType() &&
12590 return InvalidOperands(Loc, LHS, RHS);
12591
12592 const Expr::NullPointerConstantKind LHSNullKind =
12594 const Expr::NullPointerConstantKind RHSNullKind =
12596 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12597 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12598
12599 auto computeResultTy = [&]() {
12600 if (Opc != BO_Cmp)
12602 assert(getLangOpts().CPlusPlus);
12603 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12604
12605 QualType CompositeTy = LHS.get()->getType();
12606 assert(!CompositeTy->isReferenceType());
12607
12608 std::optional<ComparisonCategoryType> CCT =
12610 if (!CCT)
12611 return InvalidOperands(Loc, LHS, RHS);
12612
12613 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12614 // P0946R0: Comparisons between a null pointer constant and an object
12615 // pointer result in std::strong_equality, which is ill-formed under
12616 // P1959R0.
12617 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12618 << (LHSIsNull ? LHS.get()->getSourceRange()
12619 : RHS.get()->getSourceRange());
12620 return QualType();
12621 }
12622
12625 };
12626
12627 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12628 bool IsEquality = Opc == BO_EQ;
12629 if (RHSIsNull)
12630 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12631 RHS.get()->getSourceRange());
12632 else
12633 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12634 LHS.get()->getSourceRange());
12635 }
12636
12637 if (IsOrdered && LHSType->isFunctionPointerType() &&
12638 RHSType->isFunctionPointerType()) {
12639 // Valid unless a relational comparison of function pointers
12640 bool IsError = Opc == BO_Cmp;
12641 auto DiagID =
12642 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12643 : getLangOpts().CPlusPlus
12644 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12645 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12646 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12647 << RHS.get()->getSourceRange();
12648 if (IsError)
12649 return QualType();
12650 }
12651
12652 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12653 (RHSType->isIntegerType() && !RHSIsNull)) {
12654 // Skip normal pointer conversion checks in this case; we have better
12655 // diagnostics for this below.
12656 } else if (getLangOpts().CPlusPlus) {
12657 // Equality comparison of a function pointer to a void pointer is invalid,
12658 // but we allow it as an extension.
12659 // FIXME: If we really want to allow this, should it be part of composite
12660 // pointer type computation so it works in conditionals too?
12661 if (!IsOrdered &&
12662 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12663 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12664 // This is a gcc extension compatibility comparison.
12665 // In a SFINAE context, we treat this as a hard error to maintain
12666 // conformance with the C++ standard.
12668 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12669
12670 if (isSFINAEContext())
12671 return QualType();
12672
12673 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12674 return computeResultTy();
12675 }
12676
12677 // C++ [expr.eq]p2:
12678 // If at least one operand is a pointer [...] bring them to their
12679 // composite pointer type.
12680 // C++ [expr.spaceship]p6
12681 // If at least one of the operands is of pointer type, [...] bring them
12682 // to their composite pointer type.
12683 // C++ [expr.rel]p2:
12684 // If both operands are pointers, [...] bring them to their composite
12685 // pointer type.
12686 // For <=>, the only valid non-pointer types are arrays and functions, and
12687 // we already decayed those, so this is really the same as the relational
12688 // comparison rule.
12689 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12690 (IsOrdered ? 2 : 1) &&
12691 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12692 RHSType->isObjCObjectPointerType()))) {
12693 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12694 return QualType();
12695 return computeResultTy();
12696 }
12697 } else if (LHSType->isPointerType() &&
12698 RHSType->isPointerType()) { // C99 6.5.8p2
12699 // All of the following pointer-related warnings are GCC extensions, except
12700 // when handling null pointer constants.
12701 QualType LCanPointeeTy =
12702 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12703 QualType RCanPointeeTy =
12704 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12705
12706 // C99 6.5.9p2 and C99 6.5.8p2
12707 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12708 RCanPointeeTy.getUnqualifiedType())) {
12709 if (IsRelational) {
12710 // Pointers both need to point to complete or incomplete types
12711 if ((LCanPointeeTy->isIncompleteType() !=
12712 RCanPointeeTy->isIncompleteType()) &&
12713 !getLangOpts().C11) {
12714 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12715 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12716 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12717 << RCanPointeeTy->isIncompleteType();
12718 }
12719 }
12720 } else if (!IsRelational &&
12721 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12722 // Valid unless comparison between non-null pointer and function pointer
12723 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12724 && !LHSIsNull && !RHSIsNull)
12725 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12726 /*isError*/false);
12727 } else {
12728 // Invalid
12729 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12730 }
12731 if (LCanPointeeTy != RCanPointeeTy) {
12732 // Treat NULL constant as a special case in OpenCL.
12733 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12734 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12735 Diag(Loc,
12736 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12737 << LHSType << RHSType << 0 /* comparison */
12738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12739 }
12740 }
12741 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12742 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12743 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12744 : CK_BitCast;
12745 if (LHSIsNull && !RHSIsNull)
12746 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12747 else
12748 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12749 }
12750 return computeResultTy();
12751 }
12752
12753
12754 // C++ [expr.eq]p4:
12755 // Two operands of type std::nullptr_t or one operand of type
12756 // std::nullptr_t and the other a null pointer constant compare
12757 // equal.
12758 // C23 6.5.9p5:
12759 // If both operands have type nullptr_t or one operand has type nullptr_t
12760 // and the other is a null pointer constant, they compare equal if the
12761 // former is a null pointer.
12762 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12763 if (LHSType->isNullPtrType()) {
12764 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12765 return computeResultTy();
12766 }
12767 if (RHSType->isNullPtrType()) {
12768 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12769 return computeResultTy();
12770 }
12771 }
12772
12773 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12774 // C23 6.5.9p6:
12775 // Otherwise, at least one operand is a pointer. If one is a pointer and
12776 // the other is a null pointer constant or has type nullptr_t, they
12777 // compare equal
12778 if (LHSIsNull && RHSType->isPointerType()) {
12779 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12780 return computeResultTy();
12781 }
12782 if (RHSIsNull && LHSType->isPointerType()) {
12783 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12784 return computeResultTy();
12785 }
12786 }
12787
12788 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12789 // These aren't covered by the composite pointer type rules.
12790 if (!IsOrdered && RHSType->isNullPtrType() &&
12791 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12792 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12793 return computeResultTy();
12794 }
12795 if (!IsOrdered && LHSType->isNullPtrType() &&
12796 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12797 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12798 return computeResultTy();
12799 }
12800
12801 if (getLangOpts().CPlusPlus) {
12802 if (IsRelational &&
12803 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12804 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12805 // HACK: Relational comparison of nullptr_t against a pointer type is
12806 // invalid per DR583, but we allow it within std::less<> and friends,
12807 // since otherwise common uses of it break.
12808 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12809 // friends to have std::nullptr_t overload candidates.
12810 DeclContext *DC = CurContext;
12811 if (isa<FunctionDecl>(DC))
12812 DC = DC->getParent();
12813 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12814 if (CTSD->isInStdNamespace() &&
12815 llvm::StringSwitch<bool>(CTSD->getName())
12816 .Cases("less", "less_equal", "greater", "greater_equal", true)
12817 .Default(false)) {
12818 if (RHSType->isNullPtrType())
12819 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12820 else
12821 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12822 return computeResultTy();
12823 }
12824 }
12825 }
12826
12827 // C++ [expr.eq]p2:
12828 // If at least one operand is a pointer to member, [...] bring them to
12829 // their composite pointer type.
12830 if (!IsOrdered &&
12831 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12832 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12833 return QualType();
12834 else
12835 return computeResultTy();
12836 }
12837 }
12838
12839 // Handle block pointer types.
12840 if (!IsOrdered && LHSType->isBlockPointerType() &&
12841 RHSType->isBlockPointerType()) {
12842 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12843 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12844
12845 if (!LHSIsNull && !RHSIsNull &&
12846 !Context.typesAreCompatible(lpointee, rpointee)) {
12847 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12848 << LHSType << RHSType << LHS.get()->getSourceRange()
12849 << RHS.get()->getSourceRange();
12850 }
12851 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12852 return computeResultTy();
12853 }
12854
12855 // Allow block pointers to be compared with null pointer constants.
12856 if (!IsOrdered
12857 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12858 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12859 if (!LHSIsNull && !RHSIsNull) {
12860 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12862 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12863 ->getPointeeType()->isVoidType())))
12864 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12865 << LHSType << RHSType << LHS.get()->getSourceRange()
12866 << RHS.get()->getSourceRange();
12867 }
12868 if (LHSIsNull && !RHSIsNull)
12869 LHS = ImpCastExprToType(LHS.get(), RHSType,
12870 RHSType->isPointerType() ? CK_BitCast
12871 : CK_AnyPointerToBlockPointerCast);
12872 else
12873 RHS = ImpCastExprToType(RHS.get(), LHSType,
12874 LHSType->isPointerType() ? CK_BitCast
12875 : CK_AnyPointerToBlockPointerCast);
12876 return computeResultTy();
12877 }
12878
12879 if (LHSType->isObjCObjectPointerType() ||
12880 RHSType->isObjCObjectPointerType()) {
12881 const PointerType *LPT = LHSType->getAs<PointerType>();
12882 const PointerType *RPT = RHSType->getAs<PointerType>();
12883 if (LPT || RPT) {
12884 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12885 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12886
12887 if (!LPtrToVoid && !RPtrToVoid &&
12888 !Context.typesAreCompatible(LHSType, RHSType)) {
12889 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12890 /*isError*/false);
12891 }
12892 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12893 // the RHS, but we have test coverage for this behavior.
12894 // FIXME: Consider using convertPointersToCompositeType in C++.
12895 if (LHSIsNull && !RHSIsNull) {
12896 Expr *E = LHS.get();
12897 if (getLangOpts().ObjCAutoRefCount)
12898 CheckObjCConversion(SourceRange(), RHSType, E,
12900 LHS = ImpCastExprToType(E, RHSType,
12901 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12902 }
12903 else {
12904 Expr *E = RHS.get();
12905 if (getLangOpts().ObjCAutoRefCount)
12906 CheckObjCConversion(SourceRange(), LHSType, E,
12908 /*Diagnose=*/true,
12909 /*DiagnoseCFAudited=*/false, Opc);
12910 RHS = ImpCastExprToType(E, LHSType,
12911 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12912 }
12913 return computeResultTy();
12914 }
12915 if (LHSType->isObjCObjectPointerType() &&
12916 RHSType->isObjCObjectPointerType()) {
12917 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12918 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12919 /*isError*/false);
12921 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12922
12923 if (LHSIsNull && !RHSIsNull)
12924 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12925 else
12926 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12927 return computeResultTy();
12928 }
12929
12930 if (!IsOrdered && LHSType->isBlockPointerType() &&
12932 LHS = ImpCastExprToType(LHS.get(), RHSType,
12933 CK_BlockPointerToObjCPointerCast);
12934 return computeResultTy();
12935 } else if (!IsOrdered &&
12937 RHSType->isBlockPointerType()) {
12938 RHS = ImpCastExprToType(RHS.get(), LHSType,
12939 CK_BlockPointerToObjCPointerCast);
12940 return computeResultTy();
12941 }
12942 }
12943 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12944 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12945 unsigned DiagID = 0;
12946 bool isError = false;
12947 if (LangOpts.DebuggerSupport) {
12948 // Under a debugger, allow the comparison of pointers to integers,
12949 // since users tend to want to compare addresses.
12950 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12951 (RHSIsNull && RHSType->isIntegerType())) {
12952 if (IsOrdered) {
12953 isError = getLangOpts().CPlusPlus;
12954 DiagID =
12955 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12956 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12957 }
12958 } else if (getLangOpts().CPlusPlus) {
12959 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12960 isError = true;
12961 } else if (IsOrdered)
12962 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12963 else
12964 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12965
12966 if (DiagID) {
12967 Diag(Loc, DiagID)
12968 << LHSType << RHSType << LHS.get()->getSourceRange()
12969 << RHS.get()->getSourceRange();
12970 if (isError)
12971 return QualType();
12972 }
12973
12974 if (LHSType->isIntegerType())
12975 LHS = ImpCastExprToType(LHS.get(), RHSType,
12976 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12977 else
12978 RHS = ImpCastExprToType(RHS.get(), LHSType,
12979 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12980 return computeResultTy();
12981 }
12982
12983 // Handle block pointers.
12984 if (!IsOrdered && RHSIsNull
12985 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12986 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12987 return computeResultTy();
12988 }
12989 if (!IsOrdered && LHSIsNull
12990 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12991 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12992 return computeResultTy();
12993 }
12994
12995 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12996 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12997 return computeResultTy();
12998 }
12999
13000 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13001 return computeResultTy();
13002 }
13003
13004 if (LHSIsNull && RHSType->isQueueT()) {
13005 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13006 return computeResultTy();
13007 }
13008
13009 if (LHSType->isQueueT() && RHSIsNull) {
13010 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13011 return computeResultTy();
13012 }
13013 }
13014
13015 return InvalidOperands(Loc, LHS, RHS);
13016}
13017
13018// Return a signed ext_vector_type that is of identical size and number of
13019// elements. For floating point vectors, return an integer type of identical
13020// size and number of elements. In the non ext_vector_type case, search from
13021// the largest type to the smallest type to avoid cases where long long == long,
13022// where long gets picked over long long.
13024 const VectorType *VTy = V->castAs<VectorType>();
13025 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13026
13027 if (isa<ExtVectorType>(VTy)) {
13028 if (VTy->isExtVectorBoolType())
13030 if (TypeSize == Context.getTypeSize(Context.CharTy))
13032 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13034 if (TypeSize == Context.getTypeSize(Context.IntTy))
13036 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13038 if (TypeSize == Context.getTypeSize(Context.LongTy))
13040 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13041 "Unhandled vector element size in vector compare");
13043 }
13044
13045 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13048 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13051 if (TypeSize == Context.getTypeSize(Context.LongTy))
13054 if (TypeSize == Context.getTypeSize(Context.IntTy))
13057 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13060 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13061 "Unhandled vector element size in vector compare");
13064}
13065
13067 const BuiltinType *VTy = V->castAs<BuiltinType>();
13068 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13069
13070 const QualType ETy = V->getSveEltType(Context);
13071 const auto TypeSize = Context.getTypeSize(ETy);
13072
13073 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13074 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13075 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13076}
13077
13078/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13079/// operates on extended vector types. Instead of producing an IntTy result,
13080/// like a scalar comparison, a vector comparison produces a vector of integer
13081/// types.
13083 SourceLocation Loc,
13084 BinaryOperatorKind Opc) {
13085 if (Opc == BO_Cmp) {
13086 Diag(Loc, diag::err_three_way_vector_comparison);
13087 return QualType();
13088 }
13089
13090 // Check to make sure we're operating on vectors of the same type and width,
13091 // Allowing one side to be a scalar of element type.
13092 QualType vType =
13093 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13094 /*AllowBothBool*/ true,
13095 /*AllowBoolConversions*/ getLangOpts().ZVector,
13096 /*AllowBooleanOperation*/ true,
13097 /*ReportInvalid*/ true);
13098 if (vType.isNull())
13099 return vType;
13100
13101 QualType LHSType = LHS.get()->getType();
13102
13103 // Determine the return type of a vector compare. By default clang will return
13104 // a scalar for all vector compares except vector bool and vector pixel.
13105 // With the gcc compiler we will always return a vector type and with the xl
13106 // compiler we will always return a scalar type. This switch allows choosing
13107 // which behavior is prefered.
13108 if (getLangOpts().AltiVec) {
13109 switch (getLangOpts().getAltivecSrcCompat()) {
13111 // If AltiVec, the comparison results in a numeric type, i.e.
13112 // bool for C++, int for C
13113 if (vType->castAs<VectorType>()->getVectorKind() ==
13116 else
13117 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13118 break;
13120 // For GCC we always return the vector type.
13121 break;
13124 break;
13125 }
13126 }
13127
13128 // For non-floating point types, check for self-comparisons of the form
13129 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13130 // often indicate logic errors in the program.
13131 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13132
13133 // Check for comparisons of floating point operands using != and ==.
13134 if (LHSType->hasFloatingRepresentation()) {
13135 assert(RHS.get()->getType()->hasFloatingRepresentation());
13136 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13137 }
13138
13139 // Return a signed type for the vector.
13140 return GetSignedVectorType(vType);
13141}
13142
13144 ExprResult &RHS,
13145 SourceLocation Loc,
13146 BinaryOperatorKind Opc) {
13147 if (Opc == BO_Cmp) {
13148 Diag(Loc, diag::err_three_way_vector_comparison);
13149 return QualType();
13150 }
13151
13152 // Check to make sure we're operating on vectors of the same type and width,
13153 // Allowing one side to be a scalar of element type.
13155 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13156
13157 if (vType.isNull())
13158 return vType;
13159
13160 QualType LHSType = LHS.get()->getType();
13161
13162 // For non-floating point types, check for self-comparisons of the form
13163 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13164 // often indicate logic errors in the program.
13165 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13166
13167 // Check for comparisons of floating point operands using != and ==.
13168 if (LHSType->hasFloatingRepresentation()) {
13169 assert(RHS.get()->getType()->hasFloatingRepresentation());
13170 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13171 }
13172
13173 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13174 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13175
13176 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13177 RHSBuiltinTy->isSVEBool())
13178 return LHSType;
13179
13180 // Return a signed type for the vector.
13181 return GetSignedSizelessVectorType(vType);
13182}
13183
13184static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13185 const ExprResult &XorRHS,
13186 const SourceLocation Loc) {
13187 // Do not diagnose macros.
13188 if (Loc.isMacroID())
13189 return;
13190
13191 // Do not diagnose if both LHS and RHS are macros.
13192 if (XorLHS.get()->getExprLoc().isMacroID() &&
13193 XorRHS.get()->getExprLoc().isMacroID())
13194 return;
13195
13196 bool Negative = false;
13197 bool ExplicitPlus = false;
13198 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13199 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13200
13201 if (!LHSInt)
13202 return;
13203 if (!RHSInt) {
13204 // Check negative literals.
13205 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13206 UnaryOperatorKind Opc = UO->getOpcode();
13207 if (Opc != UO_Minus && Opc != UO_Plus)
13208 return;
13209 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13210 if (!RHSInt)
13211 return;
13212 Negative = (Opc == UO_Minus);
13213 ExplicitPlus = !Negative;
13214 } else {
13215 return;
13216 }
13217 }
13218
13219 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13220 llvm::APInt RightSideValue = RHSInt->getValue();
13221 if (LeftSideValue != 2 && LeftSideValue != 10)
13222 return;
13223
13224 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13225 return;
13226
13228 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13229 llvm::StringRef ExprStr =
13231
13232 CharSourceRange XorRange =
13234 llvm::StringRef XorStr =
13236 // Do not diagnose if xor keyword/macro is used.
13237 if (XorStr == "xor")
13238 return;
13239
13240 std::string LHSStr = std::string(Lexer::getSourceText(
13241 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13242 S.getSourceManager(), S.getLangOpts()));
13243 std::string RHSStr = std::string(Lexer::getSourceText(
13244 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13245 S.getSourceManager(), S.getLangOpts()));
13246
13247 if (Negative) {
13248 RightSideValue = -RightSideValue;
13249 RHSStr = "-" + RHSStr;
13250 } else if (ExplicitPlus) {
13251 RHSStr = "+" + RHSStr;
13252 }
13253
13254 StringRef LHSStrRef = LHSStr;
13255 StringRef RHSStrRef = RHSStr;
13256 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13257 // literals.
13258 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13259 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13260 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13261 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13262 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13263 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13264 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13265 return;
13266
13267 bool SuggestXor =
13268 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13269 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13270 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13271 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13272 std::string SuggestedExpr = "1 << " + RHSStr;
13273 bool Overflow = false;
13274 llvm::APInt One = (LeftSideValue - 1);
13275 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13276 if (Overflow) {
13277 if (RightSideIntValue < 64)
13278 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13279 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13280 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13281 else if (RightSideIntValue == 64)
13282 S.Diag(Loc, diag::warn_xor_used_as_pow)
13283 << ExprStr << toString(XorValue, 10, true);
13284 else
13285 return;
13286 } else {
13287 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13288 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13289 << toString(PowValue, 10, true)
13291 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13292 }
13293
13294 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13295 << ("0x2 ^ " + RHSStr) << SuggestXor;
13296 } else if (LeftSideValue == 10) {
13297 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13298 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13299 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13300 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13301 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13302 << ("0xA ^ " + RHSStr) << SuggestXor;
13303 }
13304}
13305
13307 SourceLocation Loc) {
13308 // Ensure that either both operands are of the same vector type, or
13309 // one operand is of a vector type and the other is of its element type.
13310 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13311 /*AllowBothBool*/ true,
13312 /*AllowBoolConversions*/ false,
13313 /*AllowBooleanOperation*/ false,
13314 /*ReportInvalid*/ false);
13315 if (vType.isNull())
13316 return InvalidOperands(Loc, LHS, RHS);
13317 if (getLangOpts().OpenCL &&
13318 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13320 return InvalidOperands(Loc, LHS, RHS);
13321 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13322 // usage of the logical operators && and || with vectors in C. This
13323 // check could be notionally dropped.
13324 if (!getLangOpts().CPlusPlus &&
13325 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13326 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13327
13328 return GetSignedVectorType(LHS.get()->getType());
13329}
13330
13332 SourceLocation Loc,
13333 bool IsCompAssign) {
13334 if (!IsCompAssign) {
13336 if (LHS.isInvalid())
13337 return QualType();
13338 }
13340 if (RHS.isInvalid())
13341 return QualType();
13342
13343 // For conversion purposes, we ignore any qualifiers.
13344 // For example, "const float" and "float" are equivalent.
13345 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13346 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13347
13348 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13349 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13350 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13351
13352 if (Context.hasSameType(LHSType, RHSType))
13353 return Context.getCommonSugaredType(LHSType, RHSType);
13354
13355 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13356 // case we have to return InvalidOperands.
13357 ExprResult OriginalLHS = LHS;
13358 ExprResult OriginalRHS = RHS;
13359 if (LHSMatType && !RHSMatType) {
13360 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13361 if (!RHS.isInvalid())
13362 return LHSType;
13363
13364 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13365 }
13366
13367 if (!LHSMatType && RHSMatType) {
13368 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13369 if (!LHS.isInvalid())
13370 return RHSType;
13371 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13372 }
13373
13374 return InvalidOperands(Loc, LHS, RHS);
13375}
13376
13378 SourceLocation Loc,
13379 bool IsCompAssign) {
13380 if (!IsCompAssign) {
13382 if (LHS.isInvalid())
13383 return QualType();
13384 }
13386 if (RHS.isInvalid())
13387 return QualType();
13388
13389 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13390 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13391 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13392
13393 if (LHSMatType && RHSMatType) {
13394 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13395 return InvalidOperands(Loc, LHS, RHS);
13396
13397 if (Context.hasSameType(LHSMatType, RHSMatType))
13399 LHS.get()->getType().getUnqualifiedType(),
13400 RHS.get()->getType().getUnqualifiedType());
13401
13402 QualType LHSELTy = LHSMatType->getElementType(),
13403 RHSELTy = RHSMatType->getElementType();
13404 if (!Context.hasSameType(LHSELTy, RHSELTy))
13405 return InvalidOperands(Loc, LHS, RHS);
13406
13408 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13409 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13410 }
13411 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13412}
13413
13415 switch (Opc) {
13416 default:
13417 return false;
13418 case BO_And:
13419 case BO_AndAssign:
13420 case BO_Or:
13421 case BO_OrAssign:
13422 case BO_Xor:
13423 case BO_XorAssign:
13424 return true;
13425 }
13426}
13427
13429 SourceLocation Loc,
13430 BinaryOperatorKind Opc) {
13431 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13432
13433 bool IsCompAssign =
13434 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13435
13436 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13437
13438 if (LHS.get()->getType()->isVectorType() ||
13439 RHS.get()->getType()->isVectorType()) {
13440 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13442 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13443 /*AllowBothBool*/ true,
13444 /*AllowBoolConversions*/ getLangOpts().ZVector,
13445 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13446 /*ReportInvalid*/ true);
13447 return InvalidOperands(Loc, LHS, RHS);
13448 }
13449
13450 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13451 RHS.get()->getType()->isSveVLSBuiltinType()) {
13452 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13454 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13456 return InvalidOperands(Loc, LHS, RHS);
13457 }
13458
13459 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13460 RHS.get()->getType()->isSveVLSBuiltinType()) {
13461 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13463 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13465 return InvalidOperands(Loc, LHS, RHS);
13466 }
13467
13468 if (Opc == BO_And)
13469 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13470
13471 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13473 return InvalidOperands(Loc, LHS, RHS);
13474
13475 ExprResult LHSResult = LHS, RHSResult = RHS;
13477 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13478 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13479 return QualType();
13480 LHS = LHSResult.get();
13481 RHS = RHSResult.get();
13482
13483 if (Opc == BO_Xor)
13484 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13485
13486 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13487 return compType;
13488 return InvalidOperands(Loc, LHS, RHS);
13489}
13490
13491// C99 6.5.[13,14]
13493 SourceLocation Loc,
13494 BinaryOperatorKind Opc) {
13495 // Check vector operands differently.
13496 if (LHS.get()->getType()->isVectorType() ||
13497 RHS.get()->getType()->isVectorType())
13498 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13499
13500 bool EnumConstantInBoolContext = false;
13501 for (const ExprResult &HS : {LHS, RHS}) {
13502 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13503 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13504 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13505 EnumConstantInBoolContext = true;
13506 }
13507 }
13508
13509 if (EnumConstantInBoolContext)
13510 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13511
13512 // WebAssembly tables can't be used with logical operators.
13513 QualType LHSTy = LHS.get()->getType();
13514 QualType RHSTy = RHS.get()->getType();
13515 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13516 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13517 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13518 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13519 return InvalidOperands(Loc, LHS, RHS);
13520 }
13521
13522 // Diagnose cases where the user write a logical and/or but probably meant a
13523 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13524 // is a constant.
13525 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13526 !LHS.get()->getType()->isBooleanType() &&
13527 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13528 // Don't warn in macros or template instantiations.
13529 !Loc.isMacroID() && !inTemplateInstantiation()) {
13530 // If the RHS can be constant folded, and if it constant folds to something
13531 // that isn't 0 or 1 (which indicate a potential logical operation that
13532 // happened to fold to true/false) then warn.
13533 // Parens on the RHS are ignored.
13534 Expr::EvalResult EVResult;
13535 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13536 llvm::APSInt Result = EVResult.Val.getInt();
13537 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13538 !RHS.get()->getExprLoc().isMacroID()) ||
13539 (Result != 0 && Result != 1)) {
13540 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13541 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13542 // Suggest replacing the logical operator with the bitwise version
13543 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13544 << (Opc == BO_LAnd ? "&" : "|")
13547 Opc == BO_LAnd ? "&" : "|");
13548 if (Opc == BO_LAnd)
13549 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13550 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13553 RHS.get()->getEndLoc()));
13554 }
13555 }
13556 }
13557
13558 if (!Context.getLangOpts().CPlusPlus) {
13559 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13560 // not operate on the built-in scalar and vector float types.
13561 if (Context.getLangOpts().OpenCL &&
13562 Context.getLangOpts().OpenCLVersion < 120) {
13563 if (LHS.get()->getType()->isFloatingType() ||
13564 RHS.get()->getType()->isFloatingType())
13565 return InvalidOperands(Loc, LHS, RHS);
13566 }
13567
13568 LHS = UsualUnaryConversions(LHS.get());
13569 if (LHS.isInvalid())
13570 return QualType();
13571
13572 RHS = UsualUnaryConversions(RHS.get());
13573 if (RHS.isInvalid())
13574 return QualType();
13575
13576 if (!LHS.get()->getType()->isScalarType() ||
13577 !RHS.get()->getType()->isScalarType())
13578 return InvalidOperands(Loc, LHS, RHS);
13579
13580 return Context.IntTy;
13581 }
13582
13583 // The following is safe because we only use this method for
13584 // non-overloadable operands.
13585
13586 // C++ [expr.log.and]p1
13587 // C++ [expr.log.or]p1
13588 // The operands are both contextually converted to type bool.
13590 if (LHSRes.isInvalid())
13591 return InvalidOperands(Loc, LHS, RHS);
13592 LHS = LHSRes;
13593
13595 if (RHSRes.isInvalid())
13596 return InvalidOperands(Loc, LHS, RHS);
13597 RHS = RHSRes;
13598
13599 // C++ [expr.log.and]p2
13600 // C++ [expr.log.or]p2
13601 // The result is a bool.
13602 return Context.BoolTy;
13603}
13604
13605static bool IsReadonlyMessage(Expr *E, Sema &S) {
13606 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13607 if (!ME) return false;
13608 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13609 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13611 if (!Base) return false;
13612 return Base->getMethodDecl() != nullptr;
13613}
13614
13615/// Is the given expression (which must be 'const') a reference to a
13616/// variable which was originally non-const, but which has become
13617/// 'const' due to being captured within a block?
13620 assert(E->isLValue() && E->getType().isConstQualified());
13621 E = E->IgnoreParens();
13622
13623 // Must be a reference to a declaration from an enclosing scope.
13624 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13625 if (!DRE) return NCCK_None;
13627
13628 // The declaration must be a variable which is not declared 'const'.
13629 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13630 if (!var) return NCCK_None;
13631 if (var->getType().isConstQualified()) return NCCK_None;
13632 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13633
13634 // Decide whether the first capture was for a block or a lambda.
13635 DeclContext *DC = S.CurContext, *Prev = nullptr;
13636 // Decide whether the first capture was for a block or a lambda.
13637 while (DC) {
13638 // For init-capture, it is possible that the variable belongs to the
13639 // template pattern of the current context.
13640 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13641 if (var->isInitCapture() &&
13642 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13643 break;
13644 if (DC == var->getDeclContext())
13645 break;
13646 Prev = DC;
13647 DC = DC->getParent();
13648 }
13649 // Unless we have an init-capture, we've gone one step too far.
13650 if (!var->isInitCapture())
13651 DC = Prev;
13652 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13653}
13654
13655static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13656 Ty = Ty.getNonReferenceType();
13657 if (IsDereference && Ty->isPointerType())
13658 Ty = Ty->getPointeeType();
13659 return !Ty.isConstQualified();
13660}
13661
13662// Update err_typecheck_assign_const and note_typecheck_assign_const
13663// when this enum is changed.
13664enum {
13670 ConstUnknown, // Keep as last element
13671};
13672
13673/// Emit the "read-only variable not assignable" error and print notes to give
13674/// more information about why the variable is not assignable, such as pointing
13675/// to the declaration of a const variable, showing that a method is const, or
13676/// that the function is returning a const reference.
13677static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13678 SourceLocation Loc) {
13679 SourceRange ExprRange = E->getSourceRange();
13680
13681 // Only emit one error on the first const found. All other consts will emit
13682 // a note to the error.
13683 bool DiagnosticEmitted = false;
13684
13685 // Track if the current expression is the result of a dereference, and if the
13686 // next checked expression is the result of a dereference.
13687 bool IsDereference = false;
13688 bool NextIsDereference = false;
13689
13690 // Loop to process MemberExpr chains.
13691 while (true) {
13692 IsDereference = NextIsDereference;
13693
13695 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13696 NextIsDereference = ME->isArrow();
13697 const ValueDecl *VD = ME->getMemberDecl();
13698 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13699 // Mutable fields can be modified even if the class is const.
13700 if (Field->isMutable()) {
13701 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13702 break;
13703 }
13704
13705 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13706 if (!DiagnosticEmitted) {
13707 S.Diag(Loc, diag::err_typecheck_assign_const)
13708 << ExprRange << ConstMember << false /*static*/ << Field
13709 << Field->getType();
13710 DiagnosticEmitted = true;
13711 }
13712 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13713 << ConstMember << false /*static*/ << Field << Field->getType()
13714 << Field->getSourceRange();
13715 }
13716 E = ME->getBase();
13717 continue;
13718 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13719 if (VDecl->getType().isConstQualified()) {
13720 if (!DiagnosticEmitted) {
13721 S.Diag(Loc, diag::err_typecheck_assign_const)
13722 << ExprRange << ConstMember << true /*static*/ << VDecl
13723 << VDecl->getType();
13724 DiagnosticEmitted = true;
13725 }
13726 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13727 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13728 << VDecl->getSourceRange();
13729 }
13730 // Static fields do not inherit constness from parents.
13731 break;
13732 }
13733 break; // End MemberExpr
13734 } else if (const ArraySubscriptExpr *ASE =
13735 dyn_cast<ArraySubscriptExpr>(E)) {
13736 E = ASE->getBase()->IgnoreParenImpCasts();
13737 continue;
13738 } else if (const ExtVectorElementExpr *EVE =
13739 dyn_cast<ExtVectorElementExpr>(E)) {
13740 E = EVE->getBase()->IgnoreParenImpCasts();
13741 continue;
13742 }
13743 break;
13744 }
13745
13746 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13747 // Function calls
13748 const FunctionDecl *FD = CE->getDirectCallee();
13749 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13750 if (!DiagnosticEmitted) {
13751 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13752 << ConstFunction << FD;
13753 DiagnosticEmitted = true;
13754 }
13756 diag::note_typecheck_assign_const)
13757 << ConstFunction << FD << FD->getReturnType()
13758 << FD->getReturnTypeSourceRange();
13759 }
13760 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13761 // Point to variable declaration.
13762 if (const ValueDecl *VD = DRE->getDecl()) {
13763 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13764 if (!DiagnosticEmitted) {
13765 S.Diag(Loc, diag::err_typecheck_assign_const)
13766 << ExprRange << ConstVariable << VD << VD->getType();
13767 DiagnosticEmitted = true;
13768 }
13769 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13770 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13771 }
13772 }
13773 } else if (isa<CXXThisExpr>(E)) {
13774 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13775 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13776 if (MD->isConst()) {
13777 if (!DiagnosticEmitted) {
13778 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13779 << ConstMethod << MD;
13780 DiagnosticEmitted = true;
13781 }
13782 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13783 << ConstMethod << MD << MD->getSourceRange();
13784 }
13785 }
13786 }
13787 }
13788
13789 if (DiagnosticEmitted)
13790 return;
13791
13792 // Can't determine a more specific message, so display the generic error.
13793 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13794}
13795
13801
13803 const RecordType *Ty,
13804 SourceLocation Loc, SourceRange Range,
13805 OriginalExprKind OEK,
13806 bool &DiagnosticEmitted) {
13807 std::vector<const RecordType *> RecordTypeList;
13808 RecordTypeList.push_back(Ty);
13809 unsigned NextToCheckIndex = 0;
13810 // We walk the record hierarchy breadth-first to ensure that we print
13811 // diagnostics in field nesting order.
13812 while (RecordTypeList.size() > NextToCheckIndex) {
13813 bool IsNested = NextToCheckIndex > 0;
13814 for (const FieldDecl *Field :
13815 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13816 // First, check every field for constness.
13817 QualType FieldTy = Field->getType();
13818 if (FieldTy.isConstQualified()) {
13819 if (!DiagnosticEmitted) {
13820 S.Diag(Loc, diag::err_typecheck_assign_const)
13821 << Range << NestedConstMember << OEK << VD
13822 << IsNested << Field;
13823 DiagnosticEmitted = true;
13824 }
13825 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13826 << NestedConstMember << IsNested << Field
13827 << FieldTy << Field->getSourceRange();
13828 }
13829
13830 // Then we append it to the list to check next in order.
13831 FieldTy = FieldTy.getCanonicalType();
13832 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13833 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13834 RecordTypeList.push_back(FieldRecTy);
13835 }
13836 }
13837 ++NextToCheckIndex;
13838 }
13839}
13840
13841/// Emit an error for the case where a record we are trying to assign to has a
13842/// const-qualified field somewhere in its hierarchy.
13843static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13844 SourceLocation Loc) {
13845 QualType Ty = E->getType();
13846 assert(Ty->isRecordType() && "lvalue was not record?");
13847 SourceRange Range = E->getSourceRange();
13848 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13849 bool DiagEmitted = false;
13850
13851 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13852 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13853 Range, OEK_Member, DiagEmitted);
13854 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13855 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13856 Range, OEK_Variable, DiagEmitted);
13857 else
13858 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13859 Range, OEK_LValue, DiagEmitted);
13860 if (!DiagEmitted)
13861 DiagnoseConstAssignment(S, E, Loc);
13862}
13863
13864/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13865/// emit an error and return true. If so, return false.
13867 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13868
13870
13871 SourceLocation OrigLoc = Loc;
13873 &Loc);
13874 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13876 if (IsLV == Expr::MLV_Valid)
13877 return false;
13878
13879 unsigned DiagID = 0;
13880 bool NeedType = false;
13881 switch (IsLV) { // C99 6.5.16p2
13883 // Use a specialized diagnostic when we're assigning to an object
13884 // from an enclosing function or block.
13886 if (NCCK == NCCK_Block)
13887 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13888 else
13889 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13890 break;
13891 }
13892
13893 // In ARC, use some specialized diagnostics for occasions where we
13894 // infer 'const'. These are always pseudo-strong variables.
13895 if (S.getLangOpts().ObjCAutoRefCount) {
13896 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13897 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13898 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13899
13900 // Use the normal diagnostic if it's pseudo-__strong but the
13901 // user actually wrote 'const'.
13902 if (var->isARCPseudoStrong() &&
13903 (!var->getTypeSourceInfo() ||
13905 // There are three pseudo-strong cases:
13906 // - self
13907 ObjCMethodDecl *method = S.getCurMethodDecl();
13908 if (method && var == method->getSelfDecl()) {
13909 DiagID = method->isClassMethod()
13910 ? diag::err_typecheck_arc_assign_self_class_method
13911 : diag::err_typecheck_arc_assign_self;
13912
13913 // - Objective-C externally_retained attribute.
13914 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13915 isa<ParmVarDecl>(var)) {
13916 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13917
13918 // - fast enumeration variables
13919 } else {
13920 DiagID = diag::err_typecheck_arr_assign_enumeration;
13921 }
13922
13923 SourceRange Assign;
13924 if (Loc != OrigLoc)
13925 Assign = SourceRange(OrigLoc, OrigLoc);
13926 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13927 // We need to preserve the AST regardless, so migration tool
13928 // can do its job.
13929 return false;
13930 }
13931 }
13932 }
13933
13934 // If none of the special cases above are triggered, then this is a
13935 // simple const assignment.
13936 if (DiagID == 0) {
13937 DiagnoseConstAssignment(S, E, Loc);
13938 return true;
13939 }
13940
13941 break;
13943 DiagnoseConstAssignment(S, E, Loc);
13944 return true;
13947 return true;
13950 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13951 NeedType = true;
13952 break;
13954 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13955 NeedType = true;
13956 break;
13958 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13959 break;
13960 case Expr::MLV_Valid:
13961 llvm_unreachable("did not take early return for MLV_Valid");
13965 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13966 break;
13969 return S.RequireCompleteType(Loc, E->getType(),
13970 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13972 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13973 break;
13975 llvm_unreachable("readonly properties should be processed differently");
13977 DiagID = diag::err_readonly_message_assignment;
13978 break;
13980 DiagID = diag::err_no_subobject_property_setting;
13981 break;
13982 }
13983
13984 SourceRange Assign;
13985 if (Loc != OrigLoc)
13986 Assign = SourceRange(OrigLoc, OrigLoc);
13987 if (NeedType)
13988 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13989 else
13990 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13991 return true;
13992}
13993
13994static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13995 SourceLocation Loc,
13996 Sema &Sema) {
13998 return;
14000 return;
14001 if (Loc.isInvalid() || Loc.isMacroID())
14002 return;
14003 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14004 return;
14005
14006 // C / C++ fields
14007 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14008 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14009 if (ML && MR) {
14010 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14011 return;
14012 const ValueDecl *LHSDecl =
14013 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14014 const ValueDecl *RHSDecl =
14015 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14016 if (LHSDecl != RHSDecl)
14017 return;
14018 if (LHSDecl->getType().isVolatileQualified())
14019 return;
14020 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14021 if (RefTy->getPointeeType().isVolatileQualified())
14022 return;
14023
14024 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14025 }
14026
14027 // Objective-C instance variables
14028 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14029 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14030 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14031 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14032 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14033 if (RL && RR && RL->getDecl() == RR->getDecl())
14034 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14035 }
14036}
14037
14038// C99 6.5.16.1
14040 SourceLocation Loc,
14041 QualType CompoundType,
14042 BinaryOperatorKind Opc) {
14043 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14044
14045 // Verify that LHS is a modifiable lvalue, and emit error if not.
14046 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14047 return QualType();
14048
14049 QualType LHSType = LHSExpr->getType();
14050 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14051 CompoundType;
14052 // OpenCL v1.2 s6.1.1.1 p2:
14053 // The half data type can only be used to declare a pointer to a buffer that
14054 // contains half values
14055 if (getLangOpts().OpenCL &&
14056 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14057 LHSType->isHalfType()) {
14058 Diag(Loc, diag::err_opencl_half_load_store) << 1
14059 << LHSType.getUnqualifiedType();
14060 return QualType();
14061 }
14062
14063 // WebAssembly tables can't be used on RHS of an assignment expression.
14064 if (RHSType->isWebAssemblyTableType()) {
14065 Diag(Loc, diag::err_wasm_table_art) << 0;
14066 return QualType();
14067 }
14068
14069 AssignConvertType ConvTy;
14070 if (CompoundType.isNull()) {
14071 Expr *RHSCheck = RHS.get();
14072
14073 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14074
14075 QualType LHSTy(LHSType);
14076 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14077 if (RHS.isInvalid())
14078 return QualType();
14079 // Special case of NSObject attributes on c-style pointer types.
14080 if (ConvTy == IncompatiblePointer &&
14081 ((Context.isObjCNSObjectType(LHSType) &&
14082 RHSType->isObjCObjectPointerType()) ||
14083 (Context.isObjCNSObjectType(RHSType) &&
14084 LHSType->isObjCObjectPointerType())))
14085 ConvTy = Compatible;
14086
14087 if (ConvTy == Compatible &&
14088 LHSType->isObjCObjectType())
14089 Diag(Loc, diag::err_objc_object_assignment)
14090 << LHSType;
14091
14092 // If the RHS is a unary plus or minus, check to see if they = and + are
14093 // right next to each other. If so, the user may have typo'd "x =+ 4"
14094 // instead of "x += 4".
14095 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14096 RHSCheck = ICE->getSubExpr();
14097 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14098 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14099 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14100 // Only if the two operators are exactly adjacent.
14101 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14102 // And there is a space or other character before the subexpr of the
14103 // unary +/-. We don't want to warn on "x=-1".
14104 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14105 UO->getSubExpr()->getBeginLoc().isFileID()) {
14106 Diag(Loc, diag::warn_not_compound_assign)
14107 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14108 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14109 }
14110 }
14111
14112 if (ConvTy == Compatible) {
14113 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14114 // Warn about retain cycles where a block captures the LHS, but
14115 // not if the LHS is a simple variable into which the block is
14116 // being stored...unless that variable can be captured by reference!
14117 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14118 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14119 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14120 checkRetainCycles(LHSExpr, RHS.get());
14121 }
14122
14123 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14125 // It is safe to assign a weak reference into a strong variable.
14126 // Although this code can still have problems:
14127 // id x = self.weakProp;
14128 // id y = self.weakProp;
14129 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14130 // paths through the function. This should be revisited if
14131 // -Wrepeated-use-of-weak is made flow-sensitive.
14132 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14133 // variable, which will be valid for the current autorelease scope.
14134 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14135 RHS.get()->getBeginLoc()))
14137
14138 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14139 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14140 }
14141 }
14142 } else {
14143 // Compound assignment "x += y"
14144 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14145 }
14146
14147 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14148 RHS.get(), AA_Assigning))
14149 return QualType();
14150
14151 CheckForNullPointerDereference(*this, LHSExpr);
14152
14153 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14154 if (CompoundType.isNull()) {
14155 // C++2a [expr.ass]p5:
14156 // A simple-assignment whose left operand is of a volatile-qualified
14157 // type is deprecated unless the assignment is either a discarded-value
14158 // expression or an unevaluated operand
14159 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14160 }
14161 }
14162
14163 // C11 6.5.16p3: The type of an assignment expression is the type of the
14164 // left operand would have after lvalue conversion.
14165 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14166 // qualified type, the value has the unqualified version of the type of the
14167 // lvalue; additionally, if the lvalue has atomic type, the value has the
14168 // non-atomic version of the type of the lvalue.
14169 // C++ 5.17p1: the type of the assignment expression is that of its left
14170 // operand.
14171 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14172}
14173
14174// Scenarios to ignore if expression E is:
14175// 1. an explicit cast expression into void
14176// 2. a function call expression that returns void
14177static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14178 E = E->IgnoreParens();
14179
14180 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14181 if (CE->getCastKind() == CK_ToVoid) {
14182 return true;
14183 }
14184
14185 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14186 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14187 CE->getSubExpr()->getType()->isDependentType()) {
14188 return true;
14189 }
14190 }
14191
14192 if (const auto *CE = dyn_cast<CallExpr>(E))
14193 return CE->getCallReturnType(Context)->isVoidType();
14194 return false;
14195}
14196
14197// Look for instances where it is likely the comma operator is confused with
14198// another operator. There is an explicit list of acceptable expressions for
14199// the left hand side of the comma operator, otherwise emit a warning.
14201 // No warnings in macros
14202 if (Loc.isMacroID())
14203 return;
14204
14205 // Don't warn in template instantiations.
14207 return;
14208
14209 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14210 // instead, skip more than needed, then call back into here with the
14211 // CommaVisitor in SemaStmt.cpp.
14212 // The listed locations are the initialization and increment portions
14213 // of a for loop. The additional checks are on the condition of
14214 // if statements, do/while loops, and for loops.
14215 // Differences in scope flags for C89 mode requires the extra logic.
14216 const unsigned ForIncrementFlags =
14217 getLangOpts().C99 || getLangOpts().CPlusPlus
14220 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14221 const unsigned ScopeFlags = getCurScope()->getFlags();
14222 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14223 (ScopeFlags & ForInitFlags) == ForInitFlags)
14224 return;
14225
14226 // If there are multiple comma operators used together, get the RHS of the
14227 // of the comma operator as the LHS.
14228 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14229 if (BO->getOpcode() != BO_Comma)
14230 break;
14231 LHS = BO->getRHS();
14232 }
14233
14234 // Only allow some expressions on LHS to not warn.
14235 if (IgnoreCommaOperand(LHS, Context))
14236 return;
14237
14238 Diag(Loc, diag::warn_comma_operator);
14239 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14240 << LHS->getSourceRange()
14242 LangOpts.CPlusPlus ? "static_cast<void>("
14243 : "(void)(")
14245 ")");
14246}
14247
14248// C99 6.5.17
14250 SourceLocation Loc) {
14251 LHS = S.CheckPlaceholderExpr(LHS.get());
14252 RHS = S.CheckPlaceholderExpr(RHS.get());
14253 if (LHS.isInvalid() || RHS.isInvalid())
14254 return QualType();
14255
14256 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14257 // operands, but not unary promotions.
14258 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14259
14260 // So we treat the LHS as a ignored value, and in C++ we allow the
14261 // containing site to determine what should be done with the RHS.
14262 LHS = S.IgnoredValueConversions(LHS.get());
14263 if (LHS.isInvalid())
14264 return QualType();
14265
14266 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14267
14268 if (!S.getLangOpts().CPlusPlus) {
14270 if (RHS.isInvalid())
14271 return QualType();
14272 if (!RHS.get()->getType()->isVoidType())
14273 S.RequireCompleteType(Loc, RHS.get()->getType(),
14274 diag::err_incomplete_type);
14275 }
14276
14277 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14278 S.DiagnoseCommaOperator(LHS.get(), Loc);
14279
14280 return RHS.get()->getType();
14281}
14282
14283/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14284/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14286 ExprValueKind &VK,
14287 ExprObjectKind &OK,
14288 SourceLocation OpLoc,
14289 bool IsInc, bool IsPrefix) {
14290 if (Op->isTypeDependent())
14291 return S.Context.DependentTy;
14292
14293 QualType ResType = Op->getType();
14294 // Atomic types can be used for increment / decrement where the non-atomic
14295 // versions can, so ignore the _Atomic() specifier for the purpose of
14296 // checking.
14297 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14298 ResType = ResAtomicType->getValueType();
14299
14300 assert(!ResType.isNull() && "no type for increment/decrement expression");
14301
14302 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14303 // Decrement of bool is not allowed.
14304 if (!IsInc) {
14305 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14306 return QualType();
14307 }
14308 // Increment of bool sets it to true, but is deprecated.
14309 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14310 : diag::warn_increment_bool)
14311 << Op->getSourceRange();
14312 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14313 // Error on enum increments and decrements in C++ mode
14314 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14315 return QualType();
14316 } else if (ResType->isRealType()) {
14317 // OK!
14318 } else if (ResType->isPointerType()) {
14319 // C99 6.5.2.4p2, 6.5.6p2
14320 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14321 return QualType();
14322 } else if (ResType->isObjCObjectPointerType()) {
14323 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14324 // Otherwise, we just need a complete type.
14325 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14326 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14327 return QualType();
14328 } else if (ResType->isAnyComplexType()) {
14329 // C99 does not support ++/-- on complex types, we allow as an extension.
14330 S.Diag(OpLoc, diag::ext_increment_complex)
14331 << IsInc << Op->getSourceRange();
14332 } else if (ResType->isPlaceholderType()) {
14334 if (PR.isInvalid()) return QualType();
14335 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14336 IsInc, IsPrefix);
14337 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14338 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14339 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14340 (ResType->castAs<VectorType>()->getVectorKind() !=
14342 // The z vector extensions allow ++ and -- for non-bool vectors.
14343 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14344 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14345 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14346 } else {
14347 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14348 << ResType << int(IsInc) << Op->getSourceRange();
14349 return QualType();
14350 }
14351 // At this point, we know we have a real, complex or pointer type.
14352 // Now make sure the operand is a modifiable lvalue.
14353 if (CheckForModifiableLvalue(Op, OpLoc, S))
14354 return QualType();
14355 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14356 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14357 // An operand with volatile-qualified type is deprecated
14358 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14359 << IsInc << ResType;
14360 }
14361 // In C++, a prefix increment is the same type as the operand. Otherwise
14362 // (in C or with postfix), the increment is the unqualified type of the
14363 // operand.
14364 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14365 VK = VK_LValue;
14366 OK = Op->getObjectKind();
14367 return ResType;
14368 } else {
14369 VK = VK_PRValue;
14370 return ResType.getUnqualifiedType();
14371 }
14372}
14373
14374
14375/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14376/// This routine allows us to typecheck complex/recursive expressions
14377/// where the declaration is needed for type checking. We only need to
14378/// handle cases when the expression references a function designator
14379/// or is an lvalue. Here are some examples:
14380/// - &(x) => x
14381/// - &*****f => f for f a function designator.
14382/// - &s.xx => s
14383/// - &s.zz[1].yy -> s, if zz is an array
14384/// - *(x + 1) -> x, if x is an array
14385/// - &"123"[2] -> 0
14386/// - & __real__ x -> x
14387///
14388/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14389/// members.
14391 switch (E->getStmtClass()) {
14392 case Stmt::DeclRefExprClass:
14393 return cast<DeclRefExpr>(E)->getDecl();
14394 case Stmt::MemberExprClass:
14395 // If this is an arrow operator, the address is an offset from
14396 // the base's value, so the object the base refers to is
14397 // irrelevant.
14398 if (cast<MemberExpr>(E)->isArrow())
14399 return nullptr;
14400 // Otherwise, the expression refers to a part of the base
14401 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14402 case Stmt::ArraySubscriptExprClass: {
14403 // FIXME: This code shouldn't be necessary! We should catch the implicit
14404 // promotion of register arrays earlier.
14405 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14406 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14407 if (ICE->getSubExpr()->getType()->isArrayType())
14408 return getPrimaryDecl(ICE->getSubExpr());
14409 }
14410 return nullptr;
14411 }
14412 case Stmt::UnaryOperatorClass: {
14413 UnaryOperator *UO = cast<UnaryOperator>(E);
14414
14415 switch(UO->getOpcode()) {
14416 case UO_Real:
14417 case UO_Imag:
14418 case UO_Extension:
14419 return getPrimaryDecl(UO->getSubExpr());
14420 default:
14421 return nullptr;
14422 }
14423 }
14424 case Stmt::ParenExprClass:
14425 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14426 case Stmt::ImplicitCastExprClass:
14427 // If the result of an implicit cast is an l-value, we care about
14428 // the sub-expression; otherwise, the result here doesn't matter.
14429 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14430 case Stmt::CXXUuidofExprClass:
14431 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14432 default:
14433 return nullptr;
14434 }
14435}
14436
14437namespace {
14438enum {
14439 AO_Bit_Field = 0,
14440 AO_Vector_Element = 1,
14441 AO_Property_Expansion = 2,
14442 AO_Register_Variable = 3,
14443 AO_Matrix_Element = 4,
14444 AO_No_Error = 5
14445};
14446}
14447/// Diagnose invalid operand for address of operations.
14448///
14449/// \param Type The type of operand which cannot have its address taken.
14451 Expr *E, unsigned Type) {
14452 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14453}
14454
14456 const Expr *Op,
14457 const CXXMethodDecl *MD) {
14458 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14459
14460 if (Op != DRE)
14461 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14462 << Op->getSourceRange();
14463
14464 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14465 if (isa<CXXDestructorDecl>(MD))
14466 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14467 << DRE->getSourceRange();
14468
14469 if (DRE->getQualifier())
14470 return false;
14471
14472 if (MD->getParent()->getName().empty())
14473 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14474 << DRE->getSourceRange();
14475
14476 SmallString<32> Str;
14477 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14478 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14479 << DRE->getSourceRange()
14480 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14481}
14482
14483/// CheckAddressOfOperand - The operand of & must be either a function
14484/// designator or an lvalue designating an object. If it is an lvalue, the
14485/// object cannot be declared with storage class register or be a bit field.
14486/// Note: The usual conversions are *not* applied to the operand of the &
14487/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14488/// In C++, the operand might be an overloaded function name, in which case
14489/// we allow the '&' but retain the overloaded-function type.
14491 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14492 if (PTy->getKind() == BuiltinType::Overload) {
14493 Expr *E = OrigOp.get()->IgnoreParens();
14494 if (!isa<OverloadExpr>(E)) {
14495 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14496 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14497 << OrigOp.get()->getSourceRange();
14498 return QualType();
14499 }
14500
14501 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14502 if (isa<UnresolvedMemberExpr>(Ovl))
14504 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14505 << OrigOp.get()->getSourceRange();
14506 return QualType();
14507 }
14508
14509 return Context.OverloadTy;
14510 }
14511
14512 if (PTy->getKind() == BuiltinType::UnknownAny)
14513 return Context.UnknownAnyTy;
14514
14515 if (PTy->getKind() == BuiltinType::BoundMember) {
14516 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14517 << OrigOp.get()->getSourceRange();
14518 return QualType();
14519 }
14520
14521 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14522 if (OrigOp.isInvalid()) return QualType();
14523 }
14524
14525 if (OrigOp.get()->isTypeDependent())
14526 return Context.DependentTy;
14527
14528 assert(!OrigOp.get()->hasPlaceholderType());
14529
14530 // Make sure to ignore parentheses in subsequent checks
14531 Expr *op = OrigOp.get()->IgnoreParens();
14532
14533 // In OpenCL captures for blocks called as lambda functions
14534 // are located in the private address space. Blocks used in
14535 // enqueue_kernel can be located in a different address space
14536 // depending on a vendor implementation. Thus preventing
14537 // taking an address of the capture to avoid invalid AS casts.
14538 if (LangOpts.OpenCL) {
14539 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14540 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14541 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14542 return QualType();
14543 }
14544 }
14545
14546 if (getLangOpts().C99) {
14547 // Implement C99-only parts of addressof rules.
14548 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14549 if (uOp->getOpcode() == UO_Deref)
14550 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14551 // (assuming the deref expression is valid).
14552 return uOp->getSubExpr()->getType();
14553 }
14554 // Technically, there should be a check for array subscript
14555 // expressions here, but the result of one is always an lvalue anyway.
14556 }
14557 ValueDecl *dcl = getPrimaryDecl(op);
14558
14559 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14560 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14561 op->getBeginLoc()))
14562 return QualType();
14563
14565 unsigned AddressOfError = AO_No_Error;
14566
14567 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14568 bool sfinae = (bool)isSFINAEContext();
14569 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14570 : diag::ext_typecheck_addrof_temporary)
14571 << op->getType() << op->getSourceRange();
14572 if (sfinae)
14573 return QualType();
14574 // Materialize the temporary as an lvalue so that we can take its address.
14575 OrigOp = op =
14576 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14577 } else if (isa<ObjCSelectorExpr>(op)) {
14578 return Context.getPointerType(op->getType());
14579 } else if (lval == Expr::LV_MemberFunction) {
14580 // If it's an instance method, make a member pointer.
14581 // The expression must have exactly the form &A::foo.
14582
14583 // If the underlying expression isn't a decl ref, give up.
14584 if (!isa<DeclRefExpr>(op)) {
14585 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14586 << OrigOp.get()->getSourceRange();
14587 return QualType();
14588 }
14589 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14590 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14591
14592 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14593
14596 // Under the MS ABI, lock down the inheritance model now.
14598 (void)isCompleteType(OpLoc, MPTy);
14599 return MPTy;
14600 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14601 // C99 6.5.3.2p1
14602 // The operand must be either an l-value or a function designator
14603 if (!op->getType()->isFunctionType()) {
14604 // Use a special diagnostic for loads from property references.
14605 if (isa<PseudoObjectExpr>(op)) {
14606 AddressOfError = AO_Property_Expansion;
14607 } else {
14608 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14609 << op->getType() << op->getSourceRange();
14610 return QualType();
14611 }
14612 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14613 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14614 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14615 }
14616
14617 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14618 // The operand cannot be a bit-field
14619 AddressOfError = AO_Bit_Field;
14620 } else if (op->getObjectKind() == OK_VectorComponent) {
14621 // The operand cannot be an element of a vector
14622 AddressOfError = AO_Vector_Element;
14623 } else if (op->getObjectKind() == OK_MatrixComponent) {
14624 // The operand cannot be an element of a matrix.
14625 AddressOfError = AO_Matrix_Element;
14626 } else if (dcl) { // C99 6.5.3.2p1
14627 // We have an lvalue with a decl. Make sure the decl is not declared
14628 // with the register storage-class specifier.
14629 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14630 // in C++ it is not error to take address of a register
14631 // variable (c++03 7.1.1P3)
14632 if (vd->getStorageClass() == SC_Register &&
14634 AddressOfError = AO_Register_Variable;
14635 }
14636 } else if (isa<MSPropertyDecl>(dcl)) {
14637 AddressOfError = AO_Property_Expansion;
14638 } else if (isa<FunctionTemplateDecl>(dcl)) {
14639 return Context.OverloadTy;
14640 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14641 // Okay: we can take the address of a field.
14642 // Could be a pointer to member, though, if there is an explicit
14643 // scope qualifier for the class.
14644 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14645 DeclContext *Ctx = dcl->getDeclContext();
14646 if (Ctx && Ctx->isRecord()) {
14647 if (dcl->getType()->isReferenceType()) {
14648 Diag(OpLoc,
14649 diag::err_cannot_form_pointer_to_member_of_reference_type)
14650 << dcl->getDeclName() << dcl->getType();
14651 return QualType();
14652 }
14653
14654 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14655 Ctx = Ctx->getParent();
14656
14658 op->getType(),
14659 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14660 // Under the MS ABI, lock down the inheritance model now.
14662 (void)isCompleteType(OpLoc, MPTy);
14663 return MPTy;
14664 }
14665 }
14668 llvm_unreachable("Unknown/unexpected decl type");
14669 }
14670
14671 if (AddressOfError != AO_No_Error) {
14672 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14673 return QualType();
14674 }
14675
14676 if (lval == Expr::LV_IncompleteVoidType) {
14677 // Taking the address of a void variable is technically illegal, but we
14678 // allow it in cases which are otherwise valid.
14679 // Example: "extern void x; void* y = &x;".
14680 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14681 }
14682
14683 // If the operand has type "type", the result has type "pointer to type".
14684 if (op->getType()->isObjCObjectType())
14686
14687 // Cannot take the address of WebAssembly references or tables.
14688 if (Context.getTargetInfo().getTriple().isWasm()) {
14689 QualType OpTy = op->getType();
14690 if (OpTy.isWebAssemblyReferenceType()) {
14691 Diag(OpLoc, diag::err_wasm_ca_reference)
14692 << 1 << OrigOp.get()->getSourceRange();
14693 return QualType();
14694 }
14695 if (OpTy->isWebAssemblyTableType()) {
14696 Diag(OpLoc, diag::err_wasm_table_pr)
14697 << 1 << OrigOp.get()->getSourceRange();
14698 return QualType();
14699 }
14700 }
14701
14702 CheckAddressOfPackedMember(op);
14703
14704 return Context.getPointerType(op->getType());
14705}
14706
14707static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14708 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14709 if (!DRE)
14710 return;
14711 const Decl *D = DRE->getDecl();
14712 if (!D)
14713 return;
14714 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14715 if (!Param)
14716 return;
14717 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14718 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14719 return;
14720 if (FunctionScopeInfo *FD = S.getCurFunction())
14721 FD->ModifiedNonNullParams.insert(Param);
14722}
14723
14724/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14726 SourceLocation OpLoc,
14727 bool IsAfterAmp = false) {
14728 if (Op->isTypeDependent())
14729 return S.Context.DependentTy;
14730
14731 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14732 if (ConvResult.isInvalid())
14733 return QualType();
14734 Op = ConvResult.get();
14735 QualType OpTy = Op->getType();
14737
14738 if (isa<CXXReinterpretCastExpr>(Op)) {
14739 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14740 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14741 Op->getSourceRange());
14742 }
14743
14744 if (const PointerType *PT = OpTy->getAs<PointerType>())
14745 {
14746 Result = PT->getPointeeType();
14747 }
14748 else if (const ObjCObjectPointerType *OPT =
14750 Result = OPT->getPointeeType();
14751 else {
14753 if (PR.isInvalid()) return QualType();
14754 if (PR.get() != Op)
14755 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14756 }
14757
14758 if (Result.isNull()) {
14759 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14760 << OpTy << Op->getSourceRange();
14761 return QualType();
14762 }
14763
14764 if (Result->isVoidType()) {
14765 // C++ [expr.unary.op]p1:
14766 // [...] the expression to which [the unary * operator] is applied shall
14767 // be a pointer to an object type, or a pointer to a function type
14768 LangOptions LO = S.getLangOpts();
14769 if (LO.CPlusPlus)
14770 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14771 << OpTy << Op->getSourceRange();
14772 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14773 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14774 << OpTy << Op->getSourceRange();
14775 }
14776
14777 // Dereferences are usually l-values...
14778 VK = VK_LValue;
14779
14780 // ...except that certain expressions are never l-values in C.
14781 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14782 VK = VK_PRValue;
14783
14784 return Result;
14785}
14786
14787BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14789 switch (Kind) {
14790 default: llvm_unreachable("Unknown binop!");
14791 case tok::periodstar: Opc = BO_PtrMemD; break;
14792 case tok::arrowstar: Opc = BO_PtrMemI; break;
14793 case tok::star: Opc = BO_Mul; break;
14794 case tok::slash: Opc = BO_Div; break;
14795 case tok::percent: Opc = BO_Rem; break;
14796 case tok::plus: Opc = BO_Add; break;
14797 case tok::minus: Opc = BO_Sub; break;
14798 case tok::lessless: Opc = BO_Shl; break;
14799 case tok::greatergreater: Opc = BO_Shr; break;
14800 case tok::lessequal: Opc = BO_LE; break;
14801 case tok::less: Opc = BO_LT; break;
14802 case tok::greaterequal: Opc = BO_GE; break;
14803 case tok::greater: Opc = BO_GT; break;
14804 case tok::exclaimequal: Opc = BO_NE; break;
14805 case tok::equalequal: Opc = BO_EQ; break;
14806 case tok::spaceship: Opc = BO_Cmp; break;
14807 case tok::amp: Opc = BO_And; break;
14808 case tok::caret: Opc = BO_Xor; break;
14809 case tok::pipe: Opc = BO_Or; break;
14810 case tok::ampamp: Opc = BO_LAnd; break;
14811 case tok::pipepipe: Opc = BO_LOr; break;
14812 case tok::equal: Opc = BO_Assign; break;
14813 case tok::starequal: Opc = BO_MulAssign; break;
14814 case tok::slashequal: Opc = BO_DivAssign; break;
14815 case tok::percentequal: Opc = BO_RemAssign; break;
14816 case tok::plusequal: Opc = BO_AddAssign; break;
14817 case tok::minusequal: Opc = BO_SubAssign; break;
14818 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14819 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14820 case tok::ampequal: Opc = BO_AndAssign; break;
14821 case tok::caretequal: Opc = BO_XorAssign; break;
14822 case tok::pipeequal: Opc = BO_OrAssign; break;
14823 case tok::comma: Opc = BO_Comma; break;
14824 }
14825 return Opc;
14826}
14827
14829 tok::TokenKind Kind) {
14831 switch (Kind) {
14832 default: llvm_unreachable("Unknown unary op!");
14833 case tok::plusplus: Opc = UO_PreInc; break;
14834 case tok::minusminus: Opc = UO_PreDec; break;
14835 case tok::amp: Opc = UO_AddrOf; break;
14836 case tok::star: Opc = UO_Deref; break;
14837 case tok::plus: Opc = UO_Plus; break;
14838 case tok::minus: Opc = UO_Minus; break;
14839 case tok::tilde: Opc = UO_Not; break;
14840 case tok::exclaim: Opc = UO_LNot; break;
14841 case tok::kw___real: Opc = UO_Real; break;
14842 case tok::kw___imag: Opc = UO_Imag; break;
14843 case tok::kw___extension__: Opc = UO_Extension; break;
14844 }
14845 return Opc;
14846}
14847
14848const FieldDecl *
14850 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14851 // common for setters.
14852 // struct A {
14853 // int X;
14854 // -void setX(int X) { X = X; }
14855 // +void setX(int X) { this->X = X; }
14856 // };
14857
14858 // Only consider parameters for self assignment fixes.
14859 if (!isa<ParmVarDecl>(SelfAssigned))
14860 return nullptr;
14861 const auto *Method =
14862 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14863 if (!Method)
14864 return nullptr;
14865
14866 const CXXRecordDecl *Parent = Method->getParent();
14867 // In theory this is fixable if the lambda explicitly captures this, but
14868 // that's added complexity that's rarely going to be used.
14869 if (Parent->isLambda())
14870 return nullptr;
14871
14872 // FIXME: Use an actual Lookup operation instead of just traversing fields
14873 // in order to get base class fields.
14874 auto Field =
14875 llvm::find_if(Parent->fields(),
14876 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14877 return F->getDeclName() == Name;
14878 });
14879 return (Field != Parent->field_end()) ? *Field : nullptr;
14880}
14881
14882/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14883/// This warning suppressed in the event of macro expansions.
14884static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14885 SourceLocation OpLoc, bool IsBuiltin) {
14887 return;
14888 if (S.isUnevaluatedContext())
14889 return;
14890 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14891 return;
14892 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14893 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14894 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14895 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14896 if (!LHSDeclRef || !RHSDeclRef ||
14897 LHSDeclRef->getLocation().isMacroID() ||
14898 RHSDeclRef->getLocation().isMacroID())
14899 return;
14900 const ValueDecl *LHSDecl =
14901 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14902 const ValueDecl *RHSDecl =
14903 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14904 if (LHSDecl != RHSDecl)
14905 return;
14906 if (LHSDecl->getType().isVolatileQualified())
14907 return;
14908 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14909 if (RefTy->getPointeeType().isVolatileQualified())
14910 return;
14911
14912 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14913 : diag::warn_self_assignment_overloaded)
14914 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14915 << RHSExpr->getSourceRange();
14916 if (const FieldDecl *SelfAssignField =
14918 Diag << 1 << SelfAssignField
14919 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14920 else
14921 Diag << 0;
14922}
14923
14924/// Check if a bitwise-& is performed on an Objective-C pointer. This
14925/// is usually indicative of introspection within the Objective-C pointer.
14927 SourceLocation OpLoc) {
14928 if (!S.getLangOpts().ObjC)
14929 return;
14930
14931 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14932 const Expr *LHS = L.get();
14933 const Expr *RHS = R.get();
14934
14936 ObjCPointerExpr = LHS;
14937 OtherExpr = RHS;
14938 }
14939 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14940 ObjCPointerExpr = RHS;
14941 OtherExpr = LHS;
14942 }
14943
14944 // This warning is deliberately made very specific to reduce false
14945 // positives with logic that uses '&' for hashing. This logic mainly
14946 // looks for code trying to introspect into tagged pointers, which
14947 // code should generally never do.
14948 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14949 unsigned Diag = diag::warn_objc_pointer_masking;
14950 // Determine if we are introspecting the result of performSelectorXXX.
14951 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14952 // Special case messages to -performSelector and friends, which
14953 // can return non-pointer values boxed in a pointer value.
14954 // Some clients may wish to silence warnings in this subcase.
14955 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14956 Selector S = ME->getSelector();
14957 StringRef SelArg0 = S.getNameForSlot(0);
14958 if (SelArg0.starts_with("performSelector"))
14959 Diag = diag::warn_objc_pointer_masking_performSelector;
14960 }
14961
14962 S.Diag(OpLoc, Diag)
14963 << ObjCPointerExpr->getSourceRange();
14964 }
14965}
14966
14968 if (!E)
14969 return nullptr;
14970 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14971 return DRE->getDecl();
14972 if (auto *ME = dyn_cast<MemberExpr>(E))
14973 return ME->getMemberDecl();
14974 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14975 return IRE->getDecl();
14976 return nullptr;
14977}
14978
14979// This helper function promotes a binary operator's operands (which are of a
14980// half vector type) to a vector of floats and then truncates the result to
14981// a vector of either half or short.
14983 BinaryOperatorKind Opc, QualType ResultTy,
14985 bool IsCompAssign, SourceLocation OpLoc,
14986 FPOptionsOverride FPFeatures) {
14987 auto &Context = S.getASTContext();
14988 assert((isVector(ResultTy, Context.HalfTy) ||
14989 isVector(ResultTy, Context.ShortTy)) &&
14990 "Result must be a vector of half or short");
14991 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14992 isVector(RHS.get()->getType(), Context.HalfTy) &&
14993 "both operands expected to be a half vector");
14994
14995 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14996 QualType BinOpResTy = RHS.get()->getType();
14997
14998 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14999 // change BinOpResTy to a vector of ints.
15000 if (isVector(ResultTy, Context.ShortTy))
15001 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15002
15003 if (IsCompAssign)
15004 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15005 ResultTy, VK, OK, OpLoc, FPFeatures,
15006 BinOpResTy, BinOpResTy);
15007
15008 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15009 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15010 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15011 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15012}
15013
15014static std::pair<ExprResult, ExprResult>
15016 Expr *RHSExpr) {
15017 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15018 if (!S.Context.isDependenceAllowed()) {
15019 // C cannot handle TypoExpr nodes on either side of a binop because it
15020 // doesn't handle dependent types properly, so make sure any TypoExprs have
15021 // been dealt with before checking the operands.
15022 LHS = S.CorrectDelayedTyposInExpr(LHS);
15024 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15025 [Opc, LHS](Expr *E) {
15026 if (Opc != BO_Assign)
15027 return ExprResult(E);
15028 // Avoid correcting the RHS to the same Expr as the LHS.
15029 Decl *D = getDeclFromExpr(E);
15030 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15031 });
15032 }
15033 return std::make_pair(LHS, RHS);
15034}
15035
15036/// Returns true if conversion between vectors of halfs and vectors of floats
15037/// is needed.
15038static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15039 Expr *E0, Expr *E1 = nullptr) {
15040 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15042 return false;
15043
15044 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15045 QualType Ty = E->IgnoreImplicit()->getType();
15046
15047 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15048 // to vectors of floats. Although the element type of the vectors is __fp16,
15049 // the vectors shouldn't be treated as storage-only types. See the
15050 // discussion here: https://reviews.llvm.org/rG825235c140e7
15051 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15052 if (VT->getVectorKind() == VectorKind::Neon)
15053 return false;
15054 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15055 }
15056 return false;
15057 };
15058
15059 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15060}
15061
15062/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15063/// operator @p Opc at location @c TokLoc. This routine only supports
15064/// built-in operations; ActOnBinOp handles overloaded operators.
15067 Expr *LHSExpr, Expr *RHSExpr) {
15068 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15069 // The syntax only allows initializer lists on the RHS of assignment,
15070 // so we don't need to worry about accepting invalid code for
15071 // non-assignment operators.
15072 // C++11 5.17p9:
15073 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15074 // of x = {} is x = T().
15076 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15077 InitializedEntity Entity =
15079 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15080 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15081 if (Init.isInvalid())
15082 return Init;
15083 RHSExpr = Init.get();
15084 }
15085
15086 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15087 QualType ResultTy; // Result type of the binary operator.
15088 // The following two variables are used for compound assignment operators
15089 QualType CompLHSTy; // Type of LHS after promotions for computation
15090 QualType CompResultTy; // Type of computation result
15093 bool ConvertHalfVec = false;
15094
15095 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15096 if (!LHS.isUsable() || !RHS.isUsable())
15097 return ExprError();
15098
15099 if (getLangOpts().OpenCL) {
15100 QualType LHSTy = LHSExpr->getType();
15101 QualType RHSTy = RHSExpr->getType();
15102 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15103 // the ATOMIC_VAR_INIT macro.
15104 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15105 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15106 if (BO_Assign == Opc)
15107 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15108 else
15109 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15110 return ExprError();
15111 }
15112
15113 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15114 // only with a builtin functions and therefore should be disallowed here.
15115 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15116 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15117 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15118 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15119 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15120 return ExprError();
15121 }
15122 }
15123
15124 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15125 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15126
15127 switch (Opc) {
15128 case BO_Assign:
15129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15130 if (getLangOpts().CPlusPlus &&
15131 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15132 VK = LHS.get()->getValueKind();
15133 OK = LHS.get()->getObjectKind();
15134 }
15135 if (!ResultTy.isNull()) {
15136 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15137 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15138
15139 // Avoid copying a block to the heap if the block is assigned to a local
15140 // auto variable that is declared in the same scope as the block. This
15141 // optimization is unsafe if the local variable is declared in an outer
15142 // scope. For example:
15143 //
15144 // BlockTy b;
15145 // {
15146 // b = ^{...};
15147 // }
15148 // // It is unsafe to invoke the block here if it wasn't copied to the
15149 // // heap.
15150 // b();
15151
15152 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15153 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15154 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15155 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15156 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15157
15159 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15161 }
15162 RecordModifiableNonNullParam(*this, LHS.get());
15163 break;
15164 case BO_PtrMemD:
15165 case BO_PtrMemI:
15166 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15167 Opc == BO_PtrMemI);
15168 break;
15169 case BO_Mul:
15170 case BO_Div:
15171 ConvertHalfVec = true;
15172 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15173 Opc == BO_Div);
15174 break;
15175 case BO_Rem:
15176 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15177 break;
15178 case BO_Add:
15179 ConvertHalfVec = true;
15180 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15181 break;
15182 case BO_Sub:
15183 ConvertHalfVec = true;
15184 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15185 break;
15186 case BO_Shl:
15187 case BO_Shr:
15188 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15189 break;
15190 case BO_LE:
15191 case BO_LT:
15192 case BO_GE:
15193 case BO_GT:
15194 ConvertHalfVec = true;
15195 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15196 break;
15197 case BO_EQ:
15198 case BO_NE:
15199 ConvertHalfVec = true;
15200 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15201 break;
15202 case BO_Cmp:
15203 ConvertHalfVec = true;
15204 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15205 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15206 break;
15207 case BO_And:
15208 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15209 [[fallthrough]];
15210 case BO_Xor:
15211 case BO_Or:
15212 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15213 break;
15214 case BO_LAnd:
15215 case BO_LOr:
15216 ConvertHalfVec = true;
15217 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15218 break;
15219 case BO_MulAssign:
15220 case BO_DivAssign:
15221 ConvertHalfVec = true;
15222 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15223 Opc == BO_DivAssign);
15224 CompLHSTy = CompResultTy;
15225 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15226 ResultTy =
15227 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15228 break;
15229 case BO_RemAssign:
15230 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15231 CompLHSTy = CompResultTy;
15232 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15233 ResultTy =
15234 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15235 break;
15236 case BO_AddAssign:
15237 ConvertHalfVec = true;
15238 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15240 ResultTy =
15241 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15242 break;
15243 case BO_SubAssign:
15244 ConvertHalfVec = true;
15245 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15246 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15247 ResultTy =
15248 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15249 break;
15250 case BO_ShlAssign:
15251 case BO_ShrAssign:
15252 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15253 CompLHSTy = CompResultTy;
15254 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15255 ResultTy =
15256 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15257 break;
15258 case BO_AndAssign:
15259 case BO_OrAssign: // fallthrough
15260 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15261 [[fallthrough]];
15262 case BO_XorAssign:
15263 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15264 CompLHSTy = CompResultTy;
15265 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15266 ResultTy =
15267 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15268 break;
15269 case BO_Comma:
15270 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15271 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15272 VK = RHS.get()->getValueKind();
15273 OK = RHS.get()->getObjectKind();
15274 }
15275 break;
15276 }
15277 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15278 return ExprError();
15279
15280 // Some of the binary operations require promoting operands of half vector to
15281 // float vectors and truncating the result back to half vector. For now, we do
15282 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15283 // arm64).
15284 assert(
15285 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15286 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15287 "both sides are half vectors or neither sides are");
15288 ConvertHalfVec =
15289 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15290
15291 // Check for array bounds violations for both sides of the BinaryOperator
15292 CheckArrayAccess(LHS.get());
15293 CheckArrayAccess(RHS.get());
15294
15295 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15296 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15297 &Context.Idents.get("object_setClass"),
15299 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15300 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15301 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15303 "object_setClass(")
15304 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15305 ",")
15306 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15307 }
15308 else
15309 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15310 }
15311 else if (const ObjCIvarRefExpr *OIRE =
15312 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15313 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15314
15315 // Opc is not a compound assignment if CompResultTy is null.
15316 if (CompResultTy.isNull()) {
15317 if (ConvertHalfVec)
15318 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15319 OpLoc, CurFPFeatureOverrides());
15320 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15321 VK, OK, OpLoc, CurFPFeatureOverrides());
15322 }
15323
15324 // Handle compound assignments.
15325 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15327 VK = VK_LValue;
15328 OK = LHS.get()->getObjectKind();
15329 }
15330
15331 // The LHS is not converted to the result type for fixed-point compound
15332 // assignment as the common type is computed on demand. Reset the CompLHSTy
15333 // to the LHS type we would have gotten after unary conversions.
15334 if (CompResultTy->isFixedPointType())
15335 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15336
15337 if (ConvertHalfVec)
15338 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15339 OpLoc, CurFPFeatureOverrides());
15340
15342 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15343 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15344}
15345
15346/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15347/// operators are mixed in a way that suggests that the programmer forgot that
15348/// comparison operators have higher precedence. The most typical example of
15349/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15351 SourceLocation OpLoc, Expr *LHSExpr,
15352 Expr *RHSExpr) {
15353 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15354 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15355
15356 // Check that one of the sides is a comparison operator and the other isn't.
15357 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15358 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15359 if (isLeftComp == isRightComp)
15360 return;
15361
15362 // Bitwise operations are sometimes used as eager logical ops.
15363 // Don't diagnose this.
15364 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15365 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15366 if (isLeftBitwise || isRightBitwise)
15367 return;
15368
15369 SourceRange DiagRange = isLeftComp
15370 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15371 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15372 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15373 SourceRange ParensRange =
15374 isLeftComp
15375 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15376 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15377
15378 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15379 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15380 SuggestParentheses(Self, OpLoc,
15381 Self.PDiag(diag::note_precedence_silence) << OpStr,
15382 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15383 SuggestParentheses(Self, OpLoc,
15384 Self.PDiag(diag::note_precedence_bitwise_first)
15386 ParensRange);
15387}
15388
15389/// It accepts a '&&' expr that is inside a '||' one.
15390/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15391/// in parentheses.
15392static void
15394 BinaryOperator *Bop) {
15395 assert(Bop->getOpcode() == BO_LAnd);
15396 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15397 << Bop->getSourceRange() << OpLoc;
15399 Self.PDiag(diag::note_precedence_silence)
15400 << Bop->getOpcodeStr(),
15401 Bop->getSourceRange());
15402}
15403
15404/// Look for '&&' in the left hand of a '||' expr.
15406 Expr *LHSExpr, Expr *RHSExpr) {
15407 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15408 if (Bop->getOpcode() == BO_LAnd) {
15409 // If it's "string_literal && a || b" don't warn since the precedence
15410 // doesn't matter.
15411 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15412 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15413 } else if (Bop->getOpcode() == BO_LOr) {
15414 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15415 // If it's "a || b && string_literal || c" we didn't warn earlier for
15416 // "a || b && string_literal", but warn now.
15417 if (RBop->getOpcode() == BO_LAnd &&
15418 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15419 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15420 }
15421 }
15422 }
15423}
15424
15425/// Look for '&&' in the right hand of a '||' expr.
15427 Expr *LHSExpr, Expr *RHSExpr) {
15428 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15429 if (Bop->getOpcode() == BO_LAnd) {
15430 // If it's "a || b && string_literal" don't warn since the precedence
15431 // doesn't matter.
15432 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15433 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15434 }
15435 }
15436}
15437
15438/// Look for bitwise op in the left or right hand of a bitwise op with
15439/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15440/// the '&' expression in parentheses.
15442 SourceLocation OpLoc, Expr *SubExpr) {
15443 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15444 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15445 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15446 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15447 << Bop->getSourceRange() << OpLoc;
15448 SuggestParentheses(S, Bop->getOperatorLoc(),
15449 S.PDiag(diag::note_precedence_silence)
15450 << Bop->getOpcodeStr(),
15451 Bop->getSourceRange());
15452 }
15453 }
15454}
15455
15457 Expr *SubExpr, StringRef Shift) {
15458 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15459 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15460 StringRef Op = Bop->getOpcodeStr();
15461 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15462 << Bop->getSourceRange() << OpLoc << Shift << Op;
15463 SuggestParentheses(S, Bop->getOperatorLoc(),
15464 S.PDiag(diag::note_precedence_silence) << Op,
15465 Bop->getSourceRange());
15466 }
15467 }
15468}
15469
15471 Expr *LHSExpr, Expr *RHSExpr) {
15472 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15473 if (!OCE)
15474 return;
15475
15476 FunctionDecl *FD = OCE->getDirectCallee();
15477 if (!FD || !FD->isOverloadedOperator())
15478 return;
15479
15481 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15482 return;
15483
15484 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15485 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15486 << (Kind == OO_LessLess);
15488 S.PDiag(diag::note_precedence_silence)
15489 << (Kind == OO_LessLess ? "<<" : ">>"),
15490 OCE->getSourceRange());
15492 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15493 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15494}
15495
15496/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15497/// precedence.
15499 SourceLocation OpLoc, Expr *LHSExpr,
15500 Expr *RHSExpr){
15501 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15503 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15504
15505 // Diagnose "arg1 & arg2 | arg3"
15506 if ((Opc == BO_Or || Opc == BO_Xor) &&
15507 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15508 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15509 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15510 }
15511
15512 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15513 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15514 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15515 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15516 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15517 }
15518
15519 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15520 || Opc == BO_Shr) {
15521 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15522 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15523 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15524 }
15525
15526 // Warn on overloaded shift operators and comparisons, such as:
15527 // cout << 5 == 4;
15529 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15530}
15531
15532// Binary Operators. 'Tok' is the token for the operator.
15534 tok::TokenKind Kind,
15535 Expr *LHSExpr, Expr *RHSExpr) {
15536 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15537 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15538 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15539
15540 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15541 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15542
15543 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15544}
15545
15547 UnresolvedSetImpl &Functions) {
15549 if (OverOp != OO_None && OverOp != OO_Equal)
15550 LookupOverloadedOperatorName(OverOp, S, Functions);
15551
15552 // In C++20 onwards, we may have a second operator to look up.
15553 if (getLangOpts().CPlusPlus20) {
15555 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15556 }
15557}
15558
15559/// Build an overloaded binary operator expression in the given scope.
15562 Expr *LHS, Expr *RHS) {
15563 switch (Opc) {
15564 case BO_Assign:
15565 // In the non-overloaded case, we warn about self-assignment (x = x) for
15566 // both simple assignment and certain compound assignments where algebra
15567 // tells us the operation yields a constant result. When the operator is
15568 // overloaded, we can't do the latter because we don't want to assume that
15569 // those algebraic identities still apply; for example, a path-building
15570 // library might use operator/= to append paths. But it's still reasonable
15571 // to assume that simple assignment is just moving/copying values around
15572 // and so self-assignment is likely a bug.
15573 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15574 [[fallthrough]];
15575 case BO_DivAssign:
15576 case BO_RemAssign:
15577 case BO_SubAssign:
15578 case BO_AndAssign:
15579 case BO_OrAssign:
15580 case BO_XorAssign:
15581 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15582 break;
15583 default:
15584 break;
15585 }
15586
15587 // Find all of the overloaded operators visible from this point.
15588 UnresolvedSet<16> Functions;
15589 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15590
15591 // Build the (potentially-overloaded, potentially-dependent)
15592 // binary operation.
15593 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15594}
15595
15598 Expr *LHSExpr, Expr *RHSExpr) {
15599 ExprResult LHS, RHS;
15600 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15601 if (!LHS.isUsable() || !RHS.isUsable())
15602 return ExprError();
15603 LHSExpr = LHS.get();
15604 RHSExpr = RHS.get();
15605
15606 // We want to end up calling one of checkPseudoObjectAssignment
15607 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15608 // both expressions are overloadable or either is type-dependent),
15609 // or CreateBuiltinBinOp (in any other case). We also want to get
15610 // any placeholder types out of the way.
15611
15612 // Handle pseudo-objects in the LHS.
15613 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15614 // Assignments with a pseudo-object l-value need special analysis.
15615 if (pty->getKind() == BuiltinType::PseudoObject &&
15617 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15618
15619 // Don't resolve overloads if the other type is overloadable.
15620 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15621 // We can't actually test that if we still have a placeholder,
15622 // though. Fortunately, none of the exceptions we see in that
15623 // code below are valid when the LHS is an overload set. Note
15624 // that an overload set can be dependently-typed, but it never
15625 // instantiates to having an overloadable type.
15626 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15627 if (resolvedRHS.isInvalid()) return ExprError();
15628 RHSExpr = resolvedRHS.get();
15629
15630 if (RHSExpr->isTypeDependent() ||
15631 RHSExpr->getType()->isOverloadableType())
15632 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15633 }
15634
15635 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15636 // template, diagnose the missing 'template' keyword instead of diagnosing
15637 // an invalid use of a bound member function.
15638 //
15639 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15640 // to C++1z [over.over]/1.4, but we already checked for that case above.
15641 if (Opc == BO_LT && inTemplateInstantiation() &&
15642 (pty->getKind() == BuiltinType::BoundMember ||
15643 pty->getKind() == BuiltinType::Overload)) {
15644 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15645 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15646 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15647 return isa<FunctionTemplateDecl>(ND);
15648 })) {
15649 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15650 : OE->getNameLoc(),
15651 diag::err_template_kw_missing)
15652 << OE->getName().getAsString() << "";
15653 return ExprError();
15654 }
15655 }
15656
15657 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15658 if (LHS.isInvalid()) return ExprError();
15659 LHSExpr = LHS.get();
15660 }
15661
15662 // Handle pseudo-objects in the RHS.
15663 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15664 // An overload in the RHS can potentially be resolved by the type
15665 // being assigned to.
15666 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15667 if (getLangOpts().CPlusPlus &&
15668 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15669 LHSExpr->getType()->isOverloadableType()))
15670 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15671
15672 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15673 }
15674
15675 // Don't resolve overloads if the other type is overloadable.
15676 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15677 LHSExpr->getType()->isOverloadableType())
15678 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15679
15680 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15681 if (!resolvedRHS.isUsable()) return ExprError();
15682 RHSExpr = resolvedRHS.get();
15683 }
15684
15685 if (getLangOpts().CPlusPlus) {
15686 // If either expression is type-dependent, always build an
15687 // overloaded op.
15688 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15689 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15690
15691 // Otherwise, build an overloaded op if either expression has an
15692 // overloadable type.
15693 if (LHSExpr->getType()->isOverloadableType() ||
15694 RHSExpr->getType()->isOverloadableType())
15695 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15696 }
15697
15698 if (getLangOpts().RecoveryAST &&
15699 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15700 assert(!getLangOpts().CPlusPlus);
15701 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15702 "Should only occur in error-recovery path.");
15704 // C [6.15.16] p3:
15705 // An assignment expression has the value of the left operand after the
15706 // assignment, but is not an lvalue.
15708 Context, LHSExpr, RHSExpr, Opc,
15710 OpLoc, CurFPFeatureOverrides());
15711 QualType ResultType;
15712 switch (Opc) {
15713 case BO_Assign:
15714 ResultType = LHSExpr->getType().getUnqualifiedType();
15715 break;
15716 case BO_LT:
15717 case BO_GT:
15718 case BO_LE:
15719 case BO_GE:
15720 case BO_EQ:
15721 case BO_NE:
15722 case BO_LAnd:
15723 case BO_LOr:
15724 // These operators have a fixed result type regardless of operands.
15725 ResultType = Context.IntTy;
15726 break;
15727 case BO_Comma:
15728 ResultType = RHSExpr->getType();
15729 break;
15730 default:
15731 ResultType = Context.DependentTy;
15732 break;
15733 }
15734 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15735 VK_PRValue, OK_Ordinary, OpLoc,
15737 }
15738
15739 // Build a built-in binary operation.
15740 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15741}
15742
15744 if (T.isNull() || T->isDependentType())
15745 return false;
15746
15747 if (!Ctx.isPromotableIntegerType(T))
15748 return true;
15749
15750 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15751}
15752
15754 UnaryOperatorKind Opc, Expr *InputExpr,
15755 bool IsAfterAmp) {
15756 ExprResult Input = InputExpr;
15759 QualType resultType;
15760 bool CanOverflow = false;
15761
15762 bool ConvertHalfVec = false;
15763 if (getLangOpts().OpenCL) {
15764 QualType Ty = InputExpr->getType();
15765 // The only legal unary operation for atomics is '&'.
15766 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15767 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15768 // only with a builtin functions and therefore should be disallowed here.
15769 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15770 || Ty->isBlockPointerType())) {
15771 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15772 << InputExpr->getType()
15773 << Input.get()->getSourceRange());
15774 }
15775 }
15776
15777 if (getLangOpts().HLSL && OpLoc.isValid()) {
15778 if (Opc == UO_AddrOf)
15779 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15780 if (Opc == UO_Deref)
15781 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15782 }
15783
15784 switch (Opc) {
15785 case UO_PreInc:
15786 case UO_PreDec:
15787 case UO_PostInc:
15788 case UO_PostDec:
15789 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15790 OpLoc,
15791 Opc == UO_PreInc ||
15792 Opc == UO_PostInc,
15793 Opc == UO_PreInc ||
15794 Opc == UO_PreDec);
15795 CanOverflow = isOverflowingIntegerType(Context, resultType);
15796 break;
15797 case UO_AddrOf:
15798 resultType = CheckAddressOfOperand(Input, OpLoc);
15799 CheckAddressOfNoDeref(InputExpr);
15800 RecordModifiableNonNullParam(*this, InputExpr);
15801 break;
15802 case UO_Deref: {
15804 if (Input.isInvalid()) return ExprError();
15805 resultType =
15806 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15807 break;
15808 }
15809 case UO_Plus:
15810 case UO_Minus:
15811 CanOverflow = Opc == UO_Minus &&
15813 Input = UsualUnaryConversions(Input.get());
15814 if (Input.isInvalid()) return ExprError();
15815 // Unary plus and minus require promoting an operand of half vector to a
15816 // float vector and truncating the result back to a half vector. For now, we
15817 // do this only when HalfArgsAndReturns is set (that is, when the target is
15818 // arm or arm64).
15819 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15820
15821 // If the operand is a half vector, promote it to a float vector.
15822 if (ConvertHalfVec)
15823 Input = convertVector(Input.get(), Context.FloatTy, *this);
15824 resultType = Input.get()->getType();
15825 if (resultType->isDependentType())
15826 break;
15827 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15828 break;
15829 else if (resultType->isVectorType() &&
15830 // The z vector extensions don't allow + or - with bool vectors.
15831 (!Context.getLangOpts().ZVector ||
15832 resultType->castAs<VectorType>()->getVectorKind() !=
15834 break;
15835 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15836 break;
15837 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15838 Opc == UO_Plus &&
15839 resultType->isPointerType())
15840 break;
15841
15842 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15843 << resultType << Input.get()->getSourceRange());
15844
15845 case UO_Not: // bitwise complement
15846 Input = UsualUnaryConversions(Input.get());
15847 if (Input.isInvalid())
15848 return ExprError();
15849 resultType = Input.get()->getType();
15850 if (resultType->isDependentType())
15851 break;
15852 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15853 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15854 // C99 does not support '~' for complex conjugation.
15855 Diag(OpLoc, diag::ext_integer_complement_complex)
15856 << resultType << Input.get()->getSourceRange();
15857 else if (resultType->hasIntegerRepresentation())
15858 break;
15859 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15860 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15861 // on vector float types.
15862 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15863 if (!T->isIntegerType())
15864 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15865 << resultType << Input.get()->getSourceRange());
15866 } else {
15867 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15868 << resultType << Input.get()->getSourceRange());
15869 }
15870 break;
15871
15872 case UO_LNot: // logical negation
15873 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15875 if (Input.isInvalid()) return ExprError();
15876 resultType = Input.get()->getType();
15877
15878 // Though we still have to promote half FP to float...
15879 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15880 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15881 resultType = Context.FloatTy;
15882 }
15883
15884 // WebAsembly tables can't be used in unary expressions.
15885 if (resultType->isPointerType() &&
15887 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15888 << resultType << Input.get()->getSourceRange());
15889 }
15890
15891 if (resultType->isDependentType())
15892 break;
15893 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15894 // C99 6.5.3.3p1: ok, fallthrough;
15895 if (Context.getLangOpts().CPlusPlus) {
15896 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15897 // operand contextually converted to bool.
15898 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15899 ScalarTypeToBooleanCastKind(resultType));
15900 } else if (Context.getLangOpts().OpenCL &&
15901 Context.getLangOpts().OpenCLVersion < 120) {
15902 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15903 // operate on scalar float types.
15904 if (!resultType->isIntegerType() && !resultType->isPointerType())
15905 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15906 << resultType << Input.get()->getSourceRange());
15907 }
15908 } else if (resultType->isExtVectorType()) {
15909 if (Context.getLangOpts().OpenCL &&
15911 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15912 // operate on vector float types.
15913 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15914 if (!T->isIntegerType())
15915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15916 << resultType << Input.get()->getSourceRange());
15917 }
15918 // Vector logical not returns the signed variant of the operand type.
15919 resultType = GetSignedVectorType(resultType);
15920 break;
15921 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15922 const VectorType *VTy = resultType->castAs<VectorType>();
15923 if (VTy->getVectorKind() != VectorKind::Generic)
15924 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15925 << resultType << Input.get()->getSourceRange());
15926
15927 // Vector logical not returns the signed variant of the operand type.
15928 resultType = GetSignedVectorType(resultType);
15929 break;
15930 } else {
15931 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15932 << resultType << Input.get()->getSourceRange());
15933 }
15934
15935 // LNot always has type int. C99 6.5.3.3p5.
15936 // In C++, it's bool. C++ 5.3.1p8
15937 resultType = Context.getLogicalOperationType();
15938 break;
15939 case UO_Real:
15940 case UO_Imag:
15941 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15942 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15943 // complex l-values to ordinary l-values and all other values to r-values.
15944 if (Input.isInvalid()) return ExprError();
15945 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15946 if (Input.get()->isGLValue() &&
15947 Input.get()->getObjectKind() == OK_Ordinary)
15948 VK = Input.get()->getValueKind();
15949 } else if (!getLangOpts().CPlusPlus) {
15950 // In C, a volatile scalar is read by __imag. In C++, it is not.
15951 Input = DefaultLvalueConversion(Input.get());
15952 }
15953 break;
15954 case UO_Extension:
15955 resultType = Input.get()->getType();
15956 VK = Input.get()->getValueKind();
15957 OK = Input.get()->getObjectKind();
15958 break;
15959 case UO_Coawait:
15960 // It's unnecessary to represent the pass-through operator co_await in the
15961 // AST; just return the input expression instead.
15962 assert(!Input.get()->getType()->isDependentType() &&
15963 "the co_await expression must be non-dependant before "
15964 "building operator co_await");
15965 return Input;
15966 }
15967 if (resultType.isNull() || Input.isInvalid())
15968 return ExprError();
15969
15970 // Check for array bounds violations in the operand of the UnaryOperator,
15971 // except for the '*' and '&' operators that have to be handled specially
15972 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15973 // that are explicitly defined as valid by the standard).
15974 if (Opc != UO_AddrOf && Opc != UO_Deref)
15975 CheckArrayAccess(Input.get());
15976
15977 auto *UO =
15978 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15979 OpLoc, CanOverflow, CurFPFeatureOverrides());
15980
15981 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15982 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15984 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15985
15986 // Convert the result back to a half vector.
15987 if (ConvertHalfVec)
15988 return convertVector(UO, Context.HalfTy, *this);
15989 return UO;
15990}
15991
15992/// Determine whether the given expression is a qualified member
15993/// access expression, of a form that could be turned into a pointer to member
15994/// with the address-of operator.
15996 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15997 if (!DRE->getQualifier())
15998 return false;
15999
16000 ValueDecl *VD = DRE->getDecl();
16001 if (!VD->isCXXClassMember())
16002 return false;
16003
16004 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16005 return true;
16006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16007 return Method->isImplicitObjectMemberFunction();
16008
16009 return false;
16010 }
16011
16012 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16013 if (!ULE->getQualifier())
16014 return false;
16015
16016 for (NamedDecl *D : ULE->decls()) {
16017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16018 if (Method->isImplicitObjectMemberFunction())
16019 return true;
16020 } else {
16021 // Overload set does not contain methods.
16022 break;
16023 }
16024 }
16025
16026 return false;
16027 }
16028
16029 return false;
16030}
16031
16033 UnaryOperatorKind Opc, Expr *Input,
16034 bool IsAfterAmp) {
16035 // First things first: handle placeholders so that the
16036 // overloaded-operator check considers the right type.
16037 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16038 // Increment and decrement of pseudo-object references.
16039 if (pty->getKind() == BuiltinType::PseudoObject &&
16041 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16042
16043 // extension is always a builtin operator.
16044 if (Opc == UO_Extension)
16045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16046
16047 // & gets special logic for several kinds of placeholder.
16048 // The builtin code knows what to do.
16049 if (Opc == UO_AddrOf &&
16050 (pty->getKind() == BuiltinType::Overload ||
16051 pty->getKind() == BuiltinType::UnknownAny ||
16052 pty->getKind() == BuiltinType::BoundMember))
16053 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16054
16055 // Anything else needs to be handled now.
16057 if (Result.isInvalid()) return ExprError();
16058 Input = Result.get();
16059 }
16060
16061 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16063 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16064 // Find all of the overloaded operators visible from this point.
16065 UnresolvedSet<16> Functions;
16067 if (S && OverOp != OO_None)
16068 LookupOverloadedOperatorName(OverOp, S, Functions);
16069
16070 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16071 }
16072
16073 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16074}
16075
16076// Unary Operators. 'Tok' is the token for the operator.
16078 Expr *Input, bool IsAfterAmp) {
16079 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16080 IsAfterAmp);
16081}
16082
16083/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16085 LabelDecl *TheDecl) {
16086 TheDecl->markUsed(Context);
16087 // Create the AST node. The address of a label always has type 'void*'.
16088 auto *Res = new (Context) AddrLabelExpr(
16089 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16090
16091 if (getCurFunction())
16092 getCurFunction()->AddrLabels.push_back(Res);
16093
16094 return Res;
16095}
16096
16099 // Make sure we diagnose jumping into a statement expression.
16101}
16102
16104 // Note that function is also called by TreeTransform when leaving a
16105 // StmtExpr scope without rebuilding anything.
16106
16109}
16110
16112 SourceLocation RPLoc) {
16113 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16114}
16115
16117 SourceLocation RPLoc, unsigned TemplateDepth) {
16118 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16119 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16120
16123 assert(!Cleanup.exprNeedsCleanups() &&
16124 "cleanups within StmtExpr not correctly bound!");
16126
16127 // FIXME: there are a variety of strange constraints to enforce here, for
16128 // example, it is not possible to goto into a stmt expression apparently.
16129 // More semantic analysis is needed.
16130
16131 // If there are sub-stmts in the compound stmt, take the type of the last one
16132 // as the type of the stmtexpr.
16133 QualType Ty = Context.VoidTy;
16134 bool StmtExprMayBindToTemp = false;
16135 if (!Compound->body_empty()) {
16136 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16137 if (const auto *LastStmt =
16138 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16139 if (const Expr *Value = LastStmt->getExprStmt()) {
16140 StmtExprMayBindToTemp = true;
16141 Ty = Value->getType();
16142 }
16143 }
16144 }
16145
16146 // FIXME: Check that expression type is complete/non-abstract; statement
16147 // expressions are not lvalues.
16148 Expr *ResStmtExpr =
16149 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16150 if (StmtExprMayBindToTemp)
16151 return MaybeBindToTemporary(ResStmtExpr);
16152 return ResStmtExpr;
16153}
16154
16156 if (ER.isInvalid())
16157 return ExprError();
16158
16159 // Do function/array conversion on the last expression, but not
16160 // lvalue-to-rvalue. However, initialize an unqualified type.
16162 if (ER.isInvalid())
16163 return ExprError();
16164 Expr *E = ER.get();
16165
16166 if (E->isTypeDependent())
16167 return E;
16168
16169 // In ARC, if the final expression ends in a consume, splice
16170 // the consume out and bind it later. In the alternate case
16171 // (when dealing with a retainable type), the result
16172 // initialization will create a produce. In both cases the
16173 // result will be +1, and we'll need to balance that out with
16174 // a bind.
16175 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16176 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16177 return Cast->getSubExpr();
16178
16179 // FIXME: Provide a better location for the initialization.
16183 SourceLocation(), E);
16184}
16185
16187 TypeSourceInfo *TInfo,
16188 ArrayRef<OffsetOfComponent> Components,
16189 SourceLocation RParenLoc) {
16190 QualType ArgTy = TInfo->getType();
16191 bool Dependent = ArgTy->isDependentType();
16192 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16193
16194 // We must have at least one component that refers to the type, and the first
16195 // one is known to be a field designator. Verify that the ArgTy represents
16196 // a struct/union/class.
16197 if (!Dependent && !ArgTy->isRecordType())
16198 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16199 << ArgTy << TypeRange);
16200
16201 // Type must be complete per C99 7.17p3 because a declaring a variable
16202 // with an incomplete type would be ill-formed.
16203 if (!Dependent
16204 && RequireCompleteType(BuiltinLoc, ArgTy,
16205 diag::err_offsetof_incomplete_type, TypeRange))
16206 return ExprError();
16207
16208 bool DidWarnAboutNonPOD = false;
16209 QualType CurrentType = ArgTy;
16212 for (const OffsetOfComponent &OC : Components) {
16213 if (OC.isBrackets) {
16214 // Offset of an array sub-field. TODO: Should we allow vector elements?
16215 if (!CurrentType->isDependentType()) {
16216 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16217 if(!AT)
16218 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16219 << CurrentType);
16220 CurrentType = AT->getElementType();
16221 } else
16222 CurrentType = Context.DependentTy;
16223
16224 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16225 if (IdxRval.isInvalid())
16226 return ExprError();
16227 Expr *Idx = IdxRval.get();
16228
16229 // The expression must be an integral expression.
16230 // FIXME: An integral constant expression?
16231 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16232 !Idx->getType()->isIntegerType())
16233 return ExprError(
16234 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16235 << Idx->getSourceRange());
16236
16237 // Record this array index.
16238 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16239 Exprs.push_back(Idx);
16240 continue;
16241 }
16242
16243 // Offset of a field.
16244 if (CurrentType->isDependentType()) {
16245 // We have the offset of a field, but we can't look into the dependent
16246 // type. Just record the identifier of the field.
16247 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16248 CurrentType = Context.DependentTy;
16249 continue;
16250 }
16251
16252 // We need to have a complete type to look into.
16253 if (RequireCompleteType(OC.LocStart, CurrentType,
16254 diag::err_offsetof_incomplete_type))
16255 return ExprError();
16256
16257 // Look for the designated field.
16258 const RecordType *RC = CurrentType->getAs<RecordType>();
16259 if (!RC)
16260 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16261 << CurrentType);
16262 RecordDecl *RD = RC->getDecl();
16263
16264 // C++ [lib.support.types]p5:
16265 // The macro offsetof accepts a restricted set of type arguments in this
16266 // International Standard. type shall be a POD structure or a POD union
16267 // (clause 9).
16268 // C++11 [support.types]p4:
16269 // If type is not a standard-layout class (Clause 9), the results are
16270 // undefined.
16271 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16272 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16273 unsigned DiagID =
16274 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16275 : diag::ext_offsetof_non_pod_type;
16276
16277 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16278 Diag(BuiltinLoc, DiagID)
16279 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16280 DidWarnAboutNonPOD = true;
16281 }
16282 }
16283
16284 // Look for the field.
16285 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16286 LookupQualifiedName(R, RD);
16287 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16288 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16289 if (!MemberDecl) {
16290 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16291 MemberDecl = IndirectMemberDecl->getAnonField();
16292 }
16293
16294 if (!MemberDecl) {
16295 // Lookup could be ambiguous when looking up a placeholder variable
16296 // __builtin_offsetof(S, _).
16297 // In that case we would already have emitted a diagnostic
16298 if (!R.isAmbiguous())
16299 Diag(BuiltinLoc, diag::err_no_member)
16300 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16301 return ExprError();
16302 }
16303
16304 // C99 7.17p3:
16305 // (If the specified member is a bit-field, the behavior is undefined.)
16306 //
16307 // We diagnose this as an error.
16308 if (MemberDecl->isBitField()) {
16309 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16310 << MemberDecl->getDeclName()
16311 << SourceRange(BuiltinLoc, RParenLoc);
16312 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16313 return ExprError();
16314 }
16315
16316 RecordDecl *Parent = MemberDecl->getParent();
16317 if (IndirectMemberDecl)
16318 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16319
16320 // If the member was found in a base class, introduce OffsetOfNodes for
16321 // the base class indirections.
16322 CXXBasePaths Paths;
16323 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16324 Paths)) {
16325 if (Paths.getDetectedVirtual()) {
16326 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16327 << MemberDecl->getDeclName()
16328 << SourceRange(BuiltinLoc, RParenLoc);
16329 return ExprError();
16330 }
16331
16332 CXXBasePath &Path = Paths.front();
16333 for (const CXXBasePathElement &B : Path)
16334 Comps.push_back(OffsetOfNode(B.Base));
16335 }
16336
16337 if (IndirectMemberDecl) {
16338 for (auto *FI : IndirectMemberDecl->chain()) {
16339 assert(isa<FieldDecl>(FI));
16340 Comps.push_back(OffsetOfNode(OC.LocStart,
16341 cast<FieldDecl>(FI), OC.LocEnd));
16342 }
16343 } else
16344 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16345
16346 CurrentType = MemberDecl->getType().getNonReferenceType();
16347 }
16348
16349 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16350 Comps, Exprs, RParenLoc);
16351}
16352
16354 SourceLocation BuiltinLoc,
16356 ParsedType ParsedArgTy,
16357 ArrayRef<OffsetOfComponent> Components,
16358 SourceLocation RParenLoc) {
16359
16360 TypeSourceInfo *ArgTInfo;
16361 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16362 if (ArgTy.isNull())
16363 return ExprError();
16364
16365 if (!ArgTInfo)
16366 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16367
16368 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16369}
16370
16371
16373 Expr *CondExpr,
16374 Expr *LHSExpr, Expr *RHSExpr,
16375 SourceLocation RPLoc) {
16376 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16377
16380 QualType resType;
16381 bool CondIsTrue = false;
16382 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16383 resType = Context.DependentTy;
16384 } else {
16385 // The conditional expression is required to be a constant expression.
16386 llvm::APSInt condEval(32);
16388 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16389 if (CondICE.isInvalid())
16390 return ExprError();
16391 CondExpr = CondICE.get();
16392 CondIsTrue = condEval.getZExtValue();
16393
16394 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16395 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16396
16397 resType = ActiveExpr->getType();
16398 VK = ActiveExpr->getValueKind();
16399 OK = ActiveExpr->getObjectKind();
16400 }
16401
16402 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16403 resType, VK, OK, RPLoc, CondIsTrue);
16404}
16405
16406//===----------------------------------------------------------------------===//
16407// Clang Extensions.
16408//===----------------------------------------------------------------------===//
16409
16410/// ActOnBlockStart - This callback is invoked when a block literal is started.
16411void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16413
16414 if (LangOpts.CPlusPlus) {
16416 Decl *ManglingContextDecl;
16417 std::tie(MCtx, ManglingContextDecl) =
16418 getCurrentMangleNumberContext(Block->getDeclContext());
16419 if (MCtx) {
16420 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16421 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16422 }
16423 }
16424
16425 PushBlockScope(CurScope, Block);
16427 if (CurScope)
16428 PushDeclContext(CurScope, Block);
16429 else
16430 CurContext = Block;
16431
16433
16434 // Enter a new evaluation context to insulate the block from any
16435 // cleanups from the enclosing full-expression.
16438}
16439
16441 Scope *CurScope) {
16442 assert(ParamInfo.getIdentifier() == nullptr &&
16443 "block-id should have no identifier!");
16444 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16445 BlockScopeInfo *CurBlock = getCurBlock();
16446
16447 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16448 QualType T = Sig->getType();
16449
16450 // FIXME: We should allow unexpanded parameter packs here, but that would,
16451 // in turn, make the block expression contain unexpanded parameter packs.
16452 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16453 // Drop the parameters.
16455 EPI.HasTrailingReturn = false;
16456 EPI.TypeQuals.addConst();
16457 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16459 }
16460
16461 // GetTypeForDeclarator always produces a function type for a block
16462 // literal signature. Furthermore, it is always a FunctionProtoType
16463 // unless the function was written with a typedef.
16464 assert(T->isFunctionType() &&
16465 "GetTypeForDeclarator made a non-function block signature");
16466
16467 // Look for an explicit signature in that function type.
16468 FunctionProtoTypeLoc ExplicitSignature;
16469
16470 if ((ExplicitSignature = Sig->getTypeLoc()
16472
16473 // Check whether that explicit signature was synthesized by
16474 // GetTypeForDeclarator. If so, don't save that as part of the
16475 // written signature.
16476 if (ExplicitSignature.getLocalRangeBegin() ==
16477 ExplicitSignature.getLocalRangeEnd()) {
16478 // This would be much cheaper if we stored TypeLocs instead of
16479 // TypeSourceInfos.
16480 TypeLoc Result = ExplicitSignature.getReturnLoc();
16481 unsigned Size = Result.getFullDataSize();
16482 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16483 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16484
16485 ExplicitSignature = FunctionProtoTypeLoc();
16486 }
16487 }
16488
16489 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16490 CurBlock->FunctionType = T;
16491
16492 const auto *Fn = T->castAs<FunctionType>();
16493 QualType RetTy = Fn->getReturnType();
16494 bool isVariadic =
16495 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16496
16497 CurBlock->TheDecl->setIsVariadic(isVariadic);
16498
16499 // Context.DependentTy is used as a placeholder for a missing block
16500 // return type. TODO: what should we do with declarators like:
16501 // ^ * { ... }
16502 // If the answer is "apply template argument deduction"....
16503 if (RetTy != Context.DependentTy) {
16504 CurBlock->ReturnType = RetTy;
16505 CurBlock->TheDecl->setBlockMissingReturnType(false);
16506 CurBlock->HasImplicitReturnType = false;
16507 }
16508
16509 // Push block parameters from the declarator if we had them.
16511 if (ExplicitSignature) {
16512 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16513 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16514 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16515 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16516 // Diagnose this as an extension in C17 and earlier.
16517 if (!getLangOpts().C23)
16518 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16519 }
16520 Params.push_back(Param);
16521 }
16522
16523 // Fake up parameter variables if we have a typedef, like
16524 // ^ fntype { ... }
16525 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16526 for (const auto &I : Fn->param_types()) {
16528 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16529 Params.push_back(Param);
16530 }
16531 }
16532
16533 // Set the parameters on the block decl.
16534 if (!Params.empty()) {
16535 CurBlock->TheDecl->setParams(Params);
16537 /*CheckParameterNames=*/false);
16538 }
16539
16540 // Finally we can process decl attributes.
16541 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16542
16543 // Put the parameter variables in scope.
16544 for (auto *AI : CurBlock->TheDecl->parameters()) {
16545 AI->setOwningFunction(CurBlock->TheDecl);
16546
16547 // If this has an identifier, add it to the scope stack.
16548 if (AI->getIdentifier()) {
16549 CheckShadow(CurBlock->TheScope, AI);
16550
16551 PushOnScopeChains(AI, CurBlock->TheScope);
16552 }
16553
16554 if (AI->isInvalidDecl())
16555 CurBlock->TheDecl->setInvalidDecl();
16556 }
16557}
16558
16559/// ActOnBlockError - If there is an error parsing a block, this callback
16560/// is invoked to pop the information about the block from the action impl.
16561void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16562 // Leave the expression-evaluation context.
16565
16566 // Pop off CurBlock, handle nested blocks.
16569}
16570
16571/// ActOnBlockStmtExpr - This is called when the body of a block statement
16572/// literal was successfully completed. ^(int x){...}
16574 Stmt *Body, Scope *CurScope) {
16575 // If blocks are disabled, emit an error.
16576 if (!LangOpts.Blocks)
16577 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16578
16579 // Leave the expression-evaluation context.
16582 assert(!Cleanup.exprNeedsCleanups() &&
16583 "cleanups within block not correctly bound!");
16585
16586 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16587 BlockDecl *BD = BSI->TheDecl;
16588
16589 if (BSI->HasImplicitReturnType)
16591
16592 QualType RetTy = Context.VoidTy;
16593 if (!BSI->ReturnType.isNull())
16594 RetTy = BSI->ReturnType;
16595
16596 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16597 QualType BlockTy;
16598
16599 // If the user wrote a function type in some form, try to use that.
16600 if (!BSI->FunctionType.isNull()) {
16601 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16602
16603 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16604 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16605
16606 // Turn protoless block types into nullary block types.
16607 if (isa<FunctionNoProtoType>(FTy)) {
16609 EPI.ExtInfo = Ext;
16610 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16611
16612 // Otherwise, if we don't need to change anything about the function type,
16613 // preserve its sugar structure.
16614 } else if (FTy->getReturnType() == RetTy &&
16615 (!NoReturn || FTy->getNoReturnAttr())) {
16616 BlockTy = BSI->FunctionType;
16617
16618 // Otherwise, make the minimal modifications to the function type.
16619 } else {
16620 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16622 EPI.TypeQuals = Qualifiers();
16623 EPI.ExtInfo = Ext;
16624 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16625 }
16626
16627 // If we don't have a function type, just build one from nothing.
16628 } else {
16630 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16631 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16632 }
16633
16635 BlockTy = Context.getBlockPointerType(BlockTy);
16636
16637 // If needed, diagnose invalid gotos and switches in the block.
16638 if (getCurFunction()->NeedsScopeChecking() &&
16640 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16641
16642 BD->setBody(cast<CompoundStmt>(Body));
16643
16644 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16646
16647 // Try to apply the named return value optimization. We have to check again
16648 // if we can do this, though, because blocks keep return statements around
16649 // to deduce an implicit return type.
16650 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16651 !BD->isDependentContext())
16652 computeNRVO(Body, BSI);
16653
16658
16660
16661 // Set the captured variables on the block.
16663 for (Capture &Cap : BSI->Captures) {
16664 if (Cap.isInvalid() || Cap.isThisCapture())
16665 continue;
16666 // Cap.getVariable() is always a VarDecl because
16667 // blocks cannot capture structured bindings or other ValueDecl kinds.
16668 auto *Var = cast<VarDecl>(Cap.getVariable());
16669 Expr *CopyExpr = nullptr;
16670 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16671 if (const RecordType *Record =
16672 Cap.getCaptureType()->getAs<RecordType>()) {
16673 // The capture logic needs the destructor, so make sure we mark it.
16674 // Usually this is unnecessary because most local variables have
16675 // their destructors marked at declaration time, but parameters are
16676 // an exception because it's technically only the call site that
16677 // actually requires the destructor.
16678 if (isa<ParmVarDecl>(Var))
16680
16681 // Enter a separate potentially-evaluated context while building block
16682 // initializers to isolate their cleanups from those of the block
16683 // itself.
16684 // FIXME: Is this appropriate even when the block itself occurs in an
16685 // unevaluated operand?
16688
16689 SourceLocation Loc = Cap.getLocation();
16690
16692 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16693
16694 // According to the blocks spec, the capture of a variable from
16695 // the stack requires a const copy constructor. This is not true
16696 // of the copy/move done to move a __block variable to the heap.
16697 if (!Result.isInvalid() &&
16698 !Result.get()->getType().isConstQualified()) {
16700 Result.get()->getType().withConst(),
16701 CK_NoOp, VK_LValue);
16702 }
16703
16704 if (!Result.isInvalid()) {
16706 InitializedEntity::InitializeBlock(Var->getLocation(),
16707 Cap.getCaptureType()),
16708 Loc, Result.get());
16709 }
16710
16711 // Build a full-expression copy expression if initialization
16712 // succeeded and used a non-trivial constructor. Recover from
16713 // errors by pretending that the copy isn't necessary.
16714 if (!Result.isInvalid() &&
16715 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16716 ->isTrivial()) {
16718 CopyExpr = Result.get();
16719 }
16720 }
16721 }
16722
16723 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16724 CopyExpr);
16725 Captures.push_back(NewCap);
16726 }
16727 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16728
16729 // Pop the block scope now but keep it alive to the end of this function.
16731 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16732
16733 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16734
16735 // If the block isn't obviously global, i.e. it captures anything at
16736 // all, then we need to do a few things in the surrounding context:
16737 if (Result->getBlockDecl()->hasCaptures()) {
16738 // First, this expression has a new cleanup object.
16739 ExprCleanupObjects.push_back(Result->getBlockDecl());
16741
16742 // It also gets a branch-protected scope if any of the captured
16743 // variables needs destruction.
16744 for (const auto &CI : Result->getBlockDecl()->captures()) {
16745 const VarDecl *var = CI.getVariable();
16746 if (var->getType().isDestructedType() != QualType::DK_none) {
16748 break;
16749 }
16750 }
16751 }
16752
16753 if (getCurFunction())
16754 getCurFunction()->addBlock(BD);
16755
16756 if (BD->isInvalidDecl())
16757 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16758 {Result}, Result->getType());
16759 return Result;
16760}
16761
16763 SourceLocation RPLoc) {
16764 TypeSourceInfo *TInfo;
16765 GetTypeFromParser(Ty, &TInfo);
16766 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16767}
16768
16770 Expr *E, TypeSourceInfo *TInfo,
16771 SourceLocation RPLoc) {
16772 Expr *OrigExpr = E;
16773 bool IsMS = false;
16774
16775 // CUDA device code does not support varargs.
16776 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16777 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16781 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16782 }
16783 }
16784
16785 // NVPTX does not support va_arg expression.
16786 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16787 Context.getTargetInfo().getTriple().isNVPTX())
16788 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16789
16790 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16791 // as Microsoft ABI on an actual Microsoft platform, where
16792 // __builtin_ms_va_list and __builtin_va_list are the same.)
16795 QualType MSVaListType = Context.getBuiltinMSVaListType();
16796 if (Context.hasSameType(MSVaListType, E->getType())) {
16797 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16798 return ExprError();
16799 IsMS = true;
16800 }
16801 }
16802
16803 // Get the va_list type
16804 QualType VaListType = Context.getBuiltinVaListType();
16805 if (!IsMS) {
16806 if (VaListType->isArrayType()) {
16807 // Deal with implicit array decay; for example, on x86-64,
16808 // va_list is an array, but it's supposed to decay to
16809 // a pointer for va_arg.
16810 VaListType = Context.getArrayDecayedType(VaListType);
16811 // Make sure the input expression also decays appropriately.
16813 if (Result.isInvalid())
16814 return ExprError();
16815 E = Result.get();
16816 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16817 // If va_list is a record type and we are compiling in C++ mode,
16818 // check the argument using reference binding.
16820 Context, Context.getLValueReferenceType(VaListType), false);
16822 if (Init.isInvalid())
16823 return ExprError();
16824 E = Init.getAs<Expr>();
16825 } else {
16826 // Otherwise, the va_list argument must be an l-value because
16827 // it is modified by va_arg.
16828 if (!E->isTypeDependent() &&
16829 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16830 return ExprError();
16831 }
16832 }
16833
16834 if (!IsMS && !E->isTypeDependent() &&
16835 !Context.hasSameType(VaListType, E->getType()))
16836 return ExprError(
16837 Diag(E->getBeginLoc(),
16838 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16839 << OrigExpr->getType() << E->getSourceRange());
16840
16841 if (!TInfo->getType()->isDependentType()) {
16842 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16843 diag::err_second_parameter_to_va_arg_incomplete,
16844 TInfo->getTypeLoc()))
16845 return ExprError();
16846
16848 TInfo->getType(),
16849 diag::err_second_parameter_to_va_arg_abstract,
16850 TInfo->getTypeLoc()))
16851 return ExprError();
16852
16853 if (!TInfo->getType().isPODType(Context)) {
16854 Diag(TInfo->getTypeLoc().getBeginLoc(),
16855 TInfo->getType()->isObjCLifetimeType()
16856 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16857 : diag::warn_second_parameter_to_va_arg_not_pod)
16858 << TInfo->getType()
16859 << TInfo->getTypeLoc().getSourceRange();
16860 }
16861
16862 // Check for va_arg where arguments of the given type will be promoted
16863 // (i.e. this va_arg is guaranteed to have undefined behavior).
16864 QualType PromoteType;
16865 if (Context.isPromotableIntegerType(TInfo->getType())) {
16866 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16867 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16868 // and C23 7.16.1.1p2 says, in part:
16869 // If type is not compatible with the type of the actual next argument
16870 // (as promoted according to the default argument promotions), the
16871 // behavior is undefined, except for the following cases:
16872 // - both types are pointers to qualified or unqualified versions of
16873 // compatible types;
16874 // - one type is compatible with a signed integer type, the other
16875 // type is compatible with the corresponding unsigned integer type,
16876 // and the value is representable in both types;
16877 // - one type is pointer to qualified or unqualified void and the
16878 // other is a pointer to a qualified or unqualified character type;
16879 // - or, the type of the next argument is nullptr_t and type is a
16880 // pointer type that has the same representation and alignment
16881 // requirements as a pointer to a character type.
16882 // Given that type compatibility is the primary requirement (ignoring
16883 // qualifications), you would think we could call typesAreCompatible()
16884 // directly to test this. However, in C++, that checks for *same type*,
16885 // which causes false positives when passing an enumeration type to
16886 // va_arg. Instead, get the underlying type of the enumeration and pass
16887 // that.
16888 QualType UnderlyingType = TInfo->getType();
16889 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16890 UnderlyingType = ET->getDecl()->getIntegerType();
16891 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16892 /*CompareUnqualified*/ true))
16893 PromoteType = QualType();
16894
16895 // If the types are still not compatible, we need to test whether the
16896 // promoted type and the underlying type are the same except for
16897 // signedness. Ask the AST for the correctly corresponding type and see
16898 // if that's compatible.
16899 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16900 PromoteType->isUnsignedIntegerType() !=
16901 UnderlyingType->isUnsignedIntegerType()) {
16902 UnderlyingType =
16903 UnderlyingType->isUnsignedIntegerType()
16904 ? Context.getCorrespondingSignedType(UnderlyingType)
16905 : Context.getCorrespondingUnsignedType(UnderlyingType);
16906 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16907 /*CompareUnqualified*/ true))
16908 PromoteType = QualType();
16909 }
16910 }
16911 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16912 PromoteType = Context.DoubleTy;
16913 if (!PromoteType.isNull())
16915 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16916 << TInfo->getType()
16917 << PromoteType
16918 << TInfo->getTypeLoc().getSourceRange());
16919 }
16920
16922 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16923}
16924
16926 // The type of __null will be int or long, depending on the size of
16927 // pointers on the target.
16928 QualType Ty;
16930 if (pw == Context.getTargetInfo().getIntWidth())
16931 Ty = Context.IntTy;
16932 else if (pw == Context.getTargetInfo().getLongWidth())
16933 Ty = Context.LongTy;
16934 else if (pw == Context.getTargetInfo().getLongLongWidth())
16935 Ty = Context.LongLongTy;
16936 else {
16937 llvm_unreachable("I don't know size of pointer!");
16938 }
16939
16940 return new (Context) GNUNullExpr(Ty, TokenLoc);
16941}
16942
16944 CXXRecordDecl *ImplDecl = nullptr;
16945
16946 // Fetch the std::source_location::__impl decl.
16947 if (NamespaceDecl *Std = S.getStdNamespace()) {
16948 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16950 if (S.LookupQualifiedName(ResultSL, Std)) {
16951 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16952 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16954 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16955 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16956 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16957 }
16958 }
16959 }
16960 }
16961
16962 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16963 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16964 return nullptr;
16965 }
16966
16967 // Verify that __impl is a trivial struct type, with no base classes, and with
16968 // only the four expected fields.
16969 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16970 ImplDecl->getNumBases() != 0) {
16971 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16972 return nullptr;
16973 }
16974
16975 unsigned Count = 0;
16976 for (FieldDecl *F : ImplDecl->fields()) {
16977 StringRef Name = F->getName();
16978
16979 if (Name == "_M_file_name") {
16980 if (F->getType() !=
16982 break;
16983 Count++;
16984 } else if (Name == "_M_function_name") {
16985 if (F->getType() !=
16987 break;
16988 Count++;
16989 } else if (Name == "_M_line") {
16990 if (!F->getType()->isIntegerType())
16991 break;
16992 Count++;
16993 } else if (Name == "_M_column") {
16994 if (!F->getType()->isIntegerType())
16995 break;
16996 Count++;
16997 } else {
16998 Count = 100; // invalid
16999 break;
17000 }
17001 }
17002 if (Count != 4) {
17003 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17004 return nullptr;
17005 }
17006
17007 return ImplDecl;
17008}
17009
17011 SourceLocation BuiltinLoc,
17012 SourceLocation RPLoc) {
17013 QualType ResultTy;
17014 switch (Kind) {
17020 ResultTy =
17022 break;
17023 }
17026 ResultTy = Context.UnsignedIntTy;
17027 break;
17031 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17033 return ExprError();
17034 }
17035 ResultTy = Context.getPointerType(
17037 break;
17038 }
17039
17040 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17041}
17042
17044 SourceLocation BuiltinLoc,
17045 SourceLocation RPLoc,
17046 DeclContext *ParentContext) {
17047 return new (Context)
17048 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17049}
17050
17052 bool Diagnose) {
17053 if (!getLangOpts().ObjC)
17054 return false;
17055
17056 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17057 if (!PT)
17058 return false;
17059 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17060
17061 // Ignore any parens, implicit casts (should only be
17062 // array-to-pointer decays), and not-so-opaque values. The last is
17063 // important for making this trigger for property assignments.
17064 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17065 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17066 if (OV->getSourceExpr())
17067 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17068
17069 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17070 if (!PT->isObjCIdType() &&
17071 !(ID && ID->getIdentifier()->isStr("NSString")))
17072 return false;
17073 if (!SL->isOrdinary())
17074 return false;
17075
17076 if (Diagnose) {
17077 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17078 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17079 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17080 }
17081 return true;
17082 }
17083
17084 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17085 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17086 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17087 !SrcExpr->isNullPointerConstant(
17089 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17090 return false;
17091 if (Diagnose) {
17092 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17093 << /*number*/1
17094 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17095 Expr *NumLit =
17096 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17097 if (NumLit)
17098 Exp = NumLit;
17099 }
17100 return true;
17101 }
17102
17103 return false;
17104}
17105
17107 const Expr *SrcExpr) {
17108 if (!DstType->isFunctionPointerType() ||
17109 !SrcExpr->getType()->isFunctionType())
17110 return false;
17111
17112 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17113 if (!DRE)
17114 return false;
17115
17116 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17117 if (!FD)
17118 return false;
17119
17121 /*Complain=*/true,
17122 SrcExpr->getBeginLoc());
17123}
17124
17126 SourceLocation Loc,
17127 QualType DstType, QualType SrcType,
17128 Expr *SrcExpr, AssignmentAction Action,
17129 bool *Complained) {
17130 if (Complained)
17131 *Complained = false;
17132
17133 // Decode the result (notice that AST's are still created for extensions).
17134 bool CheckInferredResultType = false;
17135 bool isInvalid = false;
17136 unsigned DiagKind = 0;
17137 ConversionFixItGenerator ConvHints;
17138 bool MayHaveConvFixit = false;
17139 bool MayHaveFunctionDiff = false;
17140 const ObjCInterfaceDecl *IFace = nullptr;
17141 const ObjCProtocolDecl *PDecl = nullptr;
17142
17143 switch (ConvTy) {
17144 case Compatible:
17145 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17146 return false;
17147
17148 case PointerToInt:
17149 if (getLangOpts().CPlusPlus) {
17150 DiagKind = diag::err_typecheck_convert_pointer_int;
17151 isInvalid = true;
17152 } else {
17153 DiagKind = diag::ext_typecheck_convert_pointer_int;
17154 }
17155 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17156 MayHaveConvFixit = true;
17157 break;
17158 case IntToPointer:
17159 if (getLangOpts().CPlusPlus) {
17160 DiagKind = diag::err_typecheck_convert_int_pointer;
17161 isInvalid = true;
17162 } else {
17163 DiagKind = diag::ext_typecheck_convert_int_pointer;
17164 }
17165 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17166 MayHaveConvFixit = true;
17167 break;
17169 DiagKind =
17170 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17171 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17172 MayHaveConvFixit = true;
17173 break;
17175 if (getLangOpts().CPlusPlus) {
17176 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17177 isInvalid = true;
17178 } else {
17179 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17180 }
17181 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17182 MayHaveConvFixit = true;
17183 break;
17185 if (Action == AA_Passing_CFAudited) {
17186 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17187 } else if (getLangOpts().CPlusPlus) {
17188 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17189 isInvalid = true;
17190 } else {
17191 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17192 }
17193 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17194 SrcType->isObjCObjectPointerType();
17195 if (!CheckInferredResultType) {
17196 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17197 } else if (CheckInferredResultType) {
17198 SrcType = SrcType.getUnqualifiedType();
17199 DstType = DstType.getUnqualifiedType();
17200 }
17201 MayHaveConvFixit = true;
17202 break;
17204 if (getLangOpts().CPlusPlus) {
17205 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17206 isInvalid = true;
17207 } else {
17208 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17209 }
17210 break;
17212 if (getLangOpts().CPlusPlus) {
17213 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17214 isInvalid = true;
17215 } else {
17216 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17217 }
17218 break;
17220 // Perform array-to-pointer decay if necessary.
17221 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17222
17223 isInvalid = true;
17224
17225 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17226 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17227 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17228 DiagKind = diag::err_typecheck_incompatible_address_space;
17229 break;
17230 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17231 DiagKind = diag::err_typecheck_incompatible_ownership;
17232 break;
17233 }
17234
17235 llvm_unreachable("unknown error case for discarding qualifiers!");
17236 // fallthrough
17237 }
17239 // If the qualifiers lost were because we were applying the
17240 // (deprecated) C++ conversion from a string literal to a char*
17241 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17242 // Ideally, this check would be performed in
17243 // checkPointerTypesForAssignment. However, that would require a
17244 // bit of refactoring (so that the second argument is an
17245 // expression, rather than a type), which should be done as part
17246 // of a larger effort to fix checkPointerTypesForAssignment for
17247 // C++ semantics.
17248 if (getLangOpts().CPlusPlus &&
17250 return false;
17251 if (getLangOpts().CPlusPlus) {
17252 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17253 isInvalid = true;
17254 } else {
17255 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17256 }
17257
17258 break;
17260 if (getLangOpts().CPlusPlus) {
17261 isInvalid = true;
17262 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17263 } else {
17264 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17265 }
17266 break;
17268 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17269 isInvalid = true;
17270 break;
17271 case IntToBlockPointer:
17272 DiagKind = diag::err_int_to_block_pointer;
17273 isInvalid = true;
17274 break;
17276 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17277 isInvalid = true;
17278 break;
17280 if (SrcType->isObjCQualifiedIdType()) {
17281 const ObjCObjectPointerType *srcOPT =
17282 SrcType->castAs<ObjCObjectPointerType>();
17283 for (auto *srcProto : srcOPT->quals()) {
17284 PDecl = srcProto;
17285 break;
17286 }
17287 if (const ObjCInterfaceType *IFaceT =
17289 IFace = IFaceT->getDecl();
17290 }
17291 else if (DstType->isObjCQualifiedIdType()) {
17292 const ObjCObjectPointerType *dstOPT =
17293 DstType->castAs<ObjCObjectPointerType>();
17294 for (auto *dstProto : dstOPT->quals()) {
17295 PDecl = dstProto;
17296 break;
17297 }
17298 if (const ObjCInterfaceType *IFaceT =
17300 IFace = IFaceT->getDecl();
17301 }
17302 if (getLangOpts().CPlusPlus) {
17303 DiagKind = diag::err_incompatible_qualified_id;
17304 isInvalid = true;
17305 } else {
17306 DiagKind = diag::warn_incompatible_qualified_id;
17307 }
17308 break;
17309 }
17311 if (getLangOpts().CPlusPlus) {
17312 DiagKind = diag::err_incompatible_vectors;
17313 isInvalid = true;
17314 } else {
17315 DiagKind = diag::warn_incompatible_vectors;
17316 }
17317 break;
17319 DiagKind = diag::err_arc_weak_unavailable_assign;
17320 isInvalid = true;
17321 break;
17322 case Incompatible:
17323 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17324 if (Complained)
17325 *Complained = true;
17326 return true;
17327 }
17328
17329 DiagKind = diag::err_typecheck_convert_incompatible;
17330 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17331 MayHaveConvFixit = true;
17332 isInvalid = true;
17333 MayHaveFunctionDiff = true;
17334 break;
17335 }
17336
17337 QualType FirstType, SecondType;
17338 switch (Action) {
17339 case AA_Assigning:
17340 case AA_Initializing:
17341 // The destination type comes first.
17342 FirstType = DstType;
17343 SecondType = SrcType;
17344 break;
17345
17346 case AA_Returning:
17347 case AA_Passing:
17349 case AA_Converting:
17350 case AA_Sending:
17351 case AA_Casting:
17352 // The source type comes first.
17353 FirstType = SrcType;
17354 SecondType = DstType;
17355 break;
17356 }
17357
17358 PartialDiagnostic FDiag = PDiag(DiagKind);
17359 AssignmentAction ActionForDiag = Action;
17360 if (Action == AA_Passing_CFAudited)
17361 ActionForDiag = AA_Passing;
17362
17363 FDiag << FirstType << SecondType << ActionForDiag
17364 << SrcExpr->getSourceRange();
17365
17366 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17367 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17368 auto isPlainChar = [](const clang::Type *Type) {
17369 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17370 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17371 };
17372 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17373 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17374 }
17375
17376 // If we can fix the conversion, suggest the FixIts.
17377 if (!ConvHints.isNull()) {
17378 for (FixItHint &H : ConvHints.Hints)
17379 FDiag << H;
17380 }
17381
17382 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17383
17384 if (MayHaveFunctionDiff)
17385 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17386
17387 Diag(Loc, FDiag);
17388 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17389 DiagKind == diag::err_incompatible_qualified_id) &&
17390 PDecl && IFace && !IFace->hasDefinition())
17391 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17392 << IFace << PDecl;
17393
17394 if (SecondType == Context.OverloadTy)
17396 FirstType, /*TakingAddress=*/true);
17397
17398 if (CheckInferredResultType)
17400
17401 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17403
17404 if (Complained)
17405 *Complained = true;
17406 return isInvalid;
17407}
17408
17410 llvm::APSInt *Result,
17411 AllowFoldKind CanFold) {
17412 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17413 public:
17414 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17415 QualType T) override {
17416 return S.Diag(Loc, diag::err_ice_not_integral)
17417 << T << S.LangOpts.CPlusPlus;
17418 }
17419 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17420 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17421 }
17422 } Diagnoser;
17423
17424 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17425}
17426
17428 llvm::APSInt *Result,
17429 unsigned DiagID,
17430 AllowFoldKind CanFold) {
17431 class IDDiagnoser : public VerifyICEDiagnoser {
17432 unsigned DiagID;
17433
17434 public:
17435 IDDiagnoser(unsigned DiagID)
17436 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17437
17438 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17439 return S.Diag(Loc, DiagID);
17440 }
17441 } Diagnoser(DiagID);
17442
17443 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17444}
17445
17448 QualType T) {
17449 return diagnoseNotICE(S, Loc);
17450}
17451
17454 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17455}
17456
17459 VerifyICEDiagnoser &Diagnoser,
17460 AllowFoldKind CanFold) {
17461 SourceLocation DiagLoc = E->getBeginLoc();
17462
17463 if (getLangOpts().CPlusPlus11) {
17464 // C++11 [expr.const]p5:
17465 // If an expression of literal class type is used in a context where an
17466 // integral constant expression is required, then that class type shall
17467 // have a single non-explicit conversion function to an integral or
17468 // unscoped enumeration type
17469 ExprResult Converted;
17470 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17471 VerifyICEDiagnoser &BaseDiagnoser;
17472 public:
17473 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17474 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17475 BaseDiagnoser.Suppress, true),
17476 BaseDiagnoser(BaseDiagnoser) {}
17477
17478 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17479 QualType T) override {
17480 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17481 }
17482
17483 SemaDiagnosticBuilder diagnoseIncomplete(
17484 Sema &S, SourceLocation Loc, QualType T) override {
17485 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17486 }
17487
17488 SemaDiagnosticBuilder diagnoseExplicitConv(
17489 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17490 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17491 }
17492
17493 SemaDiagnosticBuilder noteExplicitConv(
17494 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17495 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17496 << ConvTy->isEnumeralType() << ConvTy;
17497 }
17498
17499 SemaDiagnosticBuilder diagnoseAmbiguous(
17500 Sema &S, SourceLocation Loc, QualType T) override {
17501 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17502 }
17503
17504 SemaDiagnosticBuilder noteAmbiguous(
17505 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17506 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17507 << ConvTy->isEnumeralType() << ConvTy;
17508 }
17509
17510 SemaDiagnosticBuilder diagnoseConversion(
17511 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17512 llvm_unreachable("conversion functions are permitted");
17513 }
17514 } ConvertDiagnoser(Diagnoser);
17515
17516 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17517 ConvertDiagnoser);
17518 if (Converted.isInvalid())
17519 return Converted;
17520 E = Converted.get();
17521 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17522 // don't try to evaluate it later. We also don't want to return the
17523 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17524 // this function will attempt to use 'Value'.
17525 if (isa<RecoveryExpr>(E))
17526 return ExprError();
17528 return ExprError();
17529 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17530 // An ICE must be of integral or unscoped enumeration type.
17531 if (!Diagnoser.Suppress)
17532 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17533 << E->getSourceRange();
17534 return ExprError();
17535 }
17536
17537 ExprResult RValueExpr = DefaultLvalueConversion(E);
17538 if (RValueExpr.isInvalid())
17539 return ExprError();
17540
17541 E = RValueExpr.get();
17542
17543 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17544 // in the non-ICE case.
17546 if (Result)
17548 if (!isa<ConstantExpr>(E))
17551 return E;
17552 }
17553
17554 Expr::EvalResult EvalResult;
17556 EvalResult.Diag = &Notes;
17557
17558 // Try to evaluate the expression, and produce diagnostics explaining why it's
17559 // not a constant expression as a side-effect.
17560 bool Folded =
17561 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17562 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17563
17564 if (!isa<ConstantExpr>(E))
17565 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17566
17567 // In C++11, we can rely on diagnostics being produced for any expression
17568 // which is not a constant expression. If no diagnostics were produced, then
17569 // this is a constant expression.
17570 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17571 if (Result)
17572 *Result = EvalResult.Val.getInt();
17573 return E;
17574 }
17575
17576 // If our only note is the usual "invalid subexpression" note, just point
17577 // the caret at its location rather than producing an essentially
17578 // redundant note.
17579 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17580 diag::note_invalid_subexpr_in_const_expr) {
17581 DiagLoc = Notes[0].first;
17582 Notes.clear();
17583 }
17584
17585 if (!Folded || !CanFold) {
17586 if (!Diagnoser.Suppress) {
17587 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17588 for (const PartialDiagnosticAt &Note : Notes)
17589 Diag(Note.first, Note.second);
17590 }
17591
17592 return ExprError();
17593 }
17594
17595 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17596 for (const PartialDiagnosticAt &Note : Notes)
17597 Diag(Note.first, Note.second);
17598
17599 if (Result)
17600 *Result = EvalResult.Val.getInt();
17601 return E;
17602}
17603
17604namespace {
17605 // Handle the case where we conclude a expression which we speculatively
17606 // considered to be unevaluated is actually evaluated.
17607 class TransformToPE : public TreeTransform<TransformToPE> {
17608 typedef TreeTransform<TransformToPE> BaseTransform;
17609
17610 public:
17611 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17612
17613 // Make sure we redo semantic analysis
17614 bool AlwaysRebuild() { return true; }
17615 bool ReplacingOriginal() { return true; }
17616
17617 // We need to special-case DeclRefExprs referring to FieldDecls which
17618 // are not part of a member pointer formation; normal TreeTransforming
17619 // doesn't catch this case because of the way we represent them in the AST.
17620 // FIXME: This is a bit ugly; is it really the best way to handle this
17621 // case?
17622 //
17623 // Error on DeclRefExprs referring to FieldDecls.
17624 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17625 if (isa<FieldDecl>(E->getDecl()) &&
17626 !SemaRef.isUnevaluatedContext())
17627 return SemaRef.Diag(E->getLocation(),
17628 diag::err_invalid_non_static_member_use)
17629 << E->getDecl() << E->getSourceRange();
17630
17631 return BaseTransform::TransformDeclRefExpr(E);
17632 }
17633
17634 // Exception: filter out member pointer formation
17635 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17636 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17637 return E;
17638
17639 return BaseTransform::TransformUnaryOperator(E);
17640 }
17641
17642 // The body of a lambda-expression is in a separate expression evaluation
17643 // context so never needs to be transformed.
17644 // FIXME: Ideally we wouldn't transform the closure type either, and would
17645 // just recreate the capture expressions and lambda expression.
17646 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17647 return SkipLambdaBody(E, Body);
17648 }
17649 };
17650}
17651
17653 assert(isUnevaluatedContext() &&
17654 "Should only transform unevaluated expressions");
17655 ExprEvalContexts.back().Context =
17656 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17658 return E;
17659 return TransformToPE(*this).TransformExpr(E);
17660}
17661
17663 assert(isUnevaluatedContext() &&
17664 "Should only transform unevaluated expressions");
17665 ExprEvalContexts.back().Context =
17666 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17668 return TInfo;
17669 return TransformToPE(*this).TransformType(TInfo);
17670}
17671
17672void
17674 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17676 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17677 LambdaContextDecl, ExprContext);
17678
17679 // Discarded statements and immediate contexts nested in other
17680 // discarded statements or immediate context are themselves
17681 // a discarded statement or an immediate context, respectively.
17682 ExprEvalContexts.back().InDiscardedStatement =
17684 .isDiscardedStatementContext();
17685
17686 // C++23 [expr.const]/p15
17687 // An expression or conversion is in an immediate function context if [...]
17688 // it is a subexpression of a manifestly constant-evaluated expression or
17689 // conversion.
17690 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
17691 ExprEvalContexts.back().InImmediateFunctionContext =
17692 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17693
17694 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17695 Prev.InImmediateEscalatingFunctionContext;
17696
17697 Cleanup.reset();
17698 if (!MaybeODRUseExprs.empty())
17699 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17700}
17701
17702void
17706 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17707 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17708}
17709
17710namespace {
17711
17712const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17713 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17714 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17715 if (E->getOpcode() == UO_Deref)
17716 return CheckPossibleDeref(S, E->getSubExpr());
17717 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17718 return CheckPossibleDeref(S, E->getBase());
17719 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17720 return CheckPossibleDeref(S, E->getBase());
17721 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17722 QualType Inner;
17723 QualType Ty = E->getType();
17724 if (const auto *Ptr = Ty->getAs<PointerType>())
17725 Inner = Ptr->getPointeeType();
17726 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17727 Inner = Arr->getElementType();
17728 else
17729 return nullptr;
17730
17731 if (Inner->hasAttr(attr::NoDeref))
17732 return E;
17733 }
17734 return nullptr;
17735}
17736
17737} // namespace
17738
17740 for (const Expr *E : Rec.PossibleDerefs) {
17741 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17742 if (DeclRef) {
17743 const ValueDecl *Decl = DeclRef->getDecl();
17744 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17745 << Decl->getName() << E->getSourceRange();
17746 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17747 } else {
17748 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17749 << E->getSourceRange();
17750 }
17751 }
17752 Rec.PossibleDerefs.clear();
17753}
17754
17755/// Check whether E, which is either a discarded-value expression or an
17756/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17757/// and if so, remove it from the list of volatile-qualified assignments that
17758/// we are going to warn are deprecated.
17761 return;
17762
17763 // Note: ignoring parens here is not justified by the standard rules, but
17764 // ignoring parentheses seems like a more reasonable approach, and this only
17765 // drives a deprecation warning so doesn't affect conformance.
17766 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17767 if (BO->getOpcode() == BO_Assign) {
17768 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17769 llvm::erase(LHSs, BO->getLHS());
17770 }
17771 }
17772}
17773
17775 assert(getLangOpts().CPlusPlus20 &&
17776 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17777 "Cannot mark an immediate escalating expression outside of an "
17778 "immediate escalating context");
17779 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17780 Call && Call->getCallee()) {
17781 if (auto *DeclRef =
17782 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17783 DeclRef->setIsImmediateEscalating(true);
17784 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17785 Ctr->setIsImmediateEscalating(true);
17786 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17787 DeclRef->setIsImmediateEscalating(true);
17788 } else {
17789 assert(false && "expected an immediately escalating expression");
17790 }
17792 FI->FoundImmediateEscalatingExpression = true;
17793}
17794
17796 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17797 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17800 return E;
17801
17802 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17803 /// It's OK if this fails; we'll also remove this in
17804 /// HandleImmediateInvocations, but catching it here allows us to avoid
17805 /// walking the AST looking for it in simple cases.
17806 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17807 if (auto *DeclRef =
17808 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17809 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17810
17811 // C++23 [expr.const]/p16
17812 // An expression or conversion is immediate-escalating if it is not initially
17813 // in an immediate function context and it is [...] an immediate invocation
17814 // that is not a constant expression and is not a subexpression of an
17815 // immediate invocation.
17816 APValue Cached;
17817 auto CheckConstantExpressionAndKeepResult = [&]() {
17819 Expr::EvalResult Eval;
17820 Eval.Diag = &Notes;
17821 bool Res = E.get()->EvaluateAsConstantExpr(
17822 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17823 if (Res && Notes.empty()) {
17824 Cached = std::move(Eval.Val);
17825 return true;
17826 }
17827 return false;
17828 };
17829
17830 if (!E.get()->isValueDependent() &&
17831 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17832 !CheckConstantExpressionAndKeepResult()) {
17834 return E;
17835 }
17836
17837 if (Cleanup.exprNeedsCleanups()) {
17838 // Since an immediate invocation is a full expression itself - it requires
17839 // an additional ExprWithCleanups node, but it can participate to a bigger
17840 // full expression which actually requires cleanups to be run after so
17841 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17842 // may discard cleanups for outer expression too early.
17843
17844 // Note that ExprWithCleanups created here must always have empty cleanup
17845 // objects:
17846 // - compound literals do not create cleanup objects in C++ and immediate
17847 // invocations are C++-only.
17848 // - blocks are not allowed inside constant expressions and compiler will
17849 // issue an error if they appear there.
17850 //
17851 // Hence, in correct code any cleanup objects created inside current
17852 // evaluation context must be outside the immediate invocation.
17855 }
17856
17858 getASTContext(), E.get(),
17859 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17860 getASTContext()),
17861 /*IsImmediateInvocation*/ true);
17862 if (Cached.hasValue())
17863 Res->MoveIntoResult(Cached, getASTContext());
17864 /// Value-dependent constant expressions should not be immediately
17865 /// evaluated until they are instantiated.
17866 if (!Res->isValueDependent())
17867 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17868 return Res;
17869}
17870
17874 Expr::EvalResult Eval;
17875 Eval.Diag = &Notes;
17876 ConstantExpr *CE = Candidate.getPointer();
17877 bool Result = CE->EvaluateAsConstantExpr(
17878 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17879 if (!Result || !Notes.empty()) {
17881 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17882 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17883 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17884 FunctionDecl *FD = nullptr;
17885 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17886 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17887 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17888 FD = Call->getConstructor();
17889 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17890 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17891
17892 assert(FD && FD->isImmediateFunction() &&
17893 "could not find an immediate function in this expression");
17894 if (FD->isInvalidDecl())
17895 return;
17896 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17897 << FD << FD->isConsteval();
17898 if (auto Context =
17900 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17901 << Context->Decl;
17902 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17903 }
17904 if (!FD->isConsteval())
17906 for (auto &Note : Notes)
17907 SemaRef.Diag(Note.first, Note.second);
17908 return;
17909 }
17911}
17912
17916 struct ComplexRemove : TreeTransform<ComplexRemove> {
17918 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17921 CurrentII;
17922 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17925 4>::reverse_iterator Current)
17926 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17927 void RemoveImmediateInvocation(ConstantExpr* E) {
17928 auto It = std::find_if(CurrentII, IISet.rend(),
17930 return Elem.getPointer() == E;
17931 });
17932 // It is possible that some subexpression of the current immediate
17933 // invocation was handled from another expression evaluation context. Do
17934 // not handle the current immediate invocation if some of its
17935 // subexpressions failed before.
17936 if (It == IISet.rend()) {
17937 if (SemaRef.FailedImmediateInvocations.contains(E))
17938 CurrentII->setInt(1);
17939 } else {
17940 It->setInt(1); // Mark as deleted
17941 }
17942 }
17943 ExprResult TransformConstantExpr(ConstantExpr *E) {
17944 if (!E->isImmediateInvocation())
17945 return Base::TransformConstantExpr(E);
17946 RemoveImmediateInvocation(E);
17947 return Base::TransformExpr(E->getSubExpr());
17948 }
17949 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17950 /// we need to remove its DeclRefExpr from the DRSet.
17951 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17952 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17953 return Base::TransformCXXOperatorCallExpr(E);
17954 }
17955 /// Base::TransformUserDefinedLiteral doesn't preserve the
17956 /// UserDefinedLiteral node.
17957 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17958 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17959 /// here.
17960 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17961 if (!Init)
17962 return Init;
17963 /// ConstantExpr are the first layer of implicit node to be removed so if
17964 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17965 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17966 if (CE->isImmediateInvocation())
17967 RemoveImmediateInvocation(CE);
17968 return Base::TransformInitializer(Init, NotCopyInit);
17969 }
17970 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17971 DRSet.erase(E);
17972 return E;
17973 }
17974 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17975 // Do not rebuild lambdas to avoid creating a new type.
17976 // Lambdas have already been processed inside their eval context.
17977 return E;
17978 }
17979 bool AlwaysRebuild() { return false; }
17980 bool ReplacingOriginal() { return true; }
17981 bool AllowSkippingCXXConstructExpr() {
17982 bool Res = AllowSkippingFirstCXXConstructExpr;
17983 AllowSkippingFirstCXXConstructExpr = true;
17984 return Res;
17985 }
17986 bool AllowSkippingFirstCXXConstructExpr = true;
17987 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17989
17990 /// CXXConstructExpr with a single argument are getting skipped by
17991 /// TreeTransform in some situtation because they could be implicit. This
17992 /// can only occur for the top-level CXXConstructExpr because it is used
17993 /// nowhere in the expression being transformed therefore will not be rebuilt.
17994 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17995 /// skipping the first CXXConstructExpr.
17996 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17997 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17998
17999 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18000 // The result may not be usable in case of previous compilation errors.
18001 // In this case evaluation of the expression may result in crash so just
18002 // don't do anything further with the result.
18003 if (Res.isUsable()) {
18005 It->getPointer()->setSubExpr(Res.get());
18006 }
18007}
18008
18009static void
18012 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18013 Rec.ReferenceToConsteval.size() == 0) ||
18015 return;
18016
18017 /// When we have more than 1 ImmediateInvocationCandidates or previously
18018 /// failed immediate invocations, we need to check for nested
18019 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18020 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18021 /// invocation.
18022 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18024
18025 /// Prevent sema calls during the tree transform from adding pointers that
18026 /// are already in the sets.
18027 llvm::SaveAndRestore DisableIITracking(
18029
18030 /// Prevent diagnostic during tree transfrom as they are duplicates
18032
18033 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18034 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18035 if (!It->getInt())
18037 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18038 Rec.ReferenceToConsteval.size()) {
18039 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18040 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18041 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18042 bool VisitDeclRefExpr(DeclRefExpr *E) {
18043 DRSet.erase(E);
18044 return DRSet.size();
18045 }
18046 } Visitor(Rec.ReferenceToConsteval);
18047 Visitor.TraverseStmt(
18048 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18049 }
18050 for (auto CE : Rec.ImmediateInvocationCandidates)
18051 if (!CE.getInt())
18053 for (auto *DR : Rec.ReferenceToConsteval) {
18054 // If the expression is immediate escalating, it is not an error;
18055 // The outer context itself becomes immediate and further errors,
18056 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18057 if (DR->isImmediateEscalating())
18058 continue;
18059 auto *FD = cast<FunctionDecl>(DR->getDecl());
18060 const NamedDecl *ND = FD;
18061 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18062 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18063 ND = MD->getParent();
18064
18065 // C++23 [expr.const]/p16
18066 // An expression or conversion is immediate-escalating if it is not
18067 // initially in an immediate function context and it is [...] a
18068 // potentially-evaluated id-expression that denotes an immediate function
18069 // that is not a subexpression of an immediate invocation.
18070 bool ImmediateEscalating = false;
18071 bool IsPotentiallyEvaluated =
18072 Rec.Context ==
18074 Rec.Context ==
18076 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18077 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18078
18080 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18081 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18082 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18083 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18084 if (auto Context =
18086 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18087 << Context->Decl;
18088 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18089 }
18090 if (FD->isImmediateEscalating() && !FD->isConsteval())
18092
18093 } else {
18095 }
18096 }
18097}
18098
18101 unsigned NumTypos = Rec.NumTypos;
18102
18103 if (!Rec.Lambdas.empty()) {
18105 if (!getLangOpts().CPlusPlus20 &&
18106 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18107 Rec.isUnevaluated() ||
18109 unsigned D;
18110 if (Rec.isUnevaluated()) {
18111 // C++11 [expr.prim.lambda]p2:
18112 // A lambda-expression shall not appear in an unevaluated operand
18113 // (Clause 5).
18114 D = diag::err_lambda_unevaluated_operand;
18115 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18116 // C++1y [expr.const]p2:
18117 // A conditional-expression e is a core constant expression unless the
18118 // evaluation of e, following the rules of the abstract machine, would
18119 // evaluate [...] a lambda-expression.
18120 D = diag::err_lambda_in_constant_expression;
18121 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18122 // C++17 [expr.prim.lamda]p2:
18123 // A lambda-expression shall not appear [...] in a template-argument.
18124 D = diag::err_lambda_in_invalid_context;
18125 } else
18126 llvm_unreachable("Couldn't infer lambda error message.");
18127
18128 for (const auto *L : Rec.Lambdas)
18129 Diag(L->getBeginLoc(), D);
18130 }
18131 }
18132
18133 // Append the collected materialized temporaries into previous context before
18134 // exit if the previous also is a lifetime extending context.
18135 auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
18137 PrevRecord.InLifetimeExtendingContext &&
18138 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18139 PrevRecord.ForRangeLifetimeExtendTemps.append(
18141 }
18142
18144 HandleImmediateInvocations(*this, Rec);
18145
18146 // Warn on any volatile-qualified simple-assignments that are not discarded-
18147 // value expressions nor unevaluated operands (those cases get removed from
18148 // this list by CheckUnusedVolatileAssignment).
18149 for (auto *BO : Rec.VolatileAssignmentLHSs)
18150 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18151 << BO->getType();
18152
18153 // When are coming out of an unevaluated context, clear out any
18154 // temporaries that we may have created as part of the evaluation of
18155 // the expression in that context: they aren't relevant because they
18156 // will never be constructed.
18157 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18159 ExprCleanupObjects.end());
18160 Cleanup = Rec.ParentCleanup;
18163 // Otherwise, merge the contexts together.
18164 } else {
18166 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18167 Rec.SavedMaybeODRUseExprs.end());
18168 }
18169
18170 // Pop the current expression evaluation context off the stack.
18171 ExprEvalContexts.pop_back();
18172
18173 // The global expression evaluation context record is never popped.
18174 ExprEvalContexts.back().NumTypos += NumTypos;
18175}
18176
18178 ExprCleanupObjects.erase(
18179 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18180 ExprCleanupObjects.end());
18181 Cleanup.reset();
18182 MaybeODRUseExprs.clear();
18183}
18184
18187 if (Result.isInvalid())
18188 return ExprError();
18189 E = Result.get();
18190 if (!E->getType()->isVariablyModifiedType())
18191 return E;
18193}
18194
18195/// Are we in a context that is potentially constant evaluated per C++20
18196/// [expr.const]p12?
18198 /// C++2a [expr.const]p12:
18199 // An expression or conversion is potentially constant evaluated if it is
18200 switch (SemaRef.ExprEvalContexts.back().Context) {
18203
18204 // -- a manifestly constant-evaluated expression,
18208 // -- a potentially-evaluated expression,
18210 // -- an immediate subexpression of a braced-init-list,
18211
18212 // -- [FIXME] an expression of the form & cast-expression that occurs
18213 // within a templated entity
18214 // -- a subexpression of one of the above that is not a subexpression of
18215 // a nested unevaluated operand.
18216 return true;
18217
18220 // Expressions in this context are never evaluated.
18221 return false;
18222 }
18223 llvm_unreachable("Invalid context");
18224}
18225
18226/// Return true if this function has a calling convention that requires mangling
18227/// in the size of the parameter pack.
18229 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18230 // we don't need parameter type sizes.
18231 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18232 if (!TT.isOSWindows() || !TT.isX86())
18233 return false;
18234
18235 // If this is C++ and this isn't an extern "C" function, parameters do not
18236 // need to be complete. In this case, C++ mangling will apply, which doesn't
18237 // use the size of the parameters.
18238 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18239 return false;
18240
18241 // Stdcall, fastcall, and vectorcall need this special treatment.
18242 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18243 switch (CC) {
18244 case CC_X86StdCall:
18245 case CC_X86FastCall:
18246 case CC_X86VectorCall:
18247 return true;
18248 default:
18249 break;
18250 }
18251 return false;
18252}
18253
18254/// Require that all of the parameter types of function be complete. Normally,
18255/// parameter types are only required to be complete when a function is called
18256/// or defined, but to mangle functions with certain calling conventions, the
18257/// mangler needs to know the size of the parameter list. In this situation,
18258/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18259/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18260/// result in a linker error. Clang doesn't implement this behavior, and instead
18261/// attempts to error at compile time.
18263 SourceLocation Loc) {
18264 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18265 FunctionDecl *FD;
18266 ParmVarDecl *Param;
18267
18268 public:
18269 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18270 : FD(FD), Param(Param) {}
18271
18272 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18273 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18274 StringRef CCName;
18275 switch (CC) {
18276 case CC_X86StdCall:
18277 CCName = "stdcall";
18278 break;
18279 case CC_X86FastCall:
18280 CCName = "fastcall";
18281 break;
18282 case CC_X86VectorCall:
18283 CCName = "vectorcall";
18284 break;
18285 default:
18286 llvm_unreachable("CC does not need mangling");
18287 }
18288
18289 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18290 << Param->getDeclName() << FD->getDeclName() << CCName;
18291 }
18292 };
18293
18294 for (ParmVarDecl *Param : FD->parameters()) {
18295 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18296 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18297 }
18298}
18299
18300namespace {
18301enum class OdrUseContext {
18302 /// Declarations in this context are not odr-used.
18303 None,
18304 /// Declarations in this context are formally odr-used, but this is a
18305 /// dependent context.
18306 Dependent,
18307 /// Declarations in this context are odr-used but not actually used (yet).
18308 FormallyOdrUsed,
18309 /// Declarations in this context are used.
18310 Used
18311};
18312}
18313
18314/// Are we within a context in which references to resolved functions or to
18315/// variables result in odr-use?
18316static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18317 OdrUseContext Result;
18318
18319 switch (SemaRef.ExprEvalContexts.back().Context) {
18323 return OdrUseContext::None;
18324
18328 Result = OdrUseContext::Used;
18329 break;
18330
18332 Result = OdrUseContext::FormallyOdrUsed;
18333 break;
18334
18336 // A default argument formally results in odr-use, but doesn't actually
18337 // result in a use in any real sense until it itself is used.
18338 Result = OdrUseContext::FormallyOdrUsed;
18339 break;
18340 }
18341
18343 return OdrUseContext::Dependent;
18344
18345 return Result;
18346}
18347
18349 if (!Func->isConstexpr())
18350 return false;
18351
18352 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18353 return true;
18354 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18355 return CCD && CCD->getInheritedConstructor();
18356}
18357
18358/// Mark a function referenced, and check whether it is odr-used
18359/// (C++ [basic.def.odr]p2, C99 6.9p3)
18361 bool MightBeOdrUse) {
18362 assert(Func && "No function?");
18363
18364 Func->setReferenced();
18365
18366 // Recursive functions aren't really used until they're used from some other
18367 // context.
18368 bool IsRecursiveCall = CurContext == Func;
18369
18370 // C++11 [basic.def.odr]p3:
18371 // A function whose name appears as a potentially-evaluated expression is
18372 // odr-used if it is the unique lookup result or the selected member of a
18373 // set of overloaded functions [...].
18374 //
18375 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18376 // can just check that here.
18377 OdrUseContext OdrUse =
18378 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18379 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18380 OdrUse = OdrUseContext::FormallyOdrUsed;
18381
18382 // Trivial default constructors and destructors are never actually used.
18383 // FIXME: What about other special members?
18384 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18385 OdrUse == OdrUseContext::Used) {
18386 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18387 if (Constructor->isDefaultConstructor())
18388 OdrUse = OdrUseContext::FormallyOdrUsed;
18389 if (isa<CXXDestructorDecl>(Func))
18390 OdrUse = OdrUseContext::FormallyOdrUsed;
18391 }
18392
18393 // C++20 [expr.const]p12:
18394 // A function [...] is needed for constant evaluation if it is [...] a
18395 // constexpr function that is named by an expression that is potentially
18396 // constant evaluated
18397 bool NeededForConstantEvaluation =
18400
18401 // Determine whether we require a function definition to exist, per
18402 // C++11 [temp.inst]p3:
18403 // Unless a function template specialization has been explicitly
18404 // instantiated or explicitly specialized, the function template
18405 // specialization is implicitly instantiated when the specialization is
18406 // referenced in a context that requires a function definition to exist.
18407 // C++20 [temp.inst]p7:
18408 // The existence of a definition of a [...] function is considered to
18409 // affect the semantics of the program if the [...] function is needed for
18410 // constant evaluation by an expression
18411 // C++20 [basic.def.odr]p10:
18412 // Every program shall contain exactly one definition of every non-inline
18413 // function or variable that is odr-used in that program outside of a
18414 // discarded statement
18415 // C++20 [special]p1:
18416 // The implementation will implicitly define [defaulted special members]
18417 // if they are odr-used or needed for constant evaluation.
18418 //
18419 // Note that we skip the implicit instantiation of templates that are only
18420 // used in unused default arguments or by recursive calls to themselves.
18421 // This is formally non-conforming, but seems reasonable in practice.
18422 bool NeedDefinition =
18423 !IsRecursiveCall &&
18424 (OdrUse == OdrUseContext::Used ||
18425 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18426
18427 // C++14 [temp.expl.spec]p6:
18428 // If a template [...] is explicitly specialized then that specialization
18429 // shall be declared before the first use of that specialization that would
18430 // cause an implicit instantiation to take place, in every translation unit
18431 // in which such a use occurs
18432 if (NeedDefinition &&
18433 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18434 Func->getMemberSpecializationInfo()))
18436
18437 if (getLangOpts().CUDA)
18438 CUDA().CheckCall(Loc, Func);
18439
18440 // If we need a definition, try to create one.
18441 if (NeedDefinition && !Func->getBody()) {
18443 if (CXXConstructorDecl *Constructor =
18444 dyn_cast<CXXConstructorDecl>(Func)) {
18445 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18446 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18447 if (Constructor->isDefaultConstructor()) {
18448 if (Constructor->isTrivial() &&
18449 !Constructor->hasAttr<DLLExportAttr>())
18450 return;
18451 DefineImplicitDefaultConstructor(Loc, Constructor);
18452 } else if (Constructor->isCopyConstructor()) {
18453 DefineImplicitCopyConstructor(Loc, Constructor);
18454 } else if (Constructor->isMoveConstructor()) {
18455 DefineImplicitMoveConstructor(Loc, Constructor);
18456 }
18457 } else if (Constructor->getInheritedConstructor()) {
18458 DefineInheritingConstructor(Loc, Constructor);
18459 }
18460 } else if (CXXDestructorDecl *Destructor =
18461 dyn_cast<CXXDestructorDecl>(Func)) {
18462 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18463 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18464 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18465 return;
18467 }
18468 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18469 MarkVTableUsed(Loc, Destructor->getParent());
18470 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18471 if (MethodDecl->isOverloadedOperator() &&
18472 MethodDecl->getOverloadedOperator() == OO_Equal) {
18473 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18474 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18475 if (MethodDecl->isCopyAssignmentOperator())
18476 DefineImplicitCopyAssignment(Loc, MethodDecl);
18477 else if (MethodDecl->isMoveAssignmentOperator())
18478 DefineImplicitMoveAssignment(Loc, MethodDecl);
18479 }
18480 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18481 MethodDecl->getParent()->isLambda()) {
18482 CXXConversionDecl *Conversion =
18483 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18484 if (Conversion->isLambdaToBlockPointerConversion())
18486 else
18488 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18489 MarkVTableUsed(Loc, MethodDecl->getParent());
18490 }
18491
18492 if (Func->isDefaulted() && !Func->isDeleted()) {
18496 }
18497
18498 // Implicit instantiation of function templates and member functions of
18499 // class templates.
18500 if (Func->isImplicitlyInstantiable()) {
18502 Func->getTemplateSpecializationKindForInstantiation();
18503 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18504 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18505 if (FirstInstantiation) {
18506 PointOfInstantiation = Loc;
18507 if (auto *MSI = Func->getMemberSpecializationInfo())
18508 MSI->setPointOfInstantiation(Loc);
18509 // FIXME: Notify listener.
18510 else
18511 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18512 } else if (TSK != TSK_ImplicitInstantiation) {
18513 // Use the point of use as the point of instantiation, instead of the
18514 // point of explicit instantiation (which we track as the actual point
18515 // of instantiation). This gives better backtraces in diagnostics.
18516 PointOfInstantiation = Loc;
18517 }
18518
18519 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18520 Func->isConstexpr()) {
18521 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18522 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18523 CodeSynthesisContexts.size())
18525 std::make_pair(Func, PointOfInstantiation));
18526 else if (Func->isConstexpr())
18527 // Do not defer instantiations of constexpr functions, to avoid the
18528 // expression evaluator needing to call back into Sema if it sees a
18529 // call to such a function.
18530 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18531 else {
18532 Func->setInstantiationIsPending(true);
18533 PendingInstantiations.push_back(
18534 std::make_pair(Func, PointOfInstantiation));
18535 // Notify the consumer that a function was implicitly instantiated.
18537 }
18538 }
18539 } else {
18540 // Walk redefinitions, as some of them may be instantiable.
18541 for (auto *i : Func->redecls()) {
18542 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18543 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18544 }
18545 }
18546 });
18547 }
18548
18549 // If a constructor was defined in the context of a default parameter
18550 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18551 // context), its initializers may not be referenced yet.
18552 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18554 *this,
18555 Constructor->isImmediateFunction()
18558 Constructor);
18559 for (CXXCtorInitializer *Init : Constructor->inits()) {
18560 if (Init->isInClassMemberInitializer())
18561 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18562 MarkDeclarationsReferencedInExpr(Init->getInit());
18563 });
18564 }
18565 }
18566
18567 // C++14 [except.spec]p17:
18568 // An exception-specification is considered to be needed when:
18569 // - the function is odr-used or, if it appears in an unevaluated operand,
18570 // would be odr-used if the expression were potentially-evaluated;
18571 //
18572 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18573 // function is a pure virtual function we're calling, and in that case the
18574 // function was selected by overload resolution and we need to resolve its
18575 // exception specification for a different reason.
18576 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18578 ResolveExceptionSpec(Loc, FPT);
18579
18580 // A callee could be called by a host function then by a device function.
18581 // If we only try recording once, we will miss recording the use on device
18582 // side. Therefore keep trying until it is recorded.
18583 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18586
18587 // If this is the first "real" use, act on that.
18588 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18589 // Keep track of used but undefined functions.
18590 if (!Func->isDefined()) {
18591 if (mightHaveNonExternalLinkage(Func))
18592 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18593 else if (Func->getMostRecentDecl()->isInlined() &&
18594 !LangOpts.GNUInline &&
18595 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18596 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18598 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18599 }
18600
18601 // Some x86 Windows calling conventions mangle the size of the parameter
18602 // pack into the name. Computing the size of the parameters requires the
18603 // parameter types to be complete. Check that now.
18606
18607 // In the MS C++ ABI, the compiler emits destructor variants where they are
18608 // used. If the destructor is used here but defined elsewhere, mark the
18609 // virtual base destructors referenced. If those virtual base destructors
18610 // are inline, this will ensure they are defined when emitting the complete
18611 // destructor variant. This checking may be redundant if the destructor is
18612 // provided later in this TU.
18614 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18615 CXXRecordDecl *Parent = Dtor->getParent();
18616 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18618 }
18619 }
18620
18621 Func->markUsed(Context);
18622 }
18623}
18624
18625/// Directly mark a variable odr-used. Given a choice, prefer to use
18626/// MarkVariableReferenced since it does additional checks and then
18627/// calls MarkVarDeclODRUsed.
18628/// If the variable must be captured:
18629/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18630/// - else capture it in the DeclContext that maps to the
18631/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18632static void
18634 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18635 // Keep track of used but undefined variables.
18636 // FIXME: We shouldn't suppress this warning for static data members.
18637 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18638 assert(Var && "expected a capturable variable");
18639
18641 (!Var->isExternallyVisible() || Var->isInline() ||
18643 !(Var->isStaticDataMember() && Var->hasInit())) {
18645 if (old.isInvalid())
18646 old = Loc;
18647 }
18648 QualType CaptureType, DeclRefType;
18649 if (SemaRef.LangOpts.OpenMP)
18652 /*EllipsisLoc*/ SourceLocation(),
18653 /*BuildAndDiagnose*/ true, CaptureType,
18654 DeclRefType, FunctionScopeIndexToStopAt);
18655
18656 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18657 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18658 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18659 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18660 if (VarTarget == SemaCUDA::CVT_Host &&
18661 (UserTarget == CUDAFunctionTarget::Device ||
18662 UserTarget == CUDAFunctionTarget::HostDevice ||
18663 UserTarget == CUDAFunctionTarget::Global)) {
18664 // Diagnose ODR-use of host global variables in device functions.
18665 // Reference of device global variables in host functions is allowed
18666 // through shadow variables therefore it is not diagnosed.
18667 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18668 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18669 << /*host*/ 2 << /*variable*/ 1 << Var
18670 << llvm::to_underlying(UserTarget);
18672 Var->getType().isConstQualified()
18673 ? diag::note_cuda_const_var_unpromoted
18674 : diag::note_cuda_host_var);
18675 }
18676 } else if (VarTarget == SemaCUDA::CVT_Device &&
18677 !Var->hasAttr<CUDASharedAttr>() &&
18678 (UserTarget == CUDAFunctionTarget::Host ||
18679 UserTarget == CUDAFunctionTarget::HostDevice)) {
18680 // Record a CUDA/HIP device side variable if it is ODR-used
18681 // by host code. This is done conservatively, when the variable is
18682 // referenced in any of the following contexts:
18683 // - a non-function context
18684 // - a host function
18685 // - a host device function
18686 // This makes the ODR-use of the device side variable by host code to
18687 // be visible in the device compilation for the compiler to be able to
18688 // emit template variables instantiated by host code only and to
18689 // externalize the static device side variable ODR-used by host code.
18690 if (!Var->hasExternalStorage())
18692 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18693 (!FD || (!FD->getDescribedFunctionTemplate() &&
18697 }
18698 }
18699
18700 V->markUsed(SemaRef.Context);
18701}
18702
18704 SourceLocation Loc,
18705 unsigned CapturingScopeIndex) {
18706 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18707}
18708
18710 ValueDecl *var) {
18711 DeclContext *VarDC = var->getDeclContext();
18712
18713 // If the parameter still belongs to the translation unit, then
18714 // we're actually just using one parameter in the declaration of
18715 // the next.
18716 if (isa<ParmVarDecl>(var) &&
18717 isa<TranslationUnitDecl>(VarDC))
18718 return;
18719
18720 // For C code, don't diagnose about capture if we're not actually in code
18721 // right now; it's impossible to write a non-constant expression outside of
18722 // function context, so we'll get other (more useful) diagnostics later.
18723 //
18724 // For C++, things get a bit more nasty... it would be nice to suppress this
18725 // diagnostic for certain cases like using a local variable in an array bound
18726 // for a member of a local class, but the correct predicate is not obvious.
18727 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18728 return;
18729
18730 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18731 unsigned ContextKind = 3; // unknown
18732 if (isa<CXXMethodDecl>(VarDC) &&
18733 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18734 ContextKind = 2;
18735 } else if (isa<FunctionDecl>(VarDC)) {
18736 ContextKind = 0;
18737 } else if (isa<BlockDecl>(VarDC)) {
18738 ContextKind = 1;
18739 }
18740
18741 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18742 << var << ValueKind << ContextKind << VarDC;
18743 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18744 << var;
18745
18746 // FIXME: Add additional diagnostic info about class etc. which prevents
18747 // capture.
18748}
18749
18751 ValueDecl *Var,
18752 bool &SubCapturesAreNested,
18753 QualType &CaptureType,
18754 QualType &DeclRefType) {
18755 // Check whether we've already captured it.
18756 if (CSI->CaptureMap.count(Var)) {
18757 // If we found a capture, any subcaptures are nested.
18758 SubCapturesAreNested = true;
18759
18760 // Retrieve the capture type for this variable.
18761 CaptureType = CSI->getCapture(Var).getCaptureType();
18762
18763 // Compute the type of an expression that refers to this variable.
18764 DeclRefType = CaptureType.getNonReferenceType();
18765
18766 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18767 // are mutable in the sense that user can change their value - they are
18768 // private instances of the captured declarations.
18769 const Capture &Cap = CSI->getCapture(Var);
18770 if (Cap.isCopyCapture() &&
18771 !(isa<LambdaScopeInfo>(CSI) &&
18772 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18773 !(isa<CapturedRegionScopeInfo>(CSI) &&
18774 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18775 DeclRefType.addConst();
18776 return true;
18777 }
18778 return false;
18779}
18780
18781// Only block literals, captured statements, and lambda expressions can
18782// capture; other scopes don't work.
18784 ValueDecl *Var,
18785 SourceLocation Loc,
18786 const bool Diagnose,
18787 Sema &S) {
18788 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18790
18791 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18792 if (Underlying) {
18793 if (Underlying->hasLocalStorage() && Diagnose)
18795 }
18796 return nullptr;
18797}
18798
18799// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18800// certain types of variables (unnamed, variably modified types etc.)
18801// so check for eligibility.
18803 SourceLocation Loc, const bool Diagnose,
18804 Sema &S) {
18805
18806 assert((isa<VarDecl, BindingDecl>(Var)) &&
18807 "Only variables and structured bindings can be captured");
18808
18809 bool IsBlock = isa<BlockScopeInfo>(CSI);
18810 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18811
18812 // Lambdas are not allowed to capture unnamed variables
18813 // (e.g. anonymous unions).
18814 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18815 // assuming that's the intent.
18816 if (IsLambda && !Var->getDeclName()) {
18817 if (Diagnose) {
18818 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18819 S.Diag(Var->getLocation(), diag::note_declared_at);
18820 }
18821 return false;
18822 }
18823
18824 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18825 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18826 if (Diagnose) {
18827 S.Diag(Loc, diag::err_ref_vm_type);
18828 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18829 }
18830 return false;
18831 }
18832 // Prohibit structs with flexible array members too.
18833 // We cannot capture what is in the tail end of the struct.
18834 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18835 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18836 if (Diagnose) {
18837 if (IsBlock)
18838 S.Diag(Loc, diag::err_ref_flexarray_type);
18839 else
18840 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18841 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18842 }
18843 return false;
18844 }
18845 }
18846 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18847 // Lambdas and captured statements are not allowed to capture __block
18848 // variables; they don't support the expected semantics.
18849 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18850 if (Diagnose) {
18851 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18852 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18853 }
18854 return false;
18855 }
18856 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18857 if (S.getLangOpts().OpenCL && IsBlock &&
18858 Var->getType()->isBlockPointerType()) {
18859 if (Diagnose)
18860 S.Diag(Loc, diag::err_opencl_block_ref_block);
18861 return false;
18862 }
18863
18864 if (isa<BindingDecl>(Var)) {
18865 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18866 if (Diagnose)
18868 return false;
18869 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18870 S.Diag(Loc, S.LangOpts.CPlusPlus20
18871 ? diag::warn_cxx17_compat_capture_binding
18872 : diag::ext_capture_binding)
18873 << Var;
18874 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18875 }
18876 }
18877
18878 return true;
18879}
18880
18881// Returns true if the capture by block was successful.
18883 SourceLocation Loc, const bool BuildAndDiagnose,
18884 QualType &CaptureType, QualType &DeclRefType,
18885 const bool Nested, Sema &S, bool Invalid) {
18886 bool ByRef = false;
18887
18888 // Blocks are not allowed to capture arrays, excepting OpenCL.
18889 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18890 // (decayed to pointers).
18891 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18892 if (BuildAndDiagnose) {
18893 S.Diag(Loc, diag::err_ref_array_type);
18894 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18895 Invalid = true;
18896 } else {
18897 return false;
18898 }
18899 }
18900
18901 // Forbid the block-capture of autoreleasing variables.
18902 if (!Invalid &&
18904 if (BuildAndDiagnose) {
18905 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18906 << /*block*/ 0;
18907 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18908 Invalid = true;
18909 } else {
18910 return false;
18911 }
18912 }
18913
18914 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18915 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18916 QualType PointeeTy = PT->getPointeeType();
18917
18918 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18920 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18921 if (BuildAndDiagnose) {
18922 SourceLocation VarLoc = Var->getLocation();
18923 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18924 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18925 }
18926 }
18927 }
18928
18929 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18930 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18931 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18932 // Block capture by reference does not change the capture or
18933 // declaration reference types.
18934 ByRef = true;
18935 } else {
18936 // Block capture by copy introduces 'const'.
18937 CaptureType = CaptureType.getNonReferenceType().withConst();
18938 DeclRefType = CaptureType;
18939 }
18940
18941 // Actually capture the variable.
18942 if (BuildAndDiagnose)
18943 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18944 CaptureType, Invalid);
18945
18946 return !Invalid;
18947}
18948
18949/// Capture the given variable in the captured region.
18952 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18953 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18954 bool IsTopScope, Sema &S, bool Invalid) {
18955 // By default, capture variables by reference.
18956 bool ByRef = true;
18957 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18958 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18959 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18960 // Using an LValue reference type is consistent with Lambdas (see below).
18961 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18962 bool HasConst = DeclRefType.isConstQualified();
18963 DeclRefType = DeclRefType.getUnqualifiedType();
18964 // Don't lose diagnostics about assignments to const.
18965 if (HasConst)
18966 DeclRefType.addConst();
18967 }
18968 // Do not capture firstprivates in tasks.
18969 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18970 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18971 return true;
18972 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18973 RSI->OpenMPCaptureLevel);
18974 }
18975
18976 if (ByRef)
18977 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18978 else
18979 CaptureType = DeclRefType;
18980
18981 // Actually capture the variable.
18982 if (BuildAndDiagnose)
18983 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18984 Loc, SourceLocation(), CaptureType, Invalid);
18985
18986 return !Invalid;
18987}
18988
18989/// Capture the given variable in the lambda.
18991 SourceLocation Loc, const bool BuildAndDiagnose,
18992 QualType &CaptureType, QualType &DeclRefType,
18993 const bool RefersToCapturedVariable,
18994 const Sema::TryCaptureKind Kind,
18995 SourceLocation EllipsisLoc, const bool IsTopScope,
18996 Sema &S, bool Invalid) {
18997 // Determine whether we are capturing by reference or by value.
18998 bool ByRef = false;
18999 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19000 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19001 } else {
19002 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19003 }
19004
19005 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19007 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19008 Invalid = true;
19009 }
19010
19011 // Compute the type of the field that will capture this variable.
19012 if (ByRef) {
19013 // C++11 [expr.prim.lambda]p15:
19014 // An entity is captured by reference if it is implicitly or
19015 // explicitly captured but not captured by copy. It is
19016 // unspecified whether additional unnamed non-static data
19017 // members are declared in the closure type for entities
19018 // captured by reference.
19019 //
19020 // FIXME: It is not clear whether we want to build an lvalue reference
19021 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19022 // to do the former, while EDG does the latter. Core issue 1249 will
19023 // clarify, but for now we follow GCC because it's a more permissive and
19024 // easily defensible position.
19025 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19026 } else {
19027 // C++11 [expr.prim.lambda]p14:
19028 // For each entity captured by copy, an unnamed non-static
19029 // data member is declared in the closure type. The
19030 // declaration order of these members is unspecified. The type
19031 // of such a data member is the type of the corresponding
19032 // captured entity if the entity is not a reference to an
19033 // object, or the referenced type otherwise. [Note: If the
19034 // captured entity is a reference to a function, the
19035 // corresponding data member is also a reference to a
19036 // function. - end note ]
19037 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19038 if (!RefType->getPointeeType()->isFunctionType())
19039 CaptureType = RefType->getPointeeType();
19040 }
19041
19042 // Forbid the lambda copy-capture of autoreleasing variables.
19043 if (!Invalid &&
19045 if (BuildAndDiagnose) {
19046 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19047 S.Diag(Var->getLocation(), diag::note_previous_decl)
19048 << Var->getDeclName();
19049 Invalid = true;
19050 } else {
19051 return false;
19052 }
19053 }
19054
19055 // Make sure that by-copy captures are of a complete and non-abstract type.
19056 if (!Invalid && BuildAndDiagnose) {
19057 if (!CaptureType->isDependentType() &&
19059 Loc, CaptureType,
19060 diag::err_capture_of_incomplete_or_sizeless_type,
19061 Var->getDeclName()))
19062 Invalid = true;
19063 else if (S.RequireNonAbstractType(Loc, CaptureType,
19064 diag::err_capture_of_abstract_type))
19065 Invalid = true;
19066 }
19067 }
19068
19069 // Compute the type of a reference to this captured variable.
19070 if (ByRef)
19071 DeclRefType = CaptureType.getNonReferenceType();
19072 else {
19073 // C++ [expr.prim.lambda]p5:
19074 // The closure type for a lambda-expression has a public inline
19075 // function call operator [...]. This function call operator is
19076 // declared const (9.3.1) if and only if the lambda-expression's
19077 // parameter-declaration-clause is not followed by mutable.
19078 DeclRefType = CaptureType.getNonReferenceType();
19079 bool Const = LSI->lambdaCaptureShouldBeConst();
19080 if (Const && !CaptureType->isReferenceType())
19081 DeclRefType.addConst();
19082 }
19083
19084 // Add the capture.
19085 if (BuildAndDiagnose)
19086 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19087 Loc, EllipsisLoc, CaptureType, Invalid);
19088
19089 return !Invalid;
19090}
19091
19093 const ASTContext &Context) {
19094 // Offer a Copy fix even if the type is dependent.
19095 if (Var->getType()->isDependentType())
19096 return true;
19098 if (T.isTriviallyCopyableType(Context))
19099 return true;
19100 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19101
19102 if (!(RD = RD->getDefinition()))
19103 return false;
19104 if (RD->hasSimpleCopyConstructor())
19105 return true;
19106 if (RD->hasUserDeclaredCopyConstructor())
19107 for (CXXConstructorDecl *Ctor : RD->ctors())
19108 if (Ctor->isCopyConstructor())
19109 return !Ctor->isDeleted();
19110 }
19111 return false;
19112}
19113
19114/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19115/// default capture. Fixes may be omitted if they aren't allowed by the
19116/// standard, for example we can't emit a default copy capture fix-it if we
19117/// already explicitly copy capture capture another variable.
19119 ValueDecl *Var) {
19121 // Don't offer Capture by copy of default capture by copy fixes if Var is
19122 // known not to be copy constructible.
19123 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19124
19125 SmallString<32> FixBuffer;
19126 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19127 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19128 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19129 if (ShouldOfferCopyFix) {
19130 // Offer fixes to insert an explicit capture for the variable.
19131 // [] -> [VarName]
19132 // [OtherCapture] -> [OtherCapture, VarName]
19133 FixBuffer.assign({Separator, Var->getName()});
19134 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19135 << Var << /*value*/ 0
19136 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19137 }
19138 // As above but capture by reference.
19139 FixBuffer.assign({Separator, "&", Var->getName()});
19140 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19141 << Var << /*reference*/ 1
19142 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19143 }
19144
19145 // Only try to offer default capture if there are no captures excluding this
19146 // and init captures.
19147 // [this]: OK.
19148 // [X = Y]: OK.
19149 // [&A, &B]: Don't offer.
19150 // [A, B]: Don't offer.
19151 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19152 return !C.isThisCapture() && !C.isInitCapture();
19153 }))
19154 return;
19155
19156 // The default capture specifiers, '=' or '&', must appear first in the
19157 // capture body.
19158 SourceLocation DefaultInsertLoc =
19160
19161 if (ShouldOfferCopyFix) {
19162 bool CanDefaultCopyCapture = true;
19163 // [=, *this] OK since c++17
19164 // [=, this] OK since c++20
19165 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19166 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19168 : false;
19169 // We can't use default capture by copy if any captures already specified
19170 // capture by copy.
19171 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19172 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19173 })) {
19174 FixBuffer.assign({"=", Separator});
19175 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19176 << /*value*/ 0
19177 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19178 }
19179 }
19180
19181 // We can't use default capture by reference if any captures already specified
19182 // capture by reference.
19183 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19184 return !C.isInitCapture() && C.isReferenceCapture() &&
19185 !C.isThisCapture();
19186 })) {
19187 FixBuffer.assign({"&", Separator});
19188 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19189 << /*reference*/ 1
19190 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19191 }
19192}
19193
19195 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19196 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19197 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19198 // An init-capture is notionally from the context surrounding its
19199 // declaration, but its parent DC is the lambda class.
19200 DeclContext *VarDC = Var->getDeclContext();
19201 DeclContext *DC = CurContext;
19202
19203 // tryCaptureVariable is called every time a DeclRef is formed,
19204 // it can therefore have non-negigible impact on performances.
19205 // For local variables and when there is no capturing scope,
19206 // we can bailout early.
19207 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19208 return true;
19209
19210 const auto *VD = dyn_cast<VarDecl>(Var);
19211 if (VD) {
19212 if (VD->isInitCapture())
19213 VarDC = VarDC->getParent();
19214 } else {
19216 }
19217 assert(VD && "Cannot capture a null variable");
19218
19219 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19220 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19221 // We need to sync up the Declaration Context with the
19222 // FunctionScopeIndexToStopAt
19223 if (FunctionScopeIndexToStopAt) {
19224 unsigned FSIndex = FunctionScopes.size() - 1;
19225 while (FSIndex != MaxFunctionScopesIndex) {
19227 --FSIndex;
19228 }
19229 }
19230
19231 // Capture global variables if it is required to use private copy of this
19232 // variable.
19233 bool IsGlobal = !VD->hasLocalStorage();
19234 if (IsGlobal && !(LangOpts.OpenMP &&
19235 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19236 MaxFunctionScopesIndex)))
19237 return true;
19238
19239 if (isa<VarDecl>(Var))
19240 Var = cast<VarDecl>(Var->getCanonicalDecl());
19241
19242 // Walk up the stack to determine whether we can capture the variable,
19243 // performing the "simple" checks that don't depend on type. We stop when
19244 // we've either hit the declared scope of the variable or find an existing
19245 // capture of that variable. We start from the innermost capturing-entity
19246 // (the DC) and ensure that all intervening capturing-entities
19247 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19248 // declcontext can either capture the variable or have already captured
19249 // the variable.
19250 CaptureType = Var->getType();
19251 DeclRefType = CaptureType.getNonReferenceType();
19252 bool Nested = false;
19253 bool Explicit = (Kind != TryCapture_Implicit);
19254 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19255 do {
19256
19257 LambdaScopeInfo *LSI = nullptr;
19258 if (!FunctionScopes.empty())
19259 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19260 FunctionScopes[FunctionScopesIndex]);
19261
19262 bool IsInScopeDeclarationContext =
19263 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19264
19265 if (LSI && !LSI->AfterParameterList) {
19266 // This allows capturing parameters from a default value which does not
19267 // seems correct
19268 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19269 return true;
19270 }
19271 // If the variable is declared in the current context, there is no need to
19272 // capture it.
19273 if (IsInScopeDeclarationContext &&
19274 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19275 return true;
19276
19277 // Only block literals, captured statements, and lambda expressions can
19278 // capture; other scopes don't work.
19279 DeclContext *ParentDC =
19280 !IsInScopeDeclarationContext
19281 ? DC->getParent()
19282 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19283 BuildAndDiagnose, *this);
19284 // We need to check for the parent *first* because, if we *have*
19285 // private-captured a global variable, we need to recursively capture it in
19286 // intermediate blocks, lambdas, etc.
19287 if (!ParentDC) {
19288 if (IsGlobal) {
19289 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19290 break;
19291 }
19292 return true;
19293 }
19294
19295 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19296 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19297
19298 // Check whether we've already captured it.
19299 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19300 DeclRefType)) {
19301 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19302 break;
19303 }
19304
19305 // When evaluating some attributes (like enable_if) we might refer to a
19306 // function parameter appertaining to the same declaration as that
19307 // attribute.
19308 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19309 Parm && Parm->getDeclContext() == DC)
19310 return true;
19311
19312 // If we are instantiating a generic lambda call operator body,
19313 // we do not want to capture new variables. What was captured
19314 // during either a lambdas transformation or initial parsing
19315 // should be used.
19317 if (BuildAndDiagnose) {
19318 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19320 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19321 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19322 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19323 buildLambdaCaptureFixit(*this, LSI, Var);
19324 } else
19326 }
19327 return true;
19328 }
19329
19330 // Try to capture variable-length arrays types.
19331 if (Var->getType()->isVariablyModifiedType()) {
19332 // We're going to walk down into the type and look for VLA
19333 // expressions.
19334 QualType QTy = Var->getType();
19335 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19336 QTy = PVD->getOriginalType();
19338 }
19339
19340 if (getLangOpts().OpenMP) {
19341 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19342 // OpenMP private variables should not be captured in outer scope, so
19343 // just break here. Similarly, global variables that are captured in a
19344 // target region should not be captured outside the scope of the region.
19345 if (RSI->CapRegionKind == CR_OpenMP) {
19346 // FIXME: We should support capturing structured bindings in OpenMP.
19347 if (isa<BindingDecl>(Var)) {
19348 if (BuildAndDiagnose) {
19349 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19350 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19351 }
19352 return true;
19353 }
19354 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19355 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19356 // If the variable is private (i.e. not captured) and has variably
19357 // modified type, we still need to capture the type for correct
19358 // codegen in all regions, associated with the construct. Currently,
19359 // it is captured in the innermost captured region only.
19360 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19361 Var->getType()->isVariablyModifiedType()) {
19362 QualType QTy = Var->getType();
19363 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19364 QTy = PVD->getOriginalType();
19365 for (int I = 1,
19366 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19367 I < E; ++I) {
19368 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19369 FunctionScopes[FunctionScopesIndex - I]);
19370 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19371 "Wrong number of captured regions associated with the "
19372 "OpenMP construct.");
19373 captureVariablyModifiedType(Context, QTy, OuterRSI);
19374 }
19375 }
19376 bool IsTargetCap =
19377 IsOpenMPPrivateDecl != OMPC_private &&
19378 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19379 RSI->OpenMPCaptureLevel);
19380 // Do not capture global if it is not privatized in outer regions.
19381 bool IsGlobalCap =
19382 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19383 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19384
19385 // When we detect target captures we are looking from inside the
19386 // target region, therefore we need to propagate the capture from the
19387 // enclosing region. Therefore, the capture is not initially nested.
19388 if (IsTargetCap)
19389 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19390 RSI->OpenMPLevel);
19391
19392 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19393 (IsGlobal && !IsGlobalCap)) {
19394 Nested = !IsTargetCap;
19395 bool HasConst = DeclRefType.isConstQualified();
19396 DeclRefType = DeclRefType.getUnqualifiedType();
19397 // Don't lose diagnostics about assignments to const.
19398 if (HasConst)
19399 DeclRefType.addConst();
19400 CaptureType = Context.getLValueReferenceType(DeclRefType);
19401 break;
19402 }
19403 }
19404 }
19405 }
19406 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19407 // No capture-default, and this is not an explicit capture
19408 // so cannot capture this variable.
19409 if (BuildAndDiagnose) {
19410 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19411 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19412 auto *LSI = cast<LambdaScopeInfo>(CSI);
19413 if (LSI->Lambda) {
19414 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19415 buildLambdaCaptureFixit(*this, LSI, Var);
19416 }
19417 // FIXME: If we error out because an outer lambda can not implicitly
19418 // capture a variable that an inner lambda explicitly captures, we
19419 // should have the inner lambda do the explicit capture - because
19420 // it makes for cleaner diagnostics later. This would purely be done
19421 // so that the diagnostic does not misleadingly claim that a variable
19422 // can not be captured by a lambda implicitly even though it is captured
19423 // explicitly. Suggestion:
19424 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19425 // at the function head
19426 // - cache the StartingDeclContext - this must be a lambda
19427 // - captureInLambda in the innermost lambda the variable.
19428 }
19429 return true;
19430 }
19431 Explicit = false;
19432 FunctionScopesIndex--;
19433 if (IsInScopeDeclarationContext)
19434 DC = ParentDC;
19435 } while (!VarDC->Equals(DC));
19436
19437 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19438 // computing the type of the capture at each step, checking type-specific
19439 // requirements, and adding captures if requested.
19440 // If the variable had already been captured previously, we start capturing
19441 // at the lambda nested within that one.
19442 bool Invalid = false;
19443 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19444 ++I) {
19445 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19446
19447 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19448 // certain types of variables (unnamed, variably modified types etc.)
19449 // so check for eligibility.
19450 if (!Invalid)
19451 Invalid =
19452 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19453
19454 // After encountering an error, if we're actually supposed to capture, keep
19455 // capturing in nested contexts to suppress any follow-on diagnostics.
19456 if (Invalid && !BuildAndDiagnose)
19457 return true;
19458
19459 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19460 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19461 DeclRefType, Nested, *this, Invalid);
19462 Nested = true;
19463 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19465 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19466 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19467 Nested = true;
19468 } else {
19469 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19470 Invalid =
19471 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19472 DeclRefType, Nested, Kind, EllipsisLoc,
19473 /*IsTopScope*/ I == N - 1, *this, Invalid);
19474 Nested = true;
19475 }
19476
19477 if (Invalid && !BuildAndDiagnose)
19478 return true;
19479 }
19480 return Invalid;
19481}
19482
19484 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19485 QualType CaptureType;
19486 QualType DeclRefType;
19487 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19488 /*BuildAndDiagnose=*/true, CaptureType,
19489 DeclRefType, nullptr);
19490}
19491
19493 QualType CaptureType;
19494 QualType DeclRefType;
19496 /*BuildAndDiagnose=*/false, CaptureType,
19497 DeclRefType, nullptr);
19498}
19499
19501 QualType CaptureType;
19502 QualType DeclRefType;
19503
19504 // Determine whether we can capture this variable.
19506 /*BuildAndDiagnose=*/false, CaptureType,
19507 DeclRefType, nullptr))
19508 return QualType();
19509
19510 return DeclRefType;
19511}
19512
19513namespace {
19514// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19515// The produced TemplateArgumentListInfo* points to data stored within this
19516// object, so should only be used in contexts where the pointer will not be
19517// used after the CopiedTemplateArgs object is destroyed.
19518class CopiedTemplateArgs {
19519 bool HasArgs;
19520 TemplateArgumentListInfo TemplateArgStorage;
19521public:
19522 template<typename RefExpr>
19523 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19524 if (HasArgs)
19525 E->copyTemplateArgumentsInto(TemplateArgStorage);
19526 }
19527 operator TemplateArgumentListInfo*()
19528#ifdef __has_cpp_attribute
19529#if __has_cpp_attribute(clang::lifetimebound)
19530 [[clang::lifetimebound]]
19531#endif
19532#endif
19533 {
19534 return HasArgs ? &TemplateArgStorage : nullptr;
19535 }
19536};
19537}
19538
19539/// Walk the set of potential results of an expression and mark them all as
19540/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19541///
19542/// \return A new expression if we found any potential results, ExprEmpty() if
19543/// not, and ExprError() if we diagnosed an error.
19545 NonOdrUseReason NOUR) {
19546 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19547 // an object that satisfies the requirements for appearing in a
19548 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19549 // is immediately applied." This function handles the lvalue-to-rvalue
19550 // conversion part.
19551 //
19552 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19553 // transform it into the relevant kind of non-odr-use node and rebuild the
19554 // tree of nodes leading to it.
19555 //
19556 // This is a mini-TreeTransform that only transforms a restricted subset of
19557 // nodes (and only certain operands of them).
19558
19559 // Rebuild a subexpression.
19560 auto Rebuild = [&](Expr *Sub) {
19561 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19562 };
19563
19564 // Check whether a potential result satisfies the requirements of NOUR.
19565 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19566 // Any entity other than a VarDecl is always odr-used whenever it's named
19567 // in a potentially-evaluated expression.
19568 auto *VD = dyn_cast<VarDecl>(D);
19569 if (!VD)
19570 return true;
19571
19572 // C++2a [basic.def.odr]p4:
19573 // A variable x whose name appears as a potentially-evalauted expression
19574 // e is odr-used by e unless
19575 // -- x is a reference that is usable in constant expressions, or
19576 // -- x is a variable of non-reference type that is usable in constant
19577 // expressions and has no mutable subobjects, and e is an element of
19578 // the set of potential results of an expression of
19579 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19580 // conversion is applied, or
19581 // -- x is a variable of non-reference type, and e is an element of the
19582 // set of potential results of a discarded-value expression to which
19583 // the lvalue-to-rvalue conversion is not applied
19584 //
19585 // We check the first bullet and the "potentially-evaluated" condition in
19586 // BuildDeclRefExpr. We check the type requirements in the second bullet
19587 // in CheckLValueToRValueConversionOperand below.
19588 switch (NOUR) {
19589 case NOUR_None:
19590 case NOUR_Unevaluated:
19591 llvm_unreachable("unexpected non-odr-use-reason");
19592
19593 case NOUR_Constant:
19594 // Constant references were handled when they were built.
19595 if (VD->getType()->isReferenceType())
19596 return true;
19597 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19598 if (RD->hasMutableFields())
19599 return true;
19600 if (!VD->isUsableInConstantExpressions(S.Context))
19601 return true;
19602 break;
19603
19604 case NOUR_Discarded:
19605 if (VD->getType()->isReferenceType())
19606 return true;
19607 break;
19608 }
19609 return false;
19610 };
19611
19612 // Mark that this expression does not constitute an odr-use.
19613 auto MarkNotOdrUsed = [&] {
19614 S.MaybeODRUseExprs.remove(E);
19615 if (LambdaScopeInfo *LSI = S.getCurLambda())
19616 LSI->markVariableExprAsNonODRUsed(E);
19617 };
19618
19619 // C++2a [basic.def.odr]p2:
19620 // The set of potential results of an expression e is defined as follows:
19621 switch (E->getStmtClass()) {
19622 // -- If e is an id-expression, ...
19623 case Expr::DeclRefExprClass: {
19624 auto *DRE = cast<DeclRefExpr>(E);
19625 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19626 break;
19627
19628 // Rebuild as a non-odr-use DeclRefExpr.
19629 MarkNotOdrUsed();
19630 return DeclRefExpr::Create(
19631 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19632 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19633 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19634 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19635 }
19636
19637 case Expr::FunctionParmPackExprClass: {
19638 auto *FPPE = cast<FunctionParmPackExpr>(E);
19639 // If any of the declarations in the pack is odr-used, then the expression
19640 // as a whole constitutes an odr-use.
19641 for (VarDecl *D : *FPPE)
19642 if (IsPotentialResultOdrUsed(D))
19643 return ExprEmpty();
19644
19645 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19646 // nothing cares about whether we marked this as an odr-use, but it might
19647 // be useful for non-compiler tools.
19648 MarkNotOdrUsed();
19649 break;
19650 }
19651
19652 // -- If e is a subscripting operation with an array operand...
19653 case Expr::ArraySubscriptExprClass: {
19654 auto *ASE = cast<ArraySubscriptExpr>(E);
19655 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19656 if (!OldBase->getType()->isArrayType())
19657 break;
19658 ExprResult Base = Rebuild(OldBase);
19659 if (!Base.isUsable())
19660 return Base;
19661 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19662 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19663 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19664 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19665 ASE->getRBracketLoc());
19666 }
19667
19668 case Expr::MemberExprClass: {
19669 auto *ME = cast<MemberExpr>(E);
19670 // -- If e is a class member access expression [...] naming a non-static
19671 // data member...
19672 if (isa<FieldDecl>(ME->getMemberDecl())) {
19673 ExprResult Base = Rebuild(ME->getBase());
19674 if (!Base.isUsable())
19675 return Base;
19676 return MemberExpr::Create(
19677 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19678 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19679 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19680 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19681 ME->getObjectKind(), ME->isNonOdrUse());
19682 }
19683
19684 if (ME->getMemberDecl()->isCXXInstanceMember())
19685 break;
19686
19687 // -- If e is a class member access expression naming a static data member,
19688 // ...
19689 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19690 break;
19691
19692 // Rebuild as a non-odr-use MemberExpr.
19693 MarkNotOdrUsed();
19694 return MemberExpr::Create(
19695 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19696 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19697 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19698 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19699 }
19700
19701 case Expr::BinaryOperatorClass: {
19702 auto *BO = cast<BinaryOperator>(E);
19703 Expr *LHS = BO->getLHS();
19704 Expr *RHS = BO->getRHS();
19705 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19706 if (BO->getOpcode() == BO_PtrMemD) {
19707 ExprResult Sub = Rebuild(LHS);
19708 if (!Sub.isUsable())
19709 return Sub;
19710 LHS = Sub.get();
19711 // -- If e is a comma expression, ...
19712 } else if (BO->getOpcode() == BO_Comma) {
19713 ExprResult Sub = Rebuild(RHS);
19714 if (!Sub.isUsable())
19715 return Sub;
19716 RHS = Sub.get();
19717 } else {
19718 break;
19719 }
19720 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19721 LHS, RHS);
19722 }
19723
19724 // -- If e has the form (e1)...
19725 case Expr::ParenExprClass: {
19726 auto *PE = cast<ParenExpr>(E);
19727 ExprResult Sub = Rebuild(PE->getSubExpr());
19728 if (!Sub.isUsable())
19729 return Sub;
19730 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19731 }
19732
19733 // -- If e is a glvalue conditional expression, ...
19734 // We don't apply this to a binary conditional operator. FIXME: Should we?
19735 case Expr::ConditionalOperatorClass: {
19736 auto *CO = cast<ConditionalOperator>(E);
19737 ExprResult LHS = Rebuild(CO->getLHS());
19738 if (LHS.isInvalid())
19739 return ExprError();
19740 ExprResult RHS = Rebuild(CO->getRHS());
19741 if (RHS.isInvalid())
19742 return ExprError();
19743 if (!LHS.isUsable() && !RHS.isUsable())
19744 return ExprEmpty();
19745 if (!LHS.isUsable())
19746 LHS = CO->getLHS();
19747 if (!RHS.isUsable())
19748 RHS = CO->getRHS();
19749 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19750 CO->getCond(), LHS.get(), RHS.get());
19751 }
19752
19753 // [Clang extension]
19754 // -- If e has the form __extension__ e1...
19755 case Expr::UnaryOperatorClass: {
19756 auto *UO = cast<UnaryOperator>(E);
19757 if (UO->getOpcode() != UO_Extension)
19758 break;
19759 ExprResult Sub = Rebuild(UO->getSubExpr());
19760 if (!Sub.isUsable())
19761 return Sub;
19762 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19763 Sub.get());
19764 }
19765
19766 // [Clang extension]
19767 // -- If e has the form _Generic(...), the set of potential results is the
19768 // union of the sets of potential results of the associated expressions.
19769 case Expr::GenericSelectionExprClass: {
19770 auto *GSE = cast<GenericSelectionExpr>(E);
19771
19772 SmallVector<Expr *, 4> AssocExprs;
19773 bool AnyChanged = false;
19774 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19775 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19776 if (AssocExpr.isInvalid())
19777 return ExprError();
19778 if (AssocExpr.isUsable()) {
19779 AssocExprs.push_back(AssocExpr.get());
19780 AnyChanged = true;
19781 } else {
19782 AssocExprs.push_back(OrigAssocExpr);
19783 }
19784 }
19785
19786 void *ExOrTy = nullptr;
19787 bool IsExpr = GSE->isExprPredicate();
19788 if (IsExpr)
19789 ExOrTy = GSE->getControllingExpr();
19790 else
19791 ExOrTy = GSE->getControllingType();
19792 return AnyChanged ? S.CreateGenericSelectionExpr(
19793 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19794 GSE->getRParenLoc(), IsExpr, ExOrTy,
19795 GSE->getAssocTypeSourceInfos(), AssocExprs)
19796 : ExprEmpty();
19797 }
19798
19799 // [Clang extension]
19800 // -- If e has the form __builtin_choose_expr(...), the set of potential
19801 // results is the union of the sets of potential results of the
19802 // second and third subexpressions.
19803 case Expr::ChooseExprClass: {
19804 auto *CE = cast<ChooseExpr>(E);
19805
19806 ExprResult LHS = Rebuild(CE->getLHS());
19807 if (LHS.isInvalid())
19808 return ExprError();
19809
19810 ExprResult RHS = Rebuild(CE->getLHS());
19811 if (RHS.isInvalid())
19812 return ExprError();
19813
19814 if (!LHS.get() && !RHS.get())
19815 return ExprEmpty();
19816 if (!LHS.isUsable())
19817 LHS = CE->getLHS();
19818 if (!RHS.isUsable())
19819 RHS = CE->getRHS();
19820
19821 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19822 RHS.get(), CE->getRParenLoc());
19823 }
19824
19825 // Step through non-syntactic nodes.
19826 case Expr::ConstantExprClass: {
19827 auto *CE = cast<ConstantExpr>(E);
19828 ExprResult Sub = Rebuild(CE->getSubExpr());
19829 if (!Sub.isUsable())
19830 return Sub;
19831 return ConstantExpr::Create(S.Context, Sub.get());
19832 }
19833
19834 // We could mostly rely on the recursive rebuilding to rebuild implicit
19835 // casts, but not at the top level, so rebuild them here.
19836 case Expr::ImplicitCastExprClass: {
19837 auto *ICE = cast<ImplicitCastExpr>(E);
19838 // Only step through the narrow set of cast kinds we expect to encounter.
19839 // Anything else suggests we've left the region in which potential results
19840 // can be found.
19841 switch (ICE->getCastKind()) {
19842 case CK_NoOp:
19843 case CK_DerivedToBase:
19844 case CK_UncheckedDerivedToBase: {
19845 ExprResult Sub = Rebuild(ICE->getSubExpr());
19846 if (!Sub.isUsable())
19847 return Sub;
19848 CXXCastPath Path(ICE->path());
19849 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19850 ICE->getValueKind(), &Path);
19851 }
19852
19853 default:
19854 break;
19855 }
19856 break;
19857 }
19858
19859 default:
19860 break;
19861 }
19862
19863 // Can't traverse through this node. Nothing to do.
19864 return ExprEmpty();
19865}
19866
19868 // Check whether the operand is or contains an object of non-trivial C union
19869 // type.
19870 if (E->getType().isVolatileQualified() &&
19876
19877 // C++2a [basic.def.odr]p4:
19878 // [...] an expression of non-volatile-qualified non-class type to which
19879 // the lvalue-to-rvalue conversion is applied [...]
19880 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19881 return E;
19882
19885 if (Result.isInvalid())
19886 return ExprError();
19887 return Result.get() ? Result : E;
19888}
19889
19891 Res = CorrectDelayedTyposInExpr(Res);
19892
19893 if (!Res.isUsable())
19894 return Res;
19895
19896 // If a constant-expression is a reference to a variable where we delay
19897 // deciding whether it is an odr-use, just assume we will apply the
19898 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19899 // (a non-type template argument), we have special handling anyway.
19901}
19902
19904 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19905 // call.
19906 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19907 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19908
19909 for (Expr *E : LocalMaybeODRUseExprs) {
19910 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19911 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19912 DRE->getLocation(), *this);
19913 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19914 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19915 *this);
19916 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19917 for (VarDecl *VD : *FP)
19918 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19919 } else {
19920 llvm_unreachable("Unexpected expression");
19921 }
19922 }
19923
19924 assert(MaybeODRUseExprs.empty() &&
19925 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19926}
19927
19929 ValueDecl *Var, Expr *E) {
19931 if (!VD)
19932 return;
19933
19934 const bool RefersToEnclosingScope =
19935 (SemaRef.CurContext != VD->getDeclContext() &&
19937 if (RefersToEnclosingScope) {
19938 LambdaScopeInfo *const LSI =
19939 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19940 if (LSI && (!LSI->CallOperator ||
19941 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19942 // If a variable could potentially be odr-used, defer marking it so
19943 // until we finish analyzing the full expression for any
19944 // lvalue-to-rvalue
19945 // or discarded value conversions that would obviate odr-use.
19946 // Add it to the list of potential captures that will be analyzed
19947 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19948 // unless the variable is a reference that was initialized by a constant
19949 // expression (this will never need to be captured or odr-used).
19950 //
19951 // FIXME: We can simplify this a lot after implementing P0588R1.
19952 assert(E && "Capture variable should be used in an expression.");
19953 if (!Var->getType()->isReferenceType() ||
19956 }
19957 }
19958}
19959
19961 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19962 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19963 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19964 isa<FunctionParmPackExpr>(E)) &&
19965 "Invalid Expr argument to DoMarkVarDeclReferenced");
19966 Var->setReferenced();
19967
19968 if (Var->isInvalidDecl())
19969 return;
19970
19971 auto *MSI = Var->getMemberSpecializationInfo();
19974
19975 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19976 bool UsableInConstantExpr =
19978
19979 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19980 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19981 }
19982
19983 // C++20 [expr.const]p12:
19984 // A variable [...] is needed for constant evaluation if it is [...] a
19985 // variable whose name appears as a potentially constant evaluated
19986 // expression that is either a contexpr variable or is of non-volatile
19987 // const-qualified integral type or of reference type
19988 bool NeededForConstantEvaluation =
19989 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19990
19991 bool NeedDefinition =
19992 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19993
19994 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19995 "Can't instantiate a partial template specialization.");
19996
19997 // If this might be a member specialization of a static data member, check
19998 // the specialization is visible. We already did the checks for variable
19999 // template specializations when we created them.
20000 if (NeedDefinition && TSK != TSK_Undeclared &&
20001 !isa<VarTemplateSpecializationDecl>(Var))
20003
20004 // Perform implicit instantiation of static data members, static data member
20005 // templates of class templates, and variable template specializations. Delay
20006 // instantiations of variable templates, except for those that could be used
20007 // in a constant expression.
20008 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20009 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20010 // instantiation declaration if a variable is usable in a constant
20011 // expression (among other cases).
20012 bool TryInstantiating =
20014 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20015
20016 if (TryInstantiating) {
20017 SourceLocation PointOfInstantiation =
20018 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20019 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20020 if (FirstInstantiation) {
20021 PointOfInstantiation = Loc;
20022 if (MSI)
20023 MSI->setPointOfInstantiation(PointOfInstantiation);
20024 // FIXME: Notify listener.
20025 else
20026 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20027 }
20028
20029 if (UsableInConstantExpr) {
20030 // Do not defer instantiations of variables that could be used in a
20031 // constant expression.
20032 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20033 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20034 });
20035
20036 // Re-set the member to trigger a recomputation of the dependence bits
20037 // for the expression.
20038 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20039 DRE->setDecl(DRE->getDecl());
20040 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20041 ME->setMemberDecl(ME->getMemberDecl());
20042 } else if (FirstInstantiation) {
20044 .push_back(std::make_pair(Var, PointOfInstantiation));
20045 } else {
20046 bool Inserted = false;
20047 for (auto &I : SemaRef.SavedPendingInstantiations) {
20048 auto Iter = llvm::find_if(
20049 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20050 return P.first == Var;
20051 });
20052 if (Iter != I.end()) {
20054 I.erase(Iter);
20055 Inserted = true;
20056 break;
20057 }
20058 }
20059
20060 // FIXME: For a specialization of a variable template, we don't
20061 // distinguish between "declaration and type implicitly instantiated"
20062 // and "implicit instantiation of definition requested", so we have
20063 // no direct way to avoid enqueueing the pending instantiation
20064 // multiple times.
20065 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20067 .push_back(std::make_pair(Var, PointOfInstantiation));
20068 }
20069 }
20070 }
20071
20072 // C++2a [basic.def.odr]p4:
20073 // A variable x whose name appears as a potentially-evaluated expression e
20074 // is odr-used by e unless
20075 // -- x is a reference that is usable in constant expressions
20076 // -- x is a variable of non-reference type that is usable in constant
20077 // expressions and has no mutable subobjects [FIXME], and e is an
20078 // element of the set of potential results of an expression of
20079 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20080 // conversion is applied
20081 // -- x is a variable of non-reference type, and e is an element of the set
20082 // of potential results of a discarded-value expression to which the
20083 // lvalue-to-rvalue conversion is not applied [FIXME]
20084 //
20085 // We check the first part of the second bullet here, and
20086 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20087 // FIXME: To get the third bullet right, we need to delay this even for
20088 // variables that are not usable in constant expressions.
20089
20090 // If we already know this isn't an odr-use, there's nothing more to do.
20091 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20092 if (DRE->isNonOdrUse())
20093 return;
20094 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20095 if (ME->isNonOdrUse())
20096 return;
20097
20098 switch (OdrUse) {
20099 case OdrUseContext::None:
20100 // In some cases, a variable may not have been marked unevaluated, if it
20101 // appears in a defaukt initializer.
20102 assert((!E || isa<FunctionParmPackExpr>(E) ||
20104 "missing non-odr-use marking for unevaluated decl ref");
20105 break;
20106
20107 case OdrUseContext::FormallyOdrUsed:
20108 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20109 // behavior.
20110 break;
20111
20112 case OdrUseContext::Used:
20113 // If we might later find that this expression isn't actually an odr-use,
20114 // delay the marking.
20116 SemaRef.MaybeODRUseExprs.insert(E);
20117 else
20118 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20119 break;
20120
20121 case OdrUseContext::Dependent:
20122 // If this is a dependent context, we don't need to mark variables as
20123 // odr-used, but we may still need to track them for lambda capture.
20124 // FIXME: Do we also need to do this inside dependent typeid expressions
20125 // (which are modeled as unevaluated at this point)?
20126 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20127 break;
20128 }
20129}
20130
20132 BindingDecl *BD, Expr *E) {
20133 BD->setReferenced();
20134
20135 if (BD->isInvalidDecl())
20136 return;
20137
20138 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20139 if (OdrUse == OdrUseContext::Used) {
20140 QualType CaptureType, DeclRefType;
20142 /*EllipsisLoc*/ SourceLocation(),
20143 /*BuildAndDiagnose*/ true, CaptureType,
20144 DeclRefType,
20145 /*FunctionScopeIndexToStopAt*/ nullptr);
20146 } else if (OdrUse == OdrUseContext::Dependent) {
20147 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20148 }
20149}
20150
20151/// Mark a variable referenced, and check whether it is odr-used
20152/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20153/// used directly for normal expressions referring to VarDecl.
20155 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20156}
20157
20158// C++ [temp.dep.expr]p3:
20159// An id-expression is type-dependent if it contains:
20160// - an identifier associated by name lookup with an entity captured by copy
20161// in a lambda-expression that has an explicit object parameter whose type
20162// is dependent ([dcl.fct]),
20164 Sema &SemaRef, ValueDecl *D, Expr *E) {
20165 auto *ID = dyn_cast<DeclRefExpr>(E);
20166 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20167 return;
20168
20169 // If any enclosing lambda with a dependent explicit object parameter either
20170 // explicitly captures the variable by value, or has a capture default of '='
20171 // and does not capture the variable by reference, then the type of the DRE
20172 // is dependent on the type of that lambda's explicit object parameter.
20173 auto IsDependent = [&]() {
20174 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20175 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20176 if (!LSI)
20177 continue;
20178
20179 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20180 LSI->AfterParameterList)
20181 return false;
20182
20183 const auto *MD = LSI->CallOperator;
20184 if (MD->getType().isNull())
20185 continue;
20186
20187 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20188 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20189 !Ty->getParamType(0)->isDependentType())
20190 continue;
20191
20192 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20193 if (C->isCopyCapture())
20194 return true;
20195 continue;
20196 }
20197
20198 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20199 return true;
20200 }
20201 return false;
20202 }();
20203
20204 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20205 IsDependent, SemaRef.getASTContext());
20206}
20207
20208static void
20210 bool MightBeOdrUse,
20211 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20214
20215 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20217 if (SemaRef.getLangOpts().CPlusPlus)
20219 Var, E);
20220 return;
20221 }
20222
20223 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20225 if (SemaRef.getLangOpts().CPlusPlus)
20227 Decl, E);
20228 return;
20229 }
20230 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20231
20232 // If this is a call to a method via a cast, also mark the method in the
20233 // derived class used in case codegen can devirtualize the call.
20234 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20235 if (!ME)
20236 return;
20237 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20238 if (!MD)
20239 return;
20240 // Only attempt to devirtualize if this is truly a virtual call.
20241 bool IsVirtualCall = MD->isVirtual() &&
20243 if (!IsVirtualCall)
20244 return;
20245
20246 // If it's possible to devirtualize the call, mark the called function
20247 // referenced.
20249 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20250 if (DM)
20251 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20252}
20253
20254/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20255///
20256/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20257/// handled with care if the DeclRefExpr is not newly-created.
20259 // TODO: update this with DR# once a defect report is filed.
20260 // C++11 defect. The address of a pure member should not be an ODR use, even
20261 // if it's a qualified reference.
20262 bool OdrUse = true;
20263 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20264 if (Method->isVirtual() &&
20265 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20266 OdrUse = false;
20267
20268 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20272 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20273 !FD->isDependentContext())
20274 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20275 }
20276 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20278}
20279
20280/// Perform reference-marking and odr-use handling for a MemberExpr.
20282 // C++11 [basic.def.odr]p2:
20283 // A non-overloaded function whose name appears as a potentially-evaluated
20284 // expression or a member of a set of candidate functions, if selected by
20285 // overload resolution when referred to from a potentially-evaluated
20286 // expression, is odr-used, unless it is a pure virtual function and its
20287 // name is not explicitly qualified.
20288 bool MightBeOdrUse = true;
20290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20291 if (Method->isPureVirtual())
20292 MightBeOdrUse = false;
20293 }
20294 SourceLocation Loc =
20295 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20296 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20298}
20299
20300/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20302 for (VarDecl *VD : *E)
20303 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20305}
20306
20307/// Perform marking for a reference to an arbitrary declaration. It
20308/// marks the declaration referenced, and performs odr-use checking for
20309/// functions and variables. This method should not be used when building a
20310/// normal expression which refers to a variable.
20312 bool MightBeOdrUse) {
20313 if (MightBeOdrUse) {
20314 if (auto *VD = dyn_cast<VarDecl>(D)) {
20315 MarkVariableReferenced(Loc, VD);
20316 return;
20317 }
20318 }
20319 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20320 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20321 return;
20322 }
20323 D->setReferenced();
20324}
20325
20326namespace {
20327 // Mark all of the declarations used by a type as referenced.
20328 // FIXME: Not fully implemented yet! We need to have a better understanding
20329 // of when we're entering a context we should not recurse into.
20330 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20331 // TreeTransforms rebuilding the type in a new context. Rather than
20332 // duplicating the TreeTransform logic, we should consider reusing it here.
20333 // Currently that causes problems when rebuilding LambdaExprs.
20334 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20335 Sema &S;
20336 SourceLocation Loc;
20337
20338 public:
20340
20341 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20342
20343 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20344 };
20345}
20346
20347bool MarkReferencedDecls::TraverseTemplateArgument(
20348 const TemplateArgument &Arg) {
20349 {
20350 // A non-type template argument is a constant-evaluated context.
20354 if (Decl *D = Arg.getAsDecl())
20355 S.MarkAnyDeclReferenced(Loc, D, true);
20356 } else if (Arg.getKind() == TemplateArgument::Expression) {
20358 }
20359 }
20360
20361 return Inherited::TraverseTemplateArgument(Arg);
20362}
20363
20365 MarkReferencedDecls Marker(*this, Loc);
20366 Marker.TraverseType(T);
20367}
20368
20369namespace {
20370/// Helper class that marks all of the declarations referenced by
20371/// potentially-evaluated subexpressions as "referenced".
20372class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20373public:
20374 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20375 bool SkipLocalVariables;
20377
20378 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20380 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20381
20382 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20383 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20384 }
20385
20386 void Visit(Expr *E) {
20387 if (llvm::is_contained(StopAt, E))
20388 return;
20389 Inherited::Visit(E);
20390 }
20391
20392 void VisitConstantExpr(ConstantExpr *E) {
20393 // Don't mark declarations within a ConstantExpression, as this expression
20394 // will be evaluated and folded to a value.
20395 }
20396
20397 void VisitDeclRefExpr(DeclRefExpr *E) {
20398 // If we were asked not to visit local variables, don't.
20399 if (SkipLocalVariables) {
20400 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20401 if (VD->hasLocalStorage())
20402 return;
20403 }
20404
20405 // FIXME: This can trigger the instantiation of the initializer of a
20406 // variable, which can cause the expression to become value-dependent
20407 // or error-dependent. Do we need to propagate the new dependence bits?
20409 }
20410
20411 void VisitMemberExpr(MemberExpr *E) {
20413 Visit(E->getBase());
20414 }
20415};
20416} // namespace
20417
20418/// Mark any declarations that appear within this expression or any
20419/// potentially-evaluated subexpressions as "referenced".
20420///
20421/// \param SkipLocalVariables If true, don't mark local variables as
20422/// 'referenced'.
20423/// \param StopAt Subexpressions that we shouldn't recurse into.
20425 bool SkipLocalVariables,
20426 ArrayRef<const Expr*> StopAt) {
20427 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20428}
20429
20430/// Emit a diagnostic when statements are reachable.
20431/// FIXME: check for reachability even in expressions for which we don't build a
20432/// CFG (eg, in the initializer of a global or in a constant expression).
20433/// For example,
20434/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20436 const PartialDiagnostic &PD) {
20437 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20438 if (!FunctionScopes.empty())
20439 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20440 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20441 return true;
20442 }
20443
20444 // The initializer of a constexpr variable or of the first declaration of a
20445 // static data member is not syntactically a constant evaluated constant,
20446 // but nonetheless is always required to be a constant expression, so we
20447 // can skip diagnosing.
20448 // FIXME: Using the mangling context here is a hack.
20449 if (auto *VD = dyn_cast_or_null<VarDecl>(
20450 ExprEvalContexts.back().ManglingContextDecl)) {
20451 if (VD->isConstexpr() ||
20452 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20453 return false;
20454 // FIXME: For any other kind of variable, we should build a CFG for its
20455 // initializer and check whether the context in question is reachable.
20456 }
20457
20458 Diag(Loc, PD);
20459 return true;
20460}
20461
20462/// Emit a diagnostic that describes an effect on the run-time behavior
20463/// of the program being compiled.
20464///
20465/// This routine emits the given diagnostic when the code currently being
20466/// type-checked is "potentially evaluated", meaning that there is a
20467/// possibility that the code will actually be executable. Code in sizeof()
20468/// expressions, code used only during overload resolution, etc., are not
20469/// potentially evaluated. This routine will suppress such diagnostics or,
20470/// in the absolutely nutty case of potentially potentially evaluated
20471/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20472/// later.
20473///
20474/// This routine should be used for all diagnostics that describe the run-time
20475/// behavior of a program, such as passing a non-POD value through an ellipsis.
20476/// Failure to do so will likely result in spurious diagnostics or failures
20477/// during overload resolution or within sizeof/alignof/typeof/typeid.
20479 const PartialDiagnostic &PD) {
20480
20481 if (ExprEvalContexts.back().isDiscardedStatementContext())
20482 return false;
20483
20484 switch (ExprEvalContexts.back().Context) {
20489 // The argument will never be evaluated, so don't complain.
20490 break;
20491
20494 // Relevant diagnostics should be produced by constant evaluation.
20495 break;
20496
20499 return DiagIfReachable(Loc, Stmts, PD);
20500 }
20501
20502 return false;
20503}
20504
20506 const PartialDiagnostic &PD) {
20507 return DiagRuntimeBehavior(
20508 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20509}
20510
20512 CallExpr *CE, FunctionDecl *FD) {
20513 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20514 return false;
20515
20516 // If we're inside a decltype's expression, don't check for a valid return
20517 // type or construct temporaries until we know whether this is the last call.
20518 if (ExprEvalContexts.back().ExprContext ==
20520 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20521 return false;
20522 }
20523
20524 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20525 FunctionDecl *FD;
20526 CallExpr *CE;
20527
20528 public:
20529 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20530 : FD(FD), CE(CE) { }
20531
20532 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20533 if (!FD) {
20534 S.Diag(Loc, diag::err_call_incomplete_return)
20535 << T << CE->getSourceRange();
20536 return;
20537 }
20538
20539 S.Diag(Loc, diag::err_call_function_incomplete_return)
20540 << CE->getSourceRange() << FD << T;
20541 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20542 << FD->getDeclName();
20543 }
20544 } Diagnoser(FD, CE);
20545
20546 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20547 return true;
20548
20549 return false;
20550}
20551
20552// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20553// will prevent this condition from triggering, which is what we want.
20555 SourceLocation Loc;
20556
20557 unsigned diagnostic = diag::warn_condition_is_assignment;
20558 bool IsOrAssign = false;
20559
20560 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20561 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20562 return;
20563
20564 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20565
20566 // Greylist some idioms by putting them into a warning subcategory.
20567 if (ObjCMessageExpr *ME
20568 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20569 Selector Sel = ME->getSelector();
20570
20571 // self = [<foo> init...]
20572 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20573 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20574
20575 // <foo> = [<bar> nextObject]
20576 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20577 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20578 }
20579
20580 Loc = Op->getOperatorLoc();
20581 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20582 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20583 return;
20584
20585 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20586 Loc = Op->getOperatorLoc();
20587 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20588 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20589 else {
20590 // Not an assignment.
20591 return;
20592 }
20593
20594 Diag(Loc, diagnostic) << E->getSourceRange();
20595
20598 Diag(Loc, diag::note_condition_assign_silence)
20600 << FixItHint::CreateInsertion(Close, ")");
20601
20602 if (IsOrAssign)
20603 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20604 << FixItHint::CreateReplacement(Loc, "!=");
20605 else
20606 Diag(Loc, diag::note_condition_assign_to_comparison)
20607 << FixItHint::CreateReplacement(Loc, "==");
20608}
20609
20610/// Redundant parentheses over an equality comparison can indicate
20611/// that the user intended an assignment used as condition.
20613 // Don't warn if the parens came from a macro.
20614 SourceLocation parenLoc = ParenE->getBeginLoc();
20615 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20616 return;
20617 // Don't warn for dependent expressions.
20618 if (ParenE->isTypeDependent())
20619 return;
20620
20621 Expr *E = ParenE->IgnoreParens();
20622
20623 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20624 if (opE->getOpcode() == BO_EQ &&
20625 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20626 == Expr::MLV_Valid) {
20627 SourceLocation Loc = opE->getOperatorLoc();
20628
20629 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20630 SourceRange ParenERange = ParenE->getSourceRange();
20631 Diag(Loc, diag::note_equality_comparison_silence)
20632 << FixItHint::CreateRemoval(ParenERange.getBegin())
20633 << FixItHint::CreateRemoval(ParenERange.getEnd());
20634 Diag(Loc, diag::note_equality_comparison_to_assign)
20635 << FixItHint::CreateReplacement(Loc, "=");
20636 }
20637}
20638
20640 bool IsConstexpr) {
20642 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20644
20645 ExprResult result = CheckPlaceholderExpr(E);
20646 if (result.isInvalid()) return ExprError();
20647 E = result.get();
20648
20649 if (!E->isTypeDependent()) {
20650 if (getLangOpts().CPlusPlus)
20651 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20652
20654 if (ERes.isInvalid())
20655 return ExprError();
20656 E = ERes.get();
20657
20658 QualType T = E->getType();
20659 if (!T->isScalarType()) { // C99 6.8.4.1p1
20660 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20661 << T << E->getSourceRange();
20662 return ExprError();
20663 }
20664 CheckBoolLikeConversion(E, Loc);
20665 }
20666
20667 return E;
20668}
20669
20671 Expr *SubExpr, ConditionKind CK,
20672 bool MissingOK) {
20673 // MissingOK indicates whether having no condition expression is valid
20674 // (for loop) or invalid (e.g. while loop).
20675 if (!SubExpr)
20676 return MissingOK ? ConditionResult() : ConditionError();
20677
20678 ExprResult Cond;
20679 switch (CK) {
20681 Cond = CheckBooleanCondition(Loc, SubExpr);
20682 break;
20683
20685 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20686 break;
20687
20689 Cond = CheckSwitchCondition(Loc, SubExpr);
20690 break;
20691 }
20692 if (Cond.isInvalid()) {
20693 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20694 {SubExpr}, PreferredConditionType(CK));
20695 if (!Cond.get())
20696 return ConditionError();
20697 }
20698 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20699 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20700 if (!FullExpr.get())
20701 return ConditionError();
20702
20703 return ConditionResult(*this, nullptr, FullExpr,
20705}
20706
20707namespace {
20708 /// A visitor for rebuilding a call to an __unknown_any expression
20709 /// to have an appropriate type.
20710 struct RebuildUnknownAnyFunction
20711 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20712
20713 Sema &S;
20714
20715 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20716
20717 ExprResult VisitStmt(Stmt *S) {
20718 llvm_unreachable("unexpected statement!");
20719 }
20720
20721 ExprResult VisitExpr(Expr *E) {
20722 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20723 << E->getSourceRange();
20724 return ExprError();
20725 }
20726
20727 /// Rebuild an expression which simply semantically wraps another
20728 /// expression which it shares the type and value kind of.
20729 template <class T> ExprResult rebuildSugarExpr(T *E) {
20730 ExprResult SubResult = Visit(E->getSubExpr());
20731 if (SubResult.isInvalid()) return ExprError();
20732
20733 Expr *SubExpr = SubResult.get();
20734 E->setSubExpr(SubExpr);
20735 E->setType(SubExpr->getType());
20736 E->setValueKind(SubExpr->getValueKind());
20737 assert(E->getObjectKind() == OK_Ordinary);
20738 return E;
20739 }
20740
20741 ExprResult VisitParenExpr(ParenExpr *E) {
20742 return rebuildSugarExpr(E);
20743 }
20744
20745 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20746 return rebuildSugarExpr(E);
20747 }
20748
20749 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20750 ExprResult SubResult = Visit(E->getSubExpr());
20751 if (SubResult.isInvalid()) return ExprError();
20752
20753 Expr *SubExpr = SubResult.get();
20754 E->setSubExpr(SubExpr);
20755 E->setType(S.Context.getPointerType(SubExpr->getType()));
20756 assert(E->isPRValue());
20757 assert(E->getObjectKind() == OK_Ordinary);
20758 return E;
20759 }
20760
20761 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20762 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20763
20764 E->setType(VD->getType());
20765
20766 assert(E->isPRValue());
20767 if (S.getLangOpts().CPlusPlus &&
20768 !(isa<CXXMethodDecl>(VD) &&
20769 cast<CXXMethodDecl>(VD)->isInstance()))
20771
20772 return E;
20773 }
20774
20775 ExprResult VisitMemberExpr(MemberExpr *E) {
20776 return resolveDecl(E, E->getMemberDecl());
20777 }
20778
20779 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20780 return resolveDecl(E, E->getDecl());
20781 }
20782 };
20783}
20784
20785/// Given a function expression of unknown-any type, try to rebuild it
20786/// to have a function type.
20788 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20789 if (Result.isInvalid()) return ExprError();
20790 return S.DefaultFunctionArrayConversion(Result.get());
20791}
20792
20793namespace {
20794 /// A visitor for rebuilding an expression of type __unknown_anytype
20795 /// into one which resolves the type directly on the referring
20796 /// expression. Strict preservation of the original source
20797 /// structure is not a goal.
20798 struct RebuildUnknownAnyExpr
20799 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20800
20801 Sema &S;
20802
20803 /// The current destination type.
20804 QualType DestType;
20805
20806 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20807 : S(S), DestType(CastType) {}
20808
20809 ExprResult VisitStmt(Stmt *S) {
20810 llvm_unreachable("unexpected statement!");
20811 }
20812
20813 ExprResult VisitExpr(Expr *E) {
20814 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20815 << E->getSourceRange();
20816 return ExprError();
20817 }
20818
20819 ExprResult VisitCallExpr(CallExpr *E);
20820 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20821
20822 /// Rebuild an expression which simply semantically wraps another
20823 /// expression which it shares the type and value kind of.
20824 template <class T> ExprResult rebuildSugarExpr(T *E) {
20825 ExprResult SubResult = Visit(E->getSubExpr());
20826 if (SubResult.isInvalid()) return ExprError();
20827 Expr *SubExpr = SubResult.get();
20828 E->setSubExpr(SubExpr);
20829 E->setType(SubExpr->getType());
20830 E->setValueKind(SubExpr->getValueKind());
20831 assert(E->getObjectKind() == OK_Ordinary);
20832 return E;
20833 }
20834
20835 ExprResult VisitParenExpr(ParenExpr *E) {
20836 return rebuildSugarExpr(E);
20837 }
20838
20839 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20840 return rebuildSugarExpr(E);
20841 }
20842
20843 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20844 const PointerType *Ptr = DestType->getAs<PointerType>();
20845 if (!Ptr) {
20846 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20847 << E->getSourceRange();
20848 return ExprError();
20849 }
20850
20851 if (isa<CallExpr>(E->getSubExpr())) {
20852 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20853 << E->getSourceRange();
20854 return ExprError();
20855 }
20856
20857 assert(E->isPRValue());
20858 assert(E->getObjectKind() == OK_Ordinary);
20859 E->setType(DestType);
20860
20861 // Build the sub-expression as if it were an object of the pointee type.
20862 DestType = Ptr->getPointeeType();
20863 ExprResult SubResult = Visit(E->getSubExpr());
20864 if (SubResult.isInvalid()) return ExprError();
20865 E->setSubExpr(SubResult.get());
20866 return E;
20867 }
20868
20869 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20870
20871 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20872
20873 ExprResult VisitMemberExpr(MemberExpr *E) {
20874 return resolveDecl(E, E->getMemberDecl());
20875 }
20876
20877 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20878 return resolveDecl(E, E->getDecl());
20879 }
20880 };
20881}
20882
20883/// Rebuilds a call expression which yielded __unknown_anytype.
20884ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20885 Expr *CalleeExpr = E->getCallee();
20886
20887 enum FnKind {
20888 FK_MemberFunction,
20889 FK_FunctionPointer,
20890 FK_BlockPointer
20891 };
20892
20893 FnKind Kind;
20894 QualType CalleeType = CalleeExpr->getType();
20895 if (CalleeType == S.Context.BoundMemberTy) {
20896 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20897 Kind = FK_MemberFunction;
20898 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20899 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20900 CalleeType = Ptr->getPointeeType();
20901 Kind = FK_FunctionPointer;
20902 } else {
20903 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20904 Kind = FK_BlockPointer;
20905 }
20906 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20907
20908 // Verify that this is a legal result type of a function.
20909 if (DestType->isArrayType() || DestType->isFunctionType()) {
20910 unsigned diagID = diag::err_func_returning_array_function;
20911 if (Kind == FK_BlockPointer)
20912 diagID = diag::err_block_returning_array_function;
20913
20914 S.Diag(E->getExprLoc(), diagID)
20915 << DestType->isFunctionType() << DestType;
20916 return ExprError();
20917 }
20918
20919 // Otherwise, go ahead and set DestType as the call's result.
20920 E->setType(DestType.getNonLValueExprType(S.Context));
20922 assert(E->getObjectKind() == OK_Ordinary);
20923
20924 // Rebuild the function type, replacing the result type with DestType.
20925 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20926 if (Proto) {
20927 // __unknown_anytype(...) is a special case used by the debugger when
20928 // it has no idea what a function's signature is.
20929 //
20930 // We want to build this call essentially under the K&R
20931 // unprototyped rules, but making a FunctionNoProtoType in C++
20932 // would foul up all sorts of assumptions. However, we cannot
20933 // simply pass all arguments as variadic arguments, nor can we
20934 // portably just call the function under a non-variadic type; see
20935 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20936 // However, it turns out that in practice it is generally safe to
20937 // call a function declared as "A foo(B,C,D);" under the prototype
20938 // "A foo(B,C,D,...);". The only known exception is with the
20939 // Windows ABI, where any variadic function is implicitly cdecl
20940 // regardless of its normal CC. Therefore we change the parameter
20941 // types to match the types of the arguments.
20942 //
20943 // This is a hack, but it is far superior to moving the
20944 // corresponding target-specific code from IR-gen to Sema/AST.
20945
20946 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20947 SmallVector<QualType, 8> ArgTypes;
20948 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20949 ArgTypes.reserve(E->getNumArgs());
20950 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20951 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20952 }
20953 ParamTypes = ArgTypes;
20954 }
20955 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20956 Proto->getExtProtoInfo());
20957 } else {
20958 DestType = S.Context.getFunctionNoProtoType(DestType,
20959 FnType->getExtInfo());
20960 }
20961
20962 // Rebuild the appropriate pointer-to-function type.
20963 switch (Kind) {
20964 case FK_MemberFunction:
20965 // Nothing to do.
20966 break;
20967
20968 case FK_FunctionPointer:
20969 DestType = S.Context.getPointerType(DestType);
20970 break;
20971
20972 case FK_BlockPointer:
20973 DestType = S.Context.getBlockPointerType(DestType);
20974 break;
20975 }
20976
20977 // Finally, we can recurse.
20978 ExprResult CalleeResult = Visit(CalleeExpr);
20979 if (!CalleeResult.isUsable()) return ExprError();
20980 E->setCallee(CalleeResult.get());
20981
20982 // Bind a temporary if necessary.
20983 return S.MaybeBindToTemporary(E);
20984}
20985
20986ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20987 // Verify that this is a legal result type of a call.
20988 if (DestType->isArrayType() || DestType->isFunctionType()) {
20989 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20990 << DestType->isFunctionType() << DestType;
20991 return ExprError();
20992 }
20993
20994 // Rewrite the method result type if available.
20995 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20996 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20997 Method->setReturnType(DestType);
20998 }
20999
21000 // Change the type of the message.
21001 E->setType(DestType.getNonReferenceType());
21003
21004 return S.MaybeBindToTemporary(E);
21005}
21006
21007ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21008 // The only case we should ever see here is a function-to-pointer decay.
21009 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21010 assert(E->isPRValue());
21011 assert(E->getObjectKind() == OK_Ordinary);
21012
21013 E->setType(DestType);
21014
21015 // Rebuild the sub-expression as the pointee (function) type.
21016 DestType = DestType->castAs<PointerType>()->getPointeeType();
21017
21018 ExprResult Result = Visit(E->getSubExpr());
21019 if (!Result.isUsable()) return ExprError();
21020
21021 E->setSubExpr(Result.get());
21022 return E;
21023 } else if (E->getCastKind() == CK_LValueToRValue) {
21024 assert(E->isPRValue());
21025 assert(E->getObjectKind() == OK_Ordinary);
21026
21027 assert(isa<BlockPointerType>(E->getType()));
21028
21029 E->setType(DestType);
21030
21031 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21032 DestType = S.Context.getLValueReferenceType(DestType);
21033
21034 ExprResult Result = Visit(E->getSubExpr());
21035 if (!Result.isUsable()) return ExprError();
21036
21037 E->setSubExpr(Result.get());
21038 return E;
21039 } else {
21040 llvm_unreachable("Unhandled cast type!");
21041 }
21042}
21043
21044ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21045 ExprValueKind ValueKind = VK_LValue;
21046 QualType Type = DestType;
21047
21048 // We know how to make this work for certain kinds of decls:
21049
21050 // - functions
21051 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21052 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21053 DestType = Ptr->getPointeeType();
21054 ExprResult Result = resolveDecl(E, VD);
21055 if (Result.isInvalid()) return ExprError();
21056 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21057 VK_PRValue);
21058 }
21059
21060 if (!Type->isFunctionType()) {
21061 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21062 << VD << E->getSourceRange();
21063 return ExprError();
21064 }
21065 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21066 // We must match the FunctionDecl's type to the hack introduced in
21067 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21068 // type. See the lengthy commentary in that routine.
21069 QualType FDT = FD->getType();
21070 const FunctionType *FnType = FDT->castAs<FunctionType>();
21071 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21072 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21073 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21074 SourceLocation Loc = FD->getLocation();
21076 S.Context, FD->getDeclContext(), Loc, Loc,
21077 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21079 false /*isInlineSpecified*/, FD->hasPrototype(),
21080 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21081
21082 if (FD->getQualifier())
21083 NewFD->setQualifierInfo(FD->getQualifierLoc());
21084
21086 for (const auto &AI : FT->param_types()) {
21087 ParmVarDecl *Param =
21088 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21089 Param->setScopeInfo(0, Params.size());
21090 Params.push_back(Param);
21091 }
21092 NewFD->setParams(Params);
21093 DRE->setDecl(NewFD);
21094 VD = DRE->getDecl();
21095 }
21096 }
21097
21098 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21099 if (MD->isInstance()) {
21100 ValueKind = VK_PRValue;
21102 }
21103
21104 // Function references aren't l-values in C.
21105 if (!S.getLangOpts().CPlusPlus)
21106 ValueKind = VK_PRValue;
21107
21108 // - variables
21109 } else if (isa<VarDecl>(VD)) {
21110 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21111 Type = RefTy->getPointeeType();
21112 } else if (Type->isFunctionType()) {
21113 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21114 << VD << E->getSourceRange();
21115 return ExprError();
21116 }
21117
21118 // - nothing else
21119 } else {
21120 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21121 << VD << E->getSourceRange();
21122 return ExprError();
21123 }
21124
21125 // Modifying the declaration like this is friendly to IR-gen but
21126 // also really dangerous.
21127 VD->setType(DestType);
21128 E->setType(Type);
21129 E->setValueKind(ValueKind);
21130 return E;
21131}
21132
21133/// Check a cast of an unknown-any type. We intentionally only
21134/// trigger this for C-style casts.
21137 ExprValueKind &VK, CXXCastPath &Path) {
21138 // The type we're casting to must be either void or complete.
21139 if (!CastType->isVoidType() &&
21141 diag::err_typecheck_cast_to_incomplete))
21142 return ExprError();
21143
21144 // Rewrite the casted expression from scratch.
21145 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21146 if (!result.isUsable()) return ExprError();
21147
21148 CastExpr = result.get();
21149 VK = CastExpr->getValueKind();
21150 CastKind = CK_NoOp;
21151
21152 return CastExpr;
21153}
21154
21156 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21157}
21158
21160 Expr *arg, QualType &paramType) {
21161 // If the syntactic form of the argument is not an explicit cast of
21162 // any sort, just do default argument promotion.
21163 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21164 if (!castArg) {
21166 if (result.isInvalid()) return ExprError();
21167 paramType = result.get()->getType();
21168 return result;
21169 }
21170
21171 // Otherwise, use the type that was written in the explicit cast.
21172 assert(!arg->hasPlaceholderType());
21173 paramType = castArg->getTypeAsWritten();
21174
21175 // Copy-initialize a parameter of that type.
21176 InitializedEntity entity =
21178 /*consumed*/ false);
21179 return PerformCopyInitialization(entity, callLoc, arg);
21180}
21181
21183 Expr *orig = E;
21184 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21185 while (true) {
21186 E = E->IgnoreParenImpCasts();
21187 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21188 E = call->getCallee();
21189 diagID = diag::err_uncasted_call_of_unknown_any;
21190 } else {
21191 break;
21192 }
21193 }
21194
21195 SourceLocation loc;
21196 NamedDecl *d;
21197 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21198 loc = ref->getLocation();
21199 d = ref->getDecl();
21200 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21201 loc = mem->getMemberLoc();
21202 d = mem->getMemberDecl();
21203 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21204 diagID = diag::err_uncasted_call_of_unknown_any;
21205 loc = msg->getSelectorStartLoc();
21206 d = msg->getMethodDecl();
21207 if (!d) {
21208 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21209 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21210 << orig->getSourceRange();
21211 return ExprError();
21212 }
21213 } else {
21214 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21215 << E->getSourceRange();
21216 return ExprError();
21217 }
21218
21219 S.Diag(loc, diagID) << d << orig->getSourceRange();
21220
21221 // Never recoverable.
21222 return ExprError();
21223}
21224
21225/// Check for operands with placeholder types and complain if found.
21226/// Returns ExprError() if there was an error and no recovery was possible.
21229 // C cannot handle TypoExpr nodes on either side of a binop because it
21230 // doesn't handle dependent types properly, so make sure any TypoExprs have
21231 // been dealt with before checking the operands.
21233 if (!Result.isUsable()) return ExprError();
21234 E = Result.get();
21235 }
21236
21237 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21238 if (!placeholderType) return E;
21239
21240 switch (placeholderType->getKind()) {
21241
21242 // Overloaded expressions.
21243 case BuiltinType::Overload: {
21244 // Try to resolve a single function template specialization.
21245 // This is obligatory.
21246 ExprResult Result = E;
21248 return Result;
21249
21250 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21251 // leaves Result unchanged on failure.
21252 Result = E;
21254 return Result;
21255
21256 // If that failed, try to recover with a call.
21257 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21258 /*complain*/ true);
21259 return Result;
21260 }
21261
21262 // Bound member functions.
21263 case BuiltinType::BoundMember: {
21264 ExprResult result = E;
21265 const Expr *BME = E->IgnoreParens();
21266 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21267 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21268 if (isa<CXXPseudoDestructorExpr>(BME)) {
21269 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21270 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21271 if (ME->getMemberNameInfo().getName().getNameKind() ==
21273 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21274 }
21275 tryToRecoverWithCall(result, PD,
21276 /*complain*/ true);
21277 return result;
21278 }
21279
21280 // ARC unbridged casts.
21281 case BuiltinType::ARCUnbridgedCast: {
21282 Expr *realCast = stripARCUnbridgedCast(E);
21283 diagnoseARCUnbridgedCast(realCast);
21284 return realCast;
21285 }
21286
21287 // Expressions of unknown type.
21288 case BuiltinType::UnknownAny:
21289 return diagnoseUnknownAnyExpr(*this, E);
21290
21291 // Pseudo-objects.
21292 case BuiltinType::PseudoObject:
21293 return checkPseudoObjectRValue(E);
21294
21295 case BuiltinType::BuiltinFn: {
21296 // Accept __noop without parens by implicitly converting it to a call expr.
21297 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21298 if (DRE) {
21299 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21300 unsigned BuiltinID = FD->getBuiltinID();
21301 if (BuiltinID == Builtin::BI__noop) {
21302 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21303 CK_BuiltinFnToFnPtr)
21304 .get();
21305 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21308 }
21309
21310 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21311 // Any use of these other than a direct call is ill-formed as of C++20,
21312 // because they are not addressable functions. In earlier language
21313 // modes, warn and force an instantiation of the real body.
21314 Diag(E->getBeginLoc(),
21316 ? diag::err_use_of_unaddressable_function
21317 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21318 if (FD->isImplicitlyInstantiable()) {
21319 // Require a definition here because a normal attempt at
21320 // instantiation for a builtin will be ignored, and we won't try
21321 // again later. We assume that the definition of the template
21322 // precedes this use.
21324 /*Recursive=*/false,
21325 /*DefinitionRequired=*/true,
21326 /*AtEndOfTU=*/false);
21327 }
21328 // Produce a properly-typed reference to the function.
21329 CXXScopeSpec SS;
21330 SS.Adopt(DRE->getQualifierLoc());
21331 TemplateArgumentListInfo TemplateArgs;
21332 DRE->copyTemplateArgumentsInto(TemplateArgs);
21333 return BuildDeclRefExpr(
21334 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21335 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21336 DRE->getTemplateKeywordLoc(),
21337 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21338 }
21339 }
21340
21341 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21342 return ExprError();
21343 }
21344
21345 case BuiltinType::IncompleteMatrixIdx:
21346 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21347 ->getRowIdx()
21348 ->getBeginLoc(),
21349 diag::err_matrix_incomplete_index);
21350 return ExprError();
21351
21352 // Expressions of unknown type.
21353 case BuiltinType::ArraySection:
21354 Diag(E->getBeginLoc(), diag::err_array_section_use)
21355 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21356 return ExprError();
21357
21358 // Expressions of unknown type.
21359 case BuiltinType::OMPArrayShaping:
21360 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21361
21362 case BuiltinType::OMPIterator:
21363 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21364
21365 // Everything else should be impossible.
21366#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21367 case BuiltinType::Id:
21368#include "clang/Basic/OpenCLImageTypes.def"
21369#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21370 case BuiltinType::Id:
21371#include "clang/Basic/OpenCLExtensionTypes.def"
21372#define SVE_TYPE(Name, Id, SingletonId) \
21373 case BuiltinType::Id:
21374#include "clang/Basic/AArch64SVEACLETypes.def"
21375#define PPC_VECTOR_TYPE(Name, Id, Size) \
21376 case BuiltinType::Id:
21377#include "clang/Basic/PPCTypes.def"
21378#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21379#include "clang/Basic/RISCVVTypes.def"
21380#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21381#include "clang/Basic/WebAssemblyReferenceTypes.def"
21382#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21383#define PLACEHOLDER_TYPE(Id, SingletonId)
21384#include "clang/AST/BuiltinTypes.def"
21385 break;
21386 }
21387
21388 llvm_unreachable("invalid placeholder type!");
21389}
21390
21392 if (E->isTypeDependent())
21393 return true;
21395 return E->getType()->isIntegralOrEnumerationType();
21396 return false;
21397}
21398
21399/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21402 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21403 "Unknown Objective-C Boolean value!");
21405 if (!Context.getBOOLDecl()) {
21406 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21408 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21409 NamedDecl *ND = Result.getFoundDecl();
21410 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21411 Context.setBOOLDecl(TD);
21412 }
21413 }
21414 if (Context.getBOOLDecl())
21415 BoolT = Context.getBOOLType();
21416 return new (Context)
21417 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21418}
21419
21422 SourceLocation RParen) {
21423 auto FindSpecVersion =
21424 [&](StringRef Platform) -> std::optional<VersionTuple> {
21425 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21426 return Spec.getPlatform() == Platform;
21427 });
21428 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21429 // for "maccatalyst" if "maccatalyst" is not specified.
21430 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21431 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21432 return Spec.getPlatform() == "ios";
21433 });
21434 }
21435 if (Spec == AvailSpecs.end())
21436 return std::nullopt;
21437 return Spec->getVersion();
21438 };
21439
21440 VersionTuple Version;
21441 if (auto MaybeVersion =
21442 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21443 Version = *MaybeVersion;
21444
21445 // The use of `@available` in the enclosing context should be analyzed to
21446 // warn when it's used inappropriately (i.e. not if(@available)).
21448 Context->HasPotentialAvailabilityViolations = true;
21449
21450 return new (Context)
21451 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21452}
21453
21455 ArrayRef<Expr *> SubExprs, QualType T) {
21456 if (!Context.getLangOpts().RecoveryAST)
21457 return ExprError();
21458
21459 if (isSFINAEContext())
21460 return ExprError();
21461
21462 if (T.isNull() || T->isUndeducedType() ||
21463 !Context.getLangOpts().RecoveryASTType)
21464 // We don't know the concrete type, fallback to dependent type.
21466
21467 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21468}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3284
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:154
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:48
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
CastType
Definition: SemaCast.cpp:47
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9511
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:18010
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1944
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:15560
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:10393
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:18950
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:11135
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:15350
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6318
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:11054
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:9078
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3400
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8390
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
Definition: SemaExpr.cpp:8596
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:12124
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:11099
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:12074
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2227
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14828
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18348
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13618
@ NCCK_Block
Definition: SemaExpr.cpp:13618
@ NCCK_None
Definition: SemaExpr.cpp:13618
@ NCCK_Lambda
Definition: SemaExpr.cpp:13618
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:10287
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9560
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6242
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
Definition: SemaExpr.cpp:2651
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:20163
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18802
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:17106
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:8982
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1928
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16943
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:14177
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4956
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12476
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14725
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4556
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:9057
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:18197
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14884
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:11220
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8233
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19960
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3425
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8199
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:12166
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6588
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13802
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:20209
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
Definition: SemaExpr.cpp:10334
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19928
@ ConstMethod
Definition: SemaExpr.cpp:13668
@ ConstUnknown
Definition: SemaExpr.cpp:13670
@ ConstVariable
Definition: SemaExpr.cpp:13666
@ NestedConstMember
Definition: SemaExpr.cpp:13669
@ ConstMember
Definition: SemaExpr.cpp:13667
@ ConstFunction
Definition: SemaExpr.cpp:13665
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14707
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17871
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12351
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:9012
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:14982
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1314
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6478
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
Definition: SemaExpr.cpp:9948
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:8514
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8220
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:11066
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14967
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:5013
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9287
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17913
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:15441
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2373
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:14285
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8459
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:8568
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10893
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:12180
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:4426
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10941
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3724
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5955
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:144
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11572
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4348
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9460
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
Definition: SemaExpr.cpp:1271
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18633
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:11250
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13866
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14390
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:160
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:18228
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:11934
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15498
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14450
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1364
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:5027
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:10437
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:18990
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15405
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:569
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:9112
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:18316
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:13677
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3854
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13655
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18750
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:11113
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4378
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11767
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12394
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:21182
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1936
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8634
OriginalExprKind
Definition: SemaExpr.cpp:13796
@ OEK_Variable
Definition: SemaExpr.cpp:13797
@ OEK_LValue
Definition: SemaExpr.cpp:13799
@ OEK_Member
Definition: SemaExpr.cpp:13798
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18882
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1221
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:11041
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:11673
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18709
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1296
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10857
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13605
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
Definition: SemaExpr.cpp:19118
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6547
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9308
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4366
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15426
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:5046
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1496
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11301
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6505
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1410
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4408
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:11083
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
Definition: SemaExpr.cpp:8429
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:12312
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:13184
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8548
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8997
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
Definition: SemaExpr.cpp:1115
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15015
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14926
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:594
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20787
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1190
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11986
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1143
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:6405
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:20131
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1904
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:105
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1457
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1166
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14249
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:19092
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:11031
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11923
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:15038
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11973
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13619
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8364
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15470
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15456
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11963
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15393
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4622
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:10355
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18783
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15743
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13994
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13414
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:19544
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18262
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11566
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:11167
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7700
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
SourceLocation Begin
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool hasValue() const
Definition: APValue.h:399
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:82
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CanQualType AccumTy
Definition: ASTContext.h:1104
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1121
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
CanQualType Int128Ty
Definition: ASTContext.h:1100
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2118
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2132
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1104
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1103
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
CanQualType DoubleTy
Definition: ASTContext.h:1103
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
QualType getObjCSelRedefinitionType() const
Retrieve the type that 'SEL' has been defined to, which may be different from the built-in 'SEL' if '...
Definition: ASTContext.h:1890
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2911
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1590
CanQualType WideCharTy
Definition: ASTContext.h:1095
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
TypedefDecl * getBOOLDecl() const
Retrieve declaration of 'BOOL' typedef.
Definition: ASTContext.h:2094
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
void setBOOLDecl(TypedefDecl *TD)
Save declaration of 'BOOL' typedef.
Definition: ASTContext.h:2099
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1092
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1170
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1107
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
QualType getBOOLType() const
type of 'BOOL' type.
Definition: ASTContext.h:2104
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType CharTy
Definition: ASTContext.h:1093
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1100
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1162
CanQualType PseudoObjectTy
Definition: ASTContext.h:1121
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1123
CanQualType OverloadTy
Definition: ASTContext.h:1119
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2320
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2063
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1166
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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.
Definition: ASTContext.h:2340
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1877
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1568
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1864
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1100
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1107
CanQualType LongAccumTy
Definition: ASTContext.h:1105
CanQualType Char32Ty
Definition: ASTContext.h:1099
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
CanQualType LongFractTy
Definition: ASTContext.h:1107
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1129
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2359
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 ...
CanQualType LongLongTy
Definition: ASTContext.h:1100
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1793
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:1999
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1097
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1115
bool isDependenceAllowed() const
Definition: ASTContext.h:781
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2344
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4338
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2719
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3528
QualType getElementType() const
Definition: Type.h:3526
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6234
Attr - This represents one attribute.
Definition: Attr.h:42
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5655
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5977
One specifier in an @available expression.
Definition: Availability.h:31
StringRef getPlatform() const
Definition: Availability.h:53
VersionTuple getVersion() const
Definition: Availability.h:52
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3939
bool isComparisonOp() const
Definition: Expr.h:3940
StringRef getOpcodeStr() const
Definition: Expr.h:3905
bool isRelationalOp() const
Definition: Expr.h:3934
SourceLocation getOperatorLoc() const
Definition: Expr.h:3881
bool isCompoundAssignmentOp() const
Definition: Expr.h:3983
bool isMultiplicativeOp() const
Definition: Expr.h:3924
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2134
bool isShiftOp() const
Definition: Expr.h:3928
Expr * getRHS() const
Definition: Expr.h:3891
bool isEqualityOp() const
Definition: Expr.h:3937
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:4781
bool isBitwiseOp() const
Definition: Expr.h:3931
bool isAdditiveOp() const
Definition: Expr.h:3926
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:2206
Opcode getOpcode() const
Definition: Expr.h:3884
bool isAssignmentOp() const
Definition: Expr.h:3978
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3930
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
A class which contains all the information about a particular captured value.
Definition: Decl.h:4501
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5231
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4577
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4634
void setIsVariadic(bool value)
Definition: Decl.h:4571
SourceLocation getCaretLocation() const
Definition: Decl.h:4568
void setBody(CompoundStmt *B)
Definition: Decl.h:4575
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4581
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5242
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5418
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3345
This class is used for builtin types like 'int'.
Definition: Type.h:2977
bool isSVEBool() const
Definition: Type.h:3048
Kind getKind() const
Definition: Type.h:3019
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:209
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
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:1858
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2904
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:969
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
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:1023
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1035
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:1484
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
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:2293
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:149
SourceRange getSourceRange() const
Definition: ExprCXX.h:161
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:1226
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1930
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents the this expression in C++.
Definition: ExprCXX.h:1148
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
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:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
Expr * getCallee()
Definition: Expr.h:2970
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3030
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3001
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3052
void setCallee(Expr *F)
Definition: Expr.h:2972
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3043
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:3483
CastKind getCastKind() const
Definition: Expr.h:3527
const char * getCastKindName() const
Definition: Expr.h:3531
void setSubExpr(Expr *E)
Definition: Expr.h:3535
Expr * getSubExpr()
Definition: Expr.h:3533
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
unsigned getValue() const
Definition: Expr.h:1610
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4558
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: Type.h:3082
QualType getElementType() const
Definition: Type.h:3092
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:4803
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3413
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt * getStmtExprResult()
Definition: Stmt.h:1723
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3608
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3628
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1072
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:1122
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
bool isImmediateInvocation() const
Definition: Expr.h:1144
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4163
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4184
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4181
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4499
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:1262
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1231
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1567
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1946
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1215
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1409
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1458
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:1413
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1332
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1381
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:1343
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:579
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:709
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setReferenced(bool R=true)
Definition: DeclBase.h:629
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:939
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1997
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
DeclaratorContext getContext() const
Definition: DeclSpec.h:2070
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isInvalidType() const
Definition: DeclSpec.h:2712
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
RAII object that enters a new expression evaluation context.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EnumDecl * getDecl() const
Definition: Type.h:5578
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3730
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3757
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
This represents one expression.
Definition: Expr.h:110
LValueClassification
Definition: Expr.h:282
@ LV_ArrayTemporary
Definition: Expr.h:292
@ LV_ClassTemporary
Definition: Expr.h:291
@ LV_MemberFunction
Definition: Expr.h:289
@ LV_IncompleteVoidType
Definition: Expr.h:285
@ LV_Valid
Definition: Expr.h:283
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 isGLValue() const
Definition: Expr.h:280
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:3086
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...
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:3015
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:3064
void setType(QualType t)
Definition: Expr.h:143
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:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3068
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3279
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
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:3556
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:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:807
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
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:3918
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:454
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:4170
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
isModifiableLvalueResult
Definition: Expr.h:297
@ MLV_DuplicateVectorComponents
Definition: Expr.h:301
@ MLV_LValueCast
Definition: Expr.h:303
@ MLV_InvalidMessageExpression
Definition: Expr.h:312
@ MLV_ConstQualifiedField
Definition: Expr.h:306
@ MLV_InvalidExpression
Definition: Expr.h:302
@ MLV_IncompleteType
Definition: Expr.h:304
@ MLV_Valid
Definition: Expr.h:298
@ MLV_ConstQualified
Definition: Expr.h:305
@ MLV_NoSetterProperty
Definition: Expr.h:309
@ MLV_ArrayTemporary
Definition: Expr.h:314
@ MLV_SubObjCPropertySetting
Definition: Expr.h:311
@ MLV_ConstAddrSpace
Definition: Expr.h:307
@ MLV_MemberFunction
Definition: Expr.h:310
@ MLV_NotObjectType
Definition: Expr.h:299
@ MLV_ArrayType
Definition: Expr.h:308
@ MLV_ClassTemporary
Definition: Expr.h:313
@ MLV_IncompleteVoidType
Definition: Expr.h:300
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6113
ExtVectorType - Extended vector type.
Definition: Type.h:4057
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
bool isFPConstrained() const
Definition: LangOptions.h:843
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3149
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3219
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1039
const Expr * getSubExpr() const
Definition: Expr.h:1052
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:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
bool isImmediateFunction() const
Definition: Decl.cpp:3288
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2831
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2406
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2161
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2843
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2445
size_t param_size() const
Definition: Decl.h:2700
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3889
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2791
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4606
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4636
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
QualType desugar() const
Definition: Type.h:5119
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5097
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4911
bool isParamConsumed(unsigned I) const
Definition: Type.h:5111
unsigned getNumParams() const
Definition: Type.h:4885
QualType getParamType(unsigned i) const
Definition: Type.h:4887
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
ArrayRef< QualType > param_types() const
Definition: Type.h:5040
Declaration of a template function.
Definition: DeclTemplate.h:958
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4363
bool getCmseNSCall() const
Definition: Type.h:4413
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4437
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
ExtInfo getExtInfo() const
Definition: Type.h:4581
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4577
QualType getReturnType() const
Definition: Type.h:4569
bool getCmseNSCallAttr() const
Definition: Type.h:4579
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4593
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4633
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:4470
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
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:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
Describes an C or C++ initializer list.
Definition: Expr.h:4847
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8591
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:977
Represents the declaration of a label.
Definition: Decl.h:499
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition: ExprCXX.cpp:1336
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:288
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:297
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:295
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:302
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:293
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:620
bool isSignedOverflowDefined() const
Definition: LangOptions.h:616
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
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:1024
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:310
Represents the results of name lookup.
Definition: Lookup.h:46
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:603
DeclClass * getAsSingle() const
Definition: Lookup.h:556
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:662
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:573
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4289
MS property subscript expression.
Definition: ExprCXX.h:1000
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2742
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4127
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4141
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3361
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
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:1754
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3390
Expr * getBase() const
Definition: Expr.h:3249
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
A runtime availability query.
Definition: ExprObjC.h:1696
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:637
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1452
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6948
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1491
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
AccessControl getAccessControl() const
Definition: DeclObjC.h:1998
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type.
Definition: DeclObjC.cpp:1899
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
SourceLocation getLocation() const
Definition: ExprObjC.h:592
SourceLocation getOpLoc() const
Definition: ExprObjC.h:600
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
bool isArrow() const
Definition: ExprObjC.h:587
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:598
const Expr * getBase() const
Definition: ExprObjC.h:583
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
bool isInstanceMethod() const
Definition: DeclObjC.h:426
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1053
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7004
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7079
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7062
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7056
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1787
qual_range quals() const
Definition: Type.h:7123
Represents a class type in Objective C.
Definition: Type.h:6750
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1657
Helper class for OffsetOfExpr.
Definition: Expr.h:2359
void * getAsOpaquePtr() const
Definition: Ownership.h:90
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:2976
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3036
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2149
const Expr * getSubExpr() const
Definition: Expr.h:2145
Expr * getExpr(unsigned Init)
Definition: Expr.h:5655
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4723
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5653
SourceLocation getLParenLoc() const
Definition: Expr.h:5670
SourceLocation getRParenLoc() const
Definition: Expr.h:5671
Represents a parameter to a function.
Definition: Decl.h:1761
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1890
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1894
QualType getOriginalType() const
Definition: Decl.cpp:2924
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:2915
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:638
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:678
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the character.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
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:7502
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
@ DK_nontrivial_c_struct
Definition: Type.h:1523
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2810
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7537
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
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:7496
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
bool isAddressSpaceOverlapping(QualType T) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1411
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:2569
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7556
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2828
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:7563
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7476
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1618
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool isCanonical() const
Definition: Type.h:7412
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7387
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:7490
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
void removeObjCLifetime()
Definition: Type.h:537
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
Qualifiers withoutObjCLifetime() const
Definition: Type.h:519
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:514
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:754
Represents a struct/union/class.
Definition: Decl.h:4169
field_range fields() const
Definition: Decl.h:4375
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5104
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:259
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema & SemaRef
Definition: SemaBase.h:40
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition: SemaCUDA.cpp:706
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:882
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:110
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:369
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6552
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9547
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5776
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17447
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17453
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14849
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6794
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:6309
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10239
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:698
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2476
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:8840
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16077
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:6372
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3848
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15753
bool isValidRVVBitcast(QualType srcType, QualType destType)
Are the two types RVV-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7746
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:6279
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:813
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15291
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:6365
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:7415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
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:423
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19890
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13492
VariadicCallType
Definition: Sema.h:2013
@ VariadicDoesNotApply
Definition: Sema.h:2018
@ VariadicFunction
Definition: Sema.h:2014
@ VariadicMethod
Definition: Sema.h:2016
@ VariadicConstructor
Definition: Sema.h:2017
@ VariadicBlock
Definition: Sema.h:2015
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7230
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
@ NTCUC_CompoundLiteral
Definition: Sema.h:3012
@ NTCUC_Assignment
Definition: Sema.h:3010
@ NTCUC_FunctionReturn
Definition: Sema.h:3002
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3016
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7774
bool isSelfExpr(Expr *RExpr)
Private Helper predicate to check for 'self'.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:3110
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.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2351
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:16097
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:17739
void ActOnStmtExprError()
Definition: SemaExpr.cpp:16103
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:3037
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1561
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12503
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16553
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12187
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:814
SemaCUDA & CUDA()
Definition: Sema.h:998
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17673
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: Sema.h:12450
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20639
ConditionKind
Definition: Sema.h:5898
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2692
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:807
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2245
Preprocessor & getPreprocessor() const
Definition: Sema.h:526
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2107
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:13066
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:6441
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3788
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:6353
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:18703
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17458
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6853
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10529
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:1420
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7725
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.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:12032
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt=std::nullopt)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20424
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:16116
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.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16769
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:1499
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:796
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1046
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14200
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5233
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2003
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7868
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14490
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15278
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1057
ASTContext & Context
Definition: Sema.h:858
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:6266
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2690
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:10224
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:20435
@ ACR_okay
Definition: Sema.h:12402
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11859
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2946
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:8135
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...
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:21391
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:918
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13331
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:2635
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....
AllowFoldKind
Definition: Sema.h:5790
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19903
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:762
bool isImmediateFunctionContext() const
Definition: Sema.h:6291
ASTContext & getASTContext() const
Definition: Sema.h:527
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:774
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16032
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:19194
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:20154
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15546
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18099
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9967
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:645
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:879
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3736
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6380
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3344
bool isBoundsAttrContext() const
Definition: Sema.h:5176
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:7244
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:16084
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4483
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8151
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:13377
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2206
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16372
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
Definition: SemaExpr.cpp:1675
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:7478
AssumedTemplateKind
Definition: Sema.h:8875
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1973
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:518
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:648
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:6324
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:224
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:6435
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20670
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
@ UPPC_Block
Block expression.
Definition: Sema.h:10851
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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)
TypoExpr * CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12530
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7493
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13306
SemaOpenACC & OpenACC()
Definition: Sema.h:1008
ReuseLambdaContextDecl_t
Definition: Sema.h:5233
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6717
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17774
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2254
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.
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:20301
Preprocessor & PP
Definition: Sema.h:857
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11311
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5911
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6651
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14455
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:17043
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4948
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)
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
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:1916
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7763
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.
const LangOptions & LangOpts
Definition: Sema.h:856
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:16186
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2360
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:6919
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17795
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8554
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4796
SemaHLSL & HLSL()
Definition: Sema.h:1003
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17759
ObjCLiteralKind
Definition: Sema.h:5720
@ LK_Boxed
Definition: Sema.h:5724
@ LK_Dictionary
Definition: Sema.h:5722
@ LK_String
Definition: Sema.h:5725
@ LK_Array
Definition: Sema.h:5721
@ LK_Numeric
Definition: Sema.h:5723
@ LK_None
Definition: Sema.h:5727
@ LK_Block
Definition: Sema.h:5726
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:204
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:71
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20311
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)
Definition: SemaExpr.cpp:10251
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:5188
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4822
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9761
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:10521
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:944
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15995
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:727
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3340
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:3174
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3886
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10779
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10019
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
Definition: SemaStmt.cpp:1663
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5185
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2079
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:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:6295
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7463
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
Definition: SemaExpr.cpp:1643
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16561
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7909
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2316
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV)
IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is an ivar synthesized for 'Meth...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8535
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:21135
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:9571
@ VAK_Invalid
Definition: Sema.h:6053
@ VAK_Valid
Definition: Sema.h:6049
@ VAK_ValidInCXX11
Definition: Sema.h:6050
@ VAK_MSVCUndefined
Definition: Sema.h:6052
@ VAK_Undefined
Definition: Sema.h:6051
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5904
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10530
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16925
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:8160
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.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20364
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6287
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6091
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:6135
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:6101
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:6159
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:6164
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:6151
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6130
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6109
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:6168
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6093
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:6120
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6172
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:6105
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:6114
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6126
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:6147
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:6141
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:6097
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:6155
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8534
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:5934
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:5936
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:5944
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:5938
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:5942
@ ACK_Comparison
A comparison.
Definition: Sema.h:5940
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20258
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4339
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:17010
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:5022
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21227
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17652
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:10484
SourceManager & getSourceManager() const
Definition: Sema.h:525
TryCaptureKind
Definition: Sema.h:5275
@ TryCapture_Implicit
Definition: Sema.h:5276
@ TryCapture_ExplicitByRef
Definition: Sema.h:5278
AssignmentAction
Definition: Sema.h:5196
@ AA_Returning
Definition: Sema.h:5199
@ AA_Passing_CFAudited
Definition: Sema.h:5204
@ AA_Initializing
Definition: Sema.h:5201
@ AA_Converting
Definition: Sema.h:5200
@ AA_Assigning
Definition: Sema.h:5197
@ AA_Passing
Definition: Sema.h:5198
@ AA_Casting
Definition: Sema.h:5203
@ AA_Sending
Definition: Sema.h:5202
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6886
ExprResult checkPseudoObjectRValue(Expr *E)
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4612
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:9166
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:13082
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10954
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19867
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:14039
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.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:21401
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
@ NTCUK_Destruct
Definition: Sema.h:3028
@ NTCUK_Copy
Definition: Sema.h:3029
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20505
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5714
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7794
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7840
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:6342
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2138
sema::FunctionScopeInfo * getCurFunctionAvailabilityContext()
Retrieve the current function, if any, that should be analyzed for potential availability violations.
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:5020
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8374
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:2058
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11707
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15533
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:7942
@ CTK_ErrorRecovery
Definition: Sema.h:7605
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2301
bool isConstantEvaluatedContext() const
Definition: Sema.h:1864
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 mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3194
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12680
ASTConsumer & Consumer
Definition: Sema.h:859
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3424
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:5766
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:5192
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:897
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10513
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5356
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3784
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:13023
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8648
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:4964
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2042
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:6878
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4842
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20511
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4449
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16762
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:6235
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21155
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
Definition: SemaExpr.cpp:19500
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7977
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
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.
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:6277
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18177
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19492
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7889
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
SourceManager & SourceMgr
Definition: Sema.h:861
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4933
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:8050
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2414
DiagnosticsEngine & Diags
Definition: Sema.h:860
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
FPOptions CurFPFeatures
Definition: Sema.h:854
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:527
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:650
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:7824
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5788
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20554
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void PopDeclContext()
Definition: SemaDecl.cpp:1335
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13428
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4826
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16111
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:999
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6260
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13143
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number)
BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the numeric literal expression.
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9270
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13226
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16573
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:520
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20281
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:17125
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18360
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:16155
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4993
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6138
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:280
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17051
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20612
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21454
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15596
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3920
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3212
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7437
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16411
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:5066
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:15065
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9545
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6618
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4916
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:6010
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:7429
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:7435
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:7427
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:7432
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:7443
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:7439
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16440
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10993
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:10509
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.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3222
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:21420
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15959
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13478
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11426
static ConditionResult ConditionError()
Definition: Sema.h:5885
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:6905
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
const TypoExprState & getTypoExprState(TypoExpr *TE) const
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:21159
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:6000
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16353
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2292
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5841
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:6446
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2703
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:18185
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7369
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:6301
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5584
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6733
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5241
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4727
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:267
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
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:4383
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
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:1773
unsigned getLength() const
Definition: Expr.h:1890
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1865
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
StringRef getString() const
Definition: Expr.h:1850
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3688
bool isUnion() const
Definition: Decl.h:3791
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:213
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1623
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:316
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:651
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:971
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:467
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:504
IntType getSizeType() const
Definition: TargetInfo.h:366
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:514
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1540
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1633
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1012
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:848
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:509
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents a declaration of a type.
Definition: Decl.h:3391
const Type * getTypeForDecl() const
Definition: Decl.h:3415
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3418
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:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7337
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2396
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:7962
bool isBlockPointerType() const
Definition: Type.h:7616
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
bool isObjCBuiltinType() const
Definition: Type.h:7791
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:1887
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8076
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7877
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:666
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8056
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:2009
bool isVoidPointerType() const
Definition: Type.cpp:654
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:687
bool isArrayType() const
Definition: Type.h:7674
bool isCharType() const
Definition: Type.cpp:2077
bool isFunctionPointerType() const
Definition: Type.h:7642
bool isArithmeticType() const
Definition: Type.cpp:2269
bool isConstantMatrixType() const
Definition: Type.h:7732
bool isPointerType() const
Definition: Type.h:7608
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7982
bool isEnumeralType() const
Definition: Type.h:7706
bool isScalarType() const
Definition: Type.h:8000
bool isVariableArrayType() const
Definition: Type.h:7686
bool isSizelessBuiltinType() const
Definition: Type.cpp:2421
bool isClkEventT() const
Definition: Type.h:7813
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
bool isObjCQualifiedIdType() const
Definition: Type.h:7761
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8016
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2224
bool isExtVectorType() const
Definition: Type.h:7718
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2113
bool isExtVectorBoolType() const
Definition: Type.h:7722
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
bool isImageType() const
Definition: Type.h:7825
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7895
bool isPipeType() const
Definition: Type.h:7832
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isBitIntType() const
Definition: Type.h:7836
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7870
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7698
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isAnyComplexType() const
Definition: Type.h:7710
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7954
bool isHalfType() const
Definition: Type.h:7905
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7970
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2284
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7883
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2174
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool isQueueT() const
Definition: Type.h:7817
bool isMemberPointerType() const
Definition: Type.h:7656
bool isAtomicType() const
Definition: Type.h:7753
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8042
bool isObjCIdType() const
Definition: Type.h:7773
bool isMatrixType() const
Definition: Type.h:7728
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2667
bool isComplexIntegerType() const
Definition: Type.cpp:672
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2070
bool isObjCObjectType() const
Definition: Type.h:7744
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4792
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8172
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2246
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7996
bool isVectorType() const
Definition: Type.h:7714
bool isObjCQualifiedClassType() const
Definition: Type.h:7767
bool isObjCClassType() const
Definition: Type.h:7779
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
ScalarTypeKind
Definition: Type.h:2622
@ STK_FloatingComplex
Definition: Type.h:2631
@ STK_Floating
Definition: Type.h:2629
@ STK_BlockPointer
Definition: Type.h:2624
@ STK_Bool
Definition: Type.h:2627
@ STK_ObjCObjectPointer
Definition: Type.h:2625
@ STK_FixedPoint
Definition: Type.h:2632
@ STK_IntegralComplex
Definition: Type.h:2630
@ STK_CPointer
Definition: Type.h:2623
@ STK_Integral
Definition: Type.h:2628
@ STK_MemberPointer
Definition: Type.h:2626
bool isFloatingType() const
Definition: Type.cpp:2237
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:2184
bool isAnyPointerType() const
Definition: Type.h:7612
bool isRealType() const
Definition: Type.cpp:2260
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSamplerT() const
Definition: Type.h:7805
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2456
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3535
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.
bool isOverloaded() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6585
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2568
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
void setSubExpr(Expr *E)
Definition: Expr.h:2229
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
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:4838
bool isIncrementDecrementOp() const
Definition: Expr.h:2284
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
void setImplicitSelfParam(const IdentifierInfo *Id)
Specify that this unqualified-id is an implicit 'self' parameter.
Definition: DeclSpec.h:1226
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3173
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3912
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1617
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:1579
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
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:637
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4667
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5367
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:918
bool hasInit() const
Definition: Decl.cpp:2395
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2254
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
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:2463
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:2876
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1531
const Expr * getInit() const
Definition: Decl.h:1355
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1204
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1527
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
@ TLS_None
Not a TLS variable.
Definition: Decl.h:938
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1282
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2372
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:2505
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:2777
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1249
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:2756
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3743
Expr * getSizeExpr() const
Definition: Type.h:3762
Represents a GCC generic vector type.
Definition: Type.h:3965
unsigned getNumElements() const
Definition: Type.h:3980
VectorKind getVectorKind() const
Definition: Type.h:3985
QualType getElementType() const
Definition: Type.h:3979
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:790
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:794
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:668
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
bool isNested() const
Definition: ScopeInfo.h:659
Retains information about a captured region.
Definition: ScopeInfo.h:810
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:825
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:228
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:765
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:1087
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:160
void addBlock(const BlockDecl *BD)
Definition: ScopeInfo.h:493
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition: ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition: ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:989
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:995
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isa(CodeGen::Address addr)
Definition: Address.h:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ GVA_StrongExternal
Definition: Linkage.h:76
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
CUDAFunctionTarget
Definition: Cuda.h:131
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:333
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:154
@ 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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:166
BinaryOperatorKind
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_None
Definition: Specifiers.h:247
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ObjCMethodFamily
A family of Objective-C methods.
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
@ AR_Unavailable
Definition: DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4714
@ None
No keyword precedes the qualified type name.
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1970
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1584
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:170
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:180
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:172
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:177
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5711
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5698
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5706
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5705
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5691
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5656
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5662
const ASTContext & Context
Definition: SemaExpr.cpp:5650
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5683
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5687
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5672
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5654
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5651
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
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:4731
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:9821
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:5026
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:5060
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:5106
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:5065
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:5073
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:5069
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:5079
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:5045
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:5083
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:5031
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:5039
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:5028
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:5035
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6379
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:153