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"
55#include "clang/Sema/SemaObjC.h"
57#include "clang/Sema/Template.h"
58#include "llvm/ADT/STLExtras.h"
59#include "llvm/ADT/STLForwardCompat.h"
60#include "llvm/ADT/StringExtras.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ConvertUTF.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include "llvm/Support/TypeSize.h"
65#include <optional>
66
67using namespace clang;
68using namespace sema;
69
70/// Determine whether the use of this declaration is valid, without
71/// emitting diagnostics.
72bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
73 // See if this is an auto-typed variable whose initializer we are parsing.
74 if (ParsingInitForAutoVars.count(D))
75 return false;
76
77 // See if this is a deleted function.
78 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
79 if (FD->isDeleted())
80 return false;
81
82 // If the function has a deduced return type, and we can't deduce it,
83 // then we can't use it either.
84 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
85 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
86 return false;
87
88 // See if this is an aligned allocation/deallocation function that is
89 // unavailable.
90 if (TreatUnavailableAsInvalid &&
92 return false;
93 }
94
95 // See if this function is unavailable.
96 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
97 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
98 return false;
99
100 if (isa<UnresolvedUsingIfExistsDecl>(D))
101 return false;
102
103 return true;
104}
105
107 // Warn if this is used but marked unused.
108 if (const auto *A = D->getAttr<UnusedAttr>()) {
109 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
110 // should diagnose them.
111 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
112 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
113 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
114 if (DC && !DC->hasAttr<UnusedAttr>())
115 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
116 }
117 }
118}
119
120/// Emit a note explaining that this function is deleted.
122 assert(Decl && Decl->isDeleted());
123
124 if (Decl->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
132 return;
133 }
134
135 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
136 if (Ctor && Ctor->isInheritingConstructor())
138
139 Diag(Decl->getLocation(), diag::note_availability_specified_here)
140 << Decl << 1;
141}
142
143/// Determine whether a FunctionDecl was ever declared with an
144/// explicit storage class.
146 for (auto *I : D->redecls()) {
147 if (I->getStorageClass() != SC_None)
148 return true;
149 }
150 return false;
151}
152
153/// Check whether we're in an extern inline function and referring to a
154/// variable or function with internal linkage (C11 6.7.4p3).
155///
156/// This is only a warning because we used to silently accept this code, but
157/// in many cases it will not behave correctly. This is not enabled in C++ mode
158/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159/// and so while there may still be user mistakes, most of the time we can't
160/// prove that there are errors.
162 const NamedDecl *D,
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S.getLangOpts().CPlusPlus)
168 return;
169
170 // Check if this is an inlined function or method.
171 FunctionDecl *Current = S.getCurFunctionDecl();
172 if (!Current)
173 return;
174 if (!Current->isInlined())
175 return;
176 if (!Current->isExternallyVisible())
177 return;
178
179 // Check if the decl has internal linkage.
181 return;
182
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
191 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
192 if (!DowngradeWarning && UsedFn)
193 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
194
195 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline)
197 << /*IsVar=*/!UsedFn << D;
198
200
201 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
202 << D;
203}
204
206 const FunctionDecl *First = Cur->getFirstDecl();
207
208 // Suggest "static" on the function, if possible.
210 SourceLocation DeclBegin = First->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214}
215
216/// Determine whether the use of this declaration is valid, and
217/// emit any corresponding diagnostics.
218///
219/// This routine diagnoses various problems with referencing
220/// declarations that can occur when using a declaration. For example,
221/// it might warn if a deprecated or unavailable declaration is being
222/// used, or produce an error (and return true) if a C++0x deleted
223/// function is being used.
224///
225/// \returns true if there was an error (this declaration cannot be
226/// referenced), false otherwise.
227///
229 const ObjCInterfaceDecl *UnknownObjCClass,
230 bool ObjCPropertyAccess,
231 bool AvoidPartialAvailabilityChecks,
232 ObjCInterfaceDecl *ClassReceiver,
233 bool SkipTrailingRequiresClause) {
234 SourceLocation Loc = Locs.front();
235 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
236 // If there were any diagnostics suppressed by template argument deduction,
237 // emit them now.
238 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
239 if (Pos != SuppressedDiagnostics.end()) {
240 for (const PartialDiagnosticAt &Suppressed : Pos->second)
241 Diag(Suppressed.first, Suppressed.second);
242
243 // Clear out the list of suppressed diagnostics, so that we don't emit
244 // them again for this specialization. However, we don't obsolete this
245 // entry from the table, because we want to avoid ever emitting these
246 // diagnostics again.
247 Pos->second.clear();
248 }
249
250 // C++ [basic.start.main]p3:
251 // The function 'main' shall not be used within a program.
252 if (cast<FunctionDecl>(D)->isMain())
253 Diag(Loc, diag::ext_main_used);
254
255 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
256 }
257
258 // See if this is an auto-typed variable whose initializer we are parsing.
259 if (ParsingInitForAutoVars.count(D)) {
260 if (isa<BindingDecl>(D)) {
261 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 } else {
264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << D->getDeclName() << cast<VarDecl>(D)->getType();
266 }
267 return true;
268 }
269
270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271 // See if this is a deleted function.
272 if (FD->isDeleted()) {
273 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
274 if (Ctor && Ctor->isInheritingConstructor())
275 Diag(Loc, diag::err_deleted_inherited_ctor_use)
276 << Ctor->getParent()
277 << Ctor->getInheritedConstructor().getConstructor()->getParent();
278 else {
279 StringLiteral *Msg = FD->getDeletedMessage();
280 Diag(Loc, diag::err_deleted_function_use)
281 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
282 }
284 return true;
285 }
286
287 // [expr.prim.id]p4
288 // A program that refers explicitly or implicitly to a function with a
289 // trailing requires-clause whose constraint-expression is not satisfied,
290 // other than to declare it, is ill-formed. [...]
291 //
292 // See if this is a function with constraints that need to be satisfied.
293 // Check this before deducing the return type, as it might instantiate the
294 // definition.
295 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
296 ConstraintSatisfaction Satisfaction;
297 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
298 /*ForOverloadResolution*/ true))
299 // A diagnostic will have already been generated (non-constant
300 // constraint expression, for example)
301 return true;
302 if (!Satisfaction.IsSatisfied) {
303 Diag(Loc,
304 diag::err_reference_to_function_with_unsatisfied_constraints)
305 << D;
306 DiagnoseUnsatisfiedConstraint(Satisfaction);
307 return true;
308 }
309 }
310
311 // If the function has a deduced return type, and we can't deduce it,
312 // then we can't use it either.
313 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
315 return true;
316
317 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
318 return true;
319
320 }
321
322 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
323 // Lambdas are only default-constructible or assignable in C++2a onwards.
324 if (MD->getParent()->isLambda() &&
325 ((isa<CXXConstructorDecl>(MD) &&
326 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
327 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
328 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
329 << !isa<CXXConstructorDecl>(MD);
330 }
331 }
332
333 auto getReferencedObjCProp = [](const NamedDecl *D) ->
334 const ObjCPropertyDecl * {
335 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
336 return MD->findPropertyDecl();
337 return nullptr;
338 };
339 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
341 return true;
343 return true;
344 }
345
346 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
347 // Only the variables omp_in and omp_out are allowed in the combiner.
348 // Only the variables omp_priv and omp_orig are allowed in the
349 // initializer-clause.
350 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
351 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
352 isa<VarDecl>(D)) {
353 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
355 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
356 return true;
357 }
358
359 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
360 // List-items in map clauses on this construct may only refer to the declared
361 // variable var and entities that could be referenced by a procedure defined
362 // at the same location.
363 // [OpenMP 5.2] Also allow iterator declared variables.
364 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
365 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
366 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
368 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
369 return true;
370 }
371
372 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
373 Diag(Loc, diag::err_use_of_empty_using_if_exists);
374 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
375 return true;
376 }
377
378 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
379 AvoidPartialAvailabilityChecks, ClassReceiver);
380
381 DiagnoseUnusedOfDecl(*this, D, Loc);
382
384
385 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
386 if (getLangOpts().getFPEvalMethod() !=
389 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
390 Diag(D->getLocation(),
391 diag::err_type_available_only_in_default_eval_method)
392 << D->getName();
393 }
394
395 if (auto *VD = dyn_cast<ValueDecl>(D))
396 checkTypeSupport(VD->getType(), Loc, VD);
397
398 if (LangOpts.SYCLIsDevice ||
399 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
401 if (const auto *VD = dyn_cast<VarDecl>(D))
402 if (VD->getTLSKind() != VarDecl::TLS_None)
403 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
404 }
405
406 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
408 // C++ [expr.prim.req.nested] p3
409 // A local parameter shall only appear as an unevaluated operand
410 // (Clause 8) within the constraint-expression.
411 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
412 << D;
413 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
414 return true;
415 }
416
417 return false;
418}
419
420/// DiagnoseSentinelCalls - This routine checks whether a call or
421/// message-send is to a declaration with the sentinel attribute, and
422/// if so, it checks that the requirements of the sentinel are
423/// satisfied.
425 ArrayRef<Expr *> Args) {
426 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
427 if (!Attr)
428 return;
429
430 // The number of formal parameters of the declaration.
431 unsigned NumFormalParams;
432
433 // The kind of declaration. This is also an index into a %select in
434 // the diagnostic.
435 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
436
437 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
438 NumFormalParams = MD->param_size();
439 CalleeKind = CK_Method;
440 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
441 NumFormalParams = FD->param_size();
442 CalleeKind = CK_Function;
443 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
444 QualType Ty = VD->getType();
445 const FunctionType *Fn = nullptr;
446 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
447 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
448 if (!Fn)
449 return;
450 CalleeKind = CK_Function;
451 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
452 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
453 CalleeKind = CK_Block;
454 } else {
455 return;
456 }
457
458 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
459 NumFormalParams = proto->getNumParams();
460 else
461 NumFormalParams = 0;
462 } else {
463 return;
464 }
465
466 // "NullPos" is the number of formal parameters at the end which
467 // effectively count as part of the variadic arguments. This is
468 // useful if you would prefer to not have *any* formal parameters,
469 // but the language forces you to have at least one.
470 unsigned NullPos = Attr->getNullPos();
471 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
472 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
473
474 // The number of arguments which should follow the sentinel.
475 unsigned NumArgsAfterSentinel = Attr->getSentinel();
476
477 // If there aren't enough arguments for all the formal parameters,
478 // the sentinel, and the args after the sentinel, complain.
479 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
480 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
481 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
482 return;
483 }
484
485 // Otherwise, find the sentinel expression.
486 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
487 if (!SentinelExpr)
488 return;
489 if (SentinelExpr->isValueDependent())
490 return;
491 if (Context.isSentinelNullExpr(SentinelExpr))
492 return;
493
494 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
495 // or 'NULL' if those are actually defined in the context. Only use
496 // 'nil' for ObjC methods, where it's much more likely that the
497 // variadic arguments form a list of object pointers.
498 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
499 std::string NullValue;
500 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
501 NullValue = "nil";
502 else if (getLangOpts().CPlusPlus11)
503 NullValue = "nullptr";
504 else if (PP.isMacroDefined("NULL"))
505 NullValue = "NULL";
506 else
507 NullValue = "(void*) 0";
508
509 if (MissingNilLoc.isInvalid())
510 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
511 else
512 Diag(MissingNilLoc, diag::warn_missing_sentinel)
513 << int(CalleeKind)
514 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
515 Diag(D->getLocation(), diag::note_sentinel_here)
516 << int(CalleeKind) << Attr->getRange();
517}
518
520 return E ? E->getSourceRange() : SourceRange();
521}
522
523//===----------------------------------------------------------------------===//
524// Standard Promotions and Conversions
525//===----------------------------------------------------------------------===//
526
527/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
529 // Handle any placeholder expressions which made it here.
530 if (E->hasPlaceholderType()) {
532 if (result.isInvalid()) return ExprError();
533 E = result.get();
534 }
535
536 QualType Ty = E->getType();
537 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
538
539 if (Ty->isFunctionType()) {
540 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
541 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
543 return ExprError();
544
546 CK_FunctionToPointerDecay).get();
547 } else if (Ty->isArrayType()) {
548 // In C90 mode, arrays only promote to pointers if the array expression is
549 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
550 // type 'array of type' is converted to an expression that has type 'pointer
551 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
552 // that has type 'array of type' ...". The relevant change is "an lvalue"
553 // (C90) to "an expression" (C99).
554 //
555 // C++ 4.2p1:
556 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
557 // T" can be converted to an rvalue of type "pointer to T".
558 //
559 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
561 CK_ArrayToPointerDecay);
562 if (Res.isInvalid())
563 return ExprError();
564 E = Res.get();
565 }
566 }
567 return E;
568}
569
571 // Check to see if we are dereferencing a null pointer. If so,
572 // and if not volatile-qualified, this is undefined behavior that the
573 // optimizer will delete, so warn about it. People sometimes try to use this
574 // to get a deterministic trap and are surprised by clang's behavior. This
575 // only handles the pattern "*null", which is a very syntactic check.
576 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
577 if (UO && UO->getOpcode() == UO_Deref &&
578 UO->getSubExpr()->getType()->isPointerType()) {
579 const LangAS AS =
580 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
581 if ((!isTargetAddressSpace(AS) ||
582 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
583 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
585 !UO->getType().isVolatileQualified()) {
586 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
587 S.PDiag(diag::warn_indirection_through_null)
588 << UO->getSubExpr()->getSourceRange());
589 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
590 S.PDiag(diag::note_indirection_through_null));
591 }
592 }
593}
594
595static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
596 SourceLocation AssignLoc,
597 const Expr* RHS) {
598 const ObjCIvarDecl *IV = OIRE->getDecl();
599 if (!IV)
600 return;
601
602 DeclarationName MemberName = IV->getDeclName();
604 if (!Member || !Member->isStr("isa"))
605 return;
606
607 const Expr *Base = OIRE->getBase();
608 QualType BaseType = Base->getType();
609 if (OIRE->isArrow())
610 BaseType = BaseType->getPointeeType();
611 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
612 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
613 ObjCInterfaceDecl *ClassDeclared = nullptr;
614 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
615 if (!ClassDeclared->getSuperClass()
616 && (*ClassDeclared->ivar_begin()) == IV) {
617 if (RHS) {
618 NamedDecl *ObjectSetClass =
620 &S.Context.Idents.get("object_setClass"),
622 if (ObjectSetClass) {
623 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
624 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
626 "object_setClass(")
628 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
629 << FixItHint::CreateInsertion(RHSLocEnd, ")");
630 }
631 else
632 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
633 } else {
634 NamedDecl *ObjectGetClass =
636 &S.Context.Idents.get("object_getClass"),
638 if (ObjectGetClass)
639 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
641 "object_getClass(")
643 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
644 else
645 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
646 }
647 S.Diag(IV->getLocation(), diag::note_ivar_decl);
648 }
649 }
650}
651
653 // Handle any placeholder expressions which made it here.
654 if (E->hasPlaceholderType()) {
656 if (result.isInvalid()) return ExprError();
657 E = result.get();
658 }
659
660 // C++ [conv.lval]p1:
661 // A glvalue of a non-function, non-array type T can be
662 // converted to a prvalue.
663 if (!E->isGLValue()) return E;
664
665 QualType T = E->getType();
666 assert(!T.isNull() && "r-value conversion on typeless expression?");
667
668 // lvalue-to-rvalue conversion cannot be applied to types that decay to
669 // pointers (i.e. function or array types).
671 return E;
672
673 // We don't want to throw lvalue-to-rvalue casts on top of
674 // expressions of certain types in C++.
675 if (getLangOpts().CPlusPlus) {
676 if (T == Context.OverloadTy || T->isRecordType() ||
677 (T->isDependentType() && !T->isAnyPointerType() &&
679 return E;
680 }
681
682 // The C standard is actually really unclear on this point, and
683 // DR106 tells us what the result should be but not why. It's
684 // generally best to say that void types just doesn't undergo
685 // lvalue-to-rvalue at all. Note that expressions of unqualified
686 // 'void' type are never l-values, but qualified void can be.
687 if (T->isVoidType())
688 return E;
689
690 // OpenCL usually rejects direct accesses to values of 'half' type.
691 if (getLangOpts().OpenCL &&
692 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
693 T->isHalfType()) {
694 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
695 << 0 << T;
696 return ExprError();
697 }
698
700 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
701 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
702 &Context.Idents.get("object_getClass"),
704 if (ObjectGetClass)
705 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
706 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
708 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
709 else
710 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
711 }
712 else if (const ObjCIvarRefExpr *OIRE =
713 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
714 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
715
716 // C++ [conv.lval]p1:
717 // [...] If T is a non-class type, the type of the prvalue is the
718 // cv-unqualified version of T. Otherwise, the type of the
719 // rvalue is T.
720 //
721 // C99 6.3.2.1p2:
722 // If the lvalue has qualified type, the value has the unqualified
723 // version of the type of the lvalue; otherwise, the value has the
724 // type of the lvalue.
725 if (T.hasQualifiers())
726 T = T.getUnqualifiedType();
727
728 // Under the MS ABI, lock down the inheritance model now.
729 if (T->isMemberPointerType() &&
731 (void)isCompleteType(E->getExprLoc(), T);
732
734 if (Res.isInvalid())
735 return Res;
736 E = Res.get();
737
738 // Loading a __weak object implicitly retains the value, so we need a cleanup to
739 // balance that.
742
745
746 // C++ [conv.lval]p3:
747 // If T is cv std::nullptr_t, the result is a null pointer constant.
748 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
749 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
751
752 // C11 6.3.2.1p2:
753 // ... if the lvalue has atomic type, the value has the non-atomic version
754 // of the type of the lvalue ...
755 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
756 T = Atomic->getValueType().getUnqualifiedType();
757 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
758 nullptr, VK_PRValue, FPOptionsOverride());
759 }
760
761 return Res;
762}
763
766 if (Res.isInvalid())
767 return ExprError();
768 Res = DefaultLvalueConversion(Res.get());
769 if (Res.isInvalid())
770 return ExprError();
771 return Res;
772}
773
774/// CallExprUnaryConversions - a special case of an unary conversion
775/// performed on a function designator of a call expression.
777 QualType Ty = E->getType();
778 ExprResult Res = E;
779 // Only do implicit cast for a function type, but not for a pointer
780 // to function type.
781 if (Ty->isFunctionType()) {
783 CK_FunctionToPointerDecay);
784 if (Res.isInvalid())
785 return ExprError();
786 }
787 Res = DefaultLvalueConversion(Res.get());
788 if (Res.isInvalid())
789 return ExprError();
790 return Res.get();
791}
792
793/// UsualUnaryConversions - Performs various conversions that are common to most
794/// operators (C99 6.3). The conversions of array and function types are
795/// sometimes suppressed. For example, the array->pointer conversion doesn't
796/// apply if the array is an argument to the sizeof or address (&) operators.
797/// In these instances, this routine should *not* be called.
799 // First, convert to an r-value.
801 if (Res.isInvalid())
802 return ExprError();
803 E = Res.get();
804
805 QualType Ty = E->getType();
806 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
807
808 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
809 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
810 (getLangOpts().getFPEvalMethod() !=
813 switch (EvalMethod) {
814 default:
815 llvm_unreachable("Unrecognized float evaluation method");
816 break;
818 llvm_unreachable("Float evaluation method should be set by now");
819 break;
822 // Widen the expression to double.
823 return Ty->isComplexType()
826 CK_FloatingComplexCast)
827 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
828 break;
831 // Widen the expression to long double.
832 return Ty->isComplexType()
835 CK_FloatingComplexCast)
837 CK_FloatingCast);
838 break;
839 }
840 }
841
842 // Half FP have to be promoted to float unless it is natively supported
843 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
844 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
845
846 // Try to perform integral promotions if the object has a theoretically
847 // promotable type.
849 // C99 6.3.1.1p2:
850 //
851 // The following may be used in an expression wherever an int or
852 // unsigned int may be used:
853 // - an object or expression with an integer type whose integer
854 // conversion rank is less than or equal to the rank of int
855 // and unsigned int.
856 // - A bit-field of type _Bool, int, signed int, or unsigned int.
857 //
858 // If an int can represent all values of the original type, the
859 // value is converted to an int; otherwise, it is converted to an
860 // unsigned int. These are called the integer promotions. All
861 // other types are unchanged by the integer promotions.
862
864 if (!PTy.isNull()) {
865 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
866 return E;
867 }
870 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
871 return E;
872 }
873 }
874 return E;
875}
876
877/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
878/// do not have a prototype. Arguments that have type float or __fp16
879/// are promoted to double. All other argument types are converted by
880/// UsualUnaryConversions().
882 QualType Ty = E->getType();
883 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
884
886 if (Res.isInvalid())
887 return ExprError();
888 E = Res.get();
889
890 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
891 // promote to double.
892 // Note that default argument promotion applies only to float (and
893 // half/fp16); it does not apply to _Float16.
894 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
895 if (BTy && (BTy->getKind() == BuiltinType::Half ||
896 BTy->getKind() == BuiltinType::Float)) {
897 if (getLangOpts().OpenCL &&
898 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
899 if (BTy->getKind() == BuiltinType::Half) {
900 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
901 }
902 } else {
903 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
904 }
905 }
906 if (BTy &&
907 getLangOpts().getExtendIntArgs() ==
912 E = (Ty->isUnsignedIntegerType())
913 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
914 .get()
915 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
917 "Unexpected typesize for LongLongTy");
918 }
919
920 // C++ performs lvalue-to-rvalue conversion as a default argument
921 // promotion, even on class types, but note:
922 // C++11 [conv.lval]p2:
923 // When an lvalue-to-rvalue conversion occurs in an unevaluated
924 // operand or a subexpression thereof the value contained in the
925 // referenced object is not accessed. Otherwise, if the glvalue
926 // has a class type, the conversion copy-initializes a temporary
927 // of type T from the glvalue and the result of the conversion
928 // is a prvalue for the temporary.
929 // FIXME: add some way to gate this entire thing for correctness in
930 // potentially potentially evaluated contexts.
934 E->getExprLoc(), E);
935 if (Temp.isInvalid())
936 return ExprError();
937 E = Temp.get();
938 }
939
940 return E;
941}
942
943/// Determine the degree of POD-ness for an expression.
944/// Incomplete types are considered POD, since this check can be performed
945/// when we're in an unevaluated context.
947 if (Ty->isIncompleteType()) {
948 // C++11 [expr.call]p7:
949 // After these conversions, if the argument does not have arithmetic,
950 // enumeration, pointer, pointer to member, or class type, the program
951 // is ill-formed.
952 //
953 // Since we've already performed array-to-pointer and function-to-pointer
954 // decay, the only such type in C++ is cv void. This also handles
955 // initializer lists as variadic arguments.
956 if (Ty->isVoidType())
957 return VAK_Invalid;
958
959 if (Ty->isObjCObjectType())
960 return VAK_Invalid;
961 return VAK_Valid;
962 }
963
965 return VAK_Invalid;
966
967 if (Context.getTargetInfo().getTriple().isWasm() &&
969 return VAK_Invalid;
970 }
971
972 if (Ty.isCXX98PODType(Context))
973 return VAK_Valid;
974
975 // C++11 [expr.call]p7:
976 // Passing a potentially-evaluated argument of class type (Clause 9)
977 // having a non-trivial copy constructor, a non-trivial move constructor,
978 // or a non-trivial destructor, with no corresponding parameter,
979 // is conditionally-supported with implementation-defined semantics.
982 if (!Record->hasNonTrivialCopyConstructor() &&
983 !Record->hasNonTrivialMoveConstructor() &&
984 !Record->hasNonTrivialDestructor())
985 return VAK_ValidInCXX11;
986
987 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
988 return VAK_Valid;
989
990 if (Ty->isObjCObjectType())
991 return VAK_Invalid;
992
993 if (getLangOpts().MSVCCompat)
994 return VAK_MSVCUndefined;
995
996 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
997 // permitted to reject them. We should consider doing so.
998 return VAK_Undefined;
999}
1000
1002 // Don't allow one to pass an Objective-C interface to a vararg.
1003 const QualType &Ty = E->getType();
1004 VarArgKind VAK = isValidVarArgType(Ty);
1005
1006 // Complain about passing non-POD types through varargs.
1007 switch (VAK) {
1008 case VAK_ValidInCXX11:
1010 E->getBeginLoc(), nullptr,
1011 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1012 [[fallthrough]];
1013 case VAK_Valid:
1014 if (Ty->isRecordType()) {
1015 // This is unlikely to be what the user intended. If the class has a
1016 // 'c_str' member function, the user probably meant to call that.
1017 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1018 PDiag(diag::warn_pass_class_arg_to_vararg)
1019 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1020 }
1021 break;
1022
1023 case VAK_Undefined:
1024 case VAK_MSVCUndefined:
1025 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1026 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1027 << getLangOpts().CPlusPlus11 << Ty << CT);
1028 break;
1029
1030 case VAK_Invalid:
1032 Diag(E->getBeginLoc(),
1033 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1034 << Ty << CT;
1035 else if (Ty->isObjCObjectType())
1036 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1037 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1038 << Ty << CT);
1039 else
1040 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1041 << isa<InitListExpr>(E) << Ty << CT;
1042 break;
1043 }
1044}
1045
1046/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1047/// will create a trap if the resulting type is not a POD type.
1049 FunctionDecl *FDecl) {
1050 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1051 // Strip the unbridged-cast placeholder expression off, if applicable.
1052 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1053 (CT == VariadicMethod ||
1054 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1055 E = ObjC().stripARCUnbridgedCast(E);
1056
1057 // Otherwise, do normal placeholder checking.
1058 } else {
1059 ExprResult ExprRes = CheckPlaceholderExpr(E);
1060 if (ExprRes.isInvalid())
1061 return ExprError();
1062 E = ExprRes.get();
1063 }
1064 }
1065
1067 if (ExprRes.isInvalid())
1068 return ExprError();
1069
1070 // Copy blocks to the heap.
1071 if (ExprRes.get()->getType()->isBlockPointerType())
1072 maybeExtendBlockObject(ExprRes);
1073
1074 E = ExprRes.get();
1075
1076 // Diagnostics regarding non-POD argument types are
1077 // emitted along with format string checking in Sema::CheckFunctionCall().
1079 // Turn this into a trap.
1080 CXXScopeSpec SS;
1081 SourceLocation TemplateKWLoc;
1082 UnqualifiedId Name;
1083 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1084 E->getBeginLoc());
1085 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1086 /*HasTrailingLParen=*/true,
1087 /*IsAddressOfOperand=*/false);
1088 if (TrapFn.isInvalid())
1089 return ExprError();
1090
1092 std::nullopt, E->getEndLoc());
1093 if (Call.isInvalid())
1094 return ExprError();
1095
1096 ExprResult Comma =
1097 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1098 if (Comma.isInvalid())
1099 return ExprError();
1100 return Comma.get();
1101 }
1102
1103 if (!getLangOpts().CPlusPlus &&
1105 diag::err_call_incomplete_argument))
1106 return ExprError();
1107
1108 return E;
1109}
1110
1111/// Convert complex integers to complex floats and real integers to
1112/// real floats as required for complex arithmetic. Helper function of
1113/// UsualArithmeticConversions()
1114///
1115/// \return false if the integer expression is an integer type and is
1116/// successfully converted to the (complex) float type.
1118 ExprResult &ComplexExpr,
1119 QualType IntTy,
1120 QualType ComplexTy,
1121 bool SkipCast) {
1122 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1123 if (SkipCast) return false;
1124 if (IntTy->isIntegerType()) {
1125 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1126 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1127 } else {
1128 assert(IntTy->isComplexIntegerType());
1129 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1130 CK_IntegralComplexToFloatingComplex);
1131 }
1132 return false;
1133}
1134
1135// This handles complex/complex, complex/float, or float/complex.
1136// When both operands are complex, the shorter operand is converted to the
1137// type of the longer, and that is the type of the result. This corresponds
1138// to what is done when combining two real floating-point operands.
1139// The fun begins when size promotion occur across type domains.
1140// From H&S 6.3.4: When one operand is complex and the other is a real
1141// floating-point type, the less precise type is converted, within it's
1142// real or complex domain, to the precision of the other type. For example,
1143// when combining a "long double" with a "double _Complex", the
1144// "double _Complex" is promoted to "long double _Complex".
1146 QualType ShorterType,
1147 QualType LongerType,
1148 bool PromotePrecision) {
1149 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1151 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1152
1153 if (PromotePrecision) {
1154 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1155 Shorter =
1156 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1157 } else {
1158 if (LongerIsComplex)
1159 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1160 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1161 }
1162 }
1163 return Result;
1164}
1165
1166/// Handle arithmetic conversion with complex types. Helper function of
1167/// UsualArithmeticConversions()
1169 ExprResult &RHS, QualType LHSType,
1170 QualType RHSType, bool IsCompAssign) {
1171 // Handle (complex) integer types.
1172 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1173 /*SkipCast=*/false))
1174 return LHSType;
1175 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1176 /*SkipCast=*/IsCompAssign))
1177 return RHSType;
1178
1179 // Compute the rank of the two types, regardless of whether they are complex.
1180 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1181 if (Order < 0)
1182 // Promote the precision of the LHS if not an assignment.
1183 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1184 /*PromotePrecision=*/!IsCompAssign);
1185 // Promote the precision of the RHS unless it is already the same as the LHS.
1186 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1187 /*PromotePrecision=*/Order > 0);
1188}
1189
1190/// Handle arithmetic conversion from integer to float. Helper function
1191/// of UsualArithmeticConversions()
1193 ExprResult &IntExpr,
1194 QualType FloatTy, QualType IntTy,
1195 bool ConvertFloat, bool ConvertInt) {
1196 if (IntTy->isIntegerType()) {
1197 if (ConvertInt)
1198 // Convert intExpr to the lhs floating point type.
1199 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1200 CK_IntegralToFloating);
1201 return FloatTy;
1202 }
1203
1204 // Convert both sides to the appropriate complex float.
1205 assert(IntTy->isComplexIntegerType());
1206 QualType result = S.Context.getComplexType(FloatTy);
1207
1208 // _Complex int -> _Complex float
1209 if (ConvertInt)
1210 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1211 CK_IntegralComplexToFloatingComplex);
1212
1213 // float -> _Complex float
1214 if (ConvertFloat)
1215 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1216 CK_FloatingRealToComplex);
1217
1218 return result;
1219}
1220
1221/// Handle arithmethic conversion with floating point types. Helper
1222/// function of UsualArithmeticConversions()
1224 ExprResult &RHS, QualType LHSType,
1225 QualType RHSType, bool IsCompAssign) {
1226 bool LHSFloat = LHSType->isRealFloatingType();
1227 bool RHSFloat = RHSType->isRealFloatingType();
1228
1229 // N1169 4.1.4: If one of the operands has a floating type and the other
1230 // operand has a fixed-point type, the fixed-point operand
1231 // is converted to the floating type [...]
1232 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1233 if (LHSFloat)
1234 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1235 else if (!IsCompAssign)
1236 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1237 return LHSFloat ? LHSType : RHSType;
1238 }
1239
1240 // If we have two real floating types, convert the smaller operand
1241 // to the bigger result.
1242 if (LHSFloat && RHSFloat) {
1243 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1244 if (order > 0) {
1245 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1246 return LHSType;
1247 }
1248
1249 assert(order < 0 && "illegal float comparison");
1250 if (!IsCompAssign)
1251 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1252 return RHSType;
1253 }
1254
1255 if (LHSFloat) {
1256 // Half FP has to be promoted to float unless it is natively supported
1257 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1258 LHSType = S.Context.FloatTy;
1259
1260 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1261 /*ConvertFloat=*/!IsCompAssign,
1262 /*ConvertInt=*/ true);
1263 }
1264 assert(RHSFloat);
1265 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1266 /*ConvertFloat=*/ true,
1267 /*ConvertInt=*/!IsCompAssign);
1268}
1269
1270/// Diagnose attempts to convert between __float128, __ibm128 and
1271/// long double if there is no support for such conversion.
1272/// Helper function of UsualArithmeticConversions().
1273static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1274 QualType RHSType) {
1275 // No issue if either is not a floating point type.
1276 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1277 return false;
1278
1279 // No issue if both have the same 128-bit float semantics.
1280 auto *LHSComplex = LHSType->getAs<ComplexType>();
1281 auto *RHSComplex = RHSType->getAs<ComplexType>();
1282
1283 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1284 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1285
1286 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1287 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1288
1289 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1290 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1291 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1292 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1293 return false;
1294
1295 return true;
1296}
1297
1298typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1299
1300namespace {
1301/// These helper callbacks are placed in an anonymous namespace to
1302/// permit their use as function template parameters.
1303ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1304 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1305}
1306
1307ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1308 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1309 CK_IntegralComplexCast);
1310}
1311}
1312
1313/// Handle integer arithmetic conversions. Helper function of
1314/// UsualArithmeticConversions()
1315template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1317 ExprResult &RHS, QualType LHSType,
1318 QualType RHSType, bool IsCompAssign) {
1319 // The rules for this case are in C99 6.3.1.8
1320 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1321 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1322 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1323 if (LHSSigned == RHSSigned) {
1324 // Same signedness; use the higher-ranked type
1325 if (order >= 0) {
1326 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1327 return LHSType;
1328 } else if (!IsCompAssign)
1329 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1330 return RHSType;
1331 } else if (order != (LHSSigned ? 1 : -1)) {
1332 // The unsigned type has greater than or equal rank to the
1333 // signed type, so use the unsigned type
1334 if (RHSSigned) {
1335 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1336 return LHSType;
1337 } else if (!IsCompAssign)
1338 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1339 return RHSType;
1340 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1341 // The two types are different widths; if we are here, that
1342 // means the signed type is larger than the unsigned type, so
1343 // use the signed type.
1344 if (LHSSigned) {
1345 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1346 return LHSType;
1347 } else if (!IsCompAssign)
1348 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1349 return RHSType;
1350 } else {
1351 // The signed type is higher-ranked than the unsigned type,
1352 // but isn't actually any bigger (like unsigned int and long
1353 // on most 32-bit systems). Use the unsigned type corresponding
1354 // to the signed type.
1355 QualType result =
1356 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1357 RHS = (*doRHSCast)(S, RHS.get(), result);
1358 if (!IsCompAssign)
1359 LHS = (*doLHSCast)(S, LHS.get(), result);
1360 return result;
1361 }
1362}
1363
1364/// Handle conversions with GCC complex int extension. Helper function
1365/// of UsualArithmeticConversions()
1367 ExprResult &RHS, QualType LHSType,
1368 QualType RHSType,
1369 bool IsCompAssign) {
1370 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1371 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1372
1373 if (LHSComplexInt && RHSComplexInt) {
1374 QualType LHSEltType = LHSComplexInt->getElementType();
1375 QualType RHSEltType = RHSComplexInt->getElementType();
1376 QualType ScalarType =
1377 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1378 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1379
1380 return S.Context.getComplexType(ScalarType);
1381 }
1382
1383 if (LHSComplexInt) {
1384 QualType LHSEltType = LHSComplexInt->getElementType();
1385 QualType ScalarType =
1386 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1387 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1389 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1390 CK_IntegralRealToComplex);
1391
1392 return ComplexType;
1393 }
1394
1395 assert(RHSComplexInt);
1396
1397 QualType RHSEltType = RHSComplexInt->getElementType();
1398 QualType ScalarType =
1399 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1400 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1402
1403 if (!IsCompAssign)
1404 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1405 CK_IntegralRealToComplex);
1406 return ComplexType;
1407}
1408
1409/// Return the rank of a given fixed point or integer type. The value itself
1410/// doesn't matter, but the values must be increasing with proper increasing
1411/// rank as described in N1169 4.1.1.
1412static unsigned GetFixedPointRank(QualType Ty) {
1413 const auto *BTy = Ty->getAs<BuiltinType>();
1414 assert(BTy && "Expected a builtin type.");
1415
1416 switch (BTy->getKind()) {
1417 case BuiltinType::ShortFract:
1418 case BuiltinType::UShortFract:
1419 case BuiltinType::SatShortFract:
1420 case BuiltinType::SatUShortFract:
1421 return 1;
1422 case BuiltinType::Fract:
1423 case BuiltinType::UFract:
1424 case BuiltinType::SatFract:
1425 case BuiltinType::SatUFract:
1426 return 2;
1427 case BuiltinType::LongFract:
1428 case BuiltinType::ULongFract:
1429 case BuiltinType::SatLongFract:
1430 case BuiltinType::SatULongFract:
1431 return 3;
1432 case BuiltinType::ShortAccum:
1433 case BuiltinType::UShortAccum:
1434 case BuiltinType::SatShortAccum:
1435 case BuiltinType::SatUShortAccum:
1436 return 4;
1437 case BuiltinType::Accum:
1438 case BuiltinType::UAccum:
1439 case BuiltinType::SatAccum:
1440 case BuiltinType::SatUAccum:
1441 return 5;
1442 case BuiltinType::LongAccum:
1443 case BuiltinType::ULongAccum:
1444 case BuiltinType::SatLongAccum:
1445 case BuiltinType::SatULongAccum:
1446 return 6;
1447 default:
1448 if (BTy->isInteger())
1449 return 0;
1450 llvm_unreachable("Unexpected fixed point or integer type");
1451 }
1452}
1453
1454/// handleFixedPointConversion - Fixed point operations between fixed
1455/// point types and integers or other fixed point types do not fall under
1456/// usual arithmetic conversion since these conversions could result in loss
1457/// of precsision (N1169 4.1.4). These operations should be calculated with
1458/// the full precision of their result type (N1169 4.1.6.2.1).
1460 QualType RHSTy) {
1461 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1462 "Expected at least one of the operands to be a fixed point type");
1463 assert((LHSTy->isFixedPointOrIntegerType() ||
1464 RHSTy->isFixedPointOrIntegerType()) &&
1465 "Special fixed point arithmetic operation conversions are only "
1466 "applied to ints or other fixed point types");
1467
1468 // If one operand has signed fixed-point type and the other operand has
1469 // unsigned fixed-point type, then the unsigned fixed-point operand is
1470 // converted to its corresponding signed fixed-point type and the resulting
1471 // type is the type of the converted operand.
1472 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1474 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1476
1477 // The result type is the type with the highest rank, whereby a fixed-point
1478 // conversion rank is always greater than an integer conversion rank; if the
1479 // type of either of the operands is a saturating fixedpoint type, the result
1480 // type shall be the saturating fixed-point type corresponding to the type
1481 // with the highest rank; the resulting value is converted (taking into
1482 // account rounding and overflow) to the precision of the resulting type.
1483 // Same ranks between signed and unsigned types are resolved earlier, so both
1484 // types are either signed or both unsigned at this point.
1485 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1486 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1487
1488 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1489
1491 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1492
1493 return ResultTy;
1494}
1495
1496/// Check that the usual arithmetic conversions can be performed on this pair of
1497/// expressions that might be of enumeration type.
1500 Sema::ArithConvKind ACK) {
1501 // C++2a [expr.arith.conv]p1:
1502 // If one operand is of enumeration type and the other operand is of a
1503 // different enumeration type or a floating-point type, this behavior is
1504 // deprecated ([depr.arith.conv.enum]).
1505 //
1506 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1507 // Eventually we will presumably reject these cases (in C++23 onwards?).
1509 R = RHS->getEnumCoercedType(S.Context);
1510 bool LEnum = L->isUnscopedEnumerationType(),
1511 REnum = R->isUnscopedEnumerationType();
1512 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1513 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1514 (REnum && L->isFloatingType())) {
1515 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1516 ? diag::err_arith_conv_enum_float_cxx26
1517 : S.getLangOpts().CPlusPlus20
1518 ? diag::warn_arith_conv_enum_float_cxx20
1519 : diag::warn_arith_conv_enum_float)
1520 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1521 << L << R;
1522 } else if (!IsCompAssign && LEnum && REnum &&
1524 unsigned DiagID;
1525 // In C++ 26, usual arithmetic conversions between 2 different enum types
1526 // are ill-formed.
1527 if (S.getLangOpts().CPlusPlus26)
1528 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1529 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1530 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1531 // If either enumeration type is unnamed, it's less likely that the
1532 // user cares about this, but this situation is still deprecated in
1533 // C++2a. Use a different warning group.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1536 : diag::warn_arith_conv_mixed_anon_enum_types;
1537 } else if (ACK == Sema::ACK_Conditional) {
1538 // Conditional expressions are separated out because they have
1539 // historically had a different warning flag.
1540 DiagID = S.getLangOpts().CPlusPlus20
1541 ? diag::warn_conditional_mixed_enum_types_cxx20
1542 : diag::warn_conditional_mixed_enum_types;
1543 } else if (ACK == Sema::ACK_Comparison) {
1544 // Comparison expressions are separated out because they have
1545 // historically had a different warning flag.
1546 DiagID = S.getLangOpts().CPlusPlus20
1547 ? diag::warn_comparison_mixed_enum_types_cxx20
1548 : diag::warn_comparison_mixed_enum_types;
1549 } else {
1550 DiagID = S.getLangOpts().CPlusPlus20
1551 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1552 : diag::warn_arith_conv_mixed_enum_types;
1553 }
1554 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1555 << (int)ACK << L << R;
1556 }
1557}
1558
1559/// UsualArithmeticConversions - Performs various conversions that are common to
1560/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1561/// routine returns the first non-arithmetic type found. The client is
1562/// responsible for emitting appropriate error diagnostics.
1565 ArithConvKind ACK) {
1566 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1567
1568 if (ACK != ACK_CompAssign) {
1569 LHS = UsualUnaryConversions(LHS.get());
1570 if (LHS.isInvalid())
1571 return QualType();
1572 }
1573
1574 RHS = UsualUnaryConversions(RHS.get());
1575 if (RHS.isInvalid())
1576 return QualType();
1577
1578 // For conversion purposes, we ignore any qualifiers.
1579 // For example, "const float" and "float" are equivalent.
1580 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1581 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1582
1583 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1584 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1585 LHSType = AtomicLHS->getValueType();
1586
1587 // If both types are identical, no conversion is needed.
1588 if (Context.hasSameType(LHSType, RHSType))
1589 return Context.getCommonSugaredType(LHSType, RHSType);
1590
1591 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1592 // The caller can deal with this (e.g. pointer + int).
1593 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1594 return QualType();
1595
1596 // Apply unary and bitfield promotions to the LHS's type.
1597 QualType LHSUnpromotedType = LHSType;
1598 if (Context.isPromotableIntegerType(LHSType))
1599 LHSType = Context.getPromotedIntegerType(LHSType);
1600 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1601 if (!LHSBitfieldPromoteTy.isNull())
1602 LHSType = LHSBitfieldPromoteTy;
1603 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1604 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1605
1606 // If both types are identical, no conversion is needed.
1607 if (Context.hasSameType(LHSType, RHSType))
1608 return Context.getCommonSugaredType(LHSType, RHSType);
1609
1610 // At this point, we have two different arithmetic types.
1611
1612 // Diagnose attempts to convert between __ibm128, __float128 and long double
1613 // where such conversions currently can't be handled.
1614 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1615 return QualType();
1616
1617 // Handle complex types first (C99 6.3.1.8p1).
1618 if (LHSType->isComplexType() || RHSType->isComplexType())
1619 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1620 ACK == ACK_CompAssign);
1621
1622 // Now handle "real" floating types (i.e. float, double, long double).
1623 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1624 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1625 ACK == ACK_CompAssign);
1626
1627 // Handle GCC complex int extension.
1628 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1629 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1630 ACK == ACK_CompAssign);
1631
1632 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1633 return handleFixedPointConversion(*this, LHSType, RHSType);
1634
1635 // Finally, we have two differing integer types.
1636 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1637 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1638}
1639
1640//===----------------------------------------------------------------------===//
1641// Semantic Analysis for various Expression Types
1642//===----------------------------------------------------------------------===//
1643
1644
1646 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1647 bool PredicateIsExpr, void *ControllingExprOrType,
1648 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1649 unsigned NumAssocs = ArgTypes.size();
1650 assert(NumAssocs == ArgExprs.size());
1651
1652 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1653 for (unsigned i = 0; i < NumAssocs; ++i) {
1654 if (ArgTypes[i])
1655 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1656 else
1657 Types[i] = nullptr;
1658 }
1659
1660 // If we have a controlling type, we need to convert it from a parsed type
1661 // into a semantic type and then pass that along.
1662 if (!PredicateIsExpr) {
1663 TypeSourceInfo *ControllingType;
1664 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1665 &ControllingType);
1666 assert(ControllingType && "couldn't get the type out of the parser");
1667 ControllingExprOrType = ControllingType;
1668 }
1669
1671 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1672 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1673 delete [] Types;
1674 return ER;
1675}
1676
1678 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1679 bool PredicateIsExpr, void *ControllingExprOrType,
1681 unsigned NumAssocs = Types.size();
1682 assert(NumAssocs == Exprs.size());
1683 assert(ControllingExprOrType &&
1684 "Must have either a controlling expression or a controlling type");
1685
1686 Expr *ControllingExpr = nullptr;
1687 TypeSourceInfo *ControllingType = nullptr;
1688 if (PredicateIsExpr) {
1689 // Decay and strip qualifiers for the controlling expression type, and
1690 // handle placeholder type replacement. See committee discussion from WG14
1691 // DR423.
1695 reinterpret_cast<Expr *>(ControllingExprOrType));
1696 if (R.isInvalid())
1697 return ExprError();
1698 ControllingExpr = R.get();
1699 } else {
1700 // The extension form uses the type directly rather than converting it.
1701 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1702 if (!ControllingType)
1703 return ExprError();
1704 }
1705
1706 bool TypeErrorFound = false,
1707 IsResultDependent = ControllingExpr
1708 ? ControllingExpr->isTypeDependent()
1709 : ControllingType->getType()->isDependentType(),
1710 ContainsUnexpandedParameterPack =
1711 ControllingExpr
1712 ? ControllingExpr->containsUnexpandedParameterPack()
1713 : ControllingType->getType()->containsUnexpandedParameterPack();
1714
1715 // The controlling expression is an unevaluated operand, so side effects are
1716 // likely unintended.
1717 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1718 ControllingExpr->HasSideEffects(Context, false))
1719 Diag(ControllingExpr->getExprLoc(),
1720 diag::warn_side_effects_unevaluated_context);
1721
1722 for (unsigned i = 0; i < NumAssocs; ++i) {
1723 if (Exprs[i]->containsUnexpandedParameterPack())
1724 ContainsUnexpandedParameterPack = true;
1725
1726 if (Types[i]) {
1727 if (Types[i]->getType()->containsUnexpandedParameterPack())
1728 ContainsUnexpandedParameterPack = true;
1729
1730 if (Types[i]->getType()->isDependentType()) {
1731 IsResultDependent = true;
1732 } else {
1733 // We relax the restriction on use of incomplete types and non-object
1734 // types with the type-based extension of _Generic. Allowing incomplete
1735 // objects means those can be used as "tags" for a type-safe way to map
1736 // to a value. Similarly, matching on function types rather than
1737 // function pointer types can be useful. However, the restriction on VM
1738 // types makes sense to retain as there are open questions about how
1739 // the selection can be made at compile time.
1740 //
1741 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1742 // complete object type other than a variably modified type."
1743 unsigned D = 0;
1744 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1745 D = diag::err_assoc_type_incomplete;
1746 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1747 D = diag::err_assoc_type_nonobject;
1748 else if (Types[i]->getType()->isVariablyModifiedType())
1749 D = diag::err_assoc_type_variably_modified;
1750 else if (ControllingExpr) {
1751 // Because the controlling expression undergoes lvalue conversion,
1752 // array conversion, and function conversion, an association which is
1753 // of array type, function type, or is qualified can never be
1754 // reached. We will warn about this so users are less surprised by
1755 // the unreachable association. However, we don't have to handle
1756 // function types; that's not an object type, so it's handled above.
1757 //
1758 // The logic is somewhat different for C++ because C++ has different
1759 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1760 // If T is a non-class type, the type of the prvalue is the cv-
1761 // unqualified version of T. Otherwise, the type of the prvalue is T.
1762 // The result of these rules is that all qualified types in an
1763 // association in C are unreachable, and in C++, only qualified non-
1764 // class types are unreachable.
1765 //
1766 // NB: this does not apply when the first operand is a type rather
1767 // than an expression, because the type form does not undergo
1768 // conversion.
1769 unsigned Reason = 0;
1770 QualType QT = Types[i]->getType();
1771 if (QT->isArrayType())
1772 Reason = 1;
1773 else if (QT.hasQualifiers() &&
1774 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1775 Reason = 2;
1776
1777 if (Reason)
1778 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1779 diag::warn_unreachable_association)
1780 << QT << (Reason - 1);
1781 }
1782
1783 if (D != 0) {
1784 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1785 << Types[i]->getTypeLoc().getSourceRange()
1786 << Types[i]->getType();
1787 TypeErrorFound = true;
1788 }
1789
1790 // C11 6.5.1.1p2 "No two generic associations in the same generic
1791 // selection shall specify compatible types."
1792 for (unsigned j = i+1; j < NumAssocs; ++j)
1793 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1794 Context.typesAreCompatible(Types[i]->getType(),
1795 Types[j]->getType())) {
1796 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1797 diag::err_assoc_compatible_types)
1798 << Types[j]->getTypeLoc().getSourceRange()
1799 << Types[j]->getType()
1800 << Types[i]->getType();
1801 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1802 diag::note_compat_assoc)
1803 << Types[i]->getTypeLoc().getSourceRange()
1804 << Types[i]->getType();
1805 TypeErrorFound = true;
1806 }
1807 }
1808 }
1809 }
1810 if (TypeErrorFound)
1811 return ExprError();
1812
1813 // If we determined that the generic selection is result-dependent, don't
1814 // try to compute the result expression.
1815 if (IsResultDependent) {
1816 if (ControllingExpr)
1817 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1818 Types, Exprs, DefaultLoc, RParenLoc,
1819 ContainsUnexpandedParameterPack);
1820 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1821 Exprs, DefaultLoc, RParenLoc,
1822 ContainsUnexpandedParameterPack);
1823 }
1824
1825 SmallVector<unsigned, 1> CompatIndices;
1826 unsigned DefaultIndex = -1U;
1827 // Look at the canonical type of the controlling expression in case it was a
1828 // deduced type like __auto_type. However, when issuing diagnostics, use the
1829 // type the user wrote in source rather than the canonical one.
1830 for (unsigned i = 0; i < NumAssocs; ++i) {
1831 if (!Types[i])
1832 DefaultIndex = i;
1833 else if (ControllingExpr &&
1835 ControllingExpr->getType().getCanonicalType(),
1836 Types[i]->getType()))
1837 CompatIndices.push_back(i);
1838 else if (ControllingType &&
1840 ControllingType->getType().getCanonicalType(),
1841 Types[i]->getType()))
1842 CompatIndices.push_back(i);
1843 }
1844
1845 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1846 TypeSourceInfo *ControllingType) {
1847 // We strip parens here because the controlling expression is typically
1848 // parenthesized in macro definitions.
1849 if (ControllingExpr)
1850 ControllingExpr = ControllingExpr->IgnoreParens();
1851
1852 SourceRange SR = ControllingExpr
1853 ? ControllingExpr->getSourceRange()
1854 : ControllingType->getTypeLoc().getSourceRange();
1855 QualType QT = ControllingExpr ? ControllingExpr->getType()
1856 : ControllingType->getType();
1857
1858 return std::make_pair(SR, QT);
1859 };
1860
1861 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1862 // type compatible with at most one of the types named in its generic
1863 // association list."
1864 if (CompatIndices.size() > 1) {
1865 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1866 SourceRange SR = P.first;
1867 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1868 << SR << P.second << (unsigned)CompatIndices.size();
1869 for (unsigned I : CompatIndices) {
1870 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1871 diag::note_compat_assoc)
1872 << Types[I]->getTypeLoc().getSourceRange()
1873 << Types[I]->getType();
1874 }
1875 return ExprError();
1876 }
1877
1878 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1879 // its controlling expression shall have type compatible with exactly one of
1880 // the types named in its generic association list."
1881 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1882 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1883 SourceRange SR = P.first;
1884 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1885 return ExprError();
1886 }
1887
1888 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1889 // type name that is compatible with the type of the controlling expression,
1890 // then the result expression of the generic selection is the expression
1891 // in that generic association. Otherwise, the result expression of the
1892 // generic selection is the expression in the default generic association."
1893 unsigned ResultIndex =
1894 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1895
1896 if (ControllingExpr) {
1898 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1899 ContainsUnexpandedParameterPack, ResultIndex);
1900 }
1902 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1903 ContainsUnexpandedParameterPack, ResultIndex);
1904}
1905
1907 switch (Kind) {
1908 default:
1909 llvm_unreachable("unexpected TokenKind");
1910 case tok::kw___func__:
1911 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1912 case tok::kw___FUNCTION__:
1914 case tok::kw___FUNCDNAME__:
1915 return PredefinedIdentKind::FuncDName; // [MS]
1916 case tok::kw___FUNCSIG__:
1917 return PredefinedIdentKind::FuncSig; // [MS]
1918 case tok::kw_L__FUNCTION__:
1919 return PredefinedIdentKind::LFunction; // [MS]
1920 case tok::kw_L__FUNCSIG__:
1921 return PredefinedIdentKind::LFuncSig; // [MS]
1922 case tok::kw___PRETTY_FUNCTION__:
1924 }
1925}
1926
1927/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1928/// to determine the value of a PredefinedExpr. This can be either a
1929/// block, lambda, captured statement, function, otherwise a nullptr.
1931 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1932 DC = DC->getParent();
1933 return cast_or_null<Decl>(DC);
1934}
1935
1936/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1937/// location of the token and the offset of the ud-suffix within it.
1939 unsigned Offset) {
1940 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1941 S.getLangOpts());
1942}
1943
1944/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1945/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1947 IdentifierInfo *UDSuffix,
1948 SourceLocation UDSuffixLoc,
1949 ArrayRef<Expr*> Args,
1950 SourceLocation LitEndLoc) {
1951 assert(Args.size() <= 2 && "too many arguments for literal operator");
1952
1953 QualType ArgTy[2];
1954 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1955 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1956 if (ArgTy[ArgIdx]->isArrayType())
1957 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1958 }
1959
1960 DeclarationName OpName =
1962 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1963 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1964
1965 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1966 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1967 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1968 /*AllowStringTemplatePack*/ false,
1969 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1970 return ExprError();
1971
1972 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1973}
1974
1976 // StringToks needs backing storage as it doesn't hold array elements itself
1977 std::vector<Token> ExpandedToks;
1978 if (getLangOpts().MicrosoftExt)
1979 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1980
1981 StringLiteralParser Literal(StringToks, PP,
1983 if (Literal.hadError)
1984 return ExprError();
1985
1986 SmallVector<SourceLocation, 4> StringTokLocs;
1987 for (const Token &Tok : StringToks)
1988 StringTokLocs.push_back(Tok.getLocation());
1989
1991 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1992 &StringTokLocs[0], StringTokLocs.size());
1993
1994 if (!Literal.getUDSuffix().empty()) {
1995 SourceLocation UDSuffixLoc =
1996 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1997 Literal.getUDSuffixOffset());
1998 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1999 }
2000
2001 return Lit;
2002}
2003
2004std::vector<Token>
2006 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2007 // local macros that expand to string literals that may be concatenated.
2008 // These macros are expanded here (in Sema), because StringLiteralParser
2009 // (in Lex) doesn't know the enclosing function (because it hasn't been
2010 // parsed yet).
2011 assert(getLangOpts().MicrosoftExt);
2012
2013 // Note: Although function local macros are defined only inside functions,
2014 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2015 // expansion of macros into empty string literals without additional checks.
2016 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2017 if (!CurrentDecl)
2018 CurrentDecl = Context.getTranslationUnitDecl();
2019
2020 std::vector<Token> ExpandedToks;
2021 ExpandedToks.reserve(Toks.size());
2022 for (const Token &Tok : Toks) {
2023 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2024 assert(tok::isStringLiteral(Tok.getKind()));
2025 ExpandedToks.emplace_back(Tok);
2026 continue;
2027 }
2028 if (isa<TranslationUnitDecl>(CurrentDecl))
2029 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2030 // Stringify predefined expression
2031 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2032 << Tok.getKind();
2033 SmallString<64> Str;
2034 llvm::raw_svector_ostream OS(Str);
2035 Token &Exp = ExpandedToks.emplace_back();
2036 Exp.startToken();
2037 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2038 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2039 OS << 'L';
2040 Exp.setKind(tok::wide_string_literal);
2041 } else {
2042 Exp.setKind(tok::string_literal);
2043 }
2044 OS << '"'
2046 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2047 << '"';
2048 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2049 }
2050 return ExpandedToks;
2051}
2052
2053/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2054/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2055/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2056/// multiple tokens. However, the common case is that StringToks points to one
2057/// string.
2058///
2061 assert(!StringToks.empty() && "Must have at least one string!");
2062
2063 // StringToks needs backing storage as it doesn't hold array elements itself
2064 std::vector<Token> ExpandedToks;
2065 if (getLangOpts().MicrosoftExt)
2066 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2067
2068 StringLiteralParser Literal(StringToks, PP);
2069 if (Literal.hadError)
2070 return ExprError();
2071
2072 SmallVector<SourceLocation, 4> StringTokLocs;
2073 for (const Token &Tok : StringToks)
2074 StringTokLocs.push_back(Tok.getLocation());
2075
2076 QualType CharTy = Context.CharTy;
2078 if (Literal.isWide()) {
2079 CharTy = Context.getWideCharType();
2081 } else if (Literal.isUTF8()) {
2082 if (getLangOpts().Char8)
2083 CharTy = Context.Char8Ty;
2085 } else if (Literal.isUTF16()) {
2086 CharTy = Context.Char16Ty;
2088 } else if (Literal.isUTF32()) {
2089 CharTy = Context.Char32Ty;
2091 } else if (Literal.isPascal()) {
2092 CharTy = Context.UnsignedCharTy;
2093 }
2094
2095 // Warn on initializing an array of char from a u8 string literal; this
2096 // becomes ill-formed in C++2a.
2098 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2099 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2100
2101 // Create removals for all 'u8' prefixes in the string literal(s). This
2102 // ensures C++2a compatibility (but may change the program behavior when
2103 // built by non-Clang compilers for which the execution character set is
2104 // not always UTF-8).
2105 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2106 SourceLocation RemovalDiagLoc;
2107 for (const Token &Tok : StringToks) {
2108 if (Tok.getKind() == tok::utf8_string_literal) {
2109 if (RemovalDiagLoc.isInvalid())
2110 RemovalDiagLoc = Tok.getLocation();
2112 Tok.getLocation(),
2113 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2115 }
2116 }
2117 Diag(RemovalDiagLoc, RemovalDiag);
2118 }
2119
2120 QualType StrTy =
2121 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2122
2123 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2124 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2125 Kind, Literal.Pascal, StrTy,
2126 &StringTokLocs[0],
2127 StringTokLocs.size());
2128 if (Literal.getUDSuffix().empty())
2129 return Lit;
2130
2131 // We're building a user-defined literal.
2132 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2133 SourceLocation UDSuffixLoc =
2134 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2135 Literal.getUDSuffixOffset());
2136
2137 // Make sure we're allowed user-defined literals here.
2138 if (!UDLScope)
2139 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2140
2141 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2142 // operator "" X (str, len)
2143 QualType SizeType = Context.getSizeType();
2144
2145 DeclarationName OpName =
2147 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2148 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2149
2150 QualType ArgTy[] = {
2151 Context.getArrayDecayedType(StrTy), SizeType
2152 };
2153
2154 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2155 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2156 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2157 /*AllowStringTemplatePack*/ true,
2158 /*DiagnoseMissing*/ true, Lit)) {
2159
2160 case LOLR_Cooked: {
2161 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2162 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2163 StringTokLocs[0]);
2164 Expr *Args[] = { Lit, LenArg };
2165
2166 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2167 }
2168
2169 case LOLR_Template: {
2170 TemplateArgumentListInfo ExplicitArgs;
2171 TemplateArgument Arg(Lit);
2172 TemplateArgumentLocInfo ArgInfo(Lit);
2173 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2174 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2175 StringTokLocs.back(), &ExplicitArgs);
2176 }
2177
2179 TemplateArgumentListInfo ExplicitArgs;
2180
2181 unsigned CharBits = Context.getIntWidth(CharTy);
2182 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2183 llvm::APSInt Value(CharBits, CharIsUnsigned);
2184
2185 TemplateArgument TypeArg(CharTy);
2187 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2188
2189 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2190 Value = Lit->getCodeUnit(I);
2191 TemplateArgument Arg(Context, Value, CharTy);
2193 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2194 }
2195 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2196 StringTokLocs.back(), &ExplicitArgs);
2197 }
2198 case LOLR_Raw:
2200 llvm_unreachable("unexpected literal operator lookup result");
2201 case LOLR_Error:
2202 return ExprError();
2203 }
2204 llvm_unreachable("unexpected literal operator lookup result");
2205}
2206
2210 const CXXScopeSpec *SS) {
2211 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2212 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2213}
2214
2217 const DeclarationNameInfo &NameInfo,
2218 const CXXScopeSpec *SS, NamedDecl *FoundD,
2219 SourceLocation TemplateKWLoc,
2220 const TemplateArgumentListInfo *TemplateArgs) {
2223 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2224 TemplateArgs);
2225}
2226
2227// CUDA/HIP: Check whether a captured reference variable is referencing a
2228// host variable in a device or host device lambda.
2230 VarDecl *VD) {
2231 if (!S.getLangOpts().CUDA || !VD->hasInit())
2232 return false;
2233 assert(VD->getType()->isReferenceType());
2234
2235 // Check whether the reference variable is referencing a host variable.
2236 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2237 if (!DRE)
2238 return false;
2239 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2240 if (!Referee || !Referee->hasGlobalStorage() ||
2241 Referee->hasAttr<CUDADeviceAttr>())
2242 return false;
2243
2244 // Check whether the current function is a device or host device lambda.
2245 // Check whether the reference variable is a capture by getDeclContext()
2246 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2247 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2248 if (MD && MD->getParent()->isLambda() &&
2249 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2250 VD->getDeclContext() != MD)
2251 return true;
2252
2253 return false;
2254}
2255
2257 // A declaration named in an unevaluated operand never constitutes an odr-use.
2259 return NOUR_Unevaluated;
2260
2261 // C++2a [basic.def.odr]p4:
2262 // A variable x whose name appears as a potentially-evaluated expression e
2263 // is odr-used by e unless [...] x is a reference that is usable in
2264 // constant expressions.
2265 // CUDA/HIP:
2266 // If a reference variable referencing a host variable is captured in a
2267 // device or host device lambda, the value of the referee must be copied
2268 // to the capture and the reference variable must be treated as odr-use
2269 // since the value of the referee is not known at compile time and must
2270 // be loaded from the captured.
2271 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2272 if (VD->getType()->isReferenceType() &&
2273 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2275 VD->isUsableInConstantExpressions(Context))
2276 return NOUR_Constant;
2277 }
2278
2279 // All remaining non-variable cases constitute an odr-use. For variables, we
2280 // need to wait and see how the expression is used.
2281 return NOUR_None;
2282}
2283
2284/// BuildDeclRefExpr - Build an expression that references a
2285/// declaration that does not require a closure capture.
2288 const DeclarationNameInfo &NameInfo,
2289 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2290 SourceLocation TemplateKWLoc,
2291 const TemplateArgumentListInfo *TemplateArgs) {
2292 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2293 NeedToCaptureVariable(D, NameInfo.getLoc());
2294
2296 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2297 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2299
2300 // C++ [except.spec]p17:
2301 // An exception-specification is considered to be needed when:
2302 // - in an expression, the function is the unique lookup result or
2303 // the selected member of a set of overloaded functions.
2304 //
2305 // We delay doing this until after we've built the function reference and
2306 // marked it as used so that:
2307 // a) if the function is defaulted, we get errors from defining it before /
2308 // instead of errors from computing its exception specification, and
2309 // b) if the function is a defaulted comparison, we can use the body we
2310 // build when defining it as input to the exception specification
2311 // computation rather than computing a new body.
2312 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2313 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2314 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2316 }
2317 }
2318
2319 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2321 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2323
2324 const auto *FD = dyn_cast<FieldDecl>(D);
2325 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2326 FD = IFD->getAnonField();
2327 if (FD) {
2328 UnusedPrivateFields.remove(FD);
2329 // Just in case we're building an illegal pointer-to-member.
2330 if (FD->isBitField())
2332 }
2333
2334 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2335 // designates a bit-field.
2336 if (const auto *BD = dyn_cast<BindingDecl>(D))
2337 if (const auto *BE = BD->getBinding())
2338 E->setObjectKind(BE->getObjectKind());
2339
2340 return E;
2341}
2342
2343/// Decomposes the given name into a DeclarationNameInfo, its location, and
2344/// possibly a list of template arguments.
2345///
2346/// If this produces template arguments, it is permitted to call
2347/// DecomposeTemplateName.
2348///
2349/// This actually loses a lot of source location information for
2350/// non-standard name kinds; we should consider preserving that in
2351/// some way.
2352void
2355 DeclarationNameInfo &NameInfo,
2356 const TemplateArgumentListInfo *&TemplateArgs) {
2357 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2358 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2359 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2360
2361 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2362 Id.TemplateId->NumArgs);
2363 translateTemplateArguments(TemplateArgsPtr, Buffer);
2364
2365 TemplateName TName = Id.TemplateId->Template.get();
2366 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2367 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2368 TemplateArgs = &Buffer;
2369 } else {
2370 NameInfo = GetNameFromUnqualifiedId(Id);
2371 TemplateArgs = nullptr;
2372 }
2373}
2374
2376 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2378 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2379 DeclContext *Ctx =
2380 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2381 if (!TC) {
2382 // Emit a special diagnostic for failed member lookups.
2383 // FIXME: computing the declaration context might fail here (?)
2384 if (Ctx)
2385 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2386 << SS.getRange();
2387 else
2388 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2389 return;
2390 }
2391
2392 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2393 bool DroppedSpecifier =
2394 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2395 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2396 ? diag::note_implicit_param_decl
2397 : diag::note_previous_decl;
2398 if (!Ctx)
2399 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2400 SemaRef.PDiag(NoteID));
2401 else
2402 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2403 << Typo << Ctx << DroppedSpecifier
2404 << SS.getRange(),
2405 SemaRef.PDiag(NoteID));
2406}
2407
2408/// Diagnose a lookup that found results in an enclosing class during error
2409/// recovery. This usually indicates that the results were found in a dependent
2410/// base class that could not be searched as part of a template definition.
2411/// Always issues a diagnostic (though this may be only a warning in MS
2412/// compatibility mode).
2413///
2414/// Return \c true if the error is unrecoverable, or \c false if the caller
2415/// should attempt to recover using these lookup results.
2417 // During a default argument instantiation the CurContext points
2418 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2419 // function parameter list, hence add an explicit check.
2420 bool isDefaultArgument =
2421 !CodeSynthesisContexts.empty() &&
2422 CodeSynthesisContexts.back().Kind ==
2424 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2425 bool isInstance = CurMethod && CurMethod->isInstance() &&
2426 R.getNamingClass() == CurMethod->getParent() &&
2427 !isDefaultArgument;
2428
2429 // There are two ways we can find a class-scope declaration during template
2430 // instantiation that we did not find in the template definition: if it is a
2431 // member of a dependent base class, or if it is declared after the point of
2432 // use in the same class. Distinguish these by comparing the class in which
2433 // the member was found to the naming class of the lookup.
2434 unsigned DiagID = diag::err_found_in_dependent_base;
2435 unsigned NoteID = diag::note_member_declared_at;
2437 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2438 : diag::err_found_later_in_class;
2439 } else if (getLangOpts().MSVCCompat) {
2440 DiagID = diag::ext_found_in_dependent_base;
2441 NoteID = diag::note_dependent_member_use;
2442 }
2443
2444 if (isInstance) {
2445 // Give a code modification hint to insert 'this->'.
2446 Diag(R.getNameLoc(), DiagID)
2447 << R.getLookupName()
2448 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2450 } else {
2451 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2452 // they're not shadowed).
2453 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2454 }
2455
2456 for (const NamedDecl *D : R)
2457 Diag(D->getLocation(), NoteID);
2458
2459 // Return true if we are inside a default argument instantiation
2460 // and the found name refers to an instance member function, otherwise
2461 // the caller will try to create an implicit member call and this is wrong
2462 // for default arguments.
2463 //
2464 // FIXME: Is this special case necessary? We could allow the caller to
2465 // diagnose this.
2466 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2467 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2468 return true;
2469 }
2470
2471 // Tell the callee to try to recover.
2472 return false;
2473}
2474
2475/// Diagnose an empty lookup.
2476///
2477/// \return false if new lookup candidates were found
2480 TemplateArgumentListInfo *ExplicitTemplateArgs,
2481 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2482 TypoExpr **Out) {
2483 DeclarationName Name = R.getLookupName();
2484
2485 unsigned diagnostic = diag::err_undeclared_var_use;
2486 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2487 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2488 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2489 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2490 diagnostic = diag::err_undeclared_use;
2491 diagnostic_suggest = diag::err_undeclared_use_suggest;
2492 }
2493
2494 // If the original lookup was an unqualified lookup, fake an
2495 // unqualified lookup. This is useful when (for example) the
2496 // original lookup would not have found something because it was a
2497 // dependent name.
2498 DeclContext *DC =
2499 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2500 while (DC) {
2501 if (isa<CXXRecordDecl>(DC)) {
2502 LookupQualifiedName(R, DC);
2503
2504 if (!R.empty()) {
2505 // Don't give errors about ambiguities in this lookup.
2507
2508 // If there's a best viable function among the results, only mention
2509 // that one in the notes.
2510 OverloadCandidateSet Candidates(R.getNameLoc(),
2512 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2514 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2515 OR_Success) {
2516 R.clear();
2517 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2518 R.resolveKind();
2519 }
2520
2522 }
2523
2524 R.clear();
2525 }
2526
2527 DC = DC->getLookupParent();
2528 }
2529
2530 // We didn't find anything, so try to correct for a typo.
2531 TypoCorrection Corrected;
2532 if (S && Out) {
2533 SourceLocation TypoLoc = R.getNameLoc();
2534 assert(!ExplicitTemplateArgs &&
2535 "Diagnosing an empty lookup with explicit template args!");
2536 *Out = CorrectTypoDelayed(
2537 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2538 [=](const TypoCorrection &TC) {
2539 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2540 diagnostic, diagnostic_suggest);
2541 },
2542 nullptr, CTK_ErrorRecovery, LookupCtx);
2543 if (*Out)
2544 return true;
2545 } else if (S && (Corrected =
2547 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2548 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2549 bool DroppedSpecifier =
2550 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2551 R.setLookupName(Corrected.getCorrection());
2552
2553 bool AcceptableWithRecovery = false;
2554 bool AcceptableWithoutRecovery = false;
2555 NamedDecl *ND = Corrected.getFoundDecl();
2556 if (ND) {
2557 if (Corrected.isOverloaded()) {
2561 for (NamedDecl *CD : Corrected) {
2562 if (FunctionTemplateDecl *FTD =
2563 dyn_cast<FunctionTemplateDecl>(CD))
2565 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2566 Args, OCS);
2567 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2568 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2570 Args, OCS);
2571 }
2572 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2573 case OR_Success:
2574 ND = Best->FoundDecl;
2575 Corrected.setCorrectionDecl(ND);
2576 break;
2577 default:
2578 // FIXME: Arbitrarily pick the first declaration for the note.
2579 Corrected.setCorrectionDecl(ND);
2580 break;
2581 }
2582 }
2583 R.addDecl(ND);
2584 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2585 CXXRecordDecl *Record = nullptr;
2586 if (Corrected.getCorrectionSpecifier()) {
2587 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2588 Record = Ty->getAsCXXRecordDecl();
2589 }
2590 if (!Record)
2591 Record = cast<CXXRecordDecl>(
2594 }
2595
2596 auto *UnderlyingND = ND->getUnderlyingDecl();
2597 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2598 isa<FunctionTemplateDecl>(UnderlyingND);
2599 // FIXME: If we ended up with a typo for a type name or
2600 // Objective-C class name, we're in trouble because the parser
2601 // is in the wrong place to recover. Suggest the typo
2602 // correction, but don't make it a fix-it since we're not going
2603 // to recover well anyway.
2604 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2605 getAsTypeTemplateDecl(UnderlyingND) ||
2606 isa<ObjCInterfaceDecl>(UnderlyingND);
2607 } else {
2608 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2609 // because we aren't able to recover.
2610 AcceptableWithoutRecovery = true;
2611 }
2612
2613 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2614 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2615 ? diag::note_implicit_param_decl
2616 : diag::note_previous_decl;
2617 if (SS.isEmpty())
2618 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2619 PDiag(NoteID), AcceptableWithRecovery);
2620 else
2621 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2622 << Name << computeDeclContext(SS, false)
2623 << DroppedSpecifier << SS.getRange(),
2624 PDiag(NoteID), AcceptableWithRecovery);
2625
2626 // Tell the callee whether to try to recover.
2627 return !AcceptableWithRecovery;
2628 }
2629 }
2630 R.clear();
2631
2632 // Emit a special diagnostic for failed member lookups.
2633 // FIXME: computing the declaration context might fail here (?)
2634 if (!SS.isEmpty()) {
2635 Diag(R.getNameLoc(), diag::err_no_member)
2636 << Name << computeDeclContext(SS, false)
2637 << SS.getRange();
2638 return true;
2639 }
2640
2641 // Give up, we can't recover.
2642 Diag(R.getNameLoc(), diagnostic) << Name;
2643 return true;
2644}
2645
2646/// In Microsoft mode, if we are inside a template class whose parent class has
2647/// dependent base classes, and we can't resolve an unqualified identifier, then
2648/// assume the identifier is a member of a dependent base class. We can only
2649/// recover successfully in static methods, instance methods, and other contexts
2650/// where 'this' is available. This doesn't precisely match MSVC's
2651/// instantiation model, but it's close enough.
2652static Expr *
2654 DeclarationNameInfo &NameInfo,
2655 SourceLocation TemplateKWLoc,
2656 const TemplateArgumentListInfo *TemplateArgs) {
2657 // Only try to recover from lookup into dependent bases in static methods or
2658 // contexts where 'this' is available.
2659 QualType ThisType = S.getCurrentThisType();
2660 const CXXRecordDecl *RD = nullptr;
2661 if (!ThisType.isNull())
2662 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2663 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2664 RD = MD->getParent();
2665 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2666 return nullptr;
2667
2668 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2669 // is available, suggest inserting 'this->' as a fixit.
2670 SourceLocation Loc = NameInfo.getLoc();
2671 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2672 DB << NameInfo.getName() << RD;
2673
2674 if (!ThisType.isNull()) {
2675 DB << FixItHint::CreateInsertion(Loc, "this->");
2677 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2678 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2679 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2680 }
2681
2682 // Synthesize a fake NNS that points to the derived class. This will
2683 // perform name lookup during template instantiation.
2684 CXXScopeSpec SS;
2685 auto *NNS =
2686 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2687 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2689 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2690 TemplateArgs);
2691}
2692
2695 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2696 bool HasTrailingLParen, bool IsAddressOfOperand,
2698 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2699 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2700 "cannot be direct & operand and have a trailing lparen");
2701 if (SS.isInvalid())
2702 return ExprError();
2703
2704 TemplateArgumentListInfo TemplateArgsBuffer;
2705
2706 // Decompose the UnqualifiedId into the following data.
2707 DeclarationNameInfo NameInfo;
2708 const TemplateArgumentListInfo *TemplateArgs;
2709 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2710
2711 DeclarationName Name = NameInfo.getName();
2712 IdentifierInfo *II = Name.getAsIdentifierInfo();
2713 SourceLocation NameLoc = NameInfo.getLoc();
2714
2715 if (II && II->isEditorPlaceholder()) {
2716 // FIXME: When typed placeholders are supported we can create a typed
2717 // placeholder expression node.
2718 return ExprError();
2719 }
2720
2721 // C++ [temp.dep.expr]p3:
2722 // An id-expression is type-dependent if it contains:
2723 // -- an identifier that was declared with a dependent type,
2724 // (note: handled after lookup)
2725 // -- a template-id that is dependent,
2726 // (note: handled in BuildTemplateIdExpr)
2727 // -- a conversion-function-id that specifies a dependent type,
2728 // -- a nested-name-specifier that contains a class-name that
2729 // names a dependent type.
2730 // Determine whether this is a member of an unknown specialization;
2731 // we need to handle these differently.
2732 bool DependentID = false;
2733 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2734 Name.getCXXNameType()->isDependentType()) {
2735 DependentID = true;
2736 } else if (SS.isSet()) {
2737 if (DeclContext *DC = computeDeclContext(SS, false)) {
2738 if (RequireCompleteDeclContext(SS, DC))
2739 return ExprError();
2740 } else {
2741 DependentID = true;
2742 }
2743 }
2744
2745 if (DependentID)
2746 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2747 IsAddressOfOperand, TemplateArgs);
2748
2749 // BoundsSafety: This specially handles arguments of bounds attributes
2750 // appertains to a type of C struct field such that the name lookup
2751 // within a struct finds the member name, which is not the case for other
2752 // contexts in C.
2753 if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2754 // See if this is reference to a field of struct.
2755 LookupResult R(*this, NameInfo, LookupMemberName);
2756 // LookupName handles a name lookup from within anonymous struct.
2757 if (LookupName(R, S)) {
2758 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2759 QualType type = VD->getType().getNonReferenceType();
2760 // This will eventually be translated into MemberExpr upon
2761 // the use of instantiated struct fields.
2762 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2763 }
2764 }
2765 }
2766
2767 // Perform the required lookup.
2768 LookupResult R(*this, NameInfo,
2772 if (TemplateKWLoc.isValid() || TemplateArgs) {
2773 // Lookup the template name again to correctly establish the context in
2774 // which it was found. This is really unfortunate as we already did the
2775 // lookup to determine that it was a template name in the first place. If
2776 // this becomes a performance hit, we can work harder to preserve those
2777 // results until we get here but it's likely not worth it.
2778 AssumedTemplateKind AssumedTemplate;
2779 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2780 /*EnteringContext=*/false, TemplateKWLoc,
2781 &AssumedTemplate))
2782 return ExprError();
2783
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2790 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2791
2792 // If the result might be in a dependent base class, this is a dependent
2793 // id-expression.
2795 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2796 IsAddressOfOperand, TemplateArgs);
2797
2798 // If this reference is in an Objective-C method, then we need to do
2799 // some special Objective-C lookup, too.
2800 if (IvarLookupFollowUp) {
2801 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2802 if (E.isInvalid())
2803 return ExprError();
2804
2805 if (Expr *Ex = E.getAs<Expr>())
2806 return Ex;
2807 }
2808 }
2809
2810 if (R.isAmbiguous())
2811 return ExprError();
2812
2813 // This could be an implicitly declared function reference if the language
2814 // mode allows it as a feature.
2815 if (R.empty() && HasTrailingLParen && II &&
2816 getLangOpts().implicitFunctionsAllowed()) {
2817 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2818 if (D) R.addDecl(D);
2819 }
2820
2821 // Determine whether this name might be a candidate for
2822 // argument-dependent lookup.
2823 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2824
2825 if (R.empty() && !ADL) {
2826 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2827 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2828 TemplateKWLoc, TemplateArgs))
2829 return E;
2830 }
2831
2832 // Don't diagnose an empty lookup for inline assembly.
2833 if (IsInlineAsmIdentifier)
2834 return ExprError();
2835
2836 // If this name wasn't predeclared and if this is not a function
2837 // call, diagnose the problem.
2838 TypoExpr *TE = nullptr;
2839 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2840 : nullptr);
2841 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2842 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2843 "Typo correction callback misconfigured");
2844 if (CCC) {
2845 // Make sure the callback knows what the typo being diagnosed is.
2846 CCC->setTypoName(II);
2847 if (SS.isValid())
2848 CCC->setTypoNNS(SS.getScopeRep());
2849 }
2850 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2851 // a template name, but we happen to have always already looked up the name
2852 // before we get here if it must be a template name.
2853 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2854 std::nullopt, nullptr, &TE)) {
2855 if (TE && KeywordReplacement) {
2856 auto &State = getTypoExprState(TE);
2857 auto BestTC = State.Consumer->getNextCorrection();
2858 if (BestTC.isKeyword()) {
2859 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2860 if (State.DiagHandler)
2861 State.DiagHandler(BestTC);
2862 KeywordReplacement->startToken();
2863 KeywordReplacement->setKind(II->getTokenID());
2864 KeywordReplacement->setIdentifierInfo(II);
2865 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2866 // Clean up the state associated with the TypoExpr, since it has
2867 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2868 clearDelayedTypo(TE);
2869 // Signal that a correction to a keyword was performed by returning a
2870 // valid-but-null ExprResult.
2871 return (Expr*)nullptr;
2872 }
2873 State.Consumer->resetCorrectionStream();
2874 }
2875 return TE ? TE : ExprError();
2876 }
2877
2878 assert(!R.empty() &&
2879 "DiagnoseEmptyLookup returned false but added no results");
2880
2881 // If we found an Objective-C instance variable, let
2882 // LookupInObjCMethod build the appropriate expression to
2883 // reference the ivar.
2884 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2885 R.clear();
2886 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2887 // In a hopelessly buggy code, Objective-C instance variable
2888 // lookup fails and no expression will be built to reference it.
2889 if (!E.isInvalid() && !E.get())
2890 return ExprError();
2891 return E;
2892 }
2893 }
2894
2895 // This is guaranteed from this point on.
2896 assert(!R.empty() || ADL);
2897
2898 // Check whether this might be a C++ implicit instance member access.
2899 // C++ [class.mfct.non-static]p3:
2900 // When an id-expression that is not part of a class member access
2901 // syntax and not used to form a pointer to member is used in the
2902 // body of a non-static member function of class X, if name lookup
2903 // resolves the name in the id-expression to a non-static non-type
2904 // member of some class C, the id-expression is transformed into a
2905 // class member access expression using (*this) as the
2906 // postfix-expression to the left of the . operator.
2907 //
2908 // But we don't actually need to do this for '&' operands if R
2909 // resolved to a function or overloaded function set, because the
2910 // expression is ill-formed if it actually works out to be a
2911 // non-static member function:
2912 //
2913 // C++ [expr.ref]p4:
2914 // Otherwise, if E1.E2 refers to a non-static member function. . .
2915 // [t]he expression can be used only as the left-hand operand of a
2916 // member function call.
2917 //
2918 // There are other safeguards against such uses, but it's important
2919 // to get this right here so that we don't end up making a
2920 // spuriously dependent expression if we're inside a dependent
2921 // instance method.
2922 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2923 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2924 S);
2925
2926 if (TemplateArgs || TemplateKWLoc.isValid()) {
2927
2928 // In C++1y, if this is a variable template id, then check it
2929 // in BuildTemplateIdExpr().
2930 // The single lookup result must be a variable template declaration.
2931 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2932 Id.TemplateId->Kind == TNK_Var_template) {
2933 assert(R.getAsSingle<VarTemplateDecl>() &&
2934 "There should only be one declaration found.");
2935 }
2936
2937 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2938 }
2939
2940 return BuildDeclarationNameExpr(SS, R, ADL);
2941}
2942
2943/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2944/// declaration name, generally during template instantiation.
2945/// There's a large number of things which don't need to be done along
2946/// this path.
2948 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2949 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2950 if (NameInfo.getName().isDependentName())
2951 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2952 NameInfo, /*TemplateArgs=*/nullptr);
2953
2954 DeclContext *DC = computeDeclContext(SS, false);
2955 if (!DC)
2956 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2957 NameInfo, /*TemplateArgs=*/nullptr);
2958
2959 if (RequireCompleteDeclContext(SS, DC))
2960 return ExprError();
2961
2962 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2963 LookupQualifiedName(R, DC);
2964
2965 if (R.isAmbiguous())
2966 return ExprError();
2967
2969 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2970 NameInfo, /*TemplateArgs=*/nullptr);
2971
2972 if (R.empty()) {
2973 // Don't diagnose problems with invalid record decl, the secondary no_member
2974 // diagnostic during template instantiation is likely bogus, e.g. if a class
2975 // is invalid because it's derived from an invalid base class, then missing
2976 // members were likely supposed to be inherited.
2977 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2978 if (CD->isInvalidDecl())
2979 return ExprError();
2980 Diag(NameInfo.getLoc(), diag::err_no_member)
2981 << NameInfo.getName() << DC << SS.getRange();
2982 return ExprError();
2983 }
2984
2985 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2986 // Diagnose a missing typename if this resolved unambiguously to a type in
2987 // a dependent context. If we can recover with a type, downgrade this to
2988 // a warning in Microsoft compatibility mode.
2989 unsigned DiagID = diag::err_typename_missing;
2990 if (RecoveryTSI && getLangOpts().MSVCCompat)
2991 DiagID = diag::ext_typename_missing;
2993 auto D = Diag(Loc, DiagID);
2994 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2995 << SourceRange(Loc, NameInfo.getEndLoc());
2996
2997 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2998 // context.
2999 if (!RecoveryTSI)
3000 return ExprError();
3001
3002 // Only issue the fixit if we're prepared to recover.
3003 D << FixItHint::CreateInsertion(Loc, "typename ");
3004
3005 // Recover by pretending this was an elaborated type.
3007 TypeLocBuilder TLB;
3008 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
3009
3014
3015 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3016
3017 return ExprEmpty();
3018 }
3019
3020 // Defend against this resolving to an implicit member access. We usually
3021 // won't get here if this might be a legitimate a class member (we end up in
3022 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3023 // a pointer-to-member or in an unevaluated context in C++11.
3024 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3026 /*TemplateKWLoc=*/SourceLocation(),
3027 R, /*TemplateArgs=*/nullptr, S);
3028
3029 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3030}
3031
3032/// Cast a base object to a member's actual type.
3033///
3034/// There are two relevant checks:
3035///
3036/// C++ [class.access.base]p7:
3037///
3038/// If a class member access operator [...] is used to access a non-static
3039/// data member or non-static member function, the reference is ill-formed if
3040/// the left operand [...] cannot be implicitly converted to a pointer to the
3041/// naming class of the right operand.
3042///
3043/// C++ [expr.ref]p7:
3044///
3045/// If E2 is a non-static data member or a non-static member function, the
3046/// program is ill-formed if the class of which E2 is directly a member is an
3047/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3048///
3049/// Note that the latter check does not consider access; the access of the
3050/// "real" base class is checked as appropriate when checking the access of the
3051/// member name.
3054 NestedNameSpecifier *Qualifier,
3055 NamedDecl *FoundDecl,
3056 NamedDecl *Member) {
3057 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3058 if (!RD)
3059 return From;
3060
3061 QualType DestRecordType;
3062 QualType DestType;
3063 QualType FromRecordType;
3064 QualType FromType = From->getType();
3065 bool PointerConversions = false;
3066 if (isa<FieldDecl>(Member)) {
3067 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3068 auto FromPtrType = FromType->getAs<PointerType>();
3069 DestRecordType = Context.getAddrSpaceQualType(
3070 DestRecordType, FromPtrType
3071 ? FromType->getPointeeType().getAddressSpace()
3072 : FromType.getAddressSpace());
3073
3074 if (FromPtrType) {
3075 DestType = Context.getPointerType(DestRecordType);
3076 FromRecordType = FromPtrType->getPointeeType();
3077 PointerConversions = true;
3078 } else {
3079 DestType = DestRecordType;
3080 FromRecordType = FromType;
3081 }
3082 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3083 if (!Method->isImplicitObjectMemberFunction())
3084 return From;
3085
3086 DestType = Method->getThisType().getNonReferenceType();
3087 DestRecordType = Method->getFunctionObjectParameterType();
3088
3089 if (FromType->getAs<PointerType>()) {
3090 FromRecordType = FromType->getPointeeType();
3091 PointerConversions = true;
3092 } else {
3093 FromRecordType = FromType;
3094 DestType = DestRecordType;
3095 }
3096
3097 LangAS FromAS = FromRecordType.getAddressSpace();
3098 LangAS DestAS = DestRecordType.getAddressSpace();
3099 if (FromAS != DestAS) {
3100 QualType FromRecordTypeWithoutAS =
3101 Context.removeAddrSpaceQualType(FromRecordType);
3102 QualType FromTypeWithDestAS =
3103 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3104 if (PointerConversions)
3105 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3106 From = ImpCastExprToType(From, FromTypeWithDestAS,
3107 CK_AddressSpaceConversion, From->getValueKind())
3108 .get();
3109 }
3110 } else {
3111 // No conversion necessary.
3112 return From;
3113 }
3114
3115 if (DestType->isDependentType() || FromType->isDependentType())
3116 return From;
3117
3118 // If the unqualified types are the same, no conversion is necessary.
3119 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3120 return From;
3121
3122 SourceRange FromRange = From->getSourceRange();
3123 SourceLocation FromLoc = FromRange.getBegin();
3124
3125 ExprValueKind VK = From->getValueKind();
3126
3127 // C++ [class.member.lookup]p8:
3128 // [...] Ambiguities can often be resolved by qualifying a name with its
3129 // class name.
3130 //
3131 // If the member was a qualified name and the qualified referred to a
3132 // specific base subobject type, we'll cast to that intermediate type
3133 // first and then to the object in which the member is declared. That allows
3134 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3135 //
3136 // class Base { public: int x; };
3137 // class Derived1 : public Base { };
3138 // class Derived2 : public Base { };
3139 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3140 //
3141 // void VeryDerived::f() {
3142 // x = 17; // error: ambiguous base subobjects
3143 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3144 // }
3145 if (Qualifier && Qualifier->getAsType()) {
3146 QualType QType = QualType(Qualifier->getAsType(), 0);
3147 assert(QType->isRecordType() && "lookup done with non-record type");
3148
3149 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3150
3151 // In C++98, the qualifier type doesn't actually have to be a base
3152 // type of the object type, in which case we just ignore it.
3153 // Otherwise build the appropriate casts.
3154 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3155 CXXCastPath BasePath;
3156 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3157 FromLoc, FromRange, &BasePath))
3158 return ExprError();
3159
3160 if (PointerConversions)
3161 QType = Context.getPointerType(QType);
3162 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3163 VK, &BasePath).get();
3164
3165 FromType = QType;
3166 FromRecordType = QRecordType;
3167
3168 // If the qualifier type was the same as the destination type,
3169 // we're done.
3170 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3171 return From;
3172 }
3173 }
3174
3175 CXXCastPath BasePath;
3176 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3177 FromLoc, FromRange, &BasePath,
3178 /*IgnoreAccess=*/true))
3179 return ExprError();
3180
3181 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3182 VK, &BasePath);
3183}
3184
3186 const LookupResult &R,
3187 bool HasTrailingLParen) {
3188 // Only when used directly as the postfix-expression of a call.
3189 if (!HasTrailingLParen)
3190 return false;
3191
3192 // Never if a scope specifier was provided.
3193 if (SS.isSet())
3194 return false;
3195
3196 // Only in C++ or ObjC++.
3197 if (!getLangOpts().CPlusPlus)
3198 return false;
3199
3200 // Turn off ADL when we find certain kinds of declarations during
3201 // normal lookup:
3202 for (const NamedDecl *D : R) {
3203 // C++0x [basic.lookup.argdep]p3:
3204 // -- a declaration of a class member
3205 // Since using decls preserve this property, we check this on the
3206 // original decl.
3207 if (D->isCXXClassMember())
3208 return false;
3209
3210 // C++0x [basic.lookup.argdep]p3:
3211 // -- a block-scope function declaration that is not a
3212 // using-declaration
3213 // NOTE: we also trigger this for function templates (in fact, we
3214 // don't check the decl type at all, since all other decl types
3215 // turn off ADL anyway).
3216 if (isa<UsingShadowDecl>(D))
3217 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3218 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3219 return false;
3220
3221 // C++0x [basic.lookup.argdep]p3:
3222 // -- a declaration that is neither a function or a function
3223 // template
3224 // And also for builtin functions.
3225 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3226 // But also builtin functions.
3227 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3228 return false;
3229 } else if (!isa<FunctionTemplateDecl>(D))
3230 return false;
3231 }
3232
3233 return true;
3234}
3235
3236
3237/// Diagnoses obvious problems with the use of the given declaration
3238/// as an expression. This is only actually called for lookups that
3239/// were not overloaded, and it doesn't promise that the declaration
3240/// will in fact be used.
3242 bool AcceptInvalid) {
3243 if (D->isInvalidDecl() && !AcceptInvalid)
3244 return true;
3245
3246 if (isa<TypedefNameDecl>(D)) {
3247 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3248 return true;
3249 }
3250
3251 if (isa<ObjCInterfaceDecl>(D)) {
3252 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3253 return true;
3254 }
3255
3256 if (isa<NamespaceDecl>(D)) {
3257 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3258 return true;
3259 }
3260
3261 return false;
3262}
3263
3264// Certain multiversion types should be treated as overloaded even when there is
3265// only one result.
3267 assert(R.isSingleResult() && "Expected only a single result");
3268 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3269 return FD &&
3270 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3271}
3272
3274 LookupResult &R, bool NeedsADL,
3275 bool AcceptInvalidDecl) {
3276 // If this is a single, fully-resolved result and we don't need ADL,
3277 // just build an ordinary singleton decl ref.
3278 if (!NeedsADL && R.isSingleResult() &&
3282 R.getRepresentativeDecl(), nullptr,
3283 AcceptInvalidDecl);
3284
3285 // We only need to check the declaration if there's exactly one
3286 // result, because in the overloaded case the results can only be
3287 // functions and function templates.
3289 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3290 AcceptInvalidDecl))
3291 return ExprError();
3292
3293 // Otherwise, just build an unresolved lookup expression. Suppress
3294 // any lookup-related diagnostics; we'll hash these out later, when
3295 // we've picked a target.
3297
3300 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3301 /*KnownDependent=*/false);
3302
3303 return ULE;
3304}
3305
3307 SourceLocation loc,
3308 ValueDecl *var);
3309
3310/// Complete semantic analysis for a reference to the given declaration.
3312 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3313 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3314 bool AcceptInvalidDecl) {
3315 assert(D && "Cannot refer to a NULL declaration");
3316 assert(!isa<FunctionTemplateDecl>(D) &&
3317 "Cannot refer unambiguously to a function template");
3318
3319 SourceLocation Loc = NameInfo.getLoc();
3320 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3321 // Recovery from invalid cases (e.g. D is an invalid Decl).
3322 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3323 // diagnostics, as invalid decls use int as a fallback type.
3324 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3325 }
3326
3327 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3328 // Specifically diagnose references to class templates that are missing
3329 // a template argument list.
3331 return ExprError();
3332 }
3333
3334 // Make sure that we're referring to a value.
3335 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3336 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3337 Diag(D->getLocation(), diag::note_declared_at);
3338 return ExprError();
3339 }
3340
3341 // Check whether this declaration can be used. Note that we suppress
3342 // this check when we're going to perform argument-dependent lookup
3343 // on this function name, because this might not be the function
3344 // that overload resolution actually selects.
3345 if (DiagnoseUseOfDecl(D, Loc))
3346 return ExprError();
3347
3348 auto *VD = cast<ValueDecl>(D);
3349
3350 // Only create DeclRefExpr's for valid Decl's.
3351 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3352 return ExprError();
3353
3354 // Handle members of anonymous structs and unions. If we got here,
3355 // and the reference is to a class member indirect field, then this
3356 // must be the subject of a pointer-to-member expression.
3357 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3358 IndirectField && !IndirectField->isCXXClassMember())
3360 IndirectField);
3361
3362 QualType type = VD->getType();
3363 if (type.isNull())
3364 return ExprError();
3365 ExprValueKind valueKind = VK_PRValue;
3366
3367 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3368 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3369 // is expanded by some outer '...' in the context of the use.
3370 type = type.getNonPackExpansionType();
3371
3372 switch (D->getKind()) {
3373 // Ignore all the non-ValueDecl kinds.
3374#define ABSTRACT_DECL(kind)
3375#define VALUE(type, base)
3376#define DECL(type, base) case Decl::type:
3377#include "clang/AST/DeclNodes.inc"
3378 llvm_unreachable("invalid value decl kind");
3379
3380 // These shouldn't make it here.
3381 case Decl::ObjCAtDefsField:
3382 llvm_unreachable("forming non-member reference to ivar?");
3383
3384 // Enum constants are always r-values and never references.
3385 // Unresolved using declarations are dependent.
3386 case Decl::EnumConstant:
3387 case Decl::UnresolvedUsingValue:
3388 case Decl::OMPDeclareReduction:
3389 case Decl::OMPDeclareMapper:
3390 valueKind = VK_PRValue;
3391 break;
3392
3393 // Fields and indirect fields that got here must be for
3394 // pointer-to-member expressions; we just call them l-values for
3395 // internal consistency, because this subexpression doesn't really
3396 // exist in the high-level semantics.
3397 case Decl::Field:
3398 case Decl::IndirectField:
3399 case Decl::ObjCIvar:
3400 assert((getLangOpts().CPlusPlus || isBoundsAttrContext()) &&
3401 "building reference to field in C?");
3402
3403 // These can't have reference type in well-formed programs, but
3404 // for internal consistency we do this anyway.
3405 type = type.getNonReferenceType();
3406 valueKind = VK_LValue;
3407 break;
3408
3409 // Non-type template parameters are either l-values or r-values
3410 // depending on the type.
3411 case Decl::NonTypeTemplateParm: {
3412 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3413 type = reftype->getPointeeType();
3414 valueKind = VK_LValue; // even if the parameter is an r-value reference
3415 break;
3416 }
3417
3418 // [expr.prim.id.unqual]p2:
3419 // If the entity is a template parameter object for a template
3420 // parameter of type T, the type of the expression is const T.
3421 // [...] The expression is an lvalue if the entity is a [...] template
3422 // parameter object.
3423 if (type->isRecordType()) {
3424 type = type.getUnqualifiedType().withConst();
3425 valueKind = VK_LValue;
3426 break;
3427 }
3428
3429 // For non-references, we need to strip qualifiers just in case
3430 // the template parameter was declared as 'const int' or whatever.
3431 valueKind = VK_PRValue;
3432 type = type.getUnqualifiedType();
3433 break;
3434 }
3435
3436 case Decl::Var:
3437 case Decl::VarTemplateSpecialization:
3438 case Decl::VarTemplatePartialSpecialization:
3439 case Decl::Decomposition:
3440 case Decl::OMPCapturedExpr:
3441 // In C, "extern void blah;" is valid and is an r-value.
3442 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3443 type->isVoidType()) {
3444 valueKind = VK_PRValue;
3445 break;
3446 }
3447 [[fallthrough]];
3448
3449 case Decl::ImplicitParam:
3450 case Decl::ParmVar: {
3451 // These are always l-values.
3452 valueKind = VK_LValue;
3453 type = type.getNonReferenceType();
3454
3455 // FIXME: Does the addition of const really only apply in
3456 // potentially-evaluated contexts? Since the variable isn't actually
3457 // captured in an unevaluated context, it seems that the answer is no.
3458 if (!isUnevaluatedContext()) {
3459 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3460 if (!CapturedType.isNull())
3461 type = CapturedType;
3462 }
3463
3464 break;
3465 }
3466
3467 case Decl::Binding:
3468 // These are always lvalues.
3469 valueKind = VK_LValue;
3470 type = type.getNonReferenceType();
3471 break;
3472
3473 case Decl::Function: {
3474 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3477 valueKind = VK_PRValue;
3478 break;
3479 }
3480 }
3481
3482 const FunctionType *fty = type->castAs<FunctionType>();
3483
3484 // If we're referring to a function with an __unknown_anytype
3485 // result type, make the entire expression __unknown_anytype.
3486 if (fty->getReturnType() == Context.UnknownAnyTy) {
3488 valueKind = VK_PRValue;
3489 break;
3490 }
3491
3492 // Functions are l-values in C++.
3493 if (getLangOpts().CPlusPlus) {
3494 valueKind = VK_LValue;
3495 break;
3496 }
3497
3498 // C99 DR 316 says that, if a function type comes from a
3499 // function definition (without a prototype), that type is only
3500 // used for checking compatibility. Therefore, when referencing
3501 // the function, we pretend that we don't have the full function
3502 // type.
3503 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3505 fty->getExtInfo());
3506
3507 // Functions are r-values in C.
3508 valueKind = VK_PRValue;
3509 break;
3510 }
3511
3512 case Decl::CXXDeductionGuide:
3513 llvm_unreachable("building reference to deduction guide");
3514
3515 case Decl::MSProperty:
3516 case Decl::MSGuid:
3517 case Decl::TemplateParamObject:
3518 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3519 // capture in OpenMP, or duplicated between host and device?
3520 valueKind = VK_LValue;
3521 break;
3522
3523 case Decl::UnnamedGlobalConstant:
3524 valueKind = VK_LValue;
3525 break;
3526
3527 case Decl::CXXMethod:
3528 // If we're referring to a method with an __unknown_anytype
3529 // result type, make the entire expression __unknown_anytype.
3530 // This should only be possible with a type written directly.
3531 if (const FunctionProtoType *proto =
3532 dyn_cast<FunctionProtoType>(VD->getType()))
3533 if (proto->getReturnType() == Context.UnknownAnyTy) {
3535 valueKind = VK_PRValue;
3536 break;
3537 }
3538
3539 // C++ methods are l-values if static, r-values if non-static.
3540 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3541 valueKind = VK_LValue;
3542 break;
3543 }
3544 [[fallthrough]];
3545
3546 case Decl::CXXConversion:
3547 case Decl::CXXDestructor:
3548 case Decl::CXXConstructor:
3549 valueKind = VK_PRValue;
3550 break;
3551 }
3552
3553 auto *E =
3554 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3555 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3556 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3557 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3558 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3559 // diagnostics).
3560 if (VD->isInvalidDecl() && E)
3561 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3562 return E;
3563}
3564
3565static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3567 Target.resize(CharByteWidth * (Source.size() + 1));
3568 char *ResultPtr = &Target[0];
3569 const llvm::UTF8 *ErrorPtr;
3570 bool success =
3571 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3572 (void)success;
3573 assert(success);
3574 Target.resize(ResultPtr - &Target[0]);
3575}
3576
3579 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3580 if (!currentDecl) {
3581 Diag(Loc, diag::ext_predef_outside_function);
3582 currentDecl = Context.getTranslationUnitDecl();
3583 }
3584
3585 QualType ResTy;
3586 StringLiteral *SL = nullptr;
3587 if (cast<DeclContext>(currentDecl)->isDependentContext())
3588 ResTy = Context.DependentTy;
3589 else {
3590 // Pre-defined identifiers are of type char[x], where x is the length of
3591 // the string.
3592 bool ForceElaboratedPrinting =
3593 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3594 auto Str =
3595 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3596 unsigned Length = Str.length();
3597
3598 llvm::APInt LengthI(32, Length + 1);
3601 ResTy =
3603 SmallString<32> RawChars;
3605 Str, RawChars);
3606 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3608 /*IndexTypeQuals*/ 0);
3610 /*Pascal*/ false, ResTy, Loc);
3611 } else {
3613 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3615 /*IndexTypeQuals*/ 0);
3617 /*Pascal*/ false, ResTy, Loc);
3618 }
3619 }
3620
3621 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3622 SL);
3623}
3624
3627}
3628
3630 SmallString<16> CharBuffer;
3631 bool Invalid = false;
3632 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3633 if (Invalid)
3634 return ExprError();
3635
3636 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3637 PP, Tok.getKind());
3638 if (Literal.hadError())
3639 return ExprError();
3640
3641 QualType Ty;
3642 if (Literal.isWide())
3643 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3644 else if (Literal.isUTF8() && getLangOpts().C23)
3645 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3646 else if (Literal.isUTF8() && getLangOpts().Char8)
3647 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3648 else if (Literal.isUTF16())
3649 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3650 else if (Literal.isUTF32())
3651 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3652 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3653 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3654 else
3655 Ty = Context.CharTy; // 'x' -> char in C++;
3656 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3657
3659 if (Literal.isWide())
3661 else if (Literal.isUTF16())
3663 else if (Literal.isUTF32())
3665 else if (Literal.isUTF8())
3667
3668 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3669 Tok.getLocation());
3670
3671 if (Literal.getUDSuffix().empty())
3672 return Lit;
3673
3674 // We're building a user-defined literal.
3675 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3676 SourceLocation UDSuffixLoc =
3677 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3678
3679 // Make sure we're allowed user-defined literals here.
3680 if (!UDLScope)
3681 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3682
3683 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3684 // operator "" X (ch)
3685 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3686 Lit, Tok.getLocation());
3687}
3688
3690 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3691 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3692 Context.IntTy, Loc);
3693}
3694
3697 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3698
3699 using llvm::APFloat;
3700 APFloat Val(Format);
3701
3702 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3703 if (RM == llvm::RoundingMode::Dynamic)
3704 RM = llvm::RoundingMode::NearestTiesToEven;
3705 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3706
3707 // Overflow is always an error, but underflow is only an error if
3708 // we underflowed to zero (APFloat reports denormals as underflow).
3709 if ((result & APFloat::opOverflow) ||
3710 ((result & APFloat::opUnderflow) && Val.isZero())) {
3711 unsigned diagnostic;
3712 SmallString<20> buffer;
3713 if (result & APFloat::opOverflow) {
3714 diagnostic = diag::warn_float_overflow;
3715 APFloat::getLargest(Format).toString(buffer);
3716 } else {
3717 diagnostic = diag::warn_float_underflow;
3718 APFloat::getSmallest(Format).toString(buffer);
3719 }
3720
3721 S.Diag(Loc, diagnostic)
3722 << Ty
3723 << StringRef(buffer.data(), buffer.size());
3724 }
3725
3726 bool isExact = (result == APFloat::opOK);
3727 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3728}
3729
3731 assert(E && "Invalid expression");
3732
3733 if (E->isValueDependent())
3734 return false;
3735
3736 QualType QT = E->getType();
3737 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3738 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3739 return true;
3740 }
3741
3742 llvm::APSInt ValueAPS;
3744
3745 if (R.isInvalid())
3746 return true;
3747
3748 // GCC allows the value of unroll count to be 0.
3749 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3750 // "The values of 0 and 1 block any unrolling of the loop."
3751 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3752 // '#pragma unroll' cases.
3753 bool ValueIsPositive =
3754 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3755 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3756 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3757 << toString(ValueAPS, 10) << ValueIsPositive;
3758 return true;
3759 }
3760
3761 return false;
3762}
3763
3765 // Fast path for a single digit (which is quite common). A single digit
3766 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3767 if (Tok.getLength() == 1) {
3768 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3769 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3770 }
3771
3772 SmallString<128> SpellingBuffer;
3773 // NumericLiteralParser wants to overread by one character. Add padding to
3774 // the buffer in case the token is copied to the buffer. If getSpelling()
3775 // returns a StringRef to the memory buffer, it should have a null char at
3776 // the EOF, so it is also safe.
3777 SpellingBuffer.resize(Tok.getLength() + 1);
3778
3779 // Get the spelling of the token, which eliminates trigraphs, etc.
3780 bool Invalid = false;
3781 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3782 if (Invalid)
3783 return ExprError();
3784
3785 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3788 if (Literal.hadError)
3789 return ExprError();
3790
3791 if (Literal.hasUDSuffix()) {
3792 // We're building a user-defined literal.
3793 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3794 SourceLocation UDSuffixLoc =
3795 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3796
3797 // Make sure we're allowed user-defined literals here.
3798 if (!UDLScope)
3799 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3800
3801 QualType CookedTy;
3802 if (Literal.isFloatingLiteral()) {
3803 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3804 // long double, the literal is treated as a call of the form
3805 // operator "" X (f L)
3806 CookedTy = Context.LongDoubleTy;
3807 } else {
3808 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3809 // unsigned long long, the literal is treated as a call of the form
3810 // operator "" X (n ULL)
3811 CookedTy = Context.UnsignedLongLongTy;
3812 }
3813
3814 DeclarationName OpName =
3816 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3817 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3818
3819 SourceLocation TokLoc = Tok.getLocation();
3820
3821 // Perform literal operator lookup to determine if we're building a raw
3822 // literal or a cooked one.
3823 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3824 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3825 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3826 /*AllowStringTemplatePack*/ false,
3827 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3829 // Lookup failure for imaginary constants isn't fatal, there's still the
3830 // GNU extension producing _Complex types.
3831 break;
3832 case LOLR_Error:
3833 return ExprError();
3834 case LOLR_Cooked: {
3835 Expr *Lit;
3836 if (Literal.isFloatingLiteral()) {
3837 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3838 } else {
3839 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3840 if (Literal.GetIntegerValue(ResultVal))
3841 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3842 << /* Unsigned */ 1;
3843 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3844 Tok.getLocation());
3845 }
3846 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3847 }
3848
3849 case LOLR_Raw: {
3850 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3851 // literal is treated as a call of the form
3852 // operator "" X ("n")
3853 unsigned Length = Literal.getUDSuffixOffset();
3856 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3857 Expr *Lit =
3858 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3860 /*Pascal*/ false, StrTy, &TokLoc, 1);
3861 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3862 }
3863
3864 case LOLR_Template: {
3865 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3866 // template), L is treated as a call fo the form
3867 // operator "" X <'c1', 'c2', ... 'ck'>()
3868 // where n is the source character sequence c1 c2 ... ck.
3869 TemplateArgumentListInfo ExplicitArgs;
3870 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3871 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3872 llvm::APSInt Value(CharBits, CharIsUnsigned);
3873 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3874 Value = TokSpelling[I];
3877 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3878 }
3879 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3880 &ExplicitArgs);
3881 }
3883 llvm_unreachable("unexpected literal operator lookup result");
3884 }
3885 }
3886
3887 Expr *Res;
3888
3889 if (Literal.isFixedPointLiteral()) {
3890 QualType Ty;
3891
3892 if (Literal.isAccum) {
3893 if (Literal.isHalf) {
3894 Ty = Context.ShortAccumTy;
3895 } else if (Literal.isLong) {
3896 Ty = Context.LongAccumTy;
3897 } else {
3898 Ty = Context.AccumTy;
3899 }
3900 } else if (Literal.isFract) {
3901 if (Literal.isHalf) {
3902 Ty = Context.ShortFractTy;
3903 } else if (Literal.isLong) {
3904 Ty = Context.LongFractTy;
3905 } else {
3906 Ty = Context.FractTy;
3907 }
3908 }
3909
3910 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3911
3912 bool isSigned = !Literal.isUnsigned;
3913 unsigned scale = Context.getFixedPointScale(Ty);
3914 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3915
3916 llvm::APInt Val(bit_width, 0, isSigned);
3917 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3918 bool ValIsZero = Val.isZero() && !Overflowed;
3919
3920 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3921 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3922 // Clause 6.4.4 - The value of a constant shall be in the range of
3923 // representable values for its type, with exception for constants of a
3924 // fract type with a value of exactly 1; such a constant shall denote
3925 // the maximal value for the type.
3926 --Val;
3927 else if (Val.ugt(MaxVal) || Overflowed)
3928 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3929
3931 Tok.getLocation(), scale);
3932 } else if (Literal.isFloatingLiteral()) {
3933 QualType Ty;
3934 if (Literal.isHalf){
3935 if (getLangOpts().HLSL ||
3936 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3937 Ty = Context.HalfTy;
3938 else {
3939 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3940 return ExprError();
3941 }
3942 } else if (Literal.isFloat)
3943 Ty = Context.FloatTy;
3944 else if (Literal.isLong)
3946 else if (Literal.isFloat16)
3947 Ty = Context.Float16Ty;
3948 else if (Literal.isFloat128)
3949 Ty = Context.Float128Ty;
3950 else if (getLangOpts().HLSL)
3951 Ty = Context.FloatTy;
3952 else
3953 Ty = Context.DoubleTy;
3954
3955 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3956
3957 if (Ty == Context.DoubleTy) {
3958 if (getLangOpts().SinglePrecisionConstants) {
3959 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3960 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3961 }
3962 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3963 "cl_khr_fp64", getLangOpts())) {
3964 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3965 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3967 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3968 }
3969 }
3970 } else if (!Literal.isIntegerLiteral()) {
3971 return ExprError();
3972 } else {
3973 QualType Ty;
3974
3975 // 'z/uz' literals are a C++23 feature.
3976 if (Literal.isSizeT)
3979 ? diag::warn_cxx20_compat_size_t_suffix
3980 : diag::ext_cxx23_size_t_suffix
3981 : diag::err_cxx23_size_t_suffix);
3982
3983 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3984 // but we do not currently support the suffix in C++ mode because it's not
3985 // entirely clear whether WG21 will prefer this suffix to return a library
3986 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3987 // literals are a C++ extension.
3988 if (Literal.isBitInt)
3989 PP.Diag(Tok.getLocation(),
3990 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3991 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3992 : diag::ext_c23_bitint_suffix);
3993
3994 // Get the value in the widest-possible width. What is "widest" depends on
3995 // whether the literal is a bit-precise integer or not. For a bit-precise
3996 // integer type, try to scan the source to determine how many bits are
3997 // needed to represent the value. This may seem a bit expensive, but trying
3998 // to get the integer value from an overly-wide APInt is *extremely*
3999 // expensive, so the naive approach of assuming
4000 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4001 unsigned BitsNeeded =
4002 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4003 Literal.getLiteralDigits(), Literal.getRadix())
4005 llvm::APInt ResultVal(BitsNeeded, 0);
4006
4007 if (Literal.GetIntegerValue(ResultVal)) {
4008 // If this value didn't fit into uintmax_t, error and force to ull.
4009 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4010 << /* Unsigned */ 1;
4012 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4013 "long long is not intmax_t?");
4014 } else {
4015 // If this value fits into a ULL, try to figure out what else it fits into
4016 // according to the rules of C99 6.4.4.1p5.
4017
4018 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4019 // be an unsigned int.
4020 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4021
4022 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4023 // suffix for portability of code with C++, but both `l` and `ll` are
4024 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4025 // same.
4026 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4027 Literal.isLong = true;
4028 Literal.isLongLong = false;
4029 }
4030
4031 // Check from smallest to largest, picking the smallest type we can.
4032 unsigned Width = 0;
4033
4034 // Microsoft specific integer suffixes are explicitly sized.
4035 if (Literal.MicrosoftInteger) {
4036 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4037 Width = 8;
4038 Ty = Context.CharTy;
4039 } else {
4040 Width = Literal.MicrosoftInteger;
4041 Ty = Context.getIntTypeForBitwidth(Width,
4042 /*Signed=*/!Literal.isUnsigned);
4043 }
4044 }
4045
4046 // Bit-precise integer literals are automagically-sized based on the
4047 // width required by the literal.
4048 if (Literal.isBitInt) {
4049 // The signed version has one more bit for the sign value. There are no
4050 // zero-width bit-precise integers, even if the literal value is 0.
4051 Width = std::max(ResultVal.getActiveBits(), 1u) +
4052 (Literal.isUnsigned ? 0u : 1u);
4053
4054 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4055 // and reset the type to the largest supported width.
4056 unsigned int MaxBitIntWidth =
4058 if (Width > MaxBitIntWidth) {
4059 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4060 << Literal.isUnsigned;
4061 Width = MaxBitIntWidth;
4062 }
4063
4064 // Reset the result value to the smaller APInt and select the correct
4065 // type to be used. Note, we zext even for signed values because the
4066 // literal itself is always an unsigned value (a preceeding - is a
4067 // unary operator, not part of the literal).
4068 ResultVal = ResultVal.zextOrTrunc(Width);
4069 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4070 }
4071
4072 // Check C++23 size_t literals.
4073 if (Literal.isSizeT) {
4074 assert(!Literal.MicrosoftInteger &&
4075 "size_t literals can't be Microsoft literals");
4076 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4078
4079 // Does it fit in size_t?
4080 if (ResultVal.isIntN(SizeTSize)) {
4081 // Does it fit in ssize_t?
4082 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4084 else if (AllowUnsigned)
4085 Ty = Context.getSizeType();
4086 Width = SizeTSize;
4087 }
4088 }
4089
4090 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4091 !Literal.isSizeT) {
4092 // Are int/unsigned possibilities?
4093 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4094
4095 // Does it fit in a unsigned int?
4096 if (ResultVal.isIntN(IntSize)) {
4097 // Does it fit in a signed int?
4098 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4099 Ty = Context.IntTy;
4100 else if (AllowUnsigned)
4102 Width = IntSize;
4103 }
4104 }
4105
4106 // Are long/unsigned long possibilities?
4107 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4108 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4109
4110 // Does it fit in a unsigned long?
4111 if (ResultVal.isIntN(LongSize)) {
4112 // Does it fit in a signed long?
4113 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4114 Ty = Context.LongTy;
4115 else if (AllowUnsigned)
4117 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4118 // is compatible.
4119 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4120 const unsigned LongLongSize =
4122 Diag(Tok.getLocation(),
4124 ? Literal.isLong
4125 ? diag::warn_old_implicitly_unsigned_long_cxx
4126 : /*C++98 UB*/ diag::
4127 ext_old_implicitly_unsigned_long_cxx
4128 : diag::warn_old_implicitly_unsigned_long)
4129 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4130 : /*will be ill-formed*/ 1);
4132 }
4133 Width = LongSize;
4134 }
4135 }
4136
4137 // Check long long if needed.
4138 if (Ty.isNull() && !Literal.isSizeT) {
4139 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4140
4141 // Does it fit in a unsigned long long?
4142 if (ResultVal.isIntN(LongLongSize)) {
4143 // Does it fit in a signed long long?
4144 // To be compatible with MSVC, hex integer literals ending with the
4145 // LL or i64 suffix are always signed in Microsoft mode.
4146 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4147 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4148 Ty = Context.LongLongTy;
4149 else if (AllowUnsigned)
4151 Width = LongLongSize;
4152
4153 // 'long long' is a C99 or C++11 feature, whether the literal
4154 // explicitly specified 'long long' or we needed the extra width.
4155 if (getLangOpts().CPlusPlus)
4156 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4157 ? diag::warn_cxx98_compat_longlong
4158 : diag::ext_cxx11_longlong);
4159 else if (!getLangOpts().C99)
4160 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4161 }
4162 }
4163
4164 // If we still couldn't decide a type, we either have 'size_t' literal
4165 // that is out of range, or a decimal literal that does not fit in a
4166 // signed long long and has no U suffix.
4167 if (Ty.isNull()) {
4168 if (Literal.isSizeT)
4169 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4170 << Literal.isUnsigned;
4171 else
4172 Diag(Tok.getLocation(),
4173 diag::ext_integer_literal_too_large_for_signed);
4176 }
4177
4178 if (ResultVal.getBitWidth() != Width)
4179 ResultVal = ResultVal.trunc(Width);
4180 }
4181 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4182 }
4183
4184 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4185 if (Literal.isImaginary) {
4186 Res = new (Context) ImaginaryLiteral(Res,
4188
4189 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4190 }
4191 return Res;
4192}
4193
4195 assert(E && "ActOnParenExpr() missing expr");
4196 QualType ExprTy = E->getType();
4197 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4198 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4199 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4200 return new (Context) ParenExpr(L, R, E);
4201}
4202
4205 SourceRange ArgRange) {
4206 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4207 // scalar or vector data type argument..."
4208 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4209 // type (C99 6.2.5p18) or void.
4210 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4211 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4212 << T << ArgRange;
4213 return true;
4214 }
4215
4216 assert((T->isVoidType() || !T->isIncompleteType()) &&
4217 "Scalar types should always be complete");
4218 return false;
4219}
4220
4223 SourceRange ArgRange) {
4224 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4225 if (!T->isVectorType() && !T->isSizelessVectorType())
4226 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4227 << ""
4228 << "__builtin_vectorelements" << T << ArgRange;
4229
4230 return false;
4231}
4232
4235 SourceRange ArgRange,
4236 UnaryExprOrTypeTrait TraitKind) {
4237 // Invalid types must be hard errors for SFINAE in C++.
4238 if (S.LangOpts.CPlusPlus)
4239 return true;
4240
4241 // C99 6.5.3.4p1:
4242 if (T->isFunctionType() &&
4243 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4244 TraitKind == UETT_PreferredAlignOf)) {
4245 // sizeof(function)/alignof(function) is allowed as an extension.
4246 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4247 << getTraitSpelling(TraitKind) << ArgRange;
4248 return false;
4249 }
4250
4251 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4252 // this is an error (OpenCL v1.1 s6.3.k)
4253 if (T->isVoidType()) {
4254 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4255 : diag::ext_sizeof_alignof_void_type;
4256 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4257 return false;
4258 }
4259
4260 return true;
4261}
4262
4265 SourceRange ArgRange,
4266 UnaryExprOrTypeTrait TraitKind) {
4267 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4268 // runtime doesn't allow it.
4270 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4271 << T << (TraitKind == UETT_SizeOf)
4272 << ArgRange;
4273 return true;
4274 }
4275
4276 return false;
4277}
4278
4279/// Check whether E is a pointer from a decayed array type (the decayed
4280/// pointer type is equal to T) and emit a warning if it is.
4282 const Expr *E) {
4283 // Don't warn if the operation changed the type.
4284 if (T != E->getType())
4285 return;
4286
4287 // Now look for array decays.
4288 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4289 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4290 return;
4291
4292 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4293 << ICE->getType()
4294 << ICE->getSubExpr()->getType();
4295}
4296
4297/// Check the constraints on expression operands to unary type expression
4298/// and type traits.
4299///
4300/// Completes any types necessary and validates the constraints on the operand
4301/// expression. The logic mostly mirrors the type-based overload, but may modify
4302/// the expression as it completes the type for that expression through template
4303/// instantiation, etc.
4305 UnaryExprOrTypeTrait ExprKind) {
4306 QualType ExprTy = E->getType();
4307 assert(!ExprTy->isReferenceType());
4308
4309 bool IsUnevaluatedOperand =
4310 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4311 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4312 ExprKind == UETT_VecStep);
4313 if (IsUnevaluatedOperand) {
4315 if (Result.isInvalid())
4316 return true;
4317 E = Result.get();
4318 }
4319
4320 // The operand for sizeof and alignof is in an unevaluated expression context,
4321 // so side effects could result in unintended consequences.
4322 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4323 // used to build SFINAE gadgets.
4324 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4325 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4327 !E->getType()->isVariableArrayType() &&
4328 E->HasSideEffects(Context, false))
4329 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4330
4331 if (ExprKind == UETT_VecStep)
4332 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4333 E->getSourceRange());
4334
4335 if (ExprKind == UETT_VectorElements)
4336 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4337 E->getSourceRange());
4338
4339 // Explicitly list some types as extensions.
4340 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4341 E->getSourceRange(), ExprKind))
4342 return false;
4343
4344 // WebAssembly tables are always illegal operands to unary expressions and
4345 // type traits.
4346 if (Context.getTargetInfo().getTriple().isWasm() &&
4348 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4349 << getTraitSpelling(ExprKind);
4350 return true;
4351 }
4352
4353 // 'alignof' applied to an expression only requires the base element type of
4354 // the expression to be complete. 'sizeof' requires the expression's type to
4355 // be complete (and will attempt to complete it if it's an array of unknown
4356 // bound).
4357 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4360 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4361 getTraitSpelling(ExprKind), E->getSourceRange()))
4362 return true;
4363 } else {
4365 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4366 getTraitSpelling(ExprKind), E->getSourceRange()))
4367 return true;
4368 }
4369
4370 // Completing the expression's type may have changed it.
4371 ExprTy = E->getType();
4372 assert(!ExprTy->isReferenceType());
4373
4374 if (ExprTy->isFunctionType()) {
4375 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4376 << getTraitSpelling(ExprKind) << E->getSourceRange();
4377 return true;
4378 }
4379
4380 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4381 E->getSourceRange(), ExprKind))
4382 return true;
4383
4384 if (ExprKind == UETT_SizeOf) {
4385 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4386 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4387 QualType OType = PVD->getOriginalType();
4388 QualType Type = PVD->getType();
4389 if (Type->isPointerType() && OType->isArrayType()) {
4390 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4391 << Type << OType;
4392 Diag(PVD->getLocation(), diag::note_declared_at);
4393 }
4394 }
4395 }
4396
4397 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4398 // decays into a pointer and returns an unintended result. This is most
4399 // likely a typo for "sizeof(array) op x".
4400 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4401 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4402 BO->getLHS());
4403 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4404 BO->getRHS());
4405 }
4406 }
4407
4408 return false;
4409}
4410
4411static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4412 // Cannot know anything else if the expression is dependent.
4413 if (E->isTypeDependent())
4414 return false;
4415
4416 if (E->getObjectKind() == OK_BitField) {
4417 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4418 << 1 << E->getSourceRange();
4419 return true;
4420 }
4421
4422 ValueDecl *D = nullptr;
4423 Expr *Inner = E->IgnoreParens();
4424 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4425 D = DRE->getDecl();
4426 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4427 D = ME->getMemberDecl();
4428 }
4429
4430 // If it's a field, require the containing struct to have a
4431 // complete definition so that we can compute the layout.
4432 //
4433 // This can happen in C++11 onwards, either by naming the member
4434 // in a way that is not transformed into a member access expression
4435 // (in an unevaluated operand, for instance), or by naming the member
4436 // in a trailing-return-type.
4437 //
4438 // For the record, since __alignof__ on expressions is a GCC
4439 // extension, GCC seems to permit this but always gives the
4440 // nonsensical answer 0.
4441 //
4442 // We don't really need the layout here --- we could instead just
4443 // directly check for all the appropriate alignment-lowing
4444 // attributes --- but that would require duplicating a lot of
4445 // logic that just isn't worth duplicating for such a marginal
4446 // use-case.
4447 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4448 // Fast path this check, since we at least know the record has a
4449 // definition if we can find a member of it.
4450 if (!FD->getParent()->isCompleteDefinition()) {
4451 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4452 << E->getSourceRange();
4453 return true;
4454 }
4455
4456 // Otherwise, if it's a field, and the field doesn't have
4457 // reference type, then it must have a complete type (or be a
4458 // flexible array member, which we explicitly want to
4459 // white-list anyway), which makes the following checks trivial.
4460 if (!FD->getType()->isReferenceType())
4461 return false;
4462 }
4463
4464 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4465}
4466
4468 E = E->IgnoreParens();
4469
4470 // Cannot know anything else if the expression is dependent.
4471 if (E->isTypeDependent())
4472 return false;
4473
4474 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4475}
4476
4478 CapturingScopeInfo *CSI) {
4479 assert(T->isVariablyModifiedType());
4480 assert(CSI != nullptr);
4481
4482 // We're going to walk down into the type and look for VLA expressions.
4483 do {
4484 const Type *Ty = T.getTypePtr();
4485 switch (Ty->getTypeClass()) {
4486#define TYPE(Class, Base)
4487#define ABSTRACT_TYPE(Class, Base)
4488#define NON_CANONICAL_TYPE(Class, Base)
4489#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4490#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4491#include "clang/AST/TypeNodes.inc"
4492 T = QualType();
4493 break;
4494 // These types are never variably-modified.
4495 case Type::Builtin:
4496 case Type::Complex:
4497 case Type::Vector:
4498 case Type::ExtVector:
4499 case Type::ConstantMatrix:
4500 case Type::Record:
4501 case Type::Enum:
4502 case Type::TemplateSpecialization:
4503 case Type::ObjCObject:
4504 case Type::ObjCInterface:
4505 case Type::ObjCObjectPointer:
4506 case Type::ObjCTypeParam:
4507 case Type::Pipe:
4508 case Type::BitInt:
4509 llvm_unreachable("type class is never variably-modified!");
4510 case Type::Elaborated:
4511 T = cast<ElaboratedType>(Ty)->getNamedType();
4512 break;
4513 case Type::Adjusted:
4514 T = cast<AdjustedType>(Ty)->getOriginalType();
4515 break;
4516 case Type::Decayed:
4517 T = cast<DecayedType>(Ty)->getPointeeType();
4518 break;
4519 case Type::ArrayParameter:
4520 T = cast<ArrayParameterType>(Ty)->getElementType();
4521 break;
4522 case Type::Pointer:
4523 T = cast<PointerType>(Ty)->getPointeeType();
4524 break;
4525 case Type::BlockPointer:
4526 T = cast<BlockPointerType>(Ty)->getPointeeType();
4527 break;
4528 case Type::LValueReference:
4529 case Type::RValueReference:
4530 T = cast<ReferenceType>(Ty)->getPointeeType();
4531 break;
4532 case Type::MemberPointer:
4533 T = cast<MemberPointerType>(Ty)->getPointeeType();
4534 break;
4535 case Type::ConstantArray:
4536 case Type::IncompleteArray:
4537 // Losing element qualification here is fine.
4538 T = cast<ArrayType>(Ty)->getElementType();
4539 break;
4540 case Type::VariableArray: {
4541 // Losing element qualification here is fine.
4542 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4543
4544 // Unknown size indication requires no size computation.
4545 // Otherwise, evaluate and record it.
4546 auto Size = VAT->getSizeExpr();
4547 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4548 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4549 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4550
4551 T = VAT->getElementType();
4552 break;
4553 }
4554 case Type::FunctionProto:
4555 case Type::FunctionNoProto:
4556 T = cast<FunctionType>(Ty)->getReturnType();
4557 break;
4558 case Type::Paren:
4559 case Type::TypeOf:
4560 case Type::UnaryTransform:
4561 case Type::Attributed:
4562 case Type::BTFTagAttributed:
4563 case Type::SubstTemplateTypeParm:
4564 case Type::MacroQualified:
4565 case Type::CountAttributed:
4566 // Keep walking after single level desugaring.
4567 T = T.getSingleStepDesugaredType(Context);
4568 break;
4569 case Type::Typedef:
4570 T = cast<TypedefType>(Ty)->desugar();
4571 break;
4572 case Type::Decltype:
4573 T = cast<DecltypeType>(Ty)->desugar();
4574 break;
4575 case Type::PackIndexing:
4576 T = cast<PackIndexingType>(Ty)->desugar();
4577 break;
4578 case Type::Using:
4579 T = cast<UsingType>(Ty)->desugar();
4580 break;
4581 case Type::Auto:
4582 case Type::DeducedTemplateSpecialization:
4583 T = cast<DeducedType>(Ty)->getDeducedType();
4584 break;
4585 case Type::TypeOfExpr:
4586 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4587 break;
4588 case Type::Atomic:
4589 T = cast<AtomicType>(Ty)->getValueType();
4590 break;
4591 }
4592 } while (!T.isNull() && T->isVariablyModifiedType());
4593}
4594
4595/// Check the constraints on operands to unary expression and type
4596/// traits.
4597///
4598/// This will complete any types necessary, and validate the various constraints
4599/// on those operands.
4600///
4601/// The UsualUnaryConversions() function is *not* called by this routine.
4602/// C99 6.3.2.1p[2-4] all state:
4603/// Except when it is the operand of the sizeof operator ...
4604///
4605/// C++ [expr.sizeof]p4
4606/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4607/// standard conversions are not applied to the operand of sizeof.
4608///
4609/// This policy is followed for all of the unary trait expressions.
4611 SourceLocation OpLoc,
4612 SourceRange ExprRange,
4613 UnaryExprOrTypeTrait ExprKind,
4614 StringRef KWName) {
4615 if (ExprType->isDependentType())
4616 return false;
4617
4618 // C++ [expr.sizeof]p2:
4619 // When applied to a reference or a reference type, the result
4620 // is the size of the referenced type.
4621 // C++11 [expr.alignof]p3:
4622 // When alignof is applied to a reference type, the result
4623 // shall be the alignment of the referenced type.
4624 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4625 ExprType = Ref->getPointeeType();
4626
4627 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4628 // When alignof or _Alignof is applied to an array type, the result
4629 // is the alignment of the element type.
4630 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4631 ExprKind == UETT_OpenMPRequiredSimdAlign)
4632 ExprType = Context.getBaseElementType(ExprType);
4633
4634 if (ExprKind == UETT_VecStep)
4635 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4636
4637 if (ExprKind == UETT_VectorElements)
4638 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4639 ExprRange);
4640
4641 // Explicitly list some types as extensions.
4642 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4643 ExprKind))
4644 return false;
4645
4647 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4648 KWName, ExprRange))
4649 return true;
4650
4651 if (ExprType->isFunctionType()) {
4652 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4653 return true;
4654 }
4655
4656 // WebAssembly tables are always illegal operands to unary expressions and
4657 // type traits.
4658 if (Context.getTargetInfo().getTriple().isWasm() &&
4659 ExprType->isWebAssemblyTableType()) {
4660 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4661 << getTraitSpelling(ExprKind);
4662 return true;
4663 }
4664
4665 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4666 ExprKind))
4667 return true;
4668
4669 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4670 if (auto *TT = ExprType->getAs<TypedefType>()) {
4671 for (auto I = FunctionScopes.rbegin(),
4672 E = std::prev(FunctionScopes.rend());
4673 I != E; ++I) {
4674 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4675 if (CSI == nullptr)
4676 break;
4677 DeclContext *DC = nullptr;
4678 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4679 DC = LSI->CallOperator;
4680 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4681 DC = CRSI->TheCapturedDecl;
4682 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4683 DC = BSI->TheDecl;
4684 if (DC) {
4685 if (DC->containsDecl(TT->getDecl()))
4686 break;
4687 captureVariablyModifiedType(Context, ExprType, CSI);
4688 }
4689 }
4690 }
4691 }
4692
4693 return false;
4694}
4695
4696/// Build a sizeof or alignof expression given a type operand.
4698 SourceLocation OpLoc,
4699 UnaryExprOrTypeTrait ExprKind,
4700 SourceRange R) {
4701 if (!TInfo)
4702 return ExprError();
4703
4704 QualType T = TInfo->getType();
4705
4706 if (!T->isDependentType() &&
4707 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4708 getTraitSpelling(ExprKind)))
4709 return ExprError();
4710
4711 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4712 // properly deal with VLAs in nested calls of sizeof and typeof.
4713 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4714 TInfo->getType()->isVariablyModifiedType())
4715 TInfo = TransformToPotentiallyEvaluated(TInfo);
4716
4717 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4718 return new (Context) UnaryExprOrTypeTraitExpr(
4719 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4720}
4721
4722/// Build a sizeof or alignof expression given an expression
4723/// operand.
4726 UnaryExprOrTypeTrait ExprKind) {
4728 if (PE.isInvalid())
4729 return ExprError();
4730
4731 E = PE.get();
4732
4733 // Verify that the operand is valid.
4734 bool isInvalid = false;
4735 if (E->isTypeDependent()) {
4736 // Delay type-checking for type-dependent expressions.
4737 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4738 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4739 } else if (ExprKind == UETT_VecStep) {
4741 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4742 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4743 isInvalid = true;
4744 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4745 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4746 isInvalid = true;
4747 } else if (ExprKind == UETT_VectorElements) {
4748 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4749 } else {
4751 }
4752
4753 if (isInvalid)
4754 return ExprError();
4755
4756 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4758 if (PE.isInvalid()) return ExprError();
4759 E = PE.get();
4760 }
4761
4762 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4763 return new (Context) UnaryExprOrTypeTraitExpr(
4764 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4765}
4766
4767/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4768/// expr and the same for @c alignof and @c __alignof
4769/// Note that the ArgRange is invalid if isType is false.
4772 UnaryExprOrTypeTrait ExprKind, bool IsType,
4773 void *TyOrEx, SourceRange ArgRange) {
4774 // If error parsing type, ignore.
4775 if (!TyOrEx) return ExprError();
4776
4777 if (IsType) {
4778 TypeSourceInfo *TInfo;
4779 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4780 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4781 }
4782
4783 Expr *ArgEx = (Expr *)TyOrEx;
4784 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4785 return Result;
4786}
4787
4789 SourceLocation OpLoc, SourceRange R) {
4790 if (!TInfo)
4791 return true;
4792 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4793 UETT_AlignOf, KWName);
4794}
4795
4796/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4797/// _Alignas(type-name) .
4798/// [dcl.align] An alignment-specifier of the form
4799/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4800///
4801/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4802/// _Alignas(_Alignof(type-name)).
4804 SourceLocation OpLoc, SourceRange R) {
4805 TypeSourceInfo *TInfo;
4807 &TInfo);
4808 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4809}
4810
4812 bool IsReal) {
4813 if (V.get()->isTypeDependent())
4814 return S.Context.DependentTy;
4815
4816 // _Real and _Imag are only l-values for normal l-values.
4817 if (V.get()->getObjectKind() != OK_Ordinary) {
4818 V = S.DefaultLvalueConversion(V.get());
4819 if (V.isInvalid())
4820 return QualType();
4821 }
4822
4823 // These operators return the element type of a complex type.
4824 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4825 return CT->getElementType();
4826
4827 // Otherwise they pass through real integer and floating point types here.
4828 if (V.get()->getType()->isArithmeticType())
4829 return V.get()->getType();
4830
4831 // Test for placeholders.
4832 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4833 if (PR.isInvalid()) return QualType();
4834 if (PR.get() != V.get()) {
4835 V = PR;
4836 return CheckRealImagOperand(S, V, Loc, IsReal);
4837 }
4838
4839 // Reject anything else.
4840 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4841 << (IsReal ? "__real" : "__imag");
4842 return QualType();
4843}
4844
4845
4846
4849 tok::TokenKind Kind, Expr *Input) {
4851 switch (Kind) {
4852 default: llvm_unreachable("Unknown unary op!");
4853 case tok::plusplus: Opc = UO_PostInc; break;
4854 case tok::minusminus: Opc = UO_PostDec; break;
4855 }
4856
4857 // Since this might is a postfix expression, get rid of ParenListExprs.
4859 if (Result.isInvalid()) return ExprError();
4860 Input = Result.get();
4861
4862 return BuildUnaryOp(S, OpLoc, Opc, Input);
4863}
4864
4865/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4866///
4867/// \return true on error
4869 SourceLocation opLoc,
4870 Expr *op) {
4871 assert(op->getType()->isObjCObjectPointerType());
4873 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4874 return false;
4875
4876 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4877 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4878 << op->getSourceRange();
4879 return true;
4880}
4881
4883 auto *BaseNoParens = Base->IgnoreParens();
4884 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4885 return MSProp->getPropertyDecl()->getType()->isArrayType();
4886 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4887}
4888
4889// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4890// Typically this is DependentTy, but can sometimes be more precise.
4891//
4892// There are cases when we could determine a non-dependent type:
4893// - LHS and RHS may have non-dependent types despite being type-dependent
4894// (e.g. unbounded array static members of the current instantiation)
4895// - one may be a dependent-sized array with known element type
4896// - one may be a dependent-typed valid index (enum in current instantiation)
4897//
4898// We *always* return a dependent type, in such cases it is DependentTy.
4899// This avoids creating type-dependent expressions with non-dependent types.
4900// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4902 const ASTContext &Ctx) {
4903 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4904 QualType LTy = LHS->getType(), RTy = RHS->getType();
4906 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4907 if (const PointerType *PT = LTy->getAs<PointerType>())
4908 Result = PT->getPointeeType();
4909 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4910 Result = AT->getElementType();
4911 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4912 if (const PointerType *PT = RTy->getAs<PointerType>())
4913 Result = PT->getPointeeType();
4914 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4915 Result = AT->getElementType();
4916 }
4917 // Ensure we return a dependent type.
4918 return Result->isDependentType() ? Result : Ctx.DependentTy;
4919}
4920
4922 SourceLocation lbLoc,
4923 MultiExprArg ArgExprs,
4924 SourceLocation rbLoc) {
4925
4926 if (base && !base->getType().isNull() &&
4927 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4928 auto *AS = cast<ArraySectionExpr>(base);
4929 if (AS->isOMPArraySection())
4931 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4932 /*Length*/ nullptr,
4933 /*Stride=*/nullptr, rbLoc);
4934
4935 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4936 SourceLocation(), /*Length*/ nullptr,
4937 rbLoc);
4938 }
4939
4940 // Since this might be a postfix expression, get rid of ParenListExprs.
4941 if (isa<ParenListExpr>(base)) {
4943 if (result.isInvalid())
4944 return ExprError();
4945 base = result.get();
4946 }
4947
4948 // Check if base and idx form a MatrixSubscriptExpr.
4949 //
4950 // Helper to check for comma expressions, which are not allowed as indices for
4951 // matrix subscript expressions.
4952 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4953 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4954 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4955 << SourceRange(base->getBeginLoc(), rbLoc);
4956 return true;
4957 }
4958 return false;
4959 };
4960 // The matrix subscript operator ([][])is considered a single operator.
4961 // Separating the index expressions by parenthesis is not allowed.
4962 if (base && !base->getType().isNull() &&
4963 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4964 !isa<MatrixSubscriptExpr>(base)) {
4965 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4966 << SourceRange(base->getBeginLoc(), rbLoc);
4967 return ExprError();
4968 }
4969 // If the base is a MatrixSubscriptExpr, try to create a new
4970 // MatrixSubscriptExpr.
4971 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4972 if (matSubscriptE) {
4973 assert(ArgExprs.size() == 1);
4974 if (CheckAndReportCommaError(ArgExprs.front()))
4975 return ExprError();
4976
4977 assert(matSubscriptE->isIncomplete() &&
4978 "base has to be an incomplete matrix subscript");
4979 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4980 matSubscriptE->getRowIdx(),
4981 ArgExprs.front(), rbLoc);
4982 }
4983 if (base->getType()->isWebAssemblyTableType()) {
4984 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4985 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4986 return ExprError();
4987 }
4988
4989 // Handle any non-overload placeholder types in the base and index
4990 // expressions. We can't handle overloads here because the other
4991 // operand might be an overloadable type, in which case the overload
4992 // resolution for the operator overload should get the first crack
4993 // at the overload.
4994 bool IsMSPropertySubscript = false;
4995 if (base->getType()->isNonOverloadPlaceholderType()) {
4996 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4997 if (!IsMSPropertySubscript) {
4998 ExprResult result = CheckPlaceholderExpr(base);
4999 if (result.isInvalid())
5000 return ExprError();
5001 base = result.get();
5002 }
5003 }
5004
5005 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5006 if (base->getType()->isMatrixType()) {
5007 assert(ArgExprs.size() == 1);
5008 if (CheckAndReportCommaError(ArgExprs.front()))
5009 return ExprError();
5010
5011 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5012 rbLoc);
5013 }
5014
5015 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5016 Expr *idx = ArgExprs[0];
5017 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5018 (isa<CXXOperatorCallExpr>(idx) &&
5019 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5020 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5021 << SourceRange(base->getBeginLoc(), rbLoc);
5022 }
5023 }
5024
5025 if (ArgExprs.size() == 1 &&
5026 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5027 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5028 if (result.isInvalid())
5029 return ExprError();
5030 ArgExprs[0] = result.get();
5031 } else {
5032 if (CheckArgsForPlaceholders(ArgExprs))
5033 return ExprError();
5034 }
5035
5036 // Build an unanalyzed expression if either operand is type-dependent.
5037 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5038 (base->isTypeDependent() ||
5040 !isa<PackExpansionExpr>(ArgExprs[0])) {
5041 return new (Context) ArraySubscriptExpr(
5042 base, ArgExprs.front(),
5043 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5044 VK_LValue, OK_Ordinary, rbLoc);
5045 }
5046
5047 // MSDN, property (C++)
5048 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5049 // This attribute can also be used in the declaration of an empty array in a
5050 // class or structure definition. For example:
5051 // __declspec(property(get=GetX, put=PutX)) int x[];
5052 // The above statement indicates that x[] can be used with one or more array
5053 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5054 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5055 if (IsMSPropertySubscript) {
5056 assert(ArgExprs.size() == 1);
5057 // Build MS property subscript expression if base is MS property reference
5058 // or MS property subscript.
5059 return new (Context)
5060 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5061 VK_LValue, OK_Ordinary, rbLoc);
5062 }
5063
5064 // Use C++ overloaded-operator rules if either operand has record
5065 // type. The spec says to do this if either type is *overloadable*,
5066 // but enum types can't declare subscript operators or conversion
5067 // operators, so there's nothing interesting for overload resolution
5068 // to do if there aren't any record types involved.
5069 //
5070 // ObjC pointers have their own subscripting logic that is not tied
5071 // to overload resolution and so should not take this path.
5072 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5073 ((base->getType()->isRecordType() ||
5074 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5075 ArgExprs[0]->getType()->isRecordType())))) {
5076 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5077 }
5078
5079 ExprResult Res =
5080 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5081
5082 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5083 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5084
5085 return Res;
5086}
5087
5090 InitializationKind Kind =
5092 InitializationSequence InitSeq(*this, Entity, Kind, E);
5093 return InitSeq.Perform(*this, Entity, Kind, E);
5094}
5095
5097 Expr *ColumnIdx,
5098 SourceLocation RBLoc) {
5100 if (BaseR.isInvalid())
5101 return BaseR;
5102 Base = BaseR.get();
5103
5104 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5105 if (RowR.isInvalid())
5106 return RowR;
5107 RowIdx = RowR.get();
5108
5109 if (!ColumnIdx)
5110 return new (Context) MatrixSubscriptExpr(
5111 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5112
5113 // Build an unanalyzed expression if any of the operands is type-dependent.
5114 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5115 ColumnIdx->isTypeDependent())
5116 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5117 Context.DependentTy, RBLoc);
5118
5119 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5120 if (ColumnR.isInvalid())
5121 return ColumnR;
5122 ColumnIdx = ColumnR.get();
5123
5124 // Check that IndexExpr is an integer expression. If it is a constant
5125 // expression, check that it is less than Dim (= the number of elements in the
5126 // corresponding dimension).
5127 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5128 bool IsColumnIdx) -> Expr * {
5129 if (!IndexExpr->getType()->isIntegerType() &&
5130 !IndexExpr->isTypeDependent()) {
5131 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5132 << IsColumnIdx;
5133 return nullptr;
5134 }
5135
5136 if (std::optional<llvm::APSInt> Idx =
5137 IndexExpr->getIntegerConstantExpr(Context)) {
5138 if ((*Idx < 0 || *Idx >= Dim)) {
5139 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5140 << IsColumnIdx << Dim;
5141 return nullptr;
5142 }
5143 }
5144
5145 ExprResult ConvExpr =
5147 assert(!ConvExpr.isInvalid() &&
5148 "should be able to convert any integer type to size type");
5149 return ConvExpr.get();
5150 };
5151
5152 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5153 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5154 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5155 if (!RowIdx || !ColumnIdx)
5156 return ExprError();
5157
5158 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5159 MTy->getElementType(), RBLoc);
5160}
5161
5162void Sema::CheckAddressOfNoDeref(const Expr *E) {
5163 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5164 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5165
5166 // For expressions like `&(*s).b`, the base is recorded and what should be
5167 // checked.
5168 const MemberExpr *Member = nullptr;
5169 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5170 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5171
5172 LastRecord.PossibleDerefs.erase(StrippedExpr);
5173}
5174
5175void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5177 return;
5178
5179 QualType ResultTy = E->getType();
5180 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5181
5182 // Bail if the element is an array since it is not memory access.
5183 if (isa<ArrayType>(ResultTy))
5184 return;
5185
5186 if (ResultTy->hasAttr(attr::NoDeref)) {
5187 LastRecord.PossibleDerefs.insert(E);
5188 return;
5189 }
5190
5191 // Check if the base type is a pointer to a member access of a struct
5192 // marked with noderef.
5193 const Expr *Base = E->getBase();
5194 QualType BaseTy = Base->getType();
5195 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5196 // Not a pointer access
5197 return;
5198
5199 const MemberExpr *Member = nullptr;
5200 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5201 Member->isArrow())
5202 Base = Member->getBase();
5203
5204 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5205 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5206 LastRecord.PossibleDerefs.insert(E);
5207 }
5208}
5209
5212 Expr *Idx, SourceLocation RLoc) {
5213 Expr *LHSExp = Base;
5214 Expr *RHSExp = Idx;
5215
5218
5219 // Per C++ core issue 1213, the result is an xvalue if either operand is
5220 // a non-lvalue array, and an lvalue otherwise.
5221 if (getLangOpts().CPlusPlus11) {
5222 for (auto *Op : {LHSExp, RHSExp}) {
5223 Op = Op->IgnoreImplicit();
5224 if (Op->getType()->isArrayType() && !Op->isLValue())
5225 VK = VK_XValue;
5226 }
5227 }
5228
5229 // Perform default conversions.
5230 if (!LHSExp->getType()->getAs<VectorType>()) {
5232 if (Result.isInvalid())
5233 return ExprError();
5234 LHSExp = Result.get();
5235 }
5237 if (Result.isInvalid())
5238 return ExprError();
5239 RHSExp = Result.get();
5240
5241 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5242
5243 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5244 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5245 // in the subscript position. As a result, we need to derive the array base
5246 // and index from the expression types.
5247 Expr *BaseExpr, *IndexExpr;
5248 QualType ResultType;
5249 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5250 BaseExpr = LHSExp;
5251 IndexExpr = RHSExp;
5252 ResultType =
5254 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5255 BaseExpr = LHSExp;
5256 IndexExpr = RHSExp;
5257 ResultType = PTy->getPointeeType();
5258 } else if (const ObjCObjectPointerType *PTy =
5259 LHSTy->getAs<ObjCObjectPointerType>()) {
5260 BaseExpr = LHSExp;
5261 IndexExpr = RHSExp;
5262
5263 // Use custom logic if this should be the pseudo-object subscript
5264 // expression.
5266 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5267 nullptr, nullptr);
5268
5269 ResultType = PTy->getPointeeType();
5270 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5271 // Handle the uncommon case of "123[Ptr]".
5272 BaseExpr = RHSExp;
5273 IndexExpr = LHSExp;
5274 ResultType = PTy->getPointeeType();
5275 } else if (const ObjCObjectPointerType *PTy =
5276 RHSTy->getAs<ObjCObjectPointerType>()) {
5277 // Handle the uncommon case of "123[Ptr]".
5278 BaseExpr = RHSExp;
5279 IndexExpr = LHSExp;
5280 ResultType = PTy->getPointeeType();
5282 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5283 << ResultType << BaseExpr->getSourceRange();
5284 return ExprError();
5285 }
5286 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5287 BaseExpr = LHSExp; // vectors: V[123]
5288 IndexExpr = RHSExp;
5289 // We apply C++ DR1213 to vector subscripting too.
5290 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5291 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5292 if (Materialized.isInvalid())
5293 return ExprError();
5294 LHSExp = Materialized.get();
5295 }
5296 VK = LHSExp->getValueKind();
5297 if (VK != VK_PRValue)
5298 OK = OK_VectorComponent;
5299
5300 ResultType = VTy->getElementType();
5301 QualType BaseType = BaseExpr->getType();
5302 Qualifiers BaseQuals = BaseType.getQualifiers();
5303 Qualifiers MemberQuals = ResultType.getQualifiers();
5304 Qualifiers Combined = BaseQuals + MemberQuals;
5305 if (Combined != MemberQuals)
5306 ResultType = Context.getQualifiedType(ResultType, Combined);
5307 } else if (LHSTy->isBuiltinType() &&
5308 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5309 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5310 if (BTy->isSVEBool())
5311 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5312 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5313
5314 BaseExpr = LHSExp;
5315 IndexExpr = RHSExp;
5316 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5317 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5318 if (Materialized.isInvalid())
5319 return ExprError();
5320 LHSExp = Materialized.get();
5321 }
5322 VK = LHSExp->getValueKind();
5323 if (VK != VK_PRValue)
5324 OK = OK_VectorComponent;
5325
5326 ResultType = BTy->getSveEltType(Context);
5327
5328 QualType BaseType = BaseExpr->getType();
5329 Qualifiers BaseQuals = BaseType.getQualifiers();
5330 Qualifiers MemberQuals = ResultType.getQualifiers();
5331 Qualifiers Combined = BaseQuals + MemberQuals;
5332 if (Combined != MemberQuals)
5333 ResultType = Context.getQualifiedType(ResultType, Combined);
5334 } else if (LHSTy->isArrayType()) {
5335 // If we see an array that wasn't promoted by
5336 // DefaultFunctionArrayLvalueConversion, it must be an array that
5337 // wasn't promoted because of the C90 rule that doesn't
5338 // allow promoting non-lvalue arrays. Warn, then
5339 // force the promotion here.
5340 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5341 << LHSExp->getSourceRange();
5342 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5343 CK_ArrayToPointerDecay).get();
5344 LHSTy = LHSExp->getType();
5345
5346 BaseExpr = LHSExp;
5347 IndexExpr = RHSExp;
5348 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5349 } else if (RHSTy->isArrayType()) {
5350 // Same as previous, except for 123[f().a] case
5351 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5352 << RHSExp->getSourceRange();
5353 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5354 CK_ArrayToPointerDecay).get();
5355 RHSTy = RHSExp->getType();
5356
5357 BaseExpr = RHSExp;
5358 IndexExpr = LHSExp;
5359 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5360 } else {
5361 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5362 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5363 }
5364 // C99 6.5.2.1p1
5365 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5366 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5367 << IndexExpr->getSourceRange());
5368
5369 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5370 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5371 !IndexExpr->isTypeDependent()) {
5372 std::optional<llvm::APSInt> IntegerContantExpr =
5374 if (!IntegerContantExpr.has_value() ||
5375 IntegerContantExpr.value().isNegative())
5376 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5377 }
5378
5379 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5380 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5381 // type. Note that Functions are not objects, and that (in C99 parlance)
5382 // incomplete types are not object types.
5383 if (ResultType->isFunctionType()) {
5384 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5385 << ResultType << BaseExpr->getSourceRange();
5386 return ExprError();
5387 }
5388
5389 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5390 // GNU extension: subscripting on pointer to void
5391 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5392 << BaseExpr->getSourceRange();
5393
5394 // C forbids expressions of unqualified void type from being l-values.
5395 // See IsCForbiddenLValueType.
5396 if (!ResultType.hasQualifiers())
5397 VK = VK_PRValue;
5398 } else if (!ResultType->isDependentType() &&
5399 !ResultType.isWebAssemblyReferenceType() &&
5401 LLoc, ResultType,
5402 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5403 return ExprError();
5404
5405 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5406 !ResultType.isCForbiddenLValueType());
5407
5409 FunctionScopes.size() > 1) {
5410 if (auto *TT =
5411 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5412 for (auto I = FunctionScopes.rbegin(),
5413 E = std::prev(FunctionScopes.rend());
5414 I != E; ++I) {
5415 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5416 if (CSI == nullptr)
5417 break;
5418 DeclContext *DC = nullptr;
5419 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5420 DC = LSI->CallOperator;
5421 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5422 DC = CRSI->TheCapturedDecl;
5423 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5424 DC = BSI->TheDecl;
5425 if (DC) {
5426 if (DC->containsDecl(TT->getDecl()))
5427 break;
5429 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5430 }
5431 }
5432 }
5433 }
5434
5435 return new (Context)
5436 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5437}
5438
5440 ParmVarDecl *Param, Expr *RewrittenInit,
5441 bool SkipImmediateInvocations) {
5442 if (Param->hasUnparsedDefaultArg()) {
5443 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5444 // If we've already cleared out the location for the default argument,
5445 // that means we're parsing it right now.
5446 if (!UnparsedDefaultArgLocs.count(Param)) {
5447 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5448 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5449 Param->setInvalidDecl();
5450 return true;
5451 }
5452
5453 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5454 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5456 diag::note_default_argument_declared_here);
5457 return true;
5458 }
5459
5460 if (Param->hasUninstantiatedDefaultArg()) {
5461 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5462 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5463 return true;
5464 }
5465
5466 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5467 assert(Init && "default argument but no initializer?");
5468
5469 // If the default expression creates temporaries, we need to
5470 // push them to the current stack of expression temporaries so they'll
5471 // be properly destroyed.
5472 // FIXME: We should really be rebuilding the default argument with new
5473 // bound temporaries; see the comment in PR5810.
5474 // We don't need to do that with block decls, though, because
5475 // blocks in default argument expression can never capture anything.
5476 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5477 // Set the "needs cleanups" bit regardless of whether there are
5478 // any explicit objects.
5479 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5480 // Append all the objects to the cleanup list. Right now, this
5481 // should always be a no-op, because blocks in default argument
5482 // expressions should never be able to capture anything.
5483 assert(!InitWithCleanup->getNumObjects() &&
5484 "default argument expression has capturing blocks?");
5485 }
5486 // C++ [expr.const]p15.1:
5487 // An expression or conversion is in an immediate function context if it is
5488 // potentially evaluated and [...] its innermost enclosing non-block scope
5489 // is a function parameter scope of an immediate function.
5491 *this,
5495 Param);
5496 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5497 SkipImmediateInvocations;
5498 runWithSufficientStackSpace(CallLoc, [&] {
5499 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5500 });
5501 return false;
5502}
5503
5504struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5506 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5507
5508 bool HasImmediateCalls = false;
5509 bool shouldVisitImplicitCode() const { return true; }
5510
5512 if (const FunctionDecl *FD = E->getDirectCallee())
5513 HasImmediateCalls |= FD->isImmediateFunction();
5515 }
5516
5518 if (const FunctionDecl *FD = E->getConstructor())
5519 HasImmediateCalls |= FD->isImmediateFunction();
5521 }
5522
5523 // SourceLocExpr are not immediate invocations
5524 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5525 // need to be rebuilt so that they refer to the correct SourceLocation and
5526 // DeclContext.
5528 HasImmediateCalls = true;
5530 }
5531
5532 // A nested lambda might have parameters with immediate invocations
5533 // in their default arguments.
5534 // The compound statement is not visited (as it does not constitute a
5535 // subexpression).
5536 // FIXME: We should consider visiting and transforming captures
5537 // with init expressions.
5539 return VisitCXXMethodDecl(E->getCallOperator());
5540 }
5541
5543 return TraverseStmt(E->getExpr());
5544 }
5545
5547 return TraverseStmt(E->getExpr());
5548 }
5549};
5550
5552 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5554 : TreeTransform(SemaRef) {}
5555
5556 // Lambda can only have immediate invocations in the default
5557 // args of their parameters, which is transformed upon calling the closure.
5558 // The body is not a subexpression, so we have nothing to do.
5559 // FIXME: Immediate calls in capture initializers should be transformed.
5562
5563 // Make sure we don't rebuild the this pointer as it would
5564 // cause it to incorrectly point it to the outermost class
5565 // in the case of nested struct initialization.
5567};
5568
5570 FunctionDecl *FD, ParmVarDecl *Param,
5571 Expr *Init) {
5572 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5573
5574 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5575 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5576 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5577 InitializationContext =
5579 if (!InitializationContext.has_value())
5580 InitializationContext.emplace(CallLoc, Param, CurContext);
5581
5582 if (!Init && !Param->hasUnparsedDefaultArg()) {
5583 // Mark that we are replacing a default argument first.
5584 // If we are instantiating a template we won't have to
5585 // retransform immediate calls.
5586 // C++ [expr.const]p15.1:
5587 // An expression or conversion is in an immediate function context if it
5588 // is potentially evaluated and [...] its innermost enclosing non-block
5589 // scope is a function parameter scope of an immediate function.
5591 *this,
5595 Param);
5596
5597 if (Param->hasUninstantiatedDefaultArg()) {
5598 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5599 return ExprError();
5600 }
5601 // CWG2631
5602 // An immediate invocation that is not evaluated where it appears is
5603 // evaluated and checked for whether it is a constant expression at the
5604 // point where the enclosing initializer is used in a function call.
5606 if (!NestedDefaultChecking)
5607 V.TraverseDecl(Param);
5608
5609 // Rewrite the call argument that was created from the corresponding
5610 // parameter's default argument.
5611 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5612 if (V.HasImmediateCalls)
5613 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5614 CallLoc, Param, CurContext};
5615 // Pass down lifetime extending flag, and collect temporaries in
5616 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5619 ExprResult Res;
5620 runWithSufficientStackSpace(CallLoc, [&] {
5621 Res = Immediate.TransformInitializer(Param->getInit(),
5622 /*NotCopy=*/false);
5623 });
5624 if (Res.isInvalid())
5625 return ExprError();
5626 Res = ConvertParamDefaultArgument(Param, Res.get(),
5627 Res.get()->getBeginLoc());
5628 if (Res.isInvalid())
5629 return ExprError();
5630 Init = Res.get();
5631 }
5632 }
5633
5635 CallLoc, FD, Param, Init,
5636 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5637 return ExprError();
5638
5639 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5640 Init, InitializationContext->Context);
5641}
5642
5644 assert(Field->hasInClassInitializer());
5645
5646 // If we might have already tried and failed to instantiate, don't try again.
5647 if (Field->isInvalidDecl())
5648 return ExprError();
5649
5650 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5651
5652 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5653
5654 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5655 InitializationContext =
5657 if (!InitializationContext.has_value())
5658 InitializationContext.emplace(Loc, Field, CurContext);
5659
5660 Expr *Init = nullptr;
5661
5662 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5663
5666
5667 if (!Field->getInClassInitializer()) {
5668 // Maybe we haven't instantiated the in-class initializer. Go check the
5669 // pattern FieldDecl to see if it has one.
5670 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5671 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5673 ClassPattern->lookup(Field->getDeclName());
5674
5675 FieldDecl *Pattern = nullptr;
5676 for (auto *L : Lookup) {
5677 if ((Pattern = dyn_cast<FieldDecl>(L)))
5678 break;
5679 }
5680 assert(Pattern && "We must have set the Pattern!");
5681 if (!Pattern->hasInClassInitializer() ||
5682 InstantiateInClassInitializer(Loc, Field, Pattern,
5684 Field->setInvalidDecl();
5685 return ExprError();
5686 }
5687 }
5688 }
5689
5690 // CWG2631
5691 // An immediate invocation that is not evaluated where it appears is
5692 // evaluated and checked for whether it is a constant expression at the
5693 // point where the enclosing initializer is used in a [...] a constructor
5694 // definition, or an aggregate initialization.
5696 if (!NestedDefaultChecking)
5697 V.TraverseDecl(Field);
5698 if (V.HasImmediateCalls) {
5699 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5700 CurContext};
5701 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5702 NestedDefaultChecking;
5703
5705 ExprResult Res;
5707 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5708 /*CXXDirectInit=*/false);
5709 });
5710 if (!Res.isInvalid())
5711 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5712 if (Res.isInvalid()) {
5713 Field->setInvalidDecl();
5714 return ExprError();
5715 }
5716 Init = Res.get();
5717 }
5718
5719 if (Field->getInClassInitializer()) {
5720 Expr *E = Init ? Init : Field->getInClassInitializer();
5721 if (!NestedDefaultChecking)
5723 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5724 });
5725 // C++11 [class.base.init]p7:
5726 // The initialization of each base and member constitutes a
5727 // full-expression.
5728 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5729 if (Res.isInvalid()) {
5730 Field->setInvalidDecl();
5731 return ExprError();
5732 }
5733 Init = Res.get();
5734
5735 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5736 Field, InitializationContext->Context,
5737 Init);
5738 }
5739
5740 // DR1351:
5741 // If the brace-or-equal-initializer of a non-static data member
5742 // invokes a defaulted default constructor of its class or of an
5743 // enclosing class in a potentially evaluated subexpression, the
5744 // program is ill-formed.
5745 //
5746 // This resolution is unworkable: the exception specification of the
5747 // default constructor can be needed in an unevaluated context, in
5748 // particular, in the operand of a noexcept-expression, and we can be
5749 // unable to compute an exception specification for an enclosed class.
5750 //
5751 // Any attempt to resolve the exception specification of a defaulted default
5752 // constructor before the initializer is lexically complete will ultimately
5753 // come here at which point we can diagnose it.
5754 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5755 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5756 << OutermostClass << Field;
5757 Diag(Field->getEndLoc(),
5758 diag::note_default_member_initializer_not_yet_parsed);
5759 // Recover by marking the field invalid, unless we're in a SFINAE context.
5760 if (!isSFINAEContext())
5761 Field->setInvalidDecl();
5762 return ExprError();
5763}
5764
5767 Expr *Fn) {
5768 if (Proto && Proto->isVariadic()) {
5769 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5770 return VariadicConstructor;
5771 else if (Fn && Fn->getType()->isBlockPointerType())
5772 return VariadicBlock;
5773 else if (FDecl) {
5774 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5775 if (Method->isInstance())
5776 return VariadicMethod;
5777 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5778 return VariadicMethod;
5779 return VariadicFunction;
5780 }
5781 return VariadicDoesNotApply;
5782}
5783
5784namespace {
5785class FunctionCallCCC final : public FunctionCallFilterCCC {
5786public:
5787 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5788 unsigned NumArgs, MemberExpr *ME)
5789 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5790 FunctionName(FuncName) {}
5791
5792 bool ValidateCandidate(const TypoCorrection &candidate) override {
5793 if (!candidate.getCorrectionSpecifier() ||
5794 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5795 return false;
5796 }
5797
5799 }
5800
5801 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5802 return std::make_unique<FunctionCallCCC>(*this);
5803 }
5804
5805private:
5806 const IdentifierInfo *const FunctionName;
5807};
5808}
5809
5811 FunctionDecl *FDecl,
5812 ArrayRef<Expr *> Args) {
5813 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5814 DeclarationName FuncName = FDecl->getDeclName();
5815 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5816
5817 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5818 if (TypoCorrection Corrected = S.CorrectTypo(
5820 S.getScopeForContext(S.CurContext), nullptr, CCC,
5822 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5823 if (Corrected.isOverloaded()) {
5826 for (NamedDecl *CD : Corrected) {
5827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5829 OCS);
5830 }
5831 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5832 case OR_Success:
5833 ND = Best->FoundDecl;
5834 Corrected.setCorrectionDecl(ND);
5835 break;
5836 default:
5837 break;
5838 }
5839 }
5840 ND = ND->getUnderlyingDecl();
5841 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5842 return Corrected;
5843 }
5844 }
5845 return TypoCorrection();
5846}
5847
5848/// ConvertArgumentsForCall - Converts the arguments specified in
5849/// Args/NumArgs to the parameter types of the function FDecl with
5850/// function prototype Proto. Call is the call expression itself, and
5851/// Fn is the function expression. For a C++ member function, this
5852/// routine does not attempt to convert the object argument. Returns
5853/// true if the call is ill-formed.
5854bool
5856 FunctionDecl *FDecl,
5857 const FunctionProtoType *Proto,
5858 ArrayRef<Expr *> Args,
5859 SourceLocation RParenLoc,
5860 bool IsExecConfig) {
5861 // Bail out early if calling a builtin with custom typechecking.
5862 if (FDecl)
5863 if (unsigned ID = FDecl->getBuiltinID())
5865 return false;
5866
5867 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5868 // assignment, to the types of the corresponding parameter, ...
5869 bool HasExplicitObjectParameter =
5870 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5871 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5872 unsigned NumParams = Proto->getNumParams();
5873 bool Invalid = false;
5874 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5875 unsigned FnKind = Fn->getType()->isBlockPointerType()
5876 ? 1 /* block */
5877 : (IsExecConfig ? 3 /* kernel function (exec config) */
5878 : 0 /* function */);
5879
5880 // If too few arguments are available (and we don't have default
5881 // arguments for the remaining parameters), don't make the call.
5882 if (Args.size() < NumParams) {
5883 if (Args.size() < MinArgs) {
5884 TypoCorrection TC;
5885 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5886 unsigned diag_id =
5887 MinArgs == NumParams && !Proto->isVariadic()
5888 ? diag::err_typecheck_call_too_few_args_suggest
5889 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5891 TC, PDiag(diag_id)
5892 << FnKind << MinArgs - ExplicitObjectParameterOffset
5893 << static_cast<unsigned>(Args.size()) -
5894 ExplicitObjectParameterOffset
5895 << HasExplicitObjectParameter << TC.getCorrectionRange());
5896 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5897 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5898 ->getDeclName())
5899 Diag(RParenLoc,
5900 MinArgs == NumParams && !Proto->isVariadic()
5901 ? diag::err_typecheck_call_too_few_args_one
5902 : diag::err_typecheck_call_too_few_args_at_least_one)
5903 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5904 << HasExplicitObjectParameter << Fn->getSourceRange();
5905 else
5906 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5907 ? diag::err_typecheck_call_too_few_args
5908 : diag::err_typecheck_call_too_few_args_at_least)
5909 << FnKind << MinArgs - ExplicitObjectParameterOffset
5910 << static_cast<unsigned>(Args.size()) -
5911 ExplicitObjectParameterOffset
5912 << HasExplicitObjectParameter << Fn->getSourceRange();
5913
5914 // Emit the location of the prototype.
5915 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5916 Diag(FDecl->getLocation(), diag::note_callee_decl)
5917 << FDecl << FDecl->getParametersSourceRange();
5918
5919 return true;
5920 }
5921 // We reserve space for the default arguments when we create
5922 // the call expression, before calling ConvertArgumentsForCall.
5923 assert((Call->getNumArgs() == NumParams) &&
5924 "We should have reserved space for the default arguments before!");
5925 }
5926
5927 // If too many are passed and not variadic, error on the extras and drop
5928 // them.
5929 if (Args.size() > NumParams) {
5930 if (!Proto->isVariadic()) {
5931 TypoCorrection TC;
5932 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5933 unsigned diag_id =
5934 MinArgs == NumParams && !Proto->isVariadic()
5935 ? diag::err_typecheck_call_too_many_args_suggest
5936 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5938 TC, PDiag(diag_id)
5939 << FnKind << NumParams - ExplicitObjectParameterOffset
5940 << static_cast<unsigned>(Args.size()) -
5941 ExplicitObjectParameterOffset
5942 << HasExplicitObjectParameter << TC.getCorrectionRange());
5943 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5944 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5945 ->getDeclName())
5946 Diag(Args[NumParams]->getBeginLoc(),
5947 MinArgs == NumParams
5948 ? diag::err_typecheck_call_too_many_args_one
5949 : diag::err_typecheck_call_too_many_args_at_most_one)
5950 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5951 << static_cast<unsigned>(Args.size()) -
5952 ExplicitObjectParameterOffset
5953 << HasExplicitObjectParameter << Fn->getSourceRange()
5954 << SourceRange(Args[NumParams]->getBeginLoc(),
5955 Args.back()->getEndLoc());
5956 else
5957 Diag(Args[NumParams]->getBeginLoc(),
5958 MinArgs == NumParams
5959 ? diag::err_typecheck_call_too_many_args
5960 : diag::err_typecheck_call_too_many_args_at_most)
5961 << FnKind << NumParams - ExplicitObjectParameterOffset
5962 << static_cast<unsigned>(Args.size()) -
5963 ExplicitObjectParameterOffset
5964 << HasExplicitObjectParameter << Fn->getSourceRange()
5965 << SourceRange(Args[NumParams]->getBeginLoc(),
5966 Args.back()->getEndLoc());
5967
5968 // Emit the location of the prototype.
5969 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5970 Diag(FDecl->getLocation(), diag::note_callee_decl)
5971 << FDecl << FDecl->getParametersSourceRange();
5972
5973 // This deletes the extra arguments.
5974 Call->shrinkNumArgs(NumParams);
5975 return true;
5976 }
5977 }
5978 SmallVector<Expr *, 8> AllArgs;
5979 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5980
5981 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5982 AllArgs, CallType);
5983 if (Invalid)
5984 return true;
5985 unsigned TotalNumArgs = AllArgs.size();
5986 for (unsigned i = 0; i < TotalNumArgs; ++i)
5987 Call->setArg(i, AllArgs[i]);
5988
5989 Call->computeDependence();
5990 return false;
5991}
5992
5994 const FunctionProtoType *Proto,
5995 unsigned FirstParam, ArrayRef<Expr *> Args,
5996 SmallVectorImpl<Expr *> &AllArgs,
5997 VariadicCallType CallType, bool AllowExplicit,
5998 bool IsListInitialization) {
5999 unsigned NumParams = Proto->getNumParams();
6000 bool Invalid = false;
6001 size_t ArgIx = 0;
6002 // Continue to check argument types (even if we have too few/many args).
6003 for (unsigned i = FirstParam; i < NumParams; i++) {
6004 QualType ProtoArgType = Proto->getParamType(i);
6005
6006 Expr *Arg;
6007 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6008 if (ArgIx < Args.size()) {
6009 Arg = Args[ArgIx++];
6010
6011 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6012 diag::err_call_incomplete_argument, Arg))
6013 return true;
6014
6015 // Strip the unbridged-cast placeholder expression off, if applicable.
6016 bool CFAudited = false;
6017 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6018 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6019 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6020 Arg = ObjC().stripARCUnbridgedCast(Arg);
6021 else if (getLangOpts().ObjCAutoRefCount &&
6022 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6023 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6024 CFAudited = true;
6025
6026 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6027 ProtoArgType->isBlockPointerType())
6028 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6029 BE->getBlockDecl()->setDoesNotEscape();
6030
6031 InitializedEntity Entity =
6033 ProtoArgType)
6035 Context, ProtoArgType, Proto->isParamConsumed(i));
6036
6037 // Remember that parameter belongs to a CF audited API.
6038 if (CFAudited)
6039 Entity.setParameterCFAudited();
6040
6042 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6043 if (ArgE.isInvalid())
6044 return true;
6045
6046 Arg = ArgE.getAs<Expr>();
6047 } else {
6048 assert(Param && "can't use default arguments without a known callee");
6049
6050 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6051 if (ArgExpr.isInvalid())
6052 return true;
6053
6054 Arg = ArgExpr.getAs<Expr>();
6055 }
6056
6057 // Check for array bounds violations for each argument to the call. This
6058 // check only triggers warnings when the argument isn't a more complex Expr
6059 // with its own checking, such as a BinaryOperator.
6060 CheckArrayAccess(Arg);
6061
6062 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6063 CheckStaticArrayArgument(CallLoc, Param, Arg);
6064
6065 AllArgs.push_back(Arg);
6066 }
6067
6068 // If this is a variadic call, handle args passed through "...".
6069 if (CallType != VariadicDoesNotApply) {
6070 // Assume that extern "C" functions with variadic arguments that
6071 // return __unknown_anytype aren't *really* variadic.
6072 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6073 FDecl->isExternC()) {
6074 for (Expr *A : Args.slice(ArgIx)) {
6075 QualType paramType; // ignored
6076 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6077 Invalid |= arg.isInvalid();
6078 AllArgs.push_back(arg.get());
6079 }
6080
6081 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6082 } else {
6083 for (Expr *A : Args.slice(ArgIx)) {
6084 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6085 Invalid |= Arg.isInvalid();
6086 AllArgs.push_back(Arg.get());
6087 }
6088 }
6089
6090 // Check for array bounds violations.
6091 for (Expr *A : Args.slice(ArgIx))
6092 CheckArrayAccess(A);
6093 }
6094 return Invalid;
6095}
6096
6098 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6099 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6100 TL = DTL.getOriginalLoc();
6101 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6102 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6103 << ATL.getLocalSourceRange();
6104}
6105
6106/// CheckStaticArrayArgument - If the given argument corresponds to a static
6107/// array parameter, check that it is non-null, and that if it is formed by
6108/// array-to-pointer decay, the underlying array is sufficiently large.
6109///
6110/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6111/// array type derivation, then for each call to the function, the value of the
6112/// corresponding actual argument shall provide access to the first element of
6113/// an array with at least as many elements as specified by the size expression.
6114void
6116 ParmVarDecl *Param,
6117 const Expr *ArgExpr) {
6118 // Static array parameters are not supported in C++.
6119 if (!Param || getLangOpts().CPlusPlus)
6120 return;
6121
6122 QualType OrigTy = Param->getOriginalType();
6123
6124 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6125 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6126 return;
6127
6128 if (ArgExpr->isNullPointerConstant(Context,
6130 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6131 DiagnoseCalleeStaticArrayParam(*this, Param);
6132 return;
6133 }
6134
6135 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6136 if (!CAT)
6137 return;
6138
6139 const ConstantArrayType *ArgCAT =
6141 if (!ArgCAT)
6142 return;
6143
6144 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6145 ArgCAT->getElementType())) {
6146 if (ArgCAT->getSize().ult(CAT->getSize())) {
6147 Diag(CallLoc, diag::warn_static_array_too_small)
6148 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6149 << (unsigned)CAT->getZExtSize() << 0;
6150 DiagnoseCalleeStaticArrayParam(*this, Param);
6151 }
6152 return;
6153 }
6154
6155 std::optional<CharUnits> ArgSize =
6157 std::optional<CharUnits> ParmSize =
6159 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6160 Diag(CallLoc, diag::warn_static_array_too_small)
6161 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6162 << (unsigned)ParmSize->getQuantity() << 1;
6163 DiagnoseCalleeStaticArrayParam(*this, Param);
6164 }
6165}
6166
6167/// Given a function expression of unknown-any type, try to rebuild it
6168/// to have a function type.
6170
6171/// Is the given type a placeholder that we need to lower out
6172/// immediately during argument processing?
6174 // Placeholders are never sugared.
6175 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6176 if (!placeholder) return false;
6177
6178 switch (placeholder->getKind()) {
6179 // Ignore all the non-placeholder types.
6180#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6181 case BuiltinType::Id:
6182#include "clang/Basic/OpenCLImageTypes.def"
6183#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6184 case BuiltinType::Id:
6185#include "clang/Basic/OpenCLExtensionTypes.def"
6186 // In practice we'll never use this, since all SVE types are sugared
6187 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6188#define SVE_TYPE(Name, Id, SingletonId) \
6189 case BuiltinType::Id:
6190#include "clang/Basic/AArch64SVEACLETypes.def"
6191#define PPC_VECTOR_TYPE(Name, Id, Size) \
6192 case BuiltinType::Id:
6193#include "clang/Basic/PPCTypes.def"
6194#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6195#include "clang/Basic/RISCVVTypes.def"
6196#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6197#include "clang/Basic/WebAssemblyReferenceTypes.def"
6198#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6199#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6200#include "clang/AST/BuiltinTypes.def"
6201 return false;
6202
6203 case BuiltinType::UnresolvedTemplate:
6204 // We cannot lower out overload sets; they might validly be resolved
6205 // by the call machinery.
6206 case BuiltinType::Overload:
6207 return false;
6208
6209 // Unbridged casts in ARC can be handled in some call positions and
6210 // should be left in place.
6211 case BuiltinType::ARCUnbridgedCast:
6212 return false;
6213
6214 // Pseudo-objects should be converted as soon as possible.
6215 case BuiltinType::PseudoObject:
6216 return true;
6217
6218 // The debugger mode could theoretically but currently does not try
6219 // to resolve unknown-typed arguments based on known parameter types.
6220 case BuiltinType::UnknownAny:
6221 return true;
6222
6223 // These are always invalid as call arguments and should be reported.
6224 case BuiltinType::BoundMember:
6225 case BuiltinType::BuiltinFn:
6226 case BuiltinType::IncompleteMatrixIdx:
6227 case BuiltinType::ArraySection:
6228 case BuiltinType::OMPArrayShaping:
6229 case BuiltinType::OMPIterator:
6230 return true;
6231
6232 }
6233 llvm_unreachable("bad builtin type kind");
6234}
6235
6237 // Apply this processing to all the arguments at once instead of
6238 // dying at the first failure.
6239 bool hasInvalid = false;
6240 for (size_t i = 0, e = args.size(); i != e; i++) {
6241 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6242 ExprResult result = CheckPlaceholderExpr(args[i]);
6243 if (result.isInvalid()) hasInvalid = true;
6244 else args[i] = result.get();
6245 }
6246 }
6247 return hasInvalid;
6248}
6249
6250/// If a builtin function has a pointer argument with no explicit address
6251/// space, then it should be able to accept a pointer to any address
6252/// space as input. In order to do this, we need to replace the
6253/// standard builtin declaration with one that uses the same address space
6254/// as the call.
6255///
6256/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6257/// it does not contain any pointer arguments without
6258/// an address space qualifer. Otherwise the rewritten
6259/// FunctionDecl is returned.
6260/// TODO: Handle pointer return types.
6262 FunctionDecl *FDecl,
6263 MultiExprArg ArgExprs) {
6264
6265 QualType DeclType = FDecl->getType();
6266 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6267
6268 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6269 ArgExprs.size() < FT->getNumParams())
6270 return nullptr;
6271
6272 bool NeedsNewDecl = false;
6273 unsigned i = 0;
6274 SmallVector<QualType, 8> OverloadParams;
6275
6276 for (QualType ParamType : FT->param_types()) {
6277
6278 // Convert array arguments to pointer to simplify type lookup.
6279 ExprResult ArgRes =
6281 if (ArgRes.isInvalid())
6282 return nullptr;
6283 Expr *Arg = ArgRes.get();
6284 QualType ArgType = Arg->getType();
6285 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6286 !ArgType->isPointerType() ||
6287 !ArgType->getPointeeType().hasAddressSpace() ||
6289 OverloadParams.push_back(ParamType);
6290 continue;
6291 }
6292
6293 QualType PointeeType = ParamType->getPointeeType();
6294 if (PointeeType.hasAddressSpace())
6295 continue;
6296
6297 NeedsNewDecl = true;
6298 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6299
6300 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6301 OverloadParams.push_back(Context.getPointerType(PointeeType));
6302 }
6303
6304 if (!NeedsNewDecl)
6305 return nullptr;
6306
6308 EPI.Variadic = FT->isVariadic();
6309 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6310 OverloadParams, EPI);
6311 DeclContext *Parent = FDecl->getParent();
6312 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6313 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6314 FDecl->getIdentifier(), OverloadTy,
6315 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6316 false,
6317 /*hasPrototype=*/true);
6319 FT = cast<FunctionProtoType>(OverloadTy);
6320 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6321 QualType ParamType = FT->getParamType(i);
6322 ParmVarDecl *Parm =
6323 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6324 SourceLocation(), nullptr, ParamType,
6325 /*TInfo=*/nullptr, SC_None, nullptr);
6326 Parm->setScopeInfo(0, i);
6327 Params.push_back(Parm);
6328 }
6329 OverloadDecl->setParams(Params);
6330 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6331 return OverloadDecl;
6332}
6333
6334static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6335 FunctionDecl *Callee,
6336 MultiExprArg ArgExprs) {
6337 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6338 // similar attributes) really don't like it when functions are called with an
6339 // invalid number of args.
6340 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6341 /*PartialOverloading=*/false) &&
6342 !Callee->isVariadic())
6343 return;
6344 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6345 return;
6346
6347 if (const EnableIfAttr *Attr =
6348 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6349 S.Diag(Fn->getBeginLoc(),
6350 isa<CXXMethodDecl>(Callee)
6351 ? diag::err_ovl_no_viable_member_function_in_call
6352 : diag::err_ovl_no_viable_function_in_call)
6353 << Callee << Callee->getSourceRange();
6354 S.Diag(Callee->getLocation(),
6355 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6356 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6357 return;
6358 }
6359}
6360
6362 const UnresolvedMemberExpr *const UME, Sema &S) {
6363
6364 const auto GetFunctionLevelDCIfCXXClass =
6365 [](Sema &S) -> const CXXRecordDecl * {
6366 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6367 if (!DC || !DC->getParent())
6368 return nullptr;
6369
6370 // If the call to some member function was made from within a member
6371 // function body 'M' return return 'M's parent.
6372 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6373 return MD->getParent()->getCanonicalDecl();
6374 // else the call was made from within a default member initializer of a
6375 // class, so return the class.
6376 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6377 return RD->getCanonicalDecl();
6378 return nullptr;
6379 };
6380 // If our DeclContext is neither a member function nor a class (in the
6381 // case of a lambda in a default member initializer), we can't have an
6382 // enclosing 'this'.
6383
6384 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6385 if (!CurParentClass)
6386 return false;
6387
6388 // The naming class for implicit member functions call is the class in which
6389 // name lookup starts.
6390 const CXXRecordDecl *const NamingClass =
6392 assert(NamingClass && "Must have naming class even for implicit access");
6393
6394 // If the unresolved member functions were found in a 'naming class' that is
6395 // related (either the same or derived from) to the class that contains the
6396 // member function that itself contained the implicit member access.
6397
6398 return CurParentClass == NamingClass ||
6399 CurParentClass->isDerivedFrom(NamingClass);
6400}
6401
6402static void
6404 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6405
6406 if (!UME)
6407 return;
6408
6409 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6410 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6411 // already been captured, or if this is an implicit member function call (if
6412 // it isn't, an attempt to capture 'this' should already have been made).
6413 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6414 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6415 return;
6416
6417 // Check if the naming class in which the unresolved members were found is
6418 // related (same as or is a base of) to the enclosing class.
6419
6421 return;
6422
6423
6424 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6425 // If the enclosing function is not dependent, then this lambda is
6426 // capture ready, so if we can capture this, do so.
6427 if (!EnclosingFunctionCtx->isDependentContext()) {
6428 // If the current lambda and all enclosing lambdas can capture 'this' -
6429 // then go ahead and capture 'this' (since our unresolved overload set
6430 // contains at least one non-static member function).
6431 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6432 S.CheckCXXThisCapture(CallLoc);
6433 } else if (S.CurContext->isDependentContext()) {
6434 // ... since this is an implicit member reference, that might potentially
6435 // involve a 'this' capture, mark 'this' for potential capture in
6436 // enclosing lambdas.
6437 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6438 CurLSI->addPotentialThisCapture(CallLoc);
6439 }
6440}
6441
6442// Once a call is fully resolved, warn for unqualified calls to specific
6443// C++ standard functions, like move and forward.
6445 const CallExpr *Call) {
6446 // We are only checking unary move and forward so exit early here.
6447 if (Call->getNumArgs() != 1)
6448 return;
6449
6450 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6451 if (!E || isa<UnresolvedLookupExpr>(E))
6452 return;
6453 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6454 if (!DRE || !DRE->getLocation().isValid())
6455 return;
6456
6457 if (DRE->getQualifier())
6458 return;
6459
6460 const FunctionDecl *FD = Call->getDirectCallee();
6461 if (!FD)
6462 return;
6463
6464 // Only warn for some functions deemed more frequent or problematic.
6465 unsigned BuiltinID = FD->getBuiltinID();
6466 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6467 return;
6468
6469 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6471 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6472}
6473
6475 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6476 Expr *ExecConfig) {
6478 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6479 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6480 if (Call.isInvalid())
6481 return Call;
6482
6483 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6484 // language modes.
6485 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6486 ULE && ULE->hasExplicitTemplateArgs() &&
6487 ULE->decls_begin() == ULE->decls_end()) {
6489 ? diag::warn_cxx17_compat_adl_only_template_id
6490 : diag::ext_adl_only_template_id)
6491 << ULE->getName();
6492 }
6493
6494 if (LangOpts.OpenMP)
6495 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6496 ExecConfig);
6497 if (LangOpts.CPlusPlus) {
6498 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6500 }
6501 return Call;
6502}
6503
6504/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6505/// This provides the location of the left/right parens and a list of comma
6506/// locations.
6508 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6509 Expr *ExecConfig, bool IsExecConfig,
6510 bool AllowRecovery) {
6511 // Since this might be a postfix expression, get rid of ParenListExprs.
6513 if (Result.isInvalid()) return ExprError();
6514 Fn = Result.get();
6515
6516 if (CheckArgsForPlaceholders(ArgExprs))
6517 return ExprError();
6518
6519 if (getLangOpts().CPlusPlus) {
6520 // If this is a pseudo-destructor expression, build the call immediately.
6521 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6522 if (!ArgExprs.empty()) {
6523 // Pseudo-destructor calls should not have any arguments.
6524 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6526 SourceRange(ArgExprs.front()->getBeginLoc(),
6527 ArgExprs.back()->getEndLoc()));
6528 }
6529
6530 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6531 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6532 }
6533 if (Fn->getType() == Context.PseudoObjectTy) {
6534 ExprResult result = CheckPlaceholderExpr(Fn);
6535 if (result.isInvalid()) return ExprError();
6536 Fn = result.get();
6537 }
6538
6539 // Determine whether this is a dependent call inside a C++ template,
6540 // in which case we won't do any semantic analysis now.
6541 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6542 if (ExecConfig) {
6544 cast<CallExpr>(ExecConfig), ArgExprs,
6546 RParenLoc, CurFPFeatureOverrides());
6547 } else {
6548
6550 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6551 Fn->getBeginLoc());
6552
6553 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6554 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6555 }
6556 }
6557
6558 // Determine whether this is a call to an object (C++ [over.call.object]).
6559 if (Fn->getType()->isRecordType())
6560 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6561 RParenLoc);
6562
6563 if (Fn->getType() == Context.UnknownAnyTy) {
6564 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6565 if (result.isInvalid()) return ExprError();
6566 Fn = result.get();
6567 }
6568
6569 if (Fn->getType() == Context.BoundMemberTy) {
6570 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6571 RParenLoc, ExecConfig, IsExecConfig,
6572 AllowRecovery);
6573 }
6574 }
6575
6576 // Check for overloaded calls. This can happen even in C due to extensions.
6577 if (Fn->getType() == Context.OverloadTy) {
6579
6580 // We aren't supposed to apply this logic if there's an '&' involved.
6581 if (!find.HasFormOfMemberPointer) {
6583 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6584 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6585 OverloadExpr *ovl = find.Expression;
6586 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6588 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6589 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6590 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6591 RParenLoc, ExecConfig, IsExecConfig,
6592 AllowRecovery);
6593 }
6594 }
6595
6596 // If we're directly calling a function, get the appropriate declaration.
6597 if (Fn->getType() == Context.UnknownAnyTy) {
6598 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6599 if (result.isInvalid()) return ExprError();
6600 Fn = result.get();
6601 }
6602
6603 Expr *NakedFn = Fn->IgnoreParens();
6604
6605 bool CallingNDeclIndirectly = false;
6606 NamedDecl *NDecl = nullptr;
6607 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6608 if (UnOp->getOpcode() == UO_AddrOf) {
6609 CallingNDeclIndirectly = true;
6610 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6611 }
6612 }
6613
6614 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6615 NDecl = DRE->getDecl();
6616
6617 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6618 if (FDecl && FDecl->getBuiltinID()) {
6619 // Rewrite the function decl for this builtin by replacing parameters
6620 // with no explicit address space with the address space of the arguments
6621 // in ArgExprs.
6622 if ((FDecl =
6623 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6624 NDecl = FDecl;
6626 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6627 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6628 nullptr, DRE->isNonOdrUse());
6629 }
6630 }
6631 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6632 NDecl = ME->getMemberDecl();
6633
6634 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6635 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6636 FD, /*Complain=*/true, Fn->getBeginLoc()))
6637 return ExprError();
6638
6639 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6640
6641 // If this expression is a call to a builtin function in HIP device
6642 // compilation, allow a pointer-type argument to default address space to be
6643 // passed as a pointer-type parameter to a non-default address space.
6644 // If Arg is declared in the default address space and Param is declared
6645 // in a non-default address space, perform an implicit address space cast to
6646 // the parameter type.
6647 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6648 FD->getBuiltinID()) {
6649 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6650 ParmVarDecl *Param = FD->getParamDecl(Idx);
6651 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6652 !ArgExprs[Idx]->getType()->isPointerType())
6653 continue;
6654
6655 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6656 auto ArgTy = ArgExprs[Idx]->getType();
6657 auto ArgPtTy = ArgTy->getPointeeType();
6658 auto ArgAS = ArgPtTy.getAddressSpace();
6659
6660 // Add address space cast if target address spaces are different
6661 bool NeedImplicitASC =
6662 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6663 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6664 // or from specific AS which has target AS matching that of Param.
6666 if (!NeedImplicitASC)
6667 continue;
6668
6669 // First, ensure that the Arg is an RValue.
6670 if (ArgExprs[Idx]->isGLValue()) {
6671 ArgExprs[Idx] = ImplicitCastExpr::Create(
6672 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6673 nullptr, VK_PRValue, FPOptionsOverride());
6674 }
6675
6676 // Construct a new arg type with address space of Param
6677 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6678 ArgPtQuals.setAddressSpace(ParamAS);
6679 auto NewArgPtTy =
6680 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6681 auto NewArgTy =
6683 ArgTy.getQualifiers());
6684
6685 // Finally perform an implicit address space cast
6686 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6687 CK_AddressSpaceConversion)
6688 .get();
6689 }
6690 }
6691 }
6692
6695 assert(!getLangOpts().CPlusPlus);
6696 assert((Fn->containsErrors() ||
6697 llvm::any_of(ArgExprs,
6698 [](clang::Expr *E) { return E->containsErrors(); })) &&
6699 "should only occur in error-recovery path.");
6700 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6701 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6702 }
6703 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6704 ExecConfig, IsExecConfig);
6705}
6706
6707/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6708// with the specified CallArgs
6710 MultiExprArg CallArgs) {
6711 StringRef Name = Context.BuiltinInfo.getName(Id);
6712 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6714 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6715
6716 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6717 assert(BuiltInDecl && "failed to find builtin declaration");
6718
6719 ExprResult DeclRef =
6720 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6721 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6722
6724 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6725
6726 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6727 return Call.get();
6728}
6729
6730/// Parse a __builtin_astype expression.
6731///
6732/// __builtin_astype( value, dst type )
6733///
6735 SourceLocation BuiltinLoc,
6736 SourceLocation RParenLoc) {
6737 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6738 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6739}
6740
6741/// Create a new AsTypeExpr node (bitcast) from the arguments.
6743 SourceLocation BuiltinLoc,
6744 SourceLocation RParenLoc) {
6747 QualType SrcTy = E->getType();
6748 if (!SrcTy->isDependentType() &&
6749 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6750 return ExprError(
6751 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6752 << DestTy << SrcTy << E->getSourceRange());
6753 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6754}
6755
6756/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6757/// provided arguments.
6758///
6759/// __builtin_convertvector( value, dst type )
6760///
6762 SourceLocation BuiltinLoc,
6763 SourceLocation RParenLoc) {
6764 TypeSourceInfo *TInfo;
6765 GetTypeFromParser(ParsedDestTy, &TInfo);
6766 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6767}
6768
6769/// BuildResolvedCallExpr - Build a call to a resolved expression,
6770/// i.e. an expression not of \p OverloadTy. The expression should
6771/// unary-convert to an expression of function-pointer or
6772/// block-pointer type.
6773///
6774/// \param NDecl the declaration being called, if available
6776 SourceLocation LParenLoc,
6777 ArrayRef<Expr *> Args,
6778 SourceLocation RParenLoc, Expr *Config,
6779 bool IsExecConfig, ADLCallKind UsesADL) {
6780 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6781 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6782
6783 // Functions with 'interrupt' attribute cannot be called directly.
6784 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6785 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6786 return ExprError();
6787 }
6788
6789 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6790 // so there's some risk when calling out to non-interrupt handler functions
6791 // that the callee might not preserve them. This is easy to diagnose here,
6792 // but can be very challenging to debug.
6793 // Likewise, X86 interrupt handlers may only call routines with attribute
6794 // no_caller_saved_registers since there is no efficient way to
6795 // save and restore the non-GPR state.
6796 if (auto *Caller = getCurFunctionDecl()) {
6797 if (Caller->hasAttr<ARMInterruptAttr>()) {
6798 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6799 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6800 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6801 if (FDecl)
6802 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6803 }
6804 }
6805 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6806 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6807 const TargetInfo &TI = Context.getTargetInfo();
6808 bool HasNonGPRRegisters =
6809 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6810 if (HasNonGPRRegisters &&
6811 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6812 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6813 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6814 if (FDecl)
6815 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6816 }
6817 }
6818 }
6819
6820 // Promote the function operand.
6821 // We special-case function promotion here because we only allow promoting
6822 // builtin functions to function pointers in the callee of a call.
6824 QualType ResultTy;
6825 if (BuiltinID &&
6826 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6827 // Extract the return type from the (builtin) function pointer type.
6828 // FIXME Several builtins still have setType in
6829 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6830 // Builtins.td to ensure they are correct before removing setType calls.
6831 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6832 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6833 ResultTy = FDecl->getCallResultType();
6834 } else {
6836 ResultTy = Context.BoolTy;
6837 }
6838 if (Result.isInvalid())
6839 return ExprError();
6840 Fn = Result.get();
6841
6842 // Check for a valid function type, but only if it is not a builtin which
6843 // requires custom type checking. These will be handled by
6844 // CheckBuiltinFunctionCall below just after creation of the call expression.
6845 const FunctionType *FuncT = nullptr;
6846 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6847 retry:
6848 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6849 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6850 // have type pointer to function".
6851 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6852 if (!FuncT)
6853 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6854 << Fn->getType() << Fn->getSourceRange());
6855 } else if (const BlockPointerType *BPT =
6856 Fn->getType()->getAs<BlockPointerType>()) {
6857 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6858 } else {
6859 // Handle calls to expressions of unknown-any type.
6860 if (Fn->getType() == Context.UnknownAnyTy) {
6861 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6862 if (rewrite.isInvalid())
6863 return ExprError();
6864 Fn = rewrite.get();
6865 goto retry;
6866 }
6867
6868 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6869 << Fn->getType() << Fn->getSourceRange());
6870 }
6871 }
6872
6873 // Get the number of parameters in the function prototype, if any.
6874 // We will allocate space for max(Args.size(), NumParams) arguments
6875 // in the call expression.
6876 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6877 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6878
6879 CallExpr *TheCall;
6880 if (Config) {
6881 assert(UsesADL == ADLCallKind::NotADL &&
6882 "CUDAKernelCallExpr should not use ADL");
6883 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6884 Args, ResultTy, VK_PRValue, RParenLoc,
6885 CurFPFeatureOverrides(), NumParams);
6886 } else {
6887 TheCall =
6888 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6889 CurFPFeatureOverrides(), NumParams, UsesADL);
6890 }
6891
6893 // Forget about the nulled arguments since typo correction
6894 // do not handle them well.
6895 TheCall->shrinkNumArgs(Args.size());
6896 // C cannot always handle TypoExpr nodes in builtin calls and direct
6897 // function calls as their argument checking don't necessarily handle
6898 // dependent types properly, so make sure any TypoExprs have been
6899 // dealt with.
6901 if (!Result.isUsable()) return ExprError();
6902 CallExpr *TheOldCall = TheCall;
6903 TheCall = dyn_cast<CallExpr>(Result.get());
6904 bool CorrectedTypos = TheCall != TheOldCall;
6905 if (!TheCall) return Result;
6906 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6907
6908 // A new call expression node was created if some typos were corrected.
6909 // However it may not have been constructed with enough storage. In this
6910 // case, rebuild the node with enough storage. The waste of space is
6911 // immaterial since this only happens when some typos were corrected.
6912 if (CorrectedTypos && Args.size() < NumParams) {
6913 if (Config)
6915 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6916 RParenLoc, CurFPFeatureOverrides(), NumParams);
6917 else
6918 TheCall =
6919 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6920 CurFPFeatureOverrides(), NumParams, UsesADL);
6921 }
6922 // We can now handle the nulled arguments for the default arguments.
6923 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6924 }
6925
6926 // Bail out early if calling a builtin with custom type checking.
6927 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6928 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6929
6930 if (getLangOpts().CUDA) {
6931 if (Config) {
6932 // CUDA: Kernel calls must be to global functions
6933 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6934 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6935 << FDecl << Fn->getSourceRange());
6936
6937 // CUDA: Kernel function must have 'void' return type
6938 if (!FuncT->getReturnType()->isVoidType() &&
6939 !FuncT->getReturnType()->getAs<AutoType>() &&
6941 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6942 << Fn->getType() << Fn->getSourceRange());
6943 } else {
6944 // CUDA: Calls to global functions must be configured
6945 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6946 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6947 << FDecl << Fn->getSourceRange());
6948 }
6949 }
6950
6951 // Check for a valid return type
6952 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6953 FDecl))
6954 return ExprError();
6955
6956 // We know the result type of the call, set it.
6957 TheCall->setType(FuncT->getCallResultType(Context));
6959
6960 // WebAssembly tables can't be used as arguments.
6961 if (Context.getTargetInfo().getTriple().isWasm()) {
6962 for (const Expr *Arg : Args) {
6963 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6964 return ExprError(Diag(Arg->getExprLoc(),
6965 diag::err_wasm_table_as_function_parameter));
6966 }
6967 }
6968 }
6969
6970 if (Proto) {
6971 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6972 IsExecConfig))
6973 return ExprError();
6974 } else {
6975 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6976
6977 if (FDecl) {
6978 // Check if we have too few/too many template arguments, based
6979 // on our knowledge of the function definition.
6980 const FunctionDecl *Def = nullptr;
6981 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6982 Proto = Def->getType()->getAs<FunctionProtoType>();
6983 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6984 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6985 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6986 }
6987
6988 // If the function we're calling isn't a function prototype, but we have
6989 // a function prototype from a prior declaratiom, use that prototype.
6990 if (!FDecl->hasPrototype())
6991 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6992 }
6993
6994 // If we still haven't found a prototype to use but there are arguments to
6995 // the call, diagnose this as calling a function without a prototype.
6996 // However, if we found a function declaration, check to see if
6997 // -Wdeprecated-non-prototype was disabled where the function was declared.
6998 // If so, we will silence the diagnostic here on the assumption that this
6999 // interface is intentional and the user knows what they're doing. We will
7000 // also silence the diagnostic if there is a function declaration but it
7001 // was implicitly defined (the user already gets diagnostics about the
7002 // creation of the implicit function declaration, so the additional warning
7003 // is not helpful).
7004 if (!Proto && !Args.empty() &&
7005 (!FDecl || (!FDecl->isImplicit() &&
7006 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7007 FDecl->getLocation()))))
7008 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7009 << (FDecl != nullptr) << FDecl;
7010
7011 // Promote the arguments (C99 6.5.2.2p6).
7012 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7013 Expr *Arg = Args[i];
7014
7015 if (Proto && i < Proto->getNumParams()) {
7017 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7018 ExprResult ArgE =
7020 if (ArgE.isInvalid())
7021 return true;
7022
7023 Arg = ArgE.getAs<Expr>();
7024
7025 } else {
7027
7028 if (ArgE.isInvalid())
7029 return true;
7030
7031 Arg = ArgE.getAs<Expr>();
7032 }
7033
7034 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7035 diag::err_call_incomplete_argument, Arg))
7036 return ExprError();
7037
7038 TheCall->setArg(i, Arg);
7039 }
7040 TheCall->computeDependence();
7041 }
7042
7043 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7044 if (!isa<RequiresExprBodyDecl>(CurContext) &&
7045 Method->isImplicitObjectMemberFunction())
7046 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7047 << Fn->getSourceRange() << 0);
7048
7049 // Check for sentinels
7050 if (NDecl)
7051 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7052
7053 // Warn for unions passing across security boundary (CMSE).
7054 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7055 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7056 if (const auto *RT =
7057 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7058 if (RT->getDecl()->isOrContainsUnion())
7059 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7060 << 0 << i;
7061 }
7062 }
7063 }
7064
7065 // Do special checking on direct calls to functions.
7066 if (FDecl) {
7067 if (CheckFunctionCall(FDecl, TheCall, Proto))
7068 return ExprError();
7069
7070 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7071
7072 if (BuiltinID)
7073 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7074 } else if (NDecl) {
7075 if (CheckPointerCall(NDecl, TheCall, Proto))
7076 return ExprError();
7077 } else {
7078 if (CheckOtherCall(TheCall, Proto))
7079 return ExprError();
7080 }
7081
7082 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7083}
7084
7087 SourceLocation RParenLoc, Expr *InitExpr) {
7088 assert(Ty && "ActOnCompoundLiteral(): missing type");
7089 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7090
7091 TypeSourceInfo *TInfo;
7092 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7093 if (!TInfo)
7094 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7095
7096 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7097}
7098
7101 SourceLocation RParenLoc, Expr *LiteralExpr) {
7102 QualType literalType = TInfo->getType();
7103
7104 if (literalType->isArrayType()) {
7106 LParenLoc, Context.getBaseElementType(literalType),
7107 diag::err_array_incomplete_or_sizeless_type,
7108 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7109 return ExprError();
7110 if (literalType->isVariableArrayType()) {
7111 // C23 6.7.10p4: An entity of variable length array type shall not be
7112 // initialized except by an empty initializer.
7113 //
7114 // The C extension warnings are issued from ParseBraceInitializer() and
7115 // do not need to be issued here. However, we continue to issue an error
7116 // in the case there are initializers or we are compiling C++. We allow
7117 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7118 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7119 // FIXME: should we allow this construct in C++ when it makes sense to do
7120 // so?
7121 //
7122 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7123 // shall specify an object type or an array of unknown size, but not a
7124 // variable length array type. This seems odd, as it allows 'int a[size] =
7125 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7126 // says, this is what's implemented here for C (except for the extension
7127 // that permits constant foldable size arrays)
7128
7129 auto diagID = LangOpts.CPlusPlus
7130 ? diag::err_variable_object_no_init
7131 : diag::err_compound_literal_with_vla_type;
7132 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7133 diagID))
7134 return ExprError();
7135 }
7136 } else if (!literalType->isDependentType() &&
7137 RequireCompleteType(LParenLoc, literalType,
7138 diag::err_typecheck_decl_incomplete_type,
7139 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7140 return ExprError();
7141
7142 InitializedEntity Entity
7146 SourceRange(LParenLoc, RParenLoc),
7147 /*InitList=*/true);
7148 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7149 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7150 &literalType);
7151 if (Result.isInvalid())
7152 return ExprError();
7153 LiteralExpr = Result.get();
7154
7155 bool isFileScope = !CurContext->isFunctionOrMethod();
7156
7157 // In C, compound literals are l-values for some reason.
7158 // For GCC compatibility, in C++, file-scope array compound literals with
7159 // constant initializers are also l-values, and compound literals are
7160 // otherwise prvalues.
7161 //
7162 // (GCC also treats C++ list-initialized file-scope array prvalues with
7163 // constant initializers as l-values, but that's non-conforming, so we don't
7164 // follow it there.)
7165 //
7166 // FIXME: It would be better to handle the lvalue cases as materializing and
7167 // lifetime-extending a temporary object, but our materialized temporaries
7168 // representation only supports lifetime extension from a variable, not "out
7169 // of thin air".
7170 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7171 // is bound to the result of applying array-to-pointer decay to the compound
7172 // literal.
7173 // FIXME: GCC supports compound literals of reference type, which should
7174 // obviously have a value kind derived from the kind of reference involved.
7175 ExprValueKind VK =
7176 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7177 ? VK_PRValue
7178 : VK_LValue;
7179
7180 if (isFileScope)
7181 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7182 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7183 Expr *Init = ILE->getInit(i);
7184 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7185 }
7186
7187 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7188 VK, LiteralExpr, isFileScope);
7189 if (isFileScope) {
7190 if (!LiteralExpr->isTypeDependent() &&
7191 !LiteralExpr->isValueDependent() &&
7192 !literalType->isDependentType()) // C99 6.5.2.5p3
7193 if (CheckForConstantInitializer(LiteralExpr))
7194 return ExprError();
7195 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7196 literalType.getAddressSpace() != LangAS::Default) {
7197 // Embedded-C extensions to C99 6.5.2.5:
7198 // "If the compound literal occurs inside the body of a function, the
7199 // type name shall not be qualified by an address-space qualifier."
7200 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7201 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7202 return ExprError();
7203 }
7204
7205 if (!isFileScope && !getLangOpts().CPlusPlus) {
7206 // Compound literals that have automatic storage duration are destroyed at
7207 // the end of the scope in C; in C++, they're just temporaries.
7208
7209 // Emit diagnostics if it is or contains a C union type that is non-trivial
7210 // to destruct.
7214
7215 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7216 if (literalType.isDestructedType()) {
7218 ExprCleanupObjects.push_back(E);
7220 }
7221 }
7222
7225 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7226 E->getInitializer()->getExprLoc());
7227
7228 return MaybeBindToTemporary(E);
7229}
7230
7233 SourceLocation RBraceLoc) {
7234 // Only produce each kind of designated initialization diagnostic once.
7235 SourceLocation FirstDesignator;
7236 bool DiagnosedArrayDesignator = false;
7237 bool DiagnosedNestedDesignator = false;
7238 bool DiagnosedMixedDesignator = false;
7239
7240 // Check that any designated initializers are syntactically valid in the
7241 // current language mode.
7242 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7243 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7244 if (FirstDesignator.isInvalid())
7245 FirstDesignator = DIE->getBeginLoc();
7246
7247 if (!getLangOpts().CPlusPlus)
7248 break;
7249
7250 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7251 DiagnosedNestedDesignator = true;
7252 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7253 << DIE->getDesignatorsSourceRange();
7254 }
7255
7256 for (auto &Desig : DIE->designators()) {
7257 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7258 DiagnosedArrayDesignator = true;
7259 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7260 << Desig.getSourceRange();
7261 }
7262 }
7263
7264 if (!DiagnosedMixedDesignator &&
7265 !isa<DesignatedInitExpr>(InitArgList[0])) {
7266 DiagnosedMixedDesignator = true;
7267 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7268 << DIE->getSourceRange();
7269 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7270 << InitArgList[0]->getSourceRange();
7271 }
7272 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7273 isa<DesignatedInitExpr>(InitArgList[0])) {
7274 DiagnosedMixedDesignator = true;
7275 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7276 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7277 << DIE->getSourceRange();
7278 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7279 << InitArgList[I]->getSourceRange();
7280 }
7281 }
7282
7283 if (FirstDesignator.isValid()) {
7284 // Only diagnose designated initiaization as a C++20 extension if we didn't
7285 // already diagnose use of (non-C++20) C99 designator syntax.
7286 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7287 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7288 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7289 ? diag::warn_cxx17_compat_designated_init
7290 : diag::ext_cxx_designated_init);
7291 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7292 Diag(FirstDesignator, diag::ext_designated_init);
7293 }
7294 }
7295
7296 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7297}
7298
7301 SourceLocation RBraceLoc) {
7302 // Semantic analysis for initializers is done by ActOnDeclarator() and
7303 // CheckInitializer() - it requires knowledge of the object being initialized.
7304
7305 // Immediately handle non-overload placeholders. Overloads can be
7306 // resolved contextually, but everything else here can't.
7307 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7308 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7309 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7310
7311 // Ignore failures; dropping the entire initializer list because
7312 // of one failure would be terrible for indexing/etc.
7313 if (result.isInvalid()) continue;
7314
7315 InitArgList[I] = result.get();
7316 }
7317 }
7318
7319 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7320 RBraceLoc);
7321 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7322 return E;
7323}
7324
7325/// Do an explicit extend of the given block pointer if we're in ARC.
7327 assert(E.get()->getType()->isBlockPointerType());
7328 assert(E.get()->isPRValue());
7329
7330 // Only do this in an r-value context.
7331 if (!getLangOpts().ObjCAutoRefCount) return;
7332
7334 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7335 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7337}
7338
7339/// Prepares for a scalar cast, performing all the necessary stages
7340/// except the final cast and returning the kind required.
7342 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7343 // Also, callers should have filtered out the invalid cases with
7344 // pointers. Everything else should be possible.
7345
7346 QualType SrcTy = Src.get()->getType();
7347 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7348 return CK_NoOp;
7349
7350 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7352 llvm_unreachable("member pointer type in C");
7353
7354 case Type::STK_CPointer:
7357 switch (DestTy->getScalarTypeKind()) {
7358 case Type::STK_CPointer: {
7359 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7360 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7361 if (SrcAS != DestAS)
7362 return CK_AddressSpaceConversion;
7363 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7364 return CK_NoOp;
7365 return CK_BitCast;
7366 }
7368 return (SrcKind == Type::STK_BlockPointer
7369 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7371 if (SrcKind == Type::STK_ObjCObjectPointer)
7372 return CK_BitCast;
7373 if (SrcKind == Type::STK_CPointer)
7374 return CK_CPointerToObjCPointerCast;
7376 return CK_BlockPointerToObjCPointerCast;
7377 case Type::STK_Bool:
7378 return CK_PointerToBoolean;
7379 case Type::STK_Integral:
7380 return CK_PointerToIntegral;
7381 case Type::STK_Floating:
7386 llvm_unreachable("illegal cast from pointer");
7387 }
7388 llvm_unreachable("Should have returned before this");
7389
7391 switch (DestTy->getScalarTypeKind()) {
7393 return CK_FixedPointCast;
7394 case Type::STK_Bool:
7395 return CK_FixedPointToBoolean;
7396 case Type::STK_Integral:
7397 return CK_FixedPointToIntegral;
7398 case Type::STK_Floating:
7399 return CK_FixedPointToFloating;
7402 Diag(Src.get()->getExprLoc(),
7403 diag::err_unimplemented_conversion_with_fixed_point_type)
7404 << DestTy;
7405 return CK_IntegralCast;
7406 case Type::STK_CPointer:
7410 llvm_unreachable("illegal cast to pointer type");
7411 }
7412 llvm_unreachable("Should have returned before this");
7413
7414 case Type::STK_Bool: // casting from bool is like casting from an integer
7415 case Type::STK_Integral:
7416 switch (DestTy->getScalarTypeKind()) {
7417 case Type::STK_CPointer:
7422 return CK_NullToPointer;
7423 return CK_IntegralToPointer;
7424 case Type::STK_Bool:
7425 return CK_IntegralToBoolean;
7426 case Type::STK_Integral:
7427 return CK_IntegralCast;
7428 case Type::STK_Floating:
7429 return CK_IntegralToFloating;
7431 Src = ImpCastExprToType(Src.get(),
7432 DestTy->castAs<ComplexType>()->getElementType(),
7433 CK_IntegralCast);
7434 return CK_IntegralRealToComplex;
7436 Src = ImpCastExprToType(Src.get(),
7437 DestTy->castAs<ComplexType>()->getElementType(),
7438 CK_IntegralToFloating);
7439 return CK_FloatingRealToComplex;
7441 llvm_unreachable("member pointer type in C");
7443 return CK_IntegralToFixedPoint;
7444 }
7445 llvm_unreachable("Should have returned before this");
7446
7447 case Type::STK_Floating:
7448 switch (DestTy->getScalarTypeKind()) {
7449 case Type::STK_Floating:
7450 return CK_FloatingCast;
7451 case Type::STK_Bool:
7452 return CK_FloatingToBoolean;
7453 case Type::STK_Integral:
7454 return CK_FloatingToIntegral;
7456 Src = ImpCastExprToType(Src.get(),
7457 DestTy->castAs<ComplexType>()->getElementType(),
7458 CK_FloatingCast);
7459 return CK_FloatingRealToComplex;
7461 Src = ImpCastExprToType(Src.get(),
7462 DestTy->castAs<ComplexType>()->getElementType(),
7463 CK_FloatingToIntegral);
7464 return CK_IntegralRealToComplex;
7465 case Type::STK_CPointer:
7468 llvm_unreachable("valid float->pointer cast?");
7470 llvm_unreachable("member pointer type in C");
7472 return CK_FloatingToFixedPoint;
7473 }
7474 llvm_unreachable("Should have returned before this");
7475
7477 switch (DestTy->getScalarTypeKind()) {
7479 return CK_FloatingComplexCast;
7481 return CK_FloatingComplexToIntegralComplex;
7482 case Type::STK_Floating: {
7483 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7484 if (Context.hasSameType(ET, DestTy))
7485 return CK_FloatingComplexToReal;
7486 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7487 return CK_FloatingCast;
7488 }
7489 case Type::STK_Bool:
7490 return CK_FloatingComplexToBoolean;
7491 case Type::STK_Integral:
7492 Src = ImpCastExprToType(Src.get(),
7493 SrcTy->castAs<ComplexType>()->getElementType(),
7494 CK_FloatingComplexToReal);
7495 return CK_FloatingToIntegral;
7496 case Type::STK_CPointer:
7499 llvm_unreachable("valid complex float->pointer cast?");
7501 llvm_unreachable("member pointer type in C");
7503 Diag(Src.get()->getExprLoc(),
7504 diag::err_unimplemented_conversion_with_fixed_point_type)
7505 << SrcTy;
7506 return CK_IntegralCast;
7507 }
7508 llvm_unreachable("Should have returned before this");
7509
7511 switch (DestTy->getScalarTypeKind()) {
7513 return CK_IntegralComplexToFloatingComplex;
7515 return CK_IntegralComplexCast;
7516 case Type::STK_Integral: {
7517 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7518 if (Context.hasSameType(ET, DestTy))
7519 return CK_IntegralComplexToReal;
7520 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7521 return CK_IntegralCast;
7522 }
7523 case Type::STK_Bool:
7524 return CK_IntegralComplexToBoolean;
7525 case Type::STK_Floating:
7526 Src = ImpCastExprToType(Src.get(),
7527 SrcTy->castAs<ComplexType>()->getElementType(),
7528 CK_IntegralComplexToReal);
7529 return CK_IntegralToFloating;
7530 case Type::STK_CPointer:
7533 llvm_unreachable("valid complex int->pointer cast?");
7535 llvm_unreachable("member pointer type in C");
7537 Diag(Src.get()->getExprLoc(),
7538 diag::err_unimplemented_conversion_with_fixed_point_type)
7539 << SrcTy;
7540 return CK_IntegralCast;
7541 }
7542 llvm_unreachable("Should have returned before this");
7543 }
7544
7545 llvm_unreachable("Unhandled scalar cast");
7546}
7547
7548static bool breakDownVectorType(QualType type, uint64_t &len,
7549 QualType &eltType) {
7550 // Vectors are simple.
7551 if (const VectorType *vecType = type->getAs<VectorType>()) {
7552 len = vecType->getNumElements();
7553 eltType = vecType->getElementType();
7554 assert(eltType->isScalarType());
7555 return true;
7556 }
7557
7558 // We allow lax conversion to and from non-vector types, but only if
7559 // they're real types (i.e. non-complex, non-pointer scalar types).
7560 if (!type->isRealType()) return false;
7561
7562 len = 1;
7563 eltType = type;
7564 return true;
7565}
7566
7567/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7568/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7569/// allowed?
7570///
7571/// This will also return false if the two given types do not make sense from
7572/// the perspective of SVE bitcasts.
7574 assert(srcTy->isVectorType() || destTy->isVectorType());
7575
7576 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7577 if (!FirstType->isSVESizelessBuiltinType())
7578 return false;
7579
7580 const auto *VecTy = SecondType->getAs<VectorType>();
7581 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7582 };
7583
7584 return ValidScalableConversion(srcTy, destTy) ||
7585 ValidScalableConversion(destTy, srcTy);
7586}
7587
7588/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
7589/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
7590/// VLS type) allowed?
7591///
7592/// This will also return false if the two given types do not make sense from
7593/// the perspective of RVV bitcasts.
7595 assert(srcTy->isVectorType() || destTy->isVectorType());
7596
7597 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7598 if (!FirstType->isRVVSizelessBuiltinType())
7599 return false;
7600
7601 const auto *VecTy = SecondType->getAs<VectorType>();
7602 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
7603 };
7604
7605 return ValidScalableConversion(srcTy, destTy) ||
7606 ValidScalableConversion(destTy, srcTy);
7607}
7608
7609/// Are the two types matrix types and do they have the same dimensions i.e.
7610/// do they have the same number of rows and the same number of columns?
7612 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7613 return false;
7614
7615 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7616 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7617
7618 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7619 matSrcType->getNumColumns() == matDestType->getNumColumns();
7620}
7621
7623 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7624
7625 uint64_t SrcLen, DestLen;
7626 QualType SrcEltTy, DestEltTy;
7627 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7628 return false;
7629 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7630 return false;
7631
7632 // ASTContext::getTypeSize will return the size rounded up to a
7633 // power of 2, so instead of using that, we need to use the raw
7634 // element size multiplied by the element count.
7635 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7636 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7637
7638 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7639}
7640
7641// This returns true if at least one of the types is an altivec vector.
7643 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7644 "expected at least one type to be a vector here");
7645
7646 bool IsSrcTyAltivec =
7647 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7649 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7651 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7653
7654 bool IsDestTyAltivec = DestTy->isVectorType() &&
7655 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7657 (DestTy->castAs<VectorType>()->getVectorKind() ==
7659 (DestTy->castAs<VectorType>()->getVectorKind() ==
7661
7662 return (IsSrcTyAltivec || IsDestTyAltivec);
7663}
7664
7665/// Are the two types lax-compatible vector types? That is, given
7666/// that one of them is a vector, do they have equal storage sizes,
7667/// where the storage size is the number of elements times the element
7668/// size?
7669///
7670/// This will also return false if either of the types is neither a
7671/// vector nor a real type.
7673 assert(destTy->isVectorType() || srcTy->isVectorType());
7674
7675 // Disallow lax conversions between scalars and ExtVectors (these
7676 // conversions are allowed for other vector types because common headers
7677 // depend on them). Most scalar OP ExtVector cases are handled by the
7678 // splat path anyway, which does what we want (convert, not bitcast).
7679 // What this rules out for ExtVectors is crazy things like char4*float.
7680 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7681 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7682
7683 return areVectorTypesSameSize(srcTy, destTy);
7684}
7685
7686/// Is this a legal conversion between two types, one of which is
7687/// known to be a vector type?
7689 assert(destTy->isVectorType() || srcTy->isVectorType());
7690
7691 switch (Context.getLangOpts().getLaxVectorConversions()) {
7693 return false;
7694
7696 if (!srcTy->isIntegralOrEnumerationType()) {
7697 auto *Vec = srcTy->getAs<VectorType>();
7698 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7699 return false;
7700 }
7701 if (!destTy->isIntegralOrEnumerationType()) {
7702 auto *Vec = destTy->getAs<VectorType>();
7703 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7704 return false;
7705 }
7706 // OK, integer (vector) -> integer (vector) bitcast.
7707 break;
7708
7710 break;
7711 }
7712
7713 return areLaxCompatibleVectorTypes(srcTy, destTy);
7714}
7715
7717 CastKind &Kind) {
7718 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7719 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7720 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7721 << DestTy << SrcTy << R;
7722 }
7723 } else if (SrcTy->isMatrixType()) {
7724 return Diag(R.getBegin(),
7725 diag::err_invalid_conversion_between_matrix_and_type)
7726 << SrcTy << DestTy << R;
7727 } else if (DestTy->isMatrixType()) {
7728 return Diag(R.getBegin(),
7729 diag::err_invalid_conversion_between_matrix_and_type)
7730 << DestTy << SrcTy << R;
7731 }
7732
7733 Kind = CK_MatrixCast;
7734 return false;
7735}
7736
7738 CastKind &Kind) {
7739 assert(VectorTy->isVectorType() && "Not a vector type!");
7740
7741 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7742 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7743 return Diag(R.getBegin(),
7744 Ty->isVectorType() ?
7745 diag::err_invalid_conversion_between_vectors :
7746 diag::err_invalid_conversion_between_vector_and_integer)
7747 << VectorTy << Ty << R;
7748 } else
7749 return Diag(R.getBegin(),
7750 diag::err_invalid_conversion_between_vector_and_scalar)
7751 << VectorTy << Ty << R;
7752
7753 Kind = CK_BitCast;
7754 return false;
7755}
7756
7758 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7759
7760 if (DestElemTy == SplattedExpr->getType())
7761 return SplattedExpr;
7762
7763 assert(DestElemTy->isFloatingType() ||
7764 DestElemTy->isIntegralOrEnumerationType());
7765
7766 CastKind CK;
7767 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7768 // OpenCL requires that we convert `true` boolean expressions to -1, but
7769 // only when splatting vectors.
7770 if (DestElemTy->isFloatingType()) {
7771 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7772 // in two steps: boolean to signed integral, then to floating.
7773 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7774 CK_BooleanToSignedIntegral);
7775 SplattedExpr = CastExprRes.get();
7776 CK = CK_IntegralToFloating;
7777 } else {
7778 CK = CK_BooleanToSignedIntegral;
7779 }
7780 } else {
7781 ExprResult CastExprRes = SplattedExpr;
7782 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7783 if (CastExprRes.isInvalid())
7784 return ExprError();
7785 SplattedExpr = CastExprRes.get();
7786 }
7787 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7788}
7789
7791 Expr *CastExpr, CastKind &Kind) {
7792 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7793
7794 QualType SrcTy = CastExpr->getType();
7795
7796 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7797 // an ExtVectorType.
7798 // In OpenCL, casts between vectors of different types are not allowed.
7799 // (See OpenCL 6.2).
7800 if (SrcTy->isVectorType()) {
7801 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7802 (getLangOpts().OpenCL &&
7803 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7804 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7805 << DestTy << SrcTy << R;
7806 return ExprError();
7807 }
7808 Kind = CK_BitCast;
7809 return CastExpr;
7810 }
7811
7812 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7813 // conversion will take place first from scalar to elt type, and then
7814 // splat from elt type to vector.
7815 if (SrcTy->isPointerType())
7816 return Diag(R.getBegin(),
7817 diag::err_invalid_conversion_between_vector_and_scalar)
7818 << DestTy << SrcTy << R;
7819
7820 Kind = CK_VectorSplat;
7821 return prepareVectorSplat(DestTy, CastExpr);
7822}
7823
7826 Declarator &D, ParsedType &Ty,
7827 SourceLocation RParenLoc, Expr *CastExpr) {
7828 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7829 "ActOnCastExpr(): missing type or expr");
7830
7832 if (D.isInvalidType())
7833 return ExprError();
7834
7835 if (getLangOpts().CPlusPlus) {
7836 // Check that there are no default arguments (C++ only).
7838 } else {
7839 // Make sure any TypoExprs have been dealt with.
7841 if (!Res.isUsable())
7842 return ExprError();
7843 CastExpr = Res.get();
7844 }
7845
7847
7848 QualType castType = castTInfo->getType();
7849 Ty = CreateParsedType(castType, castTInfo);
7850
7851 bool isVectorLiteral = false;
7852
7853 // Check for an altivec or OpenCL literal,
7854 // i.e. all the elements are integer constants.
7855 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7856 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7857 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7858 && castType->isVectorType() && (PE || PLE)) {
7859 if (PLE && PLE->getNumExprs() == 0) {
7860 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7861 return ExprError();
7862 }
7863 if (PE || PLE->getNumExprs() == 1) {
7864 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7865 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7866 isVectorLiteral = true;
7867 }
7868 else
7869 isVectorLiteral = true;
7870 }
7871
7872 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7873 // then handle it as such.
7874 if (isVectorLiteral)
7875 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7876
7877 // If the Expr being casted is a ParenListExpr, handle it specially.
7878 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7879 // sequence of BinOp comma operators.
7880 if (isa<ParenListExpr>(CastExpr)) {
7882 if (Result.isInvalid()) return ExprError();
7883 CastExpr = Result.get();
7884 }
7885
7886 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7887 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7888
7890
7892
7894
7895 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7896}
7897
7899 SourceLocation RParenLoc, Expr *E,
7900 TypeSourceInfo *TInfo) {
7901 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7902 "Expected paren or paren list expression");
7903
7904 Expr **exprs;
7905 unsigned numExprs;
7906 Expr *subExpr;
7907 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7908 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7909 LiteralLParenLoc = PE->getLParenLoc();
7910 LiteralRParenLoc = PE->getRParenLoc();
7911 exprs = PE->getExprs();
7912 numExprs = PE->getNumExprs();
7913 } else { // isa<ParenExpr> by assertion at function entrance
7914 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7915 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7916 subExpr = cast<ParenExpr>(E)->getSubExpr();
7917 exprs = &subExpr;
7918 numExprs = 1;
7919 }
7920
7921 QualType Ty = TInfo->getType();
7922 assert(Ty->isVectorType() && "Expected vector type");
7923
7924 SmallVector<Expr *, 8> initExprs;
7925 const VectorType *VTy = Ty->castAs<VectorType>();
7926 unsigned numElems = VTy->getNumElements();
7927
7928 // '(...)' form of vector initialization in AltiVec: the number of
7929 // initializers must be one or must match the size of the vector.
7930 // If a single value is specified in the initializer then it will be
7931 // replicated to all the components of the vector
7933 VTy->getElementType()))
7934 return ExprError();
7936 // The number of initializers must be one or must match the size of the
7937 // vector. If a single value is specified in the initializer then it will
7938 // be replicated to all the components of the vector
7939 if (numExprs == 1) {
7940 QualType ElemTy = VTy->getElementType();
7941 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7942 if (Literal.isInvalid())
7943 return ExprError();
7944 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7945 PrepareScalarCast(Literal, ElemTy));
7946 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7947 }
7948 else if (numExprs < numElems) {
7949 Diag(E->getExprLoc(),
7950 diag::err_incorrect_number_of_vector_initializers);
7951 return ExprError();
7952 }
7953 else
7954 initExprs.append(exprs, exprs + numExprs);
7955 }
7956 else {
7957 // For OpenCL, when the number of initializers is a single value,
7958 // it will be replicated to all components of the vector.
7960 numExprs == 1) {
7961 QualType ElemTy = VTy->getElementType();
7962 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7963 if (Literal.isInvalid())
7964 return ExprError();
7965 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7966 PrepareScalarCast(Literal, ElemTy));
7967 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7968 }
7969
7970 initExprs.append(exprs, exprs + numExprs);
7971 }
7972 // FIXME: This means that pretty-printing the final AST will produce curly
7973 // braces instead of the original commas.
7974 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7975 initExprs, LiteralRParenLoc);
7976 initE->setType(Ty);
7977 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7978}
7979
7980/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7981/// the ParenListExpr into a sequence of comma binary operators.
7984 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7985 if (!E)
7986 return OrigExpr;
7987
7988 ExprResult Result(E->getExpr(0));
7989
7990 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7991 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7992 E->getExpr(i));
7993
7994 if (Result.isInvalid()) return ExprError();
7995
7996 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7997}
7998
8001 MultiExprArg Val) {
8002 return ParenListExpr::Create(Context, L, Val, R);
8003}
8004
8005/// Emit a specialized diagnostic when one expression is a null pointer
8006/// constant and the other is not a pointer. Returns true if a diagnostic is
8007/// emitted.
8008bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8009 SourceLocation QuestionLoc) {
8010 const Expr *NullExpr = LHSExpr;
8011 const Expr *NonPointerExpr = RHSExpr;
8015
8016 if (NullKind == Expr::NPCK_NotNull) {
8017 NullExpr = RHSExpr;
8018 NonPointerExpr = LHSExpr;
8019 NullKind =
8022 }
8023
8024 if (NullKind == Expr::NPCK_NotNull)
8025 return false;
8026
8027 if (NullKind == Expr::NPCK_ZeroExpression)
8028 return false;
8029
8030 if (NullKind == Expr::NPCK_ZeroLiteral) {
8031 // In this case, check to make sure that we got here from a "NULL"
8032 // string in the source code.
8033 NullExpr = NullExpr->IgnoreParenImpCasts();
8034 SourceLocation loc = NullExpr->getExprLoc();
8035 if (!findMacroSpelling(loc, "NULL"))
8036 return false;
8037 }
8038
8039 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8040 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8041 << NonPointerExpr->getType() << DiagType
8042 << NonPointerExpr->getSourceRange();
8043 return true;
8044}
8045
8046/// Return false if the condition expression is valid, true otherwise.
8047static bool checkCondition(Sema &S, const Expr *Cond,
8048 SourceLocation QuestionLoc) {
8049 QualType CondTy = Cond->getType();
8050
8051 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8052 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8053 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8054 << CondTy << Cond->getSourceRange();
8055 return true;
8056 }
8057
8058 // C99 6.5.15p2
8059 if (CondTy->isScalarType()) return false;
8060
8061 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8062 << CondTy << Cond->getSourceRange();
8063 return true;
8064}
8065
8066/// Return false if the NullExpr can be promoted to PointerTy,
8067/// true otherwise.
8069 QualType PointerTy) {
8070 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8071 !NullExpr.get()->isNullPointerConstant(S.Context,
8073 return true;
8074
8075 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8076 return false;
8077}
8078
8079/// Checks compatibility between two pointers and return the resulting
8080/// type.
8082 ExprResult &RHS,
8084 QualType LHSTy = LHS.get()->getType();
8085 QualType RHSTy = RHS.get()->getType();
8086
8087 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8088 // Two identical pointers types are always compatible.
8089 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8090 }
8091
8092 QualType lhptee, rhptee;
8093
8094 // Get the pointee types.
8095 bool IsBlockPointer = false;
8096 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8097 lhptee = LHSBTy->getPointeeType();
8098 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8099 IsBlockPointer = true;
8100 } else {
8101 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8102 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8103 }
8104
8105 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8106 // differently qualified versions of compatible types, the result type is
8107 // a pointer to an appropriately qualified version of the composite
8108 // type.
8109
8110 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8111 // clause doesn't make sense for our extensions. E.g. address space 2 should
8112 // be incompatible with address space 3: they may live on different devices or
8113 // anything.
8114 Qualifiers lhQual = lhptee.getQualifiers();
8115 Qualifiers rhQual = rhptee.getQualifiers();
8116
8117 LangAS ResultAddrSpace = LangAS::Default;
8118 LangAS LAddrSpace = lhQual.getAddressSpace();
8119 LangAS RAddrSpace = rhQual.getAddressSpace();
8120
8121 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8122 // spaces is disallowed.
8123 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8124 ResultAddrSpace = LAddrSpace;
8125 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8126 ResultAddrSpace = RAddrSpace;
8127 else {
8128 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8129 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8130 << RHS.get()->getSourceRange();
8131 return QualType();
8132 }
8133
8134 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8135 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8136 lhQual.removeCVRQualifiers();
8137 rhQual.removeCVRQualifiers();
8138
8139 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8140 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8141 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8142 // qual types are compatible iff
8143 // * corresponded types are compatible
8144 // * CVR qualifiers are equal
8145 // * address spaces are equal
8146 // Thus for conditional operator we merge CVR and address space unqualified
8147 // pointees and if there is a composite type we return a pointer to it with
8148 // merged qualifiers.
8149 LHSCastKind =
8150 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8151 RHSCastKind =
8152 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8153 lhQual.removeAddressSpace();
8154 rhQual.removeAddressSpace();
8155
8156 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8157 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8158
8159 QualType CompositeTy = S.Context.mergeTypes(
8160 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8161 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8162
8163 if (CompositeTy.isNull()) {
8164 // In this situation, we assume void* type. No especially good
8165 // reason, but this is what gcc does, and we do have to pick
8166 // to get a consistent AST.
8167 QualType incompatTy;
8168 incompatTy = S.Context.getPointerType(
8169 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8170 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8171 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8172
8173 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8174 // for casts between types with incompatible address space qualifiers.
8175 // For the following code the compiler produces casts between global and
8176 // local address spaces of the corresponded innermost pointees:
8177 // local int *global *a;
8178 // global int *global *b;
8179 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8180 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8181 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8182 << RHS.get()->getSourceRange();
8183
8184 return incompatTy;
8185 }
8186
8187 // The pointer types are compatible.
8188 // In case of OpenCL ResultTy should have the address space qualifier
8189 // which is a superset of address spaces of both the 2nd and the 3rd
8190 // operands of the conditional operator.
8191 QualType ResultTy = [&, ResultAddrSpace]() {
8192 if (S.getLangOpts().OpenCL) {
8193 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8194 CompositeQuals.setAddressSpace(ResultAddrSpace);
8195 return S.Context
8196 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8197 .withCVRQualifiers(MergedCVRQual);
8198 }
8199 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8200 }();
8201 if (IsBlockPointer)
8202 ResultTy = S.Context.getBlockPointerType(ResultTy);
8203 else
8204 ResultTy = S.Context.getPointerType(ResultTy);
8205
8206 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8207 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8208 return ResultTy;
8209}
8210
8211/// Return the resulting type when the operands are both block pointers.
8213 ExprResult &LHS,
8214 ExprResult &RHS,
8216 QualType LHSTy = LHS.get()->getType();
8217 QualType RHSTy = RHS.get()->getType();
8218
8219 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8220 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8222 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8223 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8224 return destType;
8225 }
8226 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8227 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8228 << RHS.get()->getSourceRange();
8229 return QualType();
8230 }
8231
8232 // We have 2 block pointer types.
8233 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8234}
8235
8236/// Return the resulting type when the operands are both pointers.
8237static QualType
8239 ExprResult &RHS,
8241 // get the pointer types
8242 QualType LHSTy = LHS.get()->getType();
8243 QualType RHSTy = RHS.get()->getType();
8244
8245 // get the "pointed to" types
8246 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8247 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8248
8249 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8250 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8251 // Figure out necessary qualifiers (C99 6.5.15p6)
8252 QualType destPointee
8253 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8254 QualType destType = S.Context.getPointerType(destPointee);
8255 // Add qualifiers if necessary.
8256 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8257 // Promote to void*.
8258 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8259 return destType;
8260 }
8261 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8262 QualType destPointee
8263 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8264 QualType destType = S.Context.getPointerType(destPointee);
8265 // Add qualifiers if necessary.
8266 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8267 // Promote to void*.
8268 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8269 return destType;
8270 }
8271
8272 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8273}
8274
8275/// Return false if the first expression is not an integer and the second
8276/// expression is not a pointer, true otherwise.
8278 Expr* PointerExpr, SourceLocation Loc,
8279 bool IsIntFirstExpr) {
8280 if (!PointerExpr->getType()->isPointerType() ||
8281 !Int.get()->getType()->isIntegerType())
8282 return false;
8283
8284 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8285 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8286
8287 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8288 << Expr1->getType() << Expr2->getType()
8289 << Expr1->getSourceRange() << Expr2->getSourceRange();
8290 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8291 CK_IntegralToPointer);
8292 return true;
8293}
8294
8295/// Simple conversion between integer and floating point types.
8296///
8297/// Used when handling the OpenCL conditional operator where the
8298/// condition is a vector while the other operands are scalar.
8299///
8300/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8301/// types are either integer or floating type. Between the two
8302/// operands, the type with the higher rank is defined as the "result
8303/// type". The other operand needs to be promoted to the same type. No
8304/// other type promotion is allowed. We cannot use
8305/// UsualArithmeticConversions() for this purpose, since it always
8306/// promotes promotable types.
8308 ExprResult &RHS,
8309 SourceLocation QuestionLoc) {
8311 if (LHS.isInvalid())
8312 return QualType();
8314 if (RHS.isInvalid())
8315 return QualType();
8316
8317 // For conversion purposes, we ignore any qualifiers.
8318 // For example, "const float" and "float" are equivalent.
8319 QualType LHSType =
8321 QualType RHSType =
8323
8324 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8325 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8326 << LHSType << LHS.get()->getSourceRange();
8327 return QualType();
8328 }
8329
8330 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8331 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8332 << RHSType << RHS.get()->getSourceRange();
8333 return QualType();
8334 }
8335
8336 // If both types are identical, no conversion is needed.
8337 if (LHSType == RHSType)
8338 return LHSType;
8339
8340 // Now handle "real" floating types (i.e. float, double, long double).
8341 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8342 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8343 /*IsCompAssign = */ false);
8344
8345 // Finally, we have two differing integer types.
8346 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8347 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8348}
8349
8350/// Convert scalar operands to a vector that matches the
8351/// condition in length.
8352///
8353/// Used when handling the OpenCL conditional operator where the
8354/// condition is a vector while the other operands are scalar.
8355///
8356/// We first compute the "result type" for the scalar operands
8357/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8358/// into a vector of that type where the length matches the condition
8359/// vector type. s6.11.6 requires that the element types of the result
8360/// and the condition must have the same number of bits.
8361static QualType
8363 QualType CondTy, SourceLocation QuestionLoc) {
8364 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8365 if (ResTy.isNull()) return QualType();
8366
8367 const VectorType *CV = CondTy->getAs<VectorType>();
8368 assert(CV);
8369
8370 // Determine the vector result type
8371 unsigned NumElements = CV->getNumElements();
8372 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8373
8374 // Ensure that all types have the same number of bits
8376 != S.Context.getTypeSize(ResTy)) {
8377 // Since VectorTy is created internally, it does not pretty print
8378 // with an OpenCL name. Instead, we just print a description.
8379 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8380 SmallString<64> Str;
8381 llvm::raw_svector_ostream OS(Str);
8382 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8383 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8384 << CondTy << OS.str();
8385 return QualType();
8386 }
8387
8388 // Convert operands to the vector result type
8389 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8390 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8391
8392 return VectorTy;
8393}
8394
8395/// Return false if this is a valid OpenCL condition vector
8397 SourceLocation QuestionLoc) {
8398 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8399 // integral type.
8400 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8401 assert(CondTy);
8402 QualType EleTy = CondTy->getElementType();
8403 if (EleTy->isIntegerType()) return false;
8404
8405 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8406 << Cond->getType() << Cond->getSourceRange();
8407 return true;
8408}
8409
8410/// Return false if the vector condition type and the vector
8411/// result type are compatible.
8412///
8413/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8414/// number of elements, and their element types have the same number
8415/// of bits.
8416static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8417 SourceLocation QuestionLoc) {
8418 const VectorType *CV = CondTy->getAs<VectorType>();
8419 const VectorType *RV = VecResTy->getAs<VectorType>();
8420 assert(CV && RV);
8421
8422 if (CV->getNumElements() != RV->getNumElements()) {
8423 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8424 << CondTy << VecResTy;
8425 return true;
8426 }
8427
8428 QualType CVE = CV->getElementType();
8429 QualType RVE = RV->getElementType();
8430
8431 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8432 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8433 << CondTy << VecResTy;
8434 return true;
8435 }
8436
8437 return false;
8438}
8439
8440/// Return the resulting type for the conditional operator in
8441/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8442/// s6.3.i) when the condition is a vector type.
8443static QualType
8445 ExprResult &LHS, ExprResult &RHS,
8446 SourceLocation QuestionLoc) {
8448 if (Cond.isInvalid())
8449 return QualType();
8450 QualType CondTy = Cond.get()->getType();
8451
8452 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8453 return QualType();
8454
8455 // If either operand is a vector then find the vector type of the
8456 // result as specified in OpenCL v1.1 s6.3.i.
8457 if (LHS.get()->getType()->isVectorType() ||
8458 RHS.get()->getType()->isVectorType()) {
8459 bool IsBoolVecLang =
8460 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8461 QualType VecResTy =
8462 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8463 /*isCompAssign*/ false,
8464 /*AllowBothBool*/ true,
8465 /*AllowBoolConversions*/ false,
8466 /*AllowBooleanOperation*/ IsBoolVecLang,
8467 /*ReportInvalid*/ true);
8468 if (VecResTy.isNull())
8469 return QualType();
8470 // The result type must match the condition type as specified in
8471 // OpenCL v1.1 s6.11.6.
8472 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8473 return QualType();
8474 return VecResTy;
8475 }
8476
8477 // Both operands are scalar.
8478 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8479}
8480
8481/// Return true if the Expr is block type
8482static bool checkBlockType(Sema &S, const Expr *E) {
8483 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8484 QualType Ty = CE->getCallee()->getType();
8485 if (Ty->isBlockPointerType()) {
8486 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8487 return true;
8488 }
8489 }
8490 return false;
8491}
8492
8493/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8494/// In that case, LHS = cond.
8495/// C99 6.5.15
8497 ExprResult &RHS, ExprValueKind &VK,
8498 ExprObjectKind &OK,
8499 SourceLocation QuestionLoc) {
8500
8501 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8502 if (!LHSResult.isUsable()) return QualType();
8503 LHS = LHSResult;
8504
8505 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8506 if (!RHSResult.isUsable()) return QualType();
8507 RHS = RHSResult;
8508
8509 // C++ is sufficiently different to merit its own checker.
8510 if (getLangOpts().CPlusPlus)
8511 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8512
8513 VK = VK_PRValue;
8514 OK = OK_Ordinary;
8515
8517 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8518 RHS.get()->isTypeDependent())) {
8519 assert(!getLangOpts().CPlusPlus);
8520 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8521 RHS.get()->containsErrors()) &&
8522 "should only occur in error-recovery path.");
8523 return Context.DependentTy;
8524 }
8525
8526 // The OpenCL operator with a vector condition is sufficiently
8527 // different to merit its own checker.
8528 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8529 Cond.get()->getType()->isExtVectorType())
8530 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8531
8532 // First, check the condition.
8533 Cond = UsualUnaryConversions(Cond.get());
8534 if (Cond.isInvalid())
8535 return QualType();
8536 if (checkCondition(*this, Cond.get(), QuestionLoc))
8537 return QualType();
8538
8539 // Handle vectors.
8540 if (LHS.get()->getType()->isVectorType() ||
8541 RHS.get()->getType()->isVectorType())
8542 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8543 /*AllowBothBool*/ true,
8544 /*AllowBoolConversions*/ false,
8545 /*AllowBooleanOperation*/ false,
8546 /*ReportInvalid*/ true);
8547
8548 QualType ResTy =
8549 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8550 if (LHS.isInvalid() || RHS.isInvalid())
8551 return QualType();
8552
8553 // WebAssembly tables are not allowed as conditional LHS or RHS.
8554 QualType LHSTy = LHS.get()->getType();
8555 QualType RHSTy = RHS.get()->getType();
8556 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8557 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8558 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8559 return QualType();
8560 }
8561
8562 // Diagnose attempts to convert between __ibm128, __float128 and long double
8563 // where such conversions currently can't be handled.
8564 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8565 Diag(QuestionLoc,
8566 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8567 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8568 return QualType();
8569 }
8570
8571 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8572 // selection operator (?:).
8573 if (getLangOpts().OpenCL &&
8574 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8575 return QualType();
8576 }
8577
8578 // If both operands have arithmetic type, do the usual arithmetic conversions
8579 // to find a common type: C99 6.5.15p3,5.
8580 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8581 // Disallow invalid arithmetic conversions, such as those between bit-
8582 // precise integers types of different sizes, or between a bit-precise
8583 // integer and another type.
8584 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8585 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8586 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8587 << RHS.get()->getSourceRange();
8588 return QualType();
8589 }
8590
8591 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8592 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8593
8594 return ResTy;
8595 }
8596
8597 // If both operands are the same structure or union type, the result is that
8598 // type.
8599 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8600 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8601 if (LHSRT->getDecl() == RHSRT->getDecl())
8602 // "If both the operands have structure or union type, the result has
8603 // that type." This implies that CV qualifiers are dropped.
8605 RHSTy.getUnqualifiedType());
8606 // FIXME: Type of conditional expression must be complete in C mode.
8607 }
8608
8609 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8610 // The following || allows only one side to be void (a GCC-ism).
8611 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8612 QualType ResTy;
8613 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8614 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8615 } else if (RHSTy->isVoidType()) {
8616 ResTy = RHSTy;
8617 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8618 << RHS.get()->getSourceRange();
8619 } else {
8620 ResTy = LHSTy;
8621 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8622 << LHS.get()->getSourceRange();
8623 }
8624 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8625 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8626 return ResTy;
8627 }
8628
8629 // C23 6.5.15p7:
8630 // ... if both the second and third operands have nullptr_t type, the
8631 // result also has that type.
8632 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8633 return ResTy;
8634
8635 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8636 // the type of the other operand."
8637 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8638 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8639
8640 // All objective-c pointer type analysis is done here.
8641 QualType compositeType =
8642 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8643 if (LHS.isInvalid() || RHS.isInvalid())
8644 return QualType();
8645 if (!compositeType.isNull())
8646 return compositeType;
8647
8648
8649 // Handle block pointer types.
8650 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8651 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8652 QuestionLoc);
8653
8654 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8655 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8656 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8657 QuestionLoc);
8658
8659 // GCC compatibility: soften pointer/integer mismatch. Note that
8660 // null pointers have been filtered out by this point.
8661 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8662 /*IsIntFirstExpr=*/true))
8663 return RHSTy;
8664 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8665 /*IsIntFirstExpr=*/false))
8666 return LHSTy;
8667
8668 // Emit a better diagnostic if one of the expressions is a null pointer
8669 // constant and the other is not a pointer type. In this case, the user most
8670 // likely forgot to take the address of the other expression.
8671 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8672 return QualType();
8673
8674 // Finally, if the LHS and RHS types are canonically the same type, we can
8675 // use the common sugared type.
8676 if (Context.hasSameType(LHSTy, RHSTy))
8677 return Context.getCommonSugaredType(LHSTy, RHSTy);
8678
8679 // Otherwise, the operands are not compatible.
8680 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8681 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8682 << RHS.get()->getSourceRange();
8683 return QualType();
8684}
8685
8686/// SuggestParentheses - Emit a note with a fixit hint that wraps
8687/// ParenRange in parentheses.
8689 const PartialDiagnostic &Note,
8690 SourceRange ParenRange) {
8691 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8692 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8693 EndLoc.isValid()) {
8694 Self.Diag(Loc, Note)
8695 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8696 << FixItHint::CreateInsertion(EndLoc, ")");
8697 } else {
8698 // We can't display the parentheses, so just show the bare note.
8699 Self.Diag(Loc, Note) << ParenRange;
8700 }
8701}
8702
8704 return BinaryOperator::isAdditiveOp(Opc) ||
8706 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8707 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8708 // not any of the logical operators. Bitwise-xor is commonly used as a
8709 // logical-xor because there is no logical-xor operator. The logical
8710 // operators, including uses of xor, have a high false positive rate for
8711 // precedence warnings.
8712}
8713
8714/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8715/// expression, either using a built-in or overloaded operator,
8716/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8717/// expression.
8718static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8719 const Expr **RHSExprs) {
8720 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8721 E = E->IgnoreImpCasts();
8723 E = E->IgnoreImpCasts();
8724 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8725 E = MTE->getSubExpr();
8726 E = E->IgnoreImpCasts();
8727 }
8728
8729 // Built-in binary operator.
8730 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8731 OP && IsArithmeticOp(OP->getOpcode())) {
8732 *Opcode = OP->getOpcode();
8733 *RHSExprs = OP->getRHS();
8734 return true;
8735 }
8736
8737 // Overloaded operator.
8738 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8739 if (Call->getNumArgs() != 2)
8740 return false;
8741
8742 // Make sure this is really a binary operator that is safe to pass into
8743 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8744 OverloadedOperatorKind OO = Call->getOperator();
8745 if (OO < OO_Plus || OO > OO_Arrow ||
8746 OO == OO_PlusPlus || OO == OO_MinusMinus)
8747 return false;
8748
8750 if (IsArithmeticOp(OpKind)) {
8751 *Opcode = OpKind;
8752 *RHSExprs = Call->getArg(1);
8753 return true;
8754 }
8755 }
8756
8757 return false;
8758}
8759
8760/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8761/// or is a logical expression such as (x==y) which has int type, but is
8762/// commonly interpreted as boolean.
8763static bool ExprLooksBoolean(const Expr *E) {
8764 E = E->IgnoreParenImpCasts();
8765
8766 if (E->getType()->isBooleanType())
8767 return true;
8768 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8769 return OP->isComparisonOp() || OP->isLogicalOp();
8770 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8771 return OP->getOpcode() == UO_LNot;
8772 if (E->getType()->isPointerType())
8773 return true;
8774 // FIXME: What about overloaded operator calls returning "unspecified boolean
8775 // type"s (commonly pointer-to-members)?
8776
8777 return false;
8778}
8779
8780/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8781/// and binary operator are mixed in a way that suggests the programmer assumed
8782/// the conditional operator has higher precedence, for example:
8783/// "int x = a + someBinaryCondition ? 1 : 2".
8785 Expr *Condition, const Expr *LHSExpr,
8786 const Expr *RHSExpr) {
8787 BinaryOperatorKind CondOpcode;
8788 const Expr *CondRHS;
8789
8790 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8791 return;
8792 if (!ExprLooksBoolean(CondRHS))
8793 return;
8794
8795 // The condition is an arithmetic binary expression, with a right-
8796 // hand side that looks boolean, so warn.
8797
8798 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8799 ? diag::warn_precedence_bitwise_conditional
8800 : diag::warn_precedence_conditional;
8801
8802 Self.Diag(OpLoc, DiagID)
8803 << Condition->getSourceRange()
8804 << BinaryOperator::getOpcodeStr(CondOpcode);
8805
8807 Self, OpLoc,
8808 Self.PDiag(diag::note_precedence_silence)
8809 << BinaryOperator::getOpcodeStr(CondOpcode),
8810 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8811
8812 SuggestParentheses(Self, OpLoc,
8813 Self.PDiag(diag::note_precedence_conditional_first),
8814 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8815}
8816
8817/// Compute the nullability of a conditional expression.
8819 QualType LHSTy, QualType RHSTy,
8820 ASTContext &Ctx) {
8821 if (!ResTy->isAnyPointerType())
8822 return ResTy;
8823
8824 auto GetNullability = [](QualType Ty) {
8825 std::optional<NullabilityKind> Kind = Ty->getNullability();
8826 if (Kind) {
8827 // For our purposes, treat _Nullable_result as _Nullable.
8830 return *Kind;
8831 }
8833 };
8834
8835 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8836 NullabilityKind MergedKind;
8837
8838 // Compute nullability of a binary conditional expression.
8839 if (IsBin) {
8840 if (LHSKind == NullabilityKind::NonNull)
8841 MergedKind = NullabilityKind::NonNull;
8842 else
8843 MergedKind = RHSKind;
8844 // Compute nullability of a normal conditional expression.
8845 } else {
8846 if (LHSKind == NullabilityKind::Nullable ||
8847 RHSKind == NullabilityKind::Nullable)
8848 MergedKind = NullabilityKind::Nullable;
8849 else if (LHSKind == NullabilityKind::NonNull)
8850 MergedKind = RHSKind;
8851 else if (RHSKind == NullabilityKind::NonNull)
8852 MergedKind = LHSKind;
8853 else
8854 MergedKind = NullabilityKind::Unspecified;
8855 }
8856
8857 // Return if ResTy already has the correct nullability.
8858 if (GetNullability(ResTy) == MergedKind)
8859 return ResTy;
8860
8861 // Strip all nullability from ResTy.
8862 while (ResTy->getNullability())
8863 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8864
8865 // Create a new AttributedType with the new nullability kind.
8866 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8867 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8868}
8869
8870/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8871/// in the case of a the GNU conditional expr extension.
8873 SourceLocation ColonLoc,
8874 Expr *CondExpr, Expr *LHSExpr,
8875 Expr *RHSExpr) {
8877 // C cannot handle TypoExpr nodes in the condition because it
8878 // doesn't handle dependent types properly, so make sure any TypoExprs have
8879 // been dealt with before checking the operands.
8880 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8881 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8882 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8883
8884 if (!CondResult.isUsable())
8885 return ExprError();
8886
8887 if (LHSExpr) {
8888 if (!LHSResult.isUsable())
8889 return ExprError();
8890 }
8891
8892 if (!RHSResult.isUsable())
8893 return ExprError();
8894
8895 CondExpr = CondResult.get();
8896 LHSExpr = LHSResult.get();
8897 RHSExpr = RHSResult.get();
8898 }
8899
8900 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8901 // was the condition.
8902 OpaqueValueExpr *opaqueValue = nullptr;
8903 Expr *commonExpr = nullptr;
8904 if (!LHSExpr) {
8905 commonExpr = CondExpr;
8906 // Lower out placeholder types first. This is important so that we don't
8907 // try to capture a placeholder. This happens in few cases in C++; such
8908 // as Objective-C++'s dictionary subscripting syntax.
8909 if (commonExpr->hasPlaceholderType()) {
8910 ExprResult result = CheckPlaceholderExpr(commonExpr);
8911 if (!result.isUsable()) return ExprError();
8912 commonExpr = result.get();
8913 }
8914 // We usually want to apply unary conversions *before* saving, except
8915 // in the special case of a C++ l-value conditional.
8916 if (!(getLangOpts().CPlusPlus
8917 && !commonExpr->isTypeDependent()
8918 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8919 && commonExpr->isGLValue()
8920 && commonExpr->isOrdinaryOrBitFieldObject()
8921 && RHSExpr->isOrdinaryOrBitFieldObject()
8922 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8923 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8924 if (commonRes.isInvalid())
8925 return ExprError();
8926 commonExpr = commonRes.get();
8927 }
8928
8929 // If the common expression is a class or array prvalue, materialize it
8930 // so that we can safely refer to it multiple times.
8931 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8932 commonExpr->getType()->isArrayType())) {
8933 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8934 if (MatExpr.isInvalid())
8935 return ExprError();
8936 commonExpr = MatExpr.get();
8937 }
8938
8939 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8940 commonExpr->getType(),
8941 commonExpr->getValueKind(),
8942 commonExpr->getObjectKind(),
8943 commonExpr);
8944 LHSExpr = CondExpr = opaqueValue;
8945 }
8946
8947 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8950 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8951 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8952 VK, OK, QuestionLoc);
8953 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8954 RHS.isInvalid())
8955 return ExprError();
8956
8957 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8958 RHS.get());
8959
8960 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8961
8962 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8963 Context);
8964
8965 if (!commonExpr)
8966 return new (Context)
8967 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8968 RHS.get(), result, VK, OK);
8969
8971 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8972 ColonLoc, result, VK, OK);
8973}
8974
8975// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
8977 unsigned FromAttributes = 0, ToAttributes = 0;
8978 if (const auto *FromFn =
8979 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8980 FromAttributes =
8981 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8982 if (const auto *ToFn =
8983 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8984 ToAttributes =
8985 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8986
8987 return FromAttributes != ToAttributes;
8988}
8989
8990// Check if we have a conversion between incompatible cmse function pointer
8991// types, that is, a conversion between a function pointer with the
8992// cmse_nonsecure_call attribute and one without.
8994 QualType ToType) {
8995 if (const auto *ToFn =
8996 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8997 if (const auto *FromFn =
8998 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8999 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9000 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9001
9002 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9003 }
9004 }
9005 return false;
9006}
9007
9008// checkPointerTypesForAssignment - This is a very tricky routine (despite
9009// being closely modeled after the C99 spec:-). The odd characteristic of this
9010// routine is it effectively iqnores the qualifiers on the top level pointee.
9011// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9012// FIXME: add a couple examples in this comment.
9016 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9017 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9018
9019 // get the "pointed to" type (ignoring qualifiers at the top level)
9020 const Type *lhptee, *rhptee;
9021 Qualifiers lhq, rhq;
9022 std::tie(lhptee, lhq) =
9023 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9024 std::tie(rhptee, rhq) =
9025 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9026
9028
9029 // C99 6.5.16.1p1: This following citation is common to constraints
9030 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9031 // qualifiers of the type *pointed to* by the right;
9032
9033 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9034 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9036 // Ignore lifetime for further calculation.
9037 lhq.removeObjCLifetime();
9038 rhq.removeObjCLifetime();
9039 }
9040
9041 if (!lhq.compatiblyIncludes(rhq)) {
9042 // Treat address-space mismatches as fatal.
9043 if (!lhq.isAddressSpaceSupersetOf(rhq))
9045
9046 // It's okay to add or remove GC or lifetime qualifiers when converting to
9047 // and from void*.
9048 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9051 && (lhptee->isVoidType() || rhptee->isVoidType()))
9052 ; // keep old
9053
9054 // Treat lifetime mismatches as fatal.
9055 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9057
9058 // For GCC/MS compatibility, other qualifier mismatches are treated
9059 // as still compatible in C.
9061 }
9062
9063 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9064 // incomplete type and the other is a pointer to a qualified or unqualified
9065 // version of void...
9066 if (lhptee->isVoidType()) {
9067 if (rhptee->isIncompleteOrObjectType())
9068 return ConvTy;
9069
9070 // As an extension, we allow cast to/from void* to function pointer.
9071 assert(rhptee->isFunctionType());
9073 }
9074
9075 if (rhptee->isVoidType()) {
9076 if (lhptee->isIncompleteOrObjectType())
9077 return ConvTy;
9078
9079 // As an extension, we allow cast to/from void* to function pointer.
9080 assert(lhptee->isFunctionType());
9082 }
9083
9084 if (!S.Diags.isIgnored(
9085 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9086 Loc) &&
9087 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9088 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9090
9091 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9092 // unqualified versions of compatible types, ...
9093 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9094 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9095 // Check if the pointee types are compatible ignoring the sign.
9096 // We explicitly check for char so that we catch "char" vs
9097 // "unsigned char" on systems where "char" is unsigned.
9098 if (lhptee->isCharType())
9099 ltrans = S.Context.UnsignedCharTy;
9100 else if (lhptee->hasSignedIntegerRepresentation())
9101 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9102
9103 if (rhptee->isCharType())
9104 rtrans = S.Context.UnsignedCharTy;
9105 else if (rhptee->hasSignedIntegerRepresentation())
9106 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9107
9108 if (ltrans == rtrans) {
9109 // Types are compatible ignoring the sign. Qualifier incompatibility
9110 // takes priority over sign incompatibility because the sign
9111 // warning can be disabled.
9112 if (ConvTy != Sema::Compatible)
9113 return ConvTy;
9114
9116 }
9117
9118 // If we are a multi-level pointer, it's possible that our issue is simply
9119 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9120 // the eventual target type is the same and the pointers have the same
9121 // level of indirection, this must be the issue.
9122 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9123 do {
9124 std::tie(lhptee, lhq) =
9125 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9126 std::tie(rhptee, rhq) =
9127 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9128
9129 // Inconsistent address spaces at this point is invalid, even if the
9130 // address spaces would be compatible.
9131 // FIXME: This doesn't catch address space mismatches for pointers of
9132 // different nesting levels, like:
9133 // __local int *** a;
9134 // int ** b = a;
9135 // It's not clear how to actually determine when such pointers are
9136 // invalidly incompatible.
9137 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9139
9140 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9141
9142 if (lhptee == rhptee)
9144 }
9145
9146 // General pointer incompatibility takes priority over qualifiers.
9147 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9150 }
9151 if (!S.getLangOpts().CPlusPlus &&
9152 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9154 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9156 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9158 return ConvTy;
9159}
9160
9161/// checkBlockPointerTypesForAssignment - This routine determines whether two
9162/// block pointer types are compatible or whether a block and normal pointer
9163/// are compatible. It is more restrict than comparing two function pointer
9164// types.
9167 QualType RHSType) {
9168 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9169 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9170
9171 QualType lhptee, rhptee;
9172
9173 // get the "pointed to" type (ignoring qualifiers at the top level)
9174 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9175 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9176
9177 // In C++, the types have to match exactly.
9178 if (S.getLangOpts().CPlusPlus)
9180
9182
9183 // For blocks we enforce that qualifiers are identical.
9184 Qualifiers LQuals = lhptee.getLocalQualifiers();
9185 Qualifiers RQuals = rhptee.getLocalQualifiers();
9186 if (S.getLangOpts().OpenCL) {
9187 LQuals.removeAddressSpace();
9188 RQuals.removeAddressSpace();
9189 }
9190 if (LQuals != RQuals)
9192
9193 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9194 // assignment.
9195 // The current behavior is similar to C++ lambdas. A block might be
9196 // assigned to a variable iff its return type and parameters are compatible
9197 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9198 // an assignment. Presumably it should behave in way that a function pointer
9199 // assignment does in C, so for each parameter and return type:
9200 // * CVR and address space of LHS should be a superset of CVR and address
9201 // space of RHS.
9202 // * unqualified types should be compatible.
9203 if (S.getLangOpts().OpenCL) {
9205 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9206 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9208 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9210
9211 return ConvTy;
9212}
9213
9214/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9215/// for assignment compatibility.
9218 QualType RHSType) {
9219 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9220 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9221
9222 if (LHSType->isObjCBuiltinType()) {
9223 // Class is not compatible with ObjC object pointers.
9224 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9225 !RHSType->isObjCQualifiedClassType())
9227 return Sema::Compatible;
9228 }
9229 if (RHSType->isObjCBuiltinType()) {
9230 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9231 !LHSType->isObjCQualifiedClassType())
9233 return Sema::Compatible;
9234 }
9235 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9236 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9237
9238 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9239 // make an exception for id<P>
9240 !LHSType->isObjCQualifiedIdType())
9242
9243 if (S.Context.typesAreCompatible(LHSType, RHSType))
9244 return Sema::Compatible;
9245 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9248}
9249
9252 QualType LHSType, QualType RHSType) {
9253 // Fake up an opaque expression. We don't actually care about what
9254 // cast operations are required, so if CheckAssignmentConstraints
9255 // adds casts to this they'll be wasted, but fortunately that doesn't
9256 // usually happen on valid code.
9257 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9258 ExprResult RHSPtr = &RHSExpr;
9259 CastKind K;
9260
9261 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9262}
9263
9264/// This helper function returns true if QT is a vector type that has element
9265/// type ElementType.
9266static bool isVector(QualType QT, QualType ElementType) {
9267 if (const VectorType *VT = QT->getAs<VectorType>())
9268 return VT->getElementType().getCanonicalType() == ElementType;
9269 return false;
9270}
9271
9272/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9273/// has code to accommodate several GCC extensions when type checking
9274/// pointers. Here are some objectionable examples that GCC considers warnings:
9275///
9276/// int a, *pint;
9277/// short *pshort;
9278/// struct foo *pfoo;
9279///
9280/// pint = pshort; // warning: assignment from incompatible pointer type
9281/// a = pint; // warning: assignment makes integer from pointer without a cast
9282/// pint = a; // warning: assignment makes pointer from integer without a cast
9283/// pint = pfoo; // warning: assignment from incompatible pointer type
9284///
9285/// As a result, the code for dealing with pointers is more complex than the
9286/// C99 spec dictates.
9287///
9288/// Sets 'Kind' for any result kind except Incompatible.
9291 CastKind &Kind, bool ConvertRHS) {
9292 QualType RHSType = RHS.get()->getType();
9293 QualType OrigLHSType = LHSType;
9294
9295 // Get canonical types. We're not formatting these types, just comparing
9296 // them.
9297 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9298 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9299
9300 // Common case: no conversion required.
9301 if (LHSType == RHSType) {
9302 Kind = CK_NoOp;
9303 return Compatible;
9304 }
9305
9306 // If the LHS has an __auto_type, there are no additional type constraints
9307 // to be worried about.
9308 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9309 if (AT->isGNUAutoType()) {
9310 Kind = CK_NoOp;
9311 return Compatible;
9312 }
9313 }
9314
9315 // If we have an atomic type, try a non-atomic assignment, then just add an
9316 // atomic qualification step.
9317 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9319 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9320 if (result != Compatible)
9321 return result;
9322 if (Kind != CK_NoOp && ConvertRHS)
9323 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9324 Kind = CK_NonAtomicToAtomic;
9325 return Compatible;
9326 }
9327
9328 // If the left-hand side is a reference type, then we are in a
9329 // (rare!) case where we've allowed the use of references in C,
9330 // e.g., as a parameter type in a built-in function. In this case,
9331 // just make sure that the type referenced is compatible with the
9332 // right-hand side type. The caller is responsible for adjusting
9333 // LHSType so that the resulting expression does not have reference
9334 // type.
9335 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9336 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9337 Kind = CK_LValueBitCast;
9338 return Compatible;
9339 }
9340 return Incompatible;
9341 }
9342
9343 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9344 // to the same ExtVector type.
9345 if (LHSType->isExtVectorType()) {
9346 if (RHSType->isExtVectorType())
9347 return Incompatible;
9348 if (RHSType->isArithmeticType()) {
9349 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9350 if (ConvertRHS)
9351 RHS = prepareVectorSplat(LHSType, RHS.get());
9352 Kind = CK_VectorSplat;
9353 return Compatible;
9354 }
9355 }
9356
9357 // Conversions to or from vector type.
9358 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9359 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9360 // Allow assignments of an AltiVec vector type to an equivalent GCC
9361 // vector type and vice versa
9362 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9363 Kind = CK_BitCast;
9364 return Compatible;
9365 }
9366
9367 // If we are allowing lax vector conversions, and LHS and RHS are both
9368 // vectors, the total size only needs to be the same. This is a bitcast;
9369 // no bits are changed but the result type is different.
9370 if (isLaxVectorConversion(RHSType, LHSType)) {
9371 // The default for lax vector conversions with Altivec vectors will
9372 // change, so if we are converting between vector types where
9373 // at least one is an Altivec vector, emit a warning.
9374 if (Context.getTargetInfo().getTriple().isPPC() &&
9375 anyAltivecTypes(RHSType, LHSType) &&
9376 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9377 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9378 << RHSType << LHSType;
9379 Kind = CK_BitCast;
9380 return IncompatibleVectors;
9381 }
9382 }
9383
9384 // When the RHS comes from another lax conversion (e.g. binops between
9385 // scalars and vectors) the result is canonicalized as a vector. When the
9386 // LHS is also a vector, the lax is allowed by the condition above. Handle
9387 // the case where LHS is a scalar.
9388 if (LHSType->isScalarType()) {
9389 const VectorType *VecType = RHSType->getAs<VectorType>();
9390 if (VecType && VecType->getNumElements() == 1 &&
9391 isLaxVectorConversion(RHSType, LHSType)) {
9392 if (Context.getTargetInfo().getTriple().isPPC() &&
9394 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9396 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9397 << RHSType << LHSType;
9398 ExprResult *VecExpr = &RHS;
9399 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9400 Kind = CK_BitCast;
9401 return Compatible;
9402 }
9403 }
9404
9405 // Allow assignments between fixed-length and sizeless SVE vectors.
9406 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9407 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9408 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9409 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9410 Kind = CK_BitCast;
9411 return Compatible;
9412 }
9413
9414 // Allow assignments between fixed-length and sizeless RVV vectors.
9415 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9416 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9417 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9418 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9419 Kind = CK_BitCast;
9420 return Compatible;
9421 }
9422 }
9423
9424 return Incompatible;
9425 }
9426
9427 // Diagnose attempts to convert between __ibm128, __float128 and long double
9428 // where such conversions currently can't be handled.
9429 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9430 return Incompatible;
9431
9432 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9433 // discards the imaginary part.
9434 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9435 !LHSType->getAs<ComplexType>())
9436 return Incompatible;
9437
9438 // Arithmetic conversions.
9439 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9440 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9441 if (ConvertRHS)
9442 Kind = PrepareScalarCast(RHS, LHSType);
9443 return Compatible;
9444 }
9445
9446 // Conversions to normal pointers.
9447 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9448 // U* -> T*
9449 if (isa<PointerType>(RHSType)) {
9450 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9451 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9452 if (AddrSpaceL != AddrSpaceR)
9453 Kind = CK_AddressSpaceConversion;
9454 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9455 Kind = CK_NoOp;
9456 else
9457 Kind = CK_BitCast;
9458 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9459 RHS.get()->getBeginLoc());
9460 }
9461
9462 // int -> T*
9463 if (RHSType->isIntegerType()) {
9464 Kind = CK_IntegralToPointer; // FIXME: null?
9465 return IntToPointer;
9466 }
9467
9468 // C pointers are not compatible with ObjC object pointers,
9469 // with two exceptions:
9470 if (isa<ObjCObjectPointerType>(RHSType)) {
9471 // - conversions to void*
9472 if (LHSPointer->getPointeeType()->isVoidType()) {
9473 Kind = CK_BitCast;
9474 return Compatible;
9475 }
9476
9477 // - conversions from 'Class' to the redefinition type
9478 if (RHSType->isObjCClassType() &&
9479 Context.hasSameType(LHSType,
9481 Kind = CK_BitCast;
9482 return Compatible;
9483 }
9484
9485 Kind = CK_BitCast;
9486 return IncompatiblePointer;
9487 }
9488
9489 // U^ -> void*
9490 if (RHSType->getAs<BlockPointerType>()) {
9491 if (LHSPointer->getPointeeType()->isVoidType()) {
9492 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9493 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9494 ->getPointeeType()
9495 .getAddressSpace();
9496 Kind =
9497 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9498 return Compatible;
9499 }
9500 }
9501
9502 return Incompatible;
9503 }
9504
9505 // Conversions to block pointers.
9506 if (isa<BlockPointerType>(LHSType)) {
9507 // U^ -> T^
9508 if (RHSType->isBlockPointerType()) {
9509 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9510 ->getPointeeType()
9511 .getAddressSpace();
9512 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9513 ->getPointeeType()
9514 .getAddressSpace();
9515 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9516 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9517 }
9518
9519 // int or null -> T^
9520 if (RHSType->isIntegerType()) {
9521 Kind = CK_IntegralToPointer; // FIXME: null
9522 return IntToBlockPointer;
9523 }
9524
9525 // id -> T^
9526 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9527 Kind = CK_AnyPointerToBlockPointerCast;
9528 return Compatible;
9529 }
9530
9531 // void* -> T^
9532 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9533 if (RHSPT->getPointeeType()->isVoidType()) {
9534 Kind = CK_AnyPointerToBlockPointerCast;
9535 return Compatible;
9536 }
9537
9538 return Incompatible;
9539 }
9540
9541 // Conversions to Objective-C pointers.
9542 if (isa<ObjCObjectPointerType>(LHSType)) {
9543 // A* -> B*
9544 if (RHSType->isObjCObjectPointerType()) {
9545 Kind = CK_BitCast;
9547 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9548 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9549 result == Compatible &&
9550 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9551 result = IncompatibleObjCWeakRef;
9552 return result;
9553 }
9554
9555 // int or null -> A*
9556 if (RHSType->isIntegerType()) {
9557 Kind = CK_IntegralToPointer; // FIXME: null
9558 return IntToPointer;
9559 }
9560
9561 // In general, C pointers are not compatible with ObjC object pointers,
9562 // with two exceptions:
9563 if (isa<PointerType>(RHSType)) {
9564 Kind = CK_CPointerToObjCPointerCast;
9565
9566 // - conversions from 'void*'
9567 if (RHSType->isVoidPointerType()) {
9568 return Compatible;
9569 }
9570
9571 // - conversions to 'Class' from its redefinition type
9572 if (LHSType->isObjCClassType() &&
9573 Context.hasSameType(RHSType,
9575 return Compatible;
9576 }
9577
9578 return IncompatiblePointer;
9579 }
9580
9581 // Only under strict condition T^ is compatible with an Objective-C pointer.
9582 if (RHSType->isBlockPointerType() &&
9584 if (ConvertRHS)
9586 Kind = CK_BlockPointerToObjCPointerCast;
9587 return Compatible;
9588 }
9589
9590 return Incompatible;
9591 }
9592
9593 // Conversion to nullptr_t (C23 only)
9594 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9597 // null -> nullptr_t
9598 Kind = CK_NullToPointer;
9599 return Compatible;
9600 }
9601
9602 // Conversions from pointers that are not covered by the above.
9603 if (isa<PointerType>(RHSType)) {
9604 // T* -> _Bool
9605 if (LHSType == Context.BoolTy) {
9606 Kind = CK_PointerToBoolean;
9607 return Compatible;
9608 }
9609
9610 // T* -> int
9611 if (LHSType->isIntegerType()) {
9612 Kind = CK_PointerToIntegral;
9613 return PointerToInt;
9614 }
9615
9616 return Incompatible;
9617 }
9618
9619 // Conversions from Objective-C pointers that are not covered by the above.
9620 if (isa<ObjCObjectPointerType>(RHSType)) {
9621 // T* -> _Bool
9622 if (LHSType == Context.BoolTy) {
9623 Kind = CK_PointerToBoolean;
9624 return Compatible;
9625 }
9626
9627 // T* -> int
9628 if (LHSType->isIntegerType()) {
9629 Kind = CK_PointerToIntegral;
9630 return PointerToInt;
9631 }
9632
9633 return Incompatible;
9634 }
9635
9636 // struct A -> struct B
9637 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9638 if (Context.typesAreCompatible(LHSType, RHSType)) {
9639 Kind = CK_NoOp;
9640 return Compatible;
9641 }
9642 }
9643
9644 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9645 Kind = CK_IntToOCLSampler;
9646 return Compatible;
9647 }
9648
9649 return Incompatible;
9650}
9651
9652/// Constructs a transparent union from an expression that is
9653/// used to initialize the transparent union.
9655 ExprResult &EResult, QualType UnionType,
9656 FieldDecl *Field) {
9657 // Build an initializer list that designates the appropriate member
9658 // of the transparent union.
9659 Expr *E = EResult.get();
9661 E, SourceLocation());
9662 Initializer->setType(UnionType);
9663 Initializer->setInitializedFieldInUnion(Field);
9664
9665 // Build a compound literal constructing a value of the transparent
9666 // union type from this initializer list.
9667 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9668 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9669 VK_PRValue, Initializer, false);
9670}
9671
9674 ExprResult &RHS) {
9675 QualType RHSType = RHS.get()->getType();
9676
9677 // If the ArgType is a Union type, we want to handle a potential
9678 // transparent_union GCC extension.
9679 const RecordType *UT = ArgType->getAsUnionType();
9680 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9681 return Incompatible;
9682
9683 // The field to initialize within the transparent union.
9684 RecordDecl *UD = UT->getDecl();
9685 FieldDecl *InitField = nullptr;
9686 // It's compatible if the expression matches any of the fields.
9687 for (auto *it : UD->fields()) {
9688 if (it->getType()->isPointerType()) {
9689 // If the transparent union contains a pointer type, we allow:
9690 // 1) void pointer
9691 // 2) null pointer constant
9692 if (RHSType->isPointerType())
9693 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9694 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9695 InitField = it;
9696 break;
9697 }
9698
9701 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9702 CK_NullToPointer);
9703 InitField = it;
9704 break;
9705 }
9706 }
9707
9708 CastKind Kind;
9709 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9710 == Compatible) {
9711 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9712 InitField = it;
9713 break;
9714 }
9715 }
9716
9717 if (!InitField)
9718 return Incompatible;
9719
9720 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9721 return Compatible;
9722}
9723
9726 bool Diagnose,
9727 bool DiagnoseCFAudited,
9728 bool ConvertRHS) {
9729 // We need to be able to tell the caller whether we diagnosed a problem, if
9730 // they ask us to issue diagnostics.
9731 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9732
9733 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9734 // we can't avoid *all* modifications at the moment, so we need some somewhere
9735 // to put the updated value.
9736 ExprResult LocalRHS = CallerRHS;
9737 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9738
9739 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9740 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9741 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9742 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9743 Diag(RHS.get()->getExprLoc(),
9744 diag::warn_noderef_to_dereferenceable_pointer)
9745 << RHS.get()->getSourceRange();
9746 }
9747 }
9748 }
9749
9750 if (getLangOpts().CPlusPlus) {
9751 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9752 // C++ 5.17p3: If the left operand is not of class type, the
9753 // expression is implicitly converted (C++ 4) to the
9754 // cv-unqualified type of the left operand.
9755 QualType RHSType = RHS.get()->getType();
9756 if (Diagnose) {
9757 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9758 AA_Assigning);
9759 } else {
9762 /*SuppressUserConversions=*/false,
9763 AllowedExplicit::None,
9764 /*InOverloadResolution=*/false,
9765 /*CStyle=*/false,
9766 /*AllowObjCWritebackConversion=*/false);
9767 if (ICS.isFailure())
9768 return Incompatible;
9769 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9770 ICS, AA_Assigning);
9771 }
9772 if (RHS.isInvalid())
9773 return Incompatible;
9775 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9776 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9777 result = IncompatibleObjCWeakRef;
9778 return result;
9779 }
9780
9781 // FIXME: Currently, we fall through and treat C++ classes like C
9782 // structures.
9783 // FIXME: We also fall through for atomics; not sure what should
9784 // happen there, though.
9785 } else if (RHS.get()->getType() == Context.OverloadTy) {
9786 // As a set of extensions to C, we support overloading on functions. These
9787 // functions need to be resolved here.
9788 DeclAccessPair DAP;
9790 RHS.get(), LHSType, /*Complain=*/false, DAP))
9791 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9792 else
9793 return Incompatible;
9794 }
9795
9796 // This check seems unnatural, however it is necessary to ensure the proper
9797 // conversion of functions/arrays. If the conversion were done for all
9798 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9799 // expressions that suppress this implicit conversion (&, sizeof). This needs
9800 // to happen before we check for null pointer conversions because C does not
9801 // undergo the same implicit conversions as C++ does above (by the calls to
9802 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9803 // lvalue to rvalue cast before checking for null pointer constraints. This
9804 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9805 //
9806 // Suppress this for references: C++ 8.5.3p5.
9807 if (!LHSType->isReferenceType()) {
9808 // FIXME: We potentially allocate here even if ConvertRHS is false.
9810 if (RHS.isInvalid())
9811 return Incompatible;
9812 }
9813
9814 // The constraints are expressed in terms of the atomic, qualified, or
9815 // unqualified type of the LHS.
9816 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9817
9818 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9819 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9820 if ((LHSTypeAfterConversion->isPointerType() ||
9821 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9822 LHSTypeAfterConversion->isBlockPointerType()) &&
9823 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9826 if (Diagnose || ConvertRHS) {
9827 CastKind Kind;
9828 CXXCastPath Path;
9829 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9830 /*IgnoreBaseAccess=*/false, Diagnose);
9831 if (ConvertRHS)
9832 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9833 }
9834 return Compatible;
9835 }
9836 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9837 // unqualified bool, and the right operand is a pointer or its type is
9838 // nullptr_t.
9839 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9840 RHS.get()->getType()->isNullPtrType()) {
9841 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9842 // only handles nullptr -> _Bool due to needing an extra conversion
9843 // step.
9844 // We model this by converting from nullptr -> void * and then let the
9845 // conversion from void * -> _Bool happen naturally.
9846 if (Diagnose || ConvertRHS) {
9847 CastKind Kind;
9848 CXXCastPath Path;
9849 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
9850 /*IgnoreBaseAccess=*/false, Diagnose);
9851 if (ConvertRHS)
9852 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9853 &Path);
9854 }
9855 }
9856
9857 // OpenCL queue_t type assignment.
9858 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9860 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9861 return Compatible;
9862 }
9863
9864 CastKind Kind;
9866 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9867
9868 // C99 6.5.16.1p2: The value of the right operand is converted to the
9869 // type of the assignment expression.
9870 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9871 // so that we can use references in built-in functions even in C.
9872 // The getNonReferenceType() call makes sure that the resulting expression
9873 // does not have reference type.
9874 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9876 Expr *E = RHS.get();
9877
9878 // Check for various Objective-C errors. If we are not reporting
9879 // diagnostics and just checking for errors, e.g., during overload
9880 // resolution, return Incompatible to indicate the failure.
9881 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9882 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9884 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9885 if (!Diagnose)
9886 return Incompatible;
9887 }
9888 if (getLangOpts().ObjC &&
9889 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9890 E->getType(), E, Diagnose) ||
9891 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9892 if (!Diagnose)
9893 return Incompatible;
9894 // Replace the expression with a corrected version and continue so we
9895 // can find further errors.
9896 RHS = E;
9897 return Compatible;
9898 }
9899
9900 if (ConvertRHS)
9901 RHS = ImpCastExprToType(E, Ty, Kind);
9902 }
9903
9904 return result;
9905}
9906
9907namespace {
9908/// The original operand to an operator, prior to the application of the usual
9909/// arithmetic conversions and converting the arguments of a builtin operator
9910/// candidate.
9911struct OriginalOperand {
9912 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9913 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9914 Op = MTE->getSubExpr();
9915 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9916 Op = BTE->getSubExpr();
9917 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9918 Orig = ICE->getSubExprAsWritten();
9919 Conversion = ICE->getConversionFunction();
9920 }
9921 }
9922
9923 QualType getType() const { return Orig->getType(); }
9924
9925 Expr *Orig;
9926 NamedDecl *Conversion;
9927};
9928}
9929
9931 ExprResult &RHS) {
9932 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9933
9934 Diag(Loc, diag::err_typecheck_invalid_operands)
9935 << OrigLHS.getType() << OrigRHS.getType()
9936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9937
9938 // If a user-defined conversion was applied to either of the operands prior
9939 // to applying the built-in operator rules, tell the user about it.
9940 if (OrigLHS.Conversion) {
9941 Diag(OrigLHS.Conversion->getLocation(),
9942 diag::note_typecheck_invalid_operands_converted)
9943 << 0 << LHS.get()->getType();
9944 }
9945 if (OrigRHS.Conversion) {
9946 Diag(OrigRHS.Conversion->getLocation(),
9947 diag::note_typecheck_invalid_operands_converted)
9948 << 1 << RHS.get()->getType();
9949 }
9950
9951 return QualType();
9952}
9953
9954// Diagnose cases where a scalar was implicitly converted to a vector and
9955// diagnose the underlying types. Otherwise, diagnose the error
9956// as invalid vector logical operands for non-C++ cases.
9958 ExprResult &RHS) {
9959 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9960 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9961
9962 bool LHSNatVec = LHSType->isVectorType();
9963 bool RHSNatVec = RHSType->isVectorType();
9964
9965 if (!(LHSNatVec && RHSNatVec)) {
9966 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9967 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9968 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9969 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9970 << Vector->getSourceRange();
9971 return QualType();
9972 }
9973
9974 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9975 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9976 << RHS.get()->getSourceRange();
9977
9978 return QualType();
9979}
9980
9981/// Try to convert a value of non-vector type to a vector type by converting
9982/// the type to the element type of the vector and then performing a splat.
9983/// If the language is OpenCL, we only use conversions that promote scalar
9984/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9985/// for float->int.
9986///
9987/// OpenCL V2.0 6.2.6.p2:
9988/// An error shall occur if any scalar operand type has greater rank
9989/// than the type of the vector element.
9990///
9991/// \param scalar - if non-null, actually perform the conversions
9992/// \return true if the operation fails (but without diagnosing the failure)
9994 QualType scalarTy,
9995 QualType vectorEltTy,
9996 QualType vectorTy,
9997 unsigned &DiagID) {
9998 // The conversion to apply to the scalar before splatting it,
9999 // if necessary.
10000 CastKind scalarCast = CK_NoOp;
10001
10002 if (vectorEltTy->isIntegralType(S.Context)) {
10003 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10004 (scalarTy->isIntegerType() &&
10005 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10006 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10007 return true;
10008 }
10009 if (!scalarTy->isIntegralType(S.Context))
10010 return true;
10011 scalarCast = CK_IntegralCast;
10012 } else if (vectorEltTy->isRealFloatingType()) {
10013 if (scalarTy->isRealFloatingType()) {
10014 if (S.getLangOpts().OpenCL &&
10015 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10016 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10017 return true;
10018 }
10019 scalarCast = CK_FloatingCast;
10020 }
10021 else if (scalarTy->isIntegralType(S.Context))
10022 scalarCast = CK_IntegralToFloating;
10023 else
10024 return true;
10025 } else {
10026 return true;
10027 }
10028
10029 // Adjust scalar if desired.
10030 if (scalar) {
10031 if (scalarCast != CK_NoOp)
10032 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10033 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10034 }
10035 return false;
10036}
10037
10038/// Convert vector E to a vector with the same number of elements but different
10039/// element type.
10040static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10041 const auto *VecTy = E->getType()->getAs<VectorType>();
10042 assert(VecTy && "Expression E must be a vector");
10043 QualType NewVecTy =
10044 VecTy->isExtVectorType()
10045 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10046 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10047 VecTy->getVectorKind());
10048
10049 // Look through the implicit cast. Return the subexpression if its type is
10050 // NewVecTy.
10051 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10052 if (ICE->getSubExpr()->getType() == NewVecTy)
10053 return ICE->getSubExpr();
10054
10055 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10056 return S.ImpCastExprToType(E, NewVecTy, Cast);
10057}
10058
10059/// Test if a (constant) integer Int can be casted to another integer type
10060/// IntTy without losing precision.
10062 QualType OtherIntTy) {
10063 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10064
10065 // Reject cases where the value of the Int is unknown as that would
10066 // possibly cause truncation, but accept cases where the scalar can be
10067 // demoted without loss of precision.
10068 Expr::EvalResult EVResult;
10069 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10070 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10071 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10072 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10073
10074 if (CstInt) {
10075 // If the scalar is constant and is of a higher order and has more active
10076 // bits that the vector element type, reject it.
10077 llvm::APSInt Result = EVResult.Val.getInt();
10078 unsigned NumBits = IntSigned
10079 ? (Result.isNegative() ? Result.getSignificantBits()
10080 : Result.getActiveBits())
10081 : Result.getActiveBits();
10082 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10083 return true;
10084
10085 // If the signedness of the scalar type and the vector element type
10086 // differs and the number of bits is greater than that of the vector
10087 // element reject it.
10088 return (IntSigned != OtherIntSigned &&
10089 NumBits > S.Context.getIntWidth(OtherIntTy));
10090 }
10091
10092 // Reject cases where the value of the scalar is not constant and it's
10093 // order is greater than that of the vector element type.
10094 return (Order < 0);
10095}
10096
10097/// Test if a (constant) integer Int can be casted to floating point type
10098/// FloatTy without losing precision.
10100 QualType FloatTy) {
10101 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10102
10103 // Determine if the integer constant can be expressed as a floating point
10104 // number of the appropriate type.
10105 Expr::EvalResult EVResult;
10106 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10107
10108 uint64_t Bits = 0;
10109 if (CstInt) {
10110 // Reject constants that would be truncated if they were converted to
10111 // the floating point type. Test by simple to/from conversion.
10112 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10113 // could be avoided if there was a convertFromAPInt method
10114 // which could signal back if implicit truncation occurred.
10115 llvm::APSInt Result = EVResult.Val.getInt();
10116 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10117 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10118 llvm::APFloat::rmTowardZero);
10119 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10121 bool Ignored = false;
10122 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10123 &Ignored);
10124 if (Result != ConvertBack)
10125 return true;
10126 } else {
10127 // Reject types that cannot be fully encoded into the mantissa of
10128 // the float.
10129 Bits = S.Context.getTypeSize(IntTy);
10130 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10131 S.Context.getFloatTypeSemantics(FloatTy));
10132 if (Bits > FloatPrec)
10133 return true;
10134 }
10135
10136 return false;
10137}
10138
10139/// Attempt to convert and splat Scalar into a vector whose types matches
10140/// Vector following GCC conversion rules. The rule is that implicit
10141/// conversion can occur when Scalar can be casted to match Vector's element
10142/// type without causing truncation of Scalar.
10144 ExprResult *Vector) {
10145 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10146 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10147 QualType VectorEltTy;
10148
10149 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10150 assert(!isa<ExtVectorType>(VT) &&
10151 "ExtVectorTypes should not be handled here!");
10152 VectorEltTy = VT->getElementType();
10153 } else if (VectorTy->isSveVLSBuiltinType()) {
10154 VectorEltTy =
10155 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10156 } else {
10157 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10158 }
10159
10160 // Reject cases where the vector element type or the scalar element type are
10161 // not integral or floating point types.
10162 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10163 return true;
10164
10165 // The conversion to apply to the scalar before splatting it,
10166 // if necessary.
10167 CastKind ScalarCast = CK_NoOp;
10168
10169 // Accept cases where the vector elements are integers and the scalar is
10170 // an integer.
10171 // FIXME: Notionally if the scalar was a floating point value with a precise
10172 // integral representation, we could cast it to an appropriate integer
10173 // type and then perform the rest of the checks here. GCC will perform
10174 // this conversion in some cases as determined by the input language.
10175 // We should accept it on a language independent basis.
10176 if (VectorEltTy->isIntegralType(S.Context) &&
10177 ScalarTy->isIntegralType(S.Context) &&
10178 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10179
10180 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10181 return true;
10182
10183 ScalarCast = CK_IntegralCast;
10184 } else if (VectorEltTy->isIntegralType(S.Context) &&
10185 ScalarTy->isRealFloatingType()) {
10186 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10187 ScalarCast = CK_FloatingToIntegral;
10188 else
10189 return true;
10190 } else if (VectorEltTy->isRealFloatingType()) {
10191 if (ScalarTy->isRealFloatingType()) {
10192
10193 // Reject cases where the scalar type is not a constant and has a higher
10194 // Order than the vector element type.
10195 llvm::APFloat Result(0.0);
10196
10197 // Determine whether this is a constant scalar. In the event that the
10198 // value is dependent (and thus cannot be evaluated by the constant
10199 // evaluator), skip the evaluation. This will then diagnose once the
10200 // expression is instantiated.
10201 bool CstScalar = Scalar->get()->isValueDependent() ||
10202 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10203 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10204 if (!CstScalar && Order < 0)
10205 return true;
10206
10207 // If the scalar cannot be safely casted to the vector element type,
10208 // reject it.
10209 if (CstScalar) {
10210 bool Truncated = false;
10211 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10212 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10213 if (Truncated)
10214 return true;
10215 }
10216
10217 ScalarCast = CK_FloatingCast;
10218 } else if (ScalarTy->isIntegralType(S.Context)) {
10219 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10220 return true;
10221
10222 ScalarCast = CK_IntegralToFloating;
10223 } else
10224 return true;
10225 } else if (ScalarTy->isEnumeralType())
10226 return true;
10227
10228 // Adjust scalar if desired.
10229 if (ScalarCast != CK_NoOp)
10230 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10231 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10232 return false;
10233}
10234
10236 SourceLocation Loc, bool IsCompAssign,
10237 bool AllowBothBool,
10238 bool AllowBoolConversions,
10239 bool AllowBoolOperation,
10240 bool ReportInvalid) {
10241 if (!IsCompAssign) {
10243 if (LHS.isInvalid())
10244 return QualType();
10245 }
10247 if (RHS.isInvalid())
10248 return QualType();
10249
10250 // For conversion purposes, we ignore any qualifiers.
10251 // For example, "const float" and "float" are equivalent.
10252 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10253 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10254
10255 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10256 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10257 assert(LHSVecType || RHSVecType);
10258
10259 // AltiVec-style "vector bool op vector bool" combinations are allowed
10260 // for some operators but not others.
10261 if (!AllowBothBool && LHSVecType &&
10262 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10263 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10264 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10265
10266 // This operation may not be performed on boolean vectors.
10267 if (!AllowBoolOperation &&
10268 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10269 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10270
10271 // If the vector types are identical, return.
10272 if (Context.hasSameType(LHSType, RHSType))
10273 return Context.getCommonSugaredType(LHSType, RHSType);
10274
10275 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10276 if (LHSVecType && RHSVecType &&
10277 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10278 if (isa<ExtVectorType>(LHSVecType)) {
10279 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10280 return LHSType;
10281 }
10282
10283 if (!IsCompAssign)
10284 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10285 return RHSType;
10286 }
10287
10288 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10289 // can be mixed, with the result being the non-bool type. The non-bool
10290 // operand must have integer element type.
10291 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10292 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10293 (Context.getTypeSize(LHSVecType->getElementType()) ==
10294 Context.getTypeSize(RHSVecType->getElementType()))) {
10295 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10296 LHSVecType->getElementType()->isIntegerType() &&
10297 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10298 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10299 return LHSType;
10300 }
10301 if (!IsCompAssign &&
10302 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10303 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10304 RHSVecType->getElementType()->isIntegerType()) {
10305 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10306 return RHSType;
10307 }
10308 }
10309
10310 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10311 // invalid since the ambiguity can affect the ABI.
10312 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10313 unsigned &SVEorRVV) {
10314 const VectorType *VecType = SecondType->getAs<VectorType>();
10315 SVEorRVV = 0;
10316 if (FirstType->isSizelessBuiltinType() && VecType) {
10319 return true;
10322 SVEorRVV = 1;
10323 return true;
10324 }
10325 }
10326
10327 return false;
10328 };
10329
10330 unsigned SVEorRVV;
10331 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10332 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10333 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10334 << SVEorRVV << LHSType << RHSType;
10335 return QualType();
10336 }
10337
10338 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10339 // invalid since the ambiguity can affect the ABI.
10340 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10341 unsigned &SVEorRVV) {
10342 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10343 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10344
10345 SVEorRVV = 0;
10346 if (FirstVecType && SecondVecType) {
10347 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10348 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10349 SecondVecType->getVectorKind() ==
10351 return true;
10352 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10353 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10354 SVEorRVV = 1;
10355 return true;
10356 }
10357 }
10358 return false;
10359 }
10360
10361 if (SecondVecType &&
10362 SecondVecType->getVectorKind() == VectorKind::Generic) {
10363 if (FirstType->isSVESizelessBuiltinType())
10364 return true;
10365 if (FirstType->isRVVSizelessBuiltinType()) {
10366 SVEorRVV = 1;
10367 return true;
10368 }
10369 }
10370
10371 return false;
10372 };
10373
10374 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10375 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10376 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10377 << SVEorRVV << LHSType << RHSType;
10378 return QualType();
10379 }
10380
10381 // If there's a vector type and a scalar, try to convert the scalar to
10382 // the vector element type and splat.
10383 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10384 if (!RHSVecType) {
10385 if (isa<ExtVectorType>(LHSVecType)) {
10386 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10387 LHSVecType->getElementType(), LHSType,
10388 DiagID))
10389 return LHSType;
10390 } else {
10391 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10392 return LHSType;
10393 }
10394 }
10395 if (!LHSVecType) {
10396 if (isa<ExtVectorType>(RHSVecType)) {
10397 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10398 LHSType, RHSVecType->getElementType(),
10399 RHSType, DiagID))
10400 return RHSType;
10401 } else {
10402 if (LHS.get()->isLValue() ||
10403 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10404 return RHSType;
10405 }
10406 }
10407
10408 // FIXME: The code below also handles conversion between vectors and
10409 // non-scalars, we should break this down into fine grained specific checks
10410 // and emit proper diagnostics.
10411 QualType VecType = LHSVecType ? LHSType : RHSType;
10412 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10413 QualType OtherType = LHSVecType ? RHSType : LHSType;
10414 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10415 if (isLaxVectorConversion(OtherType, VecType)) {
10416 if (Context.getTargetInfo().getTriple().isPPC() &&
10417 anyAltivecTypes(RHSType, LHSType) &&
10418 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10419 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10420 // If we're allowing lax vector conversions, only the total (data) size
10421 // needs to be the same. For non compound assignment, if one of the types is
10422 // scalar, the result is always the vector type.
10423 if (!IsCompAssign) {
10424 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10425 return VecType;
10426 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10427 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10428 // type. Note that this is already done by non-compound assignments in
10429 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10430 // <1 x T> -> T. The result is also a vector type.
10431 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10432 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10433 ExprResult *RHSExpr = &RHS;
10434 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10435 return VecType;
10436 }
10437 }
10438
10439 // Okay, the expression is invalid.
10440
10441 // If there's a non-vector, non-real operand, diagnose that.
10442 if ((!RHSVecType && !RHSType->isRealType()) ||
10443 (!LHSVecType && !LHSType->isRealType())) {
10444 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10445 << LHSType << RHSType
10446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10447 return QualType();
10448 }
10449
10450 // OpenCL V1.1 6.2.6.p1:
10451 // If the operands are of more than one vector type, then an error shall
10452 // occur. Implicit conversions between vector types are not permitted, per
10453 // section 6.2.1.
10454 if (getLangOpts().OpenCL &&
10455 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10456 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10457 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10458 << RHSType;
10459 return QualType();
10460 }
10461
10462
10463 // If there is a vector type that is not a ExtVector and a scalar, we reach
10464 // this point if scalar could not be converted to the vector's element type
10465 // without truncation.
10466 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10467 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10468 QualType Scalar = LHSVecType ? RHSType : LHSType;
10469 QualType Vector = LHSVecType ? LHSType : RHSType;
10470 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10471 Diag(Loc,
10472 diag::err_typecheck_vector_not_convertable_implict_truncation)
10473 << ScalarOrVector << Scalar << Vector;
10474
10475 return QualType();
10476 }
10477
10478 // Otherwise, use the generic diagnostic.
10479 Diag(Loc, DiagID)
10480 << LHSType << RHSType
10481 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10482 return QualType();
10483}
10484
10487 bool IsCompAssign,
10488 ArithConvKind OperationKind) {
10489 if (!IsCompAssign) {
10491 if (LHS.isInvalid())
10492 return QualType();
10493 }
10495 if (RHS.isInvalid())
10496 return QualType();
10497
10498 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10499 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10500
10501 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10502 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10503
10504 unsigned DiagID = diag::err_typecheck_invalid_operands;
10505 if ((OperationKind == ACK_Arithmetic) &&
10506 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10507 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10508 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10509 << RHS.get()->getSourceRange();
10510 return QualType();
10511 }
10512
10513 if (Context.hasSameType(LHSType, RHSType))
10514 return LHSType;
10515
10516 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10517 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10518 return LHSType;
10519 }
10520 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10521 if (LHS.get()->isLValue() ||
10522 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10523 return RHSType;
10524 }
10525
10526 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10527 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10528 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10529 << LHSType << RHSType << LHS.get()->getSourceRange()
10530 << RHS.get()->getSourceRange();
10531 return QualType();
10532 }
10533
10534 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10535 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10536 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10537 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10538 << LHSType << RHSType << LHS.get()->getSourceRange()
10539 << RHS.get()->getSourceRange();
10540 return QualType();
10541 }
10542
10543 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10544 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10545 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10546 bool ScalarOrVector =
10547 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10548
10549 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10550 << ScalarOrVector << Scalar << Vector;
10551
10552 return QualType();
10553 }
10554
10555 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10556 << RHS.get()->getSourceRange();
10557 return QualType();
10558}
10559
10560// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10561// expression. These are mainly cases where the null pointer is used as an
10562// integer instead of a pointer.
10564 SourceLocation Loc, bool IsCompare) {
10565 // The canonical way to check for a GNU null is with isNullPointerConstant,
10566 // but we use a bit of a hack here for speed; this is a relatively
10567 // hot path, and isNullPointerConstant is slow.
10568 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10569 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10570
10571 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10572
10573 // Avoid analyzing cases where the result will either be invalid (and
10574 // diagnosed as such) or entirely valid and not something to warn about.
10575 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10576 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10577 return;
10578
10579 // Comparison operations would not make sense with a null pointer no matter
10580 // what the other expression is.
10581 if (!IsCompare) {
10582 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10583 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10584 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10585 return;
10586 }
10587
10588 // The rest of the operations only make sense with a null pointer
10589 // if the other expression is a pointer.
10590 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10591 NonNullType->canDecayToPointerType())
10592 return;
10593
10594 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10595 << LHSNull /* LHS is NULL */ << NonNullType
10596 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10597}
10598
10601 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10602 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10603 if (!LUE || !RUE)
10604 return;
10605 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10606 RUE->getKind() != UETT_SizeOf)
10607 return;
10608
10609 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10610 QualType LHSTy = LHSArg->getType();
10611 QualType RHSTy;
10612
10613 if (RUE->isArgumentType())
10614 RHSTy = RUE->getArgumentType().getNonReferenceType();
10615 else
10616 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10617
10618 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10619 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10620 return;
10621
10622 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10623 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10624 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10625 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10626 << LHSArgDecl;
10627 }
10628 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10629 QualType ArrayElemTy = ArrayTy->getElementType();
10630 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10631 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10632 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10633 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10634 return;
10635 S.Diag(Loc, diag::warn_division_sizeof_array)
10636 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10637 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10638 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10639 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10640 << LHSArgDecl;
10641 }
10642
10643 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10644 }
10645}
10646
10648 ExprResult &RHS,
10649 SourceLocation Loc, bool IsDiv) {
10650 // Check for division/remainder by zero.
10651 Expr::EvalResult RHSValue;
10652 if (!RHS.get()->isValueDependent() &&
10653 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10654 RHSValue.Val.getInt() == 0)
10655 S.DiagRuntimeBehavior(Loc, RHS.get(),
10656 S.PDiag(diag::warn_remainder_division_by_zero)
10657 << IsDiv << RHS.get()->getSourceRange());
10658}
10659
10662 bool IsCompAssign, bool IsDiv) {
10663 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10664
10665 QualType LHSTy = LHS.get()->getType();
10666 QualType RHSTy = RHS.get()->getType();
10667 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10668 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10669 /*AllowBothBool*/ getLangOpts().AltiVec,
10670 /*AllowBoolConversions*/ false,
10671 /*AllowBooleanOperation*/ false,
10672 /*ReportInvalid*/ true);
10673 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10674 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10676 if (!IsDiv &&
10677 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10678 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10679 // For division, only matrix-by-scalar is supported. Other combinations with
10680 // matrix types are invalid.
10681 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10682 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10683
10685 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10686 if (LHS.isInvalid() || RHS.isInvalid())
10687 return QualType();
10688
10689
10690 if (compType.isNull() || !compType->isArithmeticType())
10691 return InvalidOperands(Loc, LHS, RHS);
10692 if (IsDiv) {
10693 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10694 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10695 }
10696 return compType;
10697}
10698
10700 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10701 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10702
10703 if (LHS.get()->getType()->isVectorType() ||
10704 RHS.get()->getType()->isVectorType()) {
10705 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10707 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10708 /*AllowBothBool*/ getLangOpts().AltiVec,
10709 /*AllowBoolConversions*/ false,
10710 /*AllowBooleanOperation*/ false,
10711 /*ReportInvalid*/ true);
10712 return InvalidOperands(Loc, LHS, RHS);
10713 }
10714
10715 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10716 RHS.get()->getType()->isSveVLSBuiltinType()) {
10717 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10719 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10721
10722 return InvalidOperands(Loc, LHS, RHS);
10723 }
10724
10726 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10727 if (LHS.isInvalid() || RHS.isInvalid())
10728 return QualType();
10729
10730 if (compType.isNull() || !compType->isIntegerType())
10731 return InvalidOperands(Loc, LHS, RHS);
10732 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10733 return compType;
10734}
10735
10736/// Diagnose invalid arithmetic on two void pointers.
10738 Expr *LHSExpr, Expr *RHSExpr) {
10739 S.Diag(Loc, S.getLangOpts().CPlusPlus
10740 ? diag::err_typecheck_pointer_arith_void_type
10741 : diag::ext_gnu_void_ptr)
10742 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10743 << RHSExpr->getSourceRange();
10744}
10745
10746/// Diagnose invalid arithmetic on a void pointer.
10748 Expr *Pointer) {
10749 S.Diag(Loc, S.getLangOpts().CPlusPlus
10750 ? diag::err_typecheck_pointer_arith_void_type
10751 : diag::ext_gnu_void_ptr)
10752 << 0 /* one pointer */ << Pointer->getSourceRange();
10753}
10754
10755/// Diagnose invalid arithmetic on a null pointer.
10756///
10757/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10758/// idiom, which we recognize as a GNU extension.
10759///
10761 Expr *Pointer, bool IsGNUIdiom) {
10762 if (IsGNUIdiom)
10763 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10764 << Pointer->getSourceRange();
10765 else
10766 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10767 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10768}
10769
10770/// Diagnose invalid subraction on a null pointer.
10771///
10773 Expr *Pointer, bool BothNull) {
10774 // Null - null is valid in C++ [expr.add]p7
10775 if (BothNull && S.getLangOpts().CPlusPlus)
10776 return;
10777
10778 // Is this s a macro from a system header?
10780 return;
10781
10783 S.PDiag(diag::warn_pointer_sub_null_ptr)
10784 << S.getLangOpts().CPlusPlus
10785 << Pointer->getSourceRange());
10786}
10787
10788/// Diagnose invalid arithmetic on two function pointers.
10790 Expr *LHS, Expr *RHS) {
10791 assert(LHS->getType()->isAnyPointerType());
10792 assert(RHS->getType()->isAnyPointerType());
10793 S.Diag(Loc, S.getLangOpts().CPlusPlus
10794 ? diag::err_typecheck_pointer_arith_function_type
10795 : diag::ext_gnu_ptr_func_arith)
10796 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10797 // We only show the second type if it differs from the first.
10799 RHS->getType())
10800 << RHS->getType()->getPointeeType()
10801 << LHS->getSourceRange() << RHS->getSourceRange();
10802}
10803
10804/// Diagnose invalid arithmetic on a function pointer.
10806 Expr *Pointer) {
10807 assert(Pointer->getType()->isAnyPointerType());
10808 S.Diag(Loc, S.getLangOpts().CPlusPlus
10809 ? diag::err_typecheck_pointer_arith_function_type
10810 : diag::ext_gnu_ptr_func_arith)
10811 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10812 << 0 /* one pointer, so only one type */
10813 << Pointer->getSourceRange();
10814}
10815
10816/// Emit error if Operand is incomplete pointer type
10817///
10818/// \returns True if pointer has incomplete type
10820 Expr *Operand) {
10821 QualType ResType = Operand->getType();
10822 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10823 ResType = ResAtomicType->getValueType();
10824
10825 assert(ResType->isAnyPointerType());
10826 QualType PointeeTy = ResType->getPointeeType();
10827 return S.RequireCompleteSizedType(
10828 Loc, PointeeTy,
10829 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10830 Operand->getSourceRange());
10831}
10832
10833/// Check the validity of an arithmetic pointer operand.
10834///
10835/// If the operand has pointer type, this code will check for pointer types
10836/// which are invalid in arithmetic operations. These will be diagnosed
10837/// appropriately, including whether or not the use is supported as an
10838/// extension.
10839///
10840/// \returns True when the operand is valid to use (even if as an extension).
10842 Expr *Operand) {
10843 QualType ResType = Operand->getType();
10844 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10845 ResType = ResAtomicType->getValueType();
10846
10847 if (!ResType->isAnyPointerType()) return true;
10848
10849 QualType PointeeTy = ResType->getPointeeType();
10850 if (PointeeTy->isVoidType()) {
10852 return !S.getLangOpts().CPlusPlus;
10853 }
10854 if (PointeeTy->isFunctionType()) {
10856 return !S.getLangOpts().CPlusPlus;
10857 }
10858
10859 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10860
10861 return true;
10862}
10863
10864/// Check the validity of a binary arithmetic operation w.r.t. pointer
10865/// operands.
10866///
10867/// This routine will diagnose any invalid arithmetic on pointer operands much
10868/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10869/// for emitting a single diagnostic even for operations where both LHS and RHS
10870/// are (potentially problematic) pointers.
10871///
10872/// \returns True when the operand is valid to use (even if as an extension).
10874 Expr *LHSExpr, Expr *RHSExpr) {
10875 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10876 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10877 if (!isLHSPointer && !isRHSPointer) return true;
10878
10879 QualType LHSPointeeTy, RHSPointeeTy;
10880 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10881 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10882
10883 // if both are pointers check if operation is valid wrt address spaces
10884 if (isLHSPointer && isRHSPointer) {
10885 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10886 S.Diag(Loc,
10887 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10888 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10889 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10890 return false;
10891 }
10892 }
10893
10894 // Check for arithmetic on pointers to incomplete types.
10895 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10896 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10897 if (isLHSVoidPtr || isRHSVoidPtr) {
10898 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10899 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10900 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10901
10902 return !S.getLangOpts().CPlusPlus;
10903 }
10904
10905 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10906 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10907 if (isLHSFuncPtr || isRHSFuncPtr) {
10908 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10909 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10910 RHSExpr);
10911 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10912
10913 return !S.getLangOpts().CPlusPlus;
10914 }
10915
10916 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10917 return false;
10918 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10919 return false;
10920
10921 return true;
10922}
10923
10924/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10925/// literal.
10927 Expr *LHSExpr, Expr *RHSExpr) {
10928 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10929 Expr* IndexExpr = RHSExpr;
10930 if (!StrExpr) {
10931 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10932 IndexExpr = LHSExpr;
10933 }
10934
10935 bool IsStringPlusInt = StrExpr &&
10937 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10938 return;
10939
10940 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10941 Self.Diag(OpLoc, diag::warn_string_plus_int)
10942 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10943
10944 // Only print a fixit for "str" + int, not for int + "str".
10945 if (IndexExpr == RHSExpr) {
10946 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10947 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10948 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10950 << FixItHint::CreateInsertion(EndLoc, "]");
10951 } else
10952 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10953}
10954
10955/// Emit a warning when adding a char literal to a string.
10957 Expr *LHSExpr, Expr *RHSExpr) {
10958 const Expr *StringRefExpr = LHSExpr;
10959 const CharacterLiteral *CharExpr =
10960 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10961
10962 if (!CharExpr) {
10963 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10964 StringRefExpr = RHSExpr;
10965 }
10966
10967 if (!CharExpr || !StringRefExpr)
10968 return;
10969
10970 const QualType StringType = StringRefExpr->getType();
10971
10972 // Return if not a PointerType.
10973 if (!StringType->isAnyPointerType())
10974 return;
10975
10976 // Return if not a CharacterType.
10977 if (!StringType->getPointeeType()->isAnyCharacterType())
10978 return;
10979
10980 ASTContext &Ctx = Self.getASTContext();
10981 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10982
10983 const QualType CharType = CharExpr->getType();
10984 if (!CharType->isAnyCharacterType() &&
10985 CharType->isIntegerType() &&
10986 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10987 Self.Diag(OpLoc, diag::warn_string_plus_char)
10988 << DiagRange << Ctx.CharTy;
10989 } else {
10990 Self.Diag(OpLoc, diag::warn_string_plus_char)
10991 << DiagRange << CharExpr->getType();
10992 }
10993
10994 // Only print a fixit for str + char, not for char + str.
10995 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10996 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10997 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10998 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11000 << FixItHint::CreateInsertion(EndLoc, "]");
11001 } else {
11002 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11003 }
11004}
11005
11006/// Emit error when two pointers are incompatible.
11008 Expr *LHSExpr, Expr *RHSExpr) {
11009 assert(LHSExpr->getType()->isAnyPointerType());
11010 assert(RHSExpr->getType()->isAnyPointerType());
11011 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11012 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11013 << RHSExpr->getSourceRange();
11014}
11015
11016// C99 6.5.6
11019 QualType* CompLHSTy) {
11020 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11021
11022 if (LHS.get()->getType()->isVectorType() ||
11023 RHS.get()->getType()->isVectorType()) {
11024 QualType compType =
11025 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11026 /*AllowBothBool*/ getLangOpts().AltiVec,
11027 /*AllowBoolConversions*/ getLangOpts().ZVector,
11028 /*AllowBooleanOperation*/ false,
11029 /*ReportInvalid*/ true);
11030 if (CompLHSTy) *CompLHSTy = compType;
11031 return compType;
11032 }
11033
11034 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11035 RHS.get()->getType()->isSveVLSBuiltinType()) {
11036 QualType compType =
11037 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11038 if (CompLHSTy)
11039 *CompLHSTy = compType;
11040 return compType;
11041 }
11042
11043 if (LHS.get()->getType()->isConstantMatrixType() ||
11044 RHS.get()->getType()->isConstantMatrixType()) {
11045 QualType compType =
11046 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11047 if (CompLHSTy)
11048 *CompLHSTy = compType;
11049 return compType;
11050 }
11051
11053 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11054 if (LHS.isInvalid() || RHS.isInvalid())
11055 return QualType();
11056
11057 // Diagnose "string literal" '+' int and string '+' "char literal".
11058 if (Opc == BO_Add) {
11059 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11060 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11061 }
11062
11063 // handle the common case first (both operands are arithmetic).
11064 if (!compType.isNull() && compType->isArithmeticType()) {
11065 if (CompLHSTy) *CompLHSTy = compType;
11066 return compType;
11067 }
11068
11069 // Type-checking. Ultimately the pointer's going to be in PExp;
11070 // note that we bias towards the LHS being the pointer.
11071 Expr *PExp = LHS.get(), *IExp = RHS.get();
11072
11073 bool isObjCPointer;
11074 if (PExp->getType()->isPointerType()) {
11075 isObjCPointer = false;
11076 } else if (PExp->getType()->isObjCObjectPointerType()) {
11077 isObjCPointer = true;
11078 } else {
11079 std::swap(PExp, IExp);
11080 if (PExp->getType()->isPointerType()) {
11081 isObjCPointer = false;
11082 } else if (PExp->getType()->isObjCObjectPointerType()) {
11083 isObjCPointer = true;
11084 } else {
11085 return InvalidOperands(Loc, LHS, RHS);
11086 }
11087 }
11088 assert(PExp->getType()->isAnyPointerType());
11089
11090 if (!IExp->getType()->isIntegerType())
11091 return InvalidOperands(Loc, LHS, RHS);
11092
11093 // Adding to a null pointer results in undefined behavior.
11096 // In C++ adding zero to a null pointer is defined.
11097 Expr::EvalResult KnownVal;
11098 if (!getLangOpts().CPlusPlus ||
11099 (!IExp->isValueDependent() &&
11100 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11101 KnownVal.Val.getInt() != 0))) {
11102 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11104 Context, BO_Add, PExp, IExp);
11105 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11106 }
11107 }
11108
11109 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11110 return QualType();
11111
11112 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11113 return QualType();
11114
11115 // Check array bounds for pointer arithemtic
11116 CheckArrayAccess(PExp, IExp);
11117
11118 if (CompLHSTy) {
11120 if (LHSTy.isNull()) {
11121 LHSTy = LHS.get()->getType();
11123 LHSTy = Context.getPromotedIntegerType(LHSTy);
11124 }
11125 *CompLHSTy = LHSTy;
11126 }
11127
11128 return PExp->getType();
11129}
11130
11131// C99 6.5.6
11134 QualType* CompLHSTy) {
11135 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11136
11137 if (LHS.get()->getType()->isVectorType() ||
11138 RHS.get()->getType()->isVectorType()) {
11139 QualType compType =
11140 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11141 /*AllowBothBool*/ getLangOpts().AltiVec,
11142 /*AllowBoolConversions*/ getLangOpts().ZVector,
11143 /*AllowBooleanOperation*/ false,
11144 /*ReportInvalid*/ true);
11145 if (CompLHSTy) *CompLHSTy = compType;
11146 return compType;
11147 }
11148
11149 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11150 RHS.get()->getType()->isSveVLSBuiltinType()) {
11151 QualType compType =
11152 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11153 if (CompLHSTy)
11154 *CompLHSTy = compType;
11155 return compType;
11156 }
11157
11158 if (LHS.get()->getType()->isConstantMatrixType() ||
11159 RHS.get()->getType()->isConstantMatrixType()) {
11160 QualType compType =
11161 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11162 if (CompLHSTy)
11163 *CompLHSTy = compType;
11164 return compType;
11165 }
11166
11168 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11169 if (LHS.isInvalid() || RHS.isInvalid())
11170 return QualType();
11171
11172 // Enforce type constraints: C99 6.5.6p3.
11173
11174 // Handle the common case first (both operands are arithmetic).
11175 if (!compType.isNull() && compType->isArithmeticType()) {
11176 if (CompLHSTy) *CompLHSTy = compType;
11177 return compType;
11178 }
11179
11180 // Either ptr - int or ptr - ptr.
11181 if (LHS.get()->getType()->isAnyPointerType()) {
11182 QualType lpointee = LHS.get()->getType()->getPointeeType();
11183
11184 // Diagnose bad cases where we step over interface counts.
11185 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11186 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11187 return QualType();
11188
11189 // The result type of a pointer-int computation is the pointer type.
11190 if (RHS.get()->getType()->isIntegerType()) {
11191 // Subtracting from a null pointer should produce a warning.
11192 // The last argument to the diagnose call says this doesn't match the
11193 // GNU int-to-pointer idiom.
11196 // In C++ adding zero to a null pointer is defined.
11197 Expr::EvalResult KnownVal;
11198 if (!getLangOpts().CPlusPlus ||
11199 (!RHS.get()->isValueDependent() &&
11200 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11201 KnownVal.Val.getInt() != 0))) {
11202 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11203 }
11204 }
11205
11206 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11207 return QualType();
11208
11209 // Check array bounds for pointer arithemtic
11210 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11211 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11212
11213 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11214 return LHS.get()->getType();
11215 }
11216
11217 // Handle pointer-pointer subtractions.
11218 if (const PointerType *RHSPTy
11219 = RHS.get()->getType()->getAs<PointerType>()) {
11220 QualType rpointee = RHSPTy->getPointeeType();
11221
11222 if (getLangOpts().CPlusPlus) {
11223 // Pointee types must be the same: C++ [expr.add]
11224 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11225 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11226 }
11227 } else {
11228 // Pointee types must be compatible C99 6.5.6p3
11232 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11233 return QualType();
11234 }
11235 }
11236
11238 LHS.get(), RHS.get()))
11239 return QualType();
11240
11241 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11243 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11245
11246 // Subtracting nullptr or from nullptr is suspect
11247 if (LHSIsNullPtr)
11248 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11249 if (RHSIsNullPtr)
11250 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11251
11252 // The pointee type may have zero size. As an extension, a structure or
11253 // union may have zero size or an array may have zero length. In this
11254 // case subtraction does not make sense.
11255 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11256 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11257 if (ElementSize.isZero()) {
11258 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11259 << rpointee.getUnqualifiedType()
11260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11261 }
11262 }
11263
11264 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11265 return Context.getPointerDiffType();
11266 }
11267 }
11268
11269 return InvalidOperands(Loc, LHS, RHS);
11270}
11271
11273 if (const EnumType *ET = T->getAs<EnumType>())
11274 return ET->getDecl()->isScoped();
11275 return false;
11276}
11277
11280 QualType LHSType) {
11281 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11282 // so skip remaining warnings as we don't want to modify values within Sema.
11283 if (S.getLangOpts().OpenCL)
11284 return;
11285
11286 // Check right/shifter operand
11287 Expr::EvalResult RHSResult;
11288 if (RHS.get()->isValueDependent() ||
11289 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11290 return;
11291 llvm::APSInt Right = RHSResult.Val.getInt();
11292
11293 if (Right.isNegative()) {
11294 S.DiagRuntimeBehavior(Loc, RHS.get(),
11295 S.PDiag(diag::warn_shift_negative)
11296 << RHS.get()->getSourceRange());
11297 return;
11298 }
11299
11300 QualType LHSExprType = LHS.get()->getType();
11301 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11302 if (LHSExprType->isBitIntType())
11303 LeftSize = S.Context.getIntWidth(LHSExprType);
11304 else if (LHSExprType->isFixedPointType()) {
11305 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11306 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11307 }
11308 if (Right.uge(LeftSize)) {
11309 S.DiagRuntimeBehavior(Loc, RHS.get(),
11310 S.PDiag(diag::warn_shift_gt_typewidth)
11311 << RHS.get()->getSourceRange());
11312 return;
11313 }
11314
11315 // FIXME: We probably need to handle fixed point types specially here.
11316 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11317 return;
11318
11319 // When left shifting an ICE which is signed, we can check for overflow which
11320 // according to C++ standards prior to C++2a has undefined behavior
11321 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11322 // more than the maximum value representable in the result type, so never
11323 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11324 // expression is still probably a bug.)
11325 Expr::EvalResult LHSResult;
11326 if (LHS.get()->isValueDependent() ||
11328 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11329 return;
11330 llvm::APSInt Left = LHSResult.Val.getInt();
11331
11332 // Don't warn if signed overflow is defined, then all the rest of the
11333 // diagnostics will not be triggered because the behavior is defined.
11334 // Also don't warn in C++20 mode (and newer), as signed left shifts
11335 // always wrap and never overflow.
11336 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11337 return;
11338
11339 // If LHS does not have a non-negative value then, the
11340 // behavior is undefined before C++2a. Warn about it.
11341 if (Left.isNegative()) {
11342 S.DiagRuntimeBehavior(Loc, LHS.get(),
11343 S.PDiag(diag::warn_shift_lhs_negative)
11344 << LHS.get()->getSourceRange());
11345 return;
11346 }
11347
11348 llvm::APInt ResultBits =
11349 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11350 if (ResultBits.ule(LeftSize))
11351 return;
11352 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11353 Result = Result.shl(Right);
11354
11355 // Print the bit representation of the signed integer as an unsigned
11356 // hexadecimal number.
11357 SmallString<40> HexResult;
11358 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11359
11360 // If we are only missing a sign bit, this is less likely to result in actual
11361 // bugs -- if the result is cast back to an unsigned type, it will have the
11362 // expected value. Thus we place this behind a different warning that can be
11363 // turned off separately if needed.
11364 if (ResultBits - 1 == LeftSize) {
11365 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11366 << HexResult << LHSType
11367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11368 return;
11369 }
11370
11371 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11372 << HexResult.str() << Result.getSignificantBits() << LHSType
11373 << Left.getBitWidth() << LHS.get()->getSourceRange()
11374 << RHS.get()->getSourceRange();
11375}
11376
11377/// Return the resulting type when a vector is shifted
11378/// by a scalar or vector shift amount.
11380 SourceLocation Loc, bool IsCompAssign) {
11381 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11382 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11383 !LHS.get()->getType()->isVectorType()) {
11384 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11385 << RHS.get()->getType() << LHS.get()->getType()
11386 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11387 return QualType();
11388 }
11389
11390 if (!IsCompAssign) {
11391 LHS = S.UsualUnaryConversions(LHS.get());
11392 if (LHS.isInvalid()) return QualType();
11393 }
11394
11395 RHS = S.UsualUnaryConversions(RHS.get());
11396 if (RHS.isInvalid()) return QualType();
11397
11398 QualType LHSType = LHS.get()->getType();
11399 // Note that LHS might be a scalar because the routine calls not only in
11400 // OpenCL case.
11401 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11402 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11403
11404 // Note that RHS might not be a vector.
11405 QualType RHSType = RHS.get()->getType();
11406 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11407 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11408
11409 // Do not allow shifts for boolean vectors.
11410 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11411 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11412 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11413 << LHS.get()->getType() << RHS.get()->getType()
11414 << LHS.get()->getSourceRange();
11415 return QualType();
11416 }
11417
11418 // The operands need to be integers.
11419 if (!LHSEleType->isIntegerType()) {
11420 S.Diag(Loc, diag::err_typecheck_expect_int)
11421 << LHS.get()->getType() << LHS.get()->getSourceRange();
11422 return QualType();
11423 }
11424
11425 if (!RHSEleType->isIntegerType()) {
11426 S.Diag(Loc, diag::err_typecheck_expect_int)
11427 << RHS.get()->getType() << RHS.get()->getSourceRange();
11428 return QualType();
11429 }
11430
11431 if (!LHSVecTy) {
11432 assert(RHSVecTy);
11433 if (IsCompAssign)
11434 return RHSType;
11435 if (LHSEleType != RHSEleType) {
11436 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11437 LHSEleType = RHSEleType;
11438 }
11439 QualType VecTy =
11440 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11441 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11442 LHSType = VecTy;
11443 } else if (RHSVecTy) {
11444 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11445 // are applied component-wise. So if RHS is a vector, then ensure
11446 // that the number of elements is the same as LHS...
11447 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11448 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11449 << LHS.get()->getType() << RHS.get()->getType()
11450 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11451 return QualType();
11452 }
11453 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11454 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11455 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11456 if (LHSBT != RHSBT &&
11457 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11458 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11459 << LHS.get()->getType() << RHS.get()->getType()
11460 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11461 }
11462 }
11463 } else {
11464 // ...else expand RHS to match the number of elements in LHS.
11465 QualType VecTy =
11466 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11467 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11468 }
11469
11470 return LHSType;
11471}
11472
11475 bool IsCompAssign) {
11476 if (!IsCompAssign) {
11477 LHS = S.UsualUnaryConversions(LHS.get());
11478 if (LHS.isInvalid())
11479 return QualType();
11480 }
11481
11482 RHS = S.UsualUnaryConversions(RHS.get());
11483 if (RHS.isInvalid())
11484 return QualType();
11485
11486 QualType LHSType = LHS.get()->getType();
11487 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11488 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11489 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11490 : LHSType;
11491
11492 // Note that RHS might not be a vector
11493 QualType RHSType = RHS.get()->getType();
11494 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11495 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11496 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11497 : RHSType;
11498
11499 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11500 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11501 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11502 << LHSType << RHSType << LHS.get()->getSourceRange();
11503 return QualType();
11504 }
11505
11506 if (!LHSEleType->isIntegerType()) {
11507 S.Diag(Loc, diag::err_typecheck_expect_int)
11508 << LHS.get()->getType() << LHS.get()->getSourceRange();
11509 return QualType();
11510 }
11511
11512 if (!RHSEleType->isIntegerType()) {
11513 S.Diag(Loc, diag::err_typecheck_expect_int)
11514 << RHS.get()->getType() << RHS.get()->getSourceRange();
11515 return QualType();
11516 }
11517
11518 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11519 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11520 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11521 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11522 << LHSType << RHSType << LHS.get()->getSourceRange()
11523 << RHS.get()->getSourceRange();
11524 return QualType();
11525 }
11526
11527 if (!LHSType->isSveVLSBuiltinType()) {
11528 assert(RHSType->isSveVLSBuiltinType());
11529 if (IsCompAssign)
11530 return RHSType;
11531 if (LHSEleType != RHSEleType) {
11532 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11533 LHSEleType = RHSEleType;
11534 }
11535 const llvm::ElementCount VecSize =
11536 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11537 QualType VecTy =
11538 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11539 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11540 LHSType = VecTy;
11541 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11542 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11543 S.Context.getTypeSize(LHSBuiltinTy)) {
11544 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11545 << LHSType << RHSType << LHS.get()->getSourceRange()
11546 << RHS.get()->getSourceRange();
11547 return QualType();
11548 }
11549 } else {
11550 const llvm::ElementCount VecSize =
11551 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11552 if (LHSEleType != RHSEleType) {
11553 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11554 RHSEleType = LHSEleType;
11555 }
11556 QualType VecTy =
11557 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11558 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11559 }
11560
11561 return LHSType;
11562}
11563
11564// C99 6.5.7
11567 bool IsCompAssign) {
11568 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11569
11570 // Vector shifts promote their scalar inputs to vector type.
11571 if (LHS.get()->getType()->isVectorType() ||
11572 RHS.get()->getType()->isVectorType()) {
11573 if (LangOpts.ZVector) {
11574 // The shift operators for the z vector extensions work basically
11575 // like general shifts, except that neither the LHS nor the RHS is
11576 // allowed to be a "vector bool".
11577 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11578 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11579 return InvalidOperands(Loc, LHS, RHS);
11580 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11581 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11582 return InvalidOperands(Loc, LHS, RHS);
11583 }
11584 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11585 }
11586
11587 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11588 RHS.get()->getType()->isSveVLSBuiltinType())
11589 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11590
11591 // Shifts don't perform usual arithmetic conversions, they just do integer
11592 // promotions on each operand. C99 6.5.7p3
11593
11594 // For the LHS, do usual unary conversions, but then reset them away
11595 // if this is a compound assignment.
11596 ExprResult OldLHS = LHS;
11597 LHS = UsualUnaryConversions(LHS.get());
11598 if (LHS.isInvalid())
11599 return QualType();
11600 QualType LHSType = LHS.get()->getType();
11601 if (IsCompAssign) LHS = OldLHS;
11602
11603 // The RHS is simpler.
11604 RHS = UsualUnaryConversions(RHS.get());
11605 if (RHS.isInvalid())
11606 return QualType();
11607 QualType RHSType = RHS.get()->getType();
11608
11609 // C99 6.5.7p2: Each of the operands shall have integer type.
11610 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11611 if ((!LHSType->isFixedPointOrIntegerType() &&
11612 !LHSType->hasIntegerRepresentation()) ||
11613 !RHSType->hasIntegerRepresentation())
11614 return InvalidOperands(Loc, LHS, RHS);
11615
11616 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11617 // hasIntegerRepresentation() above instead of this.
11618 if (isScopedEnumerationType(LHSType) ||
11619 isScopedEnumerationType(RHSType)) {
11620 return InvalidOperands(Loc, LHS, RHS);
11621 }
11622 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11623
11624 // "The type of the result is that of the promoted left operand."
11625 return LHSType;
11626}
11627
11628/// Diagnose bad pointer comparisons.
11630 ExprResult &LHS, ExprResult &RHS,
11631 bool IsError) {
11632 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11633 : diag::ext_typecheck_comparison_of_distinct_pointers)
11634 << LHS.get()->getType() << RHS.get()->getType()
11635 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11636}
11637
11638/// Returns false if the pointers are converted to a composite type,
11639/// true otherwise.
11641 ExprResult &LHS, ExprResult &RHS) {
11642 // C++ [expr.rel]p2:
11643 // [...] Pointer conversions (4.10) and qualification
11644 // conversions (4.4) are performed on pointer operands (or on
11645 // a pointer operand and a null pointer constant) to bring
11646 // them to their composite pointer type. [...]
11647 //
11648 // C++ [expr.eq]p1 uses the same notion for (in)equality
11649 // comparisons of pointers.
11650
11651 QualType LHSType = LHS.get()->getType();
11652 QualType RHSType = RHS.get()->getType();
11653 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11654 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11655
11656 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11657 if (T.isNull()) {
11658 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11659 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11660 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11661 else
11662 S.InvalidOperands(Loc, LHS, RHS);
11663 return true;
11664 }
11665
11666 return false;
11667}
11668
11670 ExprResult &LHS,
11671 ExprResult &RHS,
11672 bool IsError) {
11673 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11674 : diag::ext_typecheck_comparison_of_fptr_to_void)
11675 << LHS.get()->getType() << RHS.get()->getType()
11676 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11677}
11678
11680 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11681 case Stmt::ObjCArrayLiteralClass:
11682 case Stmt::ObjCDictionaryLiteralClass:
11683 case Stmt::ObjCStringLiteralClass:
11684 case Stmt::ObjCBoxedExprClass:
11685 return true;
11686 default:
11687 // Note that ObjCBoolLiteral is NOT an object literal!
11688 return false;
11689 }
11690}
11691
11692static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11695
11696 // If this is not actually an Objective-C object, bail out.
11697 if (!Type)
11698 return false;
11699
11700 // Get the LHS object's interface type.
11701 QualType InterfaceType = Type->getPointeeType();
11702
11703 // If the RHS isn't an Objective-C object, bail out.
11704 if (!RHS->getType()->isObjCObjectPointerType())
11705 return false;
11706
11707 // Try to find the -isEqual: method.
11708 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11709 ObjCMethodDecl *Method =
11710 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11711 /*IsInstance=*/true);
11712 if (!Method) {
11713 if (Type->isObjCIdType()) {
11714 // For 'id', just check the global pool.
11715 Method =
11717 /*receiverId=*/true);
11718 } else {
11719 // Check protocols.
11720 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11721 /*IsInstance=*/true);
11722 }
11723 }
11724
11725 if (!Method)
11726 return false;
11727
11728 QualType T = Method->parameters()[0]->getType();
11729 if (!T->isObjCObjectPointerType())
11730 return false;
11731
11732 QualType R = Method->getReturnType();
11733 if (!R->isScalarType())
11734 return false;
11735
11736 return true;
11737}
11738
11740 ExprResult &LHS, ExprResult &RHS,
11742 Expr *Literal;
11743 Expr *Other;
11744 if (isObjCObjectLiteral(LHS)) {
11745 Literal = LHS.get();
11746 Other = RHS.get();
11747 } else {
11748 Literal = RHS.get();
11749 Other = LHS.get();
11750 }
11751
11752 // Don't warn on comparisons against nil.
11753 Other = Other->IgnoreParenCasts();
11754 if (Other->isNullPointerConstant(S.getASTContext(),
11756 return;
11757
11758 // This should be kept in sync with warn_objc_literal_comparison.
11759 // LK_String should always be after the other literals, since it has its own
11760 // warning flag.
11761 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11762 assert(LiteralKind != SemaObjC::LK_Block);
11763 if (LiteralKind == SemaObjC::LK_None) {
11764 llvm_unreachable("Unknown Objective-C object literal kind");
11765 }
11766
11767 if (LiteralKind == SemaObjC::LK_String)
11768 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11769 << Literal->getSourceRange();
11770 else
11771 S.Diag(Loc, diag::warn_objc_literal_comparison)
11772 << LiteralKind << Literal->getSourceRange();
11773
11775 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11776 SourceLocation Start = LHS.get()->getBeginLoc();
11778 CharSourceRange OpRange =
11780
11781 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11782 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11783 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11784 << FixItHint::CreateInsertion(End, "]");
11785 }
11786}
11787
11788/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11791 BinaryOperatorKind Opc) {
11792 // Check that left hand side is !something.
11793 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11794 if (!UO || UO->getOpcode() != UO_LNot) return;
11795
11796 // Only check if the right hand side is non-bool arithmetic type.
11797 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11798
11799 // Make sure that the something in !something is not bool.
11800 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11801 if (SubExpr->isKnownToHaveBooleanValue()) return;
11802
11803 // Emit warning.
11804 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11805 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11806 << Loc << IsBitwiseOp;
11807
11808 // First note suggest !(x < y)
11809 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11810 SourceLocation FirstClose = RHS.get()->getEndLoc();
11811 FirstClose = S.getLocForEndOfToken(FirstClose);
11812 if (FirstClose.isInvalid())
11813 FirstOpen = SourceLocation();
11814 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11815 << IsBitwiseOp
11816 << FixItHint::CreateInsertion(FirstOpen, "(")
11817 << FixItHint::CreateInsertion(FirstClose, ")");
11818
11819 // Second note suggests (!x) < y
11820 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11821 SourceLocation SecondClose = LHS.get()->getEndLoc();
11822 SecondClose = S.getLocForEndOfToken(SecondClose);
11823 if (SecondClose.isInvalid())
11824 SecondOpen = SourceLocation();
11825 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11826 << FixItHint::CreateInsertion(SecondOpen, "(")
11827 << FixItHint::CreateInsertion(SecondClose, ")");
11828}
11829
11830// Returns true if E refers to a non-weak array.
11831static bool checkForArray(const Expr *E) {
11832 const ValueDecl *D = nullptr;
11833 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11834 D = DR->getDecl();
11835 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11836 if (Mem->isImplicitAccess())
11837 D = Mem->getMemberDecl();
11838 }
11839 if (!D)
11840 return false;
11841 return D->getType()->isArrayType() && !D->isWeak();
11842}
11843
11844/// Diagnose some forms of syntactically-obvious tautological comparison.
11846 Expr *LHS, Expr *RHS,
11847 BinaryOperatorKind Opc) {
11848 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11849 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11850
11851 QualType LHSType = LHS->getType();
11852 QualType RHSType = RHS->getType();
11853 if (LHSType->hasFloatingRepresentation() ||
11854 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11856 return;
11857
11858 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11859 // Tautological diagnostics.
11860 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11861 return;
11862
11863 // Comparisons between two array types are ill-formed for operator<=>, so
11864 // we shouldn't emit any additional warnings about it.
11865 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11866 return;
11867
11868 // For non-floating point types, check for self-comparisons of the form
11869 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11870 // often indicate logic errors in the program.
11871 //
11872 // NOTE: Don't warn about comparison expressions resulting from macro
11873 // expansion. Also don't warn about comparisons which are only self
11874 // comparisons within a template instantiation. The warnings should catch
11875 // obvious cases in the definition of the template anyways. The idea is to
11876 // warn when the typed comparison operator will always evaluate to the same
11877 // result.
11878
11879 // Used for indexing into %select in warn_comparison_always
11880 enum {
11881 AlwaysConstant,
11882 AlwaysTrue,
11883 AlwaysFalse,
11884 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11885 };
11886
11887 // C++2a [depr.array.comp]:
11888 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11889 // operands of array type are deprecated.
11890 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11891 RHSStripped->getType()->isArrayType()) {
11892 S.Diag(Loc, diag::warn_depr_array_comparison)
11893 << LHS->getSourceRange() << RHS->getSourceRange()
11894 << LHSStripped->getType() << RHSStripped->getType();
11895 // Carry on to produce the tautological comparison warning, if this
11896 // expression is potentially-evaluated, we can resolve the array to a
11897 // non-weak declaration, and so on.
11898 }
11899
11900 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11901 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11902 unsigned Result;
11903 switch (Opc) {
11904 case BO_EQ:
11905 case BO_LE:
11906 case BO_GE:
11907 Result = AlwaysTrue;
11908 break;
11909 case BO_NE:
11910 case BO_LT:
11911 case BO_GT:
11912 Result = AlwaysFalse;
11913 break;
11914 case BO_Cmp:
11915 Result = AlwaysEqual;
11916 break;
11917 default:
11918 Result = AlwaysConstant;
11919 break;
11920 }
11921 S.DiagRuntimeBehavior(Loc, nullptr,
11922 S.PDiag(diag::warn_comparison_always)
11923 << 0 /*self-comparison*/
11924 << Result);
11925 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11926 // What is it always going to evaluate to?
11927 unsigned Result;
11928 switch (Opc) {
11929 case BO_EQ: // e.g. array1 == array2
11930 Result = AlwaysFalse;
11931 break;
11932 case BO_NE: // e.g. array1 != array2
11933 Result = AlwaysTrue;
11934 break;
11935 default: // e.g. array1 <= array2
11936 // The best we can say is 'a constant'
11937 Result = AlwaysConstant;
11938 break;
11939 }
11940 S.DiagRuntimeBehavior(Loc, nullptr,
11941 S.PDiag(diag::warn_comparison_always)
11942 << 1 /*array comparison*/
11943 << Result);
11944 }
11945 }
11946
11947 if (isa<CastExpr>(LHSStripped))
11948 LHSStripped = LHSStripped->IgnoreParenCasts();
11949 if (isa<CastExpr>(RHSStripped))
11950 RHSStripped = RHSStripped->IgnoreParenCasts();
11951
11952 // Warn about comparisons against a string constant (unless the other
11953 // operand is null); the user probably wants string comparison function.
11954 Expr *LiteralString = nullptr;
11955 Expr *LiteralStringStripped = nullptr;
11956 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11957 !RHSStripped->isNullPointerConstant(S.Context,
11959 LiteralString = LHS;
11960 LiteralStringStripped = LHSStripped;
11961 } else if ((isa<StringLiteral>(RHSStripped) ||
11962 isa<ObjCEncodeExpr>(RHSStripped)) &&
11963 !LHSStripped->isNullPointerConstant(S.Context,
11965 LiteralString = RHS;
11966 LiteralStringStripped = RHSStripped;
11967 }
11968
11969 if (LiteralString) {
11970 S.DiagRuntimeBehavior(Loc, nullptr,
11971 S.PDiag(diag::warn_stringcompare)
11972 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11973 << LiteralString->getSourceRange());
11974 }
11975}
11976
11978 switch (CK) {
11979 default: {
11980#ifndef NDEBUG
11981 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11982 << "\n";
11983#endif
11984 llvm_unreachable("unhandled cast kind");
11985 }
11986 case CK_UserDefinedConversion:
11987 return ICK_Identity;
11988 case CK_LValueToRValue:
11989 return ICK_Lvalue_To_Rvalue;
11990 case CK_ArrayToPointerDecay:
11991 return ICK_Array_To_Pointer;
11992 case CK_FunctionToPointerDecay:
11994 case CK_IntegralCast:
11996 case CK_FloatingCast:
11998 case CK_IntegralToFloating:
11999 case CK_FloatingToIntegral:
12000 return ICK_Floating_Integral;
12001 case CK_IntegralComplexCast:
12002 case CK_FloatingComplexCast:
12003 case CK_FloatingComplexToIntegralComplex:
12004 case CK_IntegralComplexToFloatingComplex:
12006 case CK_FloatingComplexToReal:
12007 case CK_FloatingRealToComplex:
12008 case CK_IntegralComplexToReal:
12009 case CK_IntegralRealToComplex:
12010 return ICK_Complex_Real;
12011 case CK_HLSLArrayRValue:
12012 return ICK_HLSL_Array_RValue;
12013 }
12014}
12015
12017 QualType FromType,
12019 // Check for a narrowing implicit conversion.
12022 SCS.setToType(0, FromType);
12023 SCS.setToType(1, ToType);
12024 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12025 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12026
12027 APValue PreNarrowingValue;
12028 QualType PreNarrowingType;
12029 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12030 PreNarrowingType,
12031 /*IgnoreFloatToIntegralConversion*/ true)) {
12033 // Implicit conversion to a narrower type, but the expression is
12034 // value-dependent so we can't tell whether it's actually narrowing.
12035 case NK_Not_Narrowing:
12036 return false;
12037
12039 // Implicit conversion to a narrower type, and the value is not a constant
12040 // expression.
12041 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12042 << /*Constant*/ 1
12043 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12044 return true;
12045
12047 // Implicit conversion to a narrower type, and the value is not a constant
12048 // expression.
12049 case NK_Type_Narrowing:
12050 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12051 << /*Constant*/ 0 << FromType << ToType;
12052 // TODO: It's not a constant expression, but what if the user intended it
12053 // to be? Can we produce notes to help them figure out why it isn't?
12054 return true;
12055 }
12056 llvm_unreachable("unhandled case in switch");
12057}
12058
12060 ExprResult &LHS,
12061 ExprResult &RHS,
12063 QualType LHSType = LHS.get()->getType();
12064 QualType RHSType = RHS.get()->getType();
12065 // Dig out the original argument type and expression before implicit casts
12066 // were applied. These are the types/expressions we need to check the
12067 // [expr.spaceship] requirements against.
12068 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12069 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12070 QualType LHSStrippedType = LHSStripped.get()->getType();
12071 QualType RHSStrippedType = RHSStripped.get()->getType();
12072
12073 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12074 // other is not, the program is ill-formed.
12075 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12076 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12077 return QualType();
12078 }
12079
12080 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12081 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12082 RHSStrippedType->isEnumeralType();
12083 if (NumEnumArgs == 1) {
12084 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12085 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12086 if (OtherTy->hasFloatingRepresentation()) {
12087 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12088 return QualType();
12089 }
12090 }
12091 if (NumEnumArgs == 2) {
12092 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12093 // type E, the operator yields the result of converting the operands
12094 // to the underlying type of E and applying <=> to the converted operands.
12095 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12096 S.InvalidOperands(Loc, LHS, RHS);
12097 return QualType();
12098 }
12099 QualType IntType =
12100 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12101 assert(IntType->isArithmeticType());
12102
12103 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12104 // promote the boolean type, and all other promotable integer types, to
12105 // avoid this.
12106 if (S.Context.isPromotableIntegerType(IntType))
12107 IntType = S.Context.getPromotedIntegerType(IntType);
12108
12109 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12110 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12111 LHSType = RHSType = IntType;
12112 }
12113
12114 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12115 // usual arithmetic conversions are applied to the operands.
12116 QualType Type =
12118 if (LHS.isInvalid() || RHS.isInvalid())
12119 return QualType();
12120 if (Type.isNull())
12121 return S.InvalidOperands(Loc, LHS, RHS);
12122
12123 std::optional<ComparisonCategoryType> CCT =
12125 if (!CCT)
12126 return S.InvalidOperands(Loc, LHS, RHS);
12127
12128 bool HasNarrowing = checkThreeWayNarrowingConversion(
12129 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12130 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12131 RHS.get()->getBeginLoc());
12132 if (HasNarrowing)
12133 return QualType();
12134
12135 assert(!Type.isNull() && "composite type for <=> has not been set");
12136
12139}
12140
12142 ExprResult &RHS,
12144 BinaryOperatorKind Opc) {
12145 if (Opc == BO_Cmp)
12146 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12147
12148 // C99 6.5.8p3 / C99 6.5.9p4
12149 QualType Type =
12151 if (LHS.isInvalid() || RHS.isInvalid())
12152 return QualType();
12153 if (Type.isNull())
12154 return S.InvalidOperands(Loc, LHS, RHS);
12155 assert(Type->isArithmeticType() || Type->isEnumeralType());
12156
12158 return S.InvalidOperands(Loc, LHS, RHS);
12159
12160 // Check for comparisons of floating point operands using != and ==.
12162 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12163
12164 // The result of comparisons is 'bool' in C++, 'int' in C.
12166}
12167
12169 if (!NullE.get()->getType()->isAnyPointerType())
12170 return;
12171 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12172 if (!E.get()->getType()->isAnyPointerType() &&
12176 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12177 if (CL->getValue() == 0)
12178 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12179 << NullValue
12181 NullValue ? "NULL" : "(void *)0");
12182 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12183 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12185 if (T == Context.CharTy)
12186 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12187 << NullValue
12189 NullValue ? "NULL" : "(void *)0");
12190 }
12191 }
12192}
12193
12194// C99 6.5.8, C++ [expr.rel]
12197 BinaryOperatorKind Opc) {
12198 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12199 bool IsThreeWay = Opc == BO_Cmp;
12200 bool IsOrdered = IsRelational || IsThreeWay;
12201 auto IsAnyPointerType = [](ExprResult E) {
12202 QualType Ty = E.get()->getType();
12203 return Ty->isPointerType() || Ty->isMemberPointerType();
12204 };
12205
12206 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12207 // type, array-to-pointer, ..., conversions are performed on both operands to
12208 // bring them to their composite type.
12209 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12210 // any type-related checks.
12211 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12213 if (LHS.isInvalid())
12214 return QualType();
12216 if (RHS.isInvalid())
12217 return QualType();
12218 } else {
12219 LHS = DefaultLvalueConversion(LHS.get());
12220 if (LHS.isInvalid())
12221 return QualType();
12222 RHS = DefaultLvalueConversion(RHS.get());
12223 if (RHS.isInvalid())
12224 return QualType();
12225 }
12226
12227 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12231 }
12232
12233 // Handle vector comparisons separately.
12234 if (LHS.get()->getType()->isVectorType() ||
12235 RHS.get()->getType()->isVectorType())
12236 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12237
12238 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12239 RHS.get()->getType()->isSveVLSBuiltinType())
12240 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12241
12242 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12243 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12244
12245 QualType LHSType = LHS.get()->getType();
12246 QualType RHSType = RHS.get()->getType();
12247 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12248 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12249 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12250
12251 if ((LHSType->isPointerType() &&
12253 (RHSType->isPointerType() &&
12255 return InvalidOperands(Loc, LHS, RHS);
12256
12257 const Expr::NullPointerConstantKind LHSNullKind =
12259 const Expr::NullPointerConstantKind RHSNullKind =
12261 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12262 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12263
12264 auto computeResultTy = [&]() {
12265 if (Opc != BO_Cmp)
12267 assert(getLangOpts().CPlusPlus);
12268 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12269
12270 QualType CompositeTy = LHS.get()->getType();
12271 assert(!CompositeTy->isReferenceType());
12272
12273 std::optional<ComparisonCategoryType> CCT =
12275 if (!CCT)
12276 return InvalidOperands(Loc, LHS, RHS);
12277
12278 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12279 // P0946R0: Comparisons between a null pointer constant and an object
12280 // pointer result in std::strong_equality, which is ill-formed under
12281 // P1959R0.
12282 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12283 << (LHSIsNull ? LHS.get()->getSourceRange()
12284 : RHS.get()->getSourceRange());
12285 return QualType();
12286 }
12287
12290 };
12291
12292 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12293 bool IsEquality = Opc == BO_EQ;
12294 if (RHSIsNull)
12295 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12296 RHS.get()->getSourceRange());
12297 else
12298 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12299 LHS.get()->getSourceRange());
12300 }
12301
12302 if (IsOrdered && LHSType->isFunctionPointerType() &&
12303 RHSType->isFunctionPointerType()) {
12304 // Valid unless a relational comparison of function pointers
12305 bool IsError = Opc == BO_Cmp;
12306 auto DiagID =
12307 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12308 : getLangOpts().CPlusPlus
12309 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12310 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12311 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12312 << RHS.get()->getSourceRange();
12313 if (IsError)
12314 return QualType();
12315 }
12316
12317 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12318 (RHSType->isIntegerType() && !RHSIsNull)) {
12319 // Skip normal pointer conversion checks in this case; we have better
12320 // diagnostics for this below.
12321 } else if (getLangOpts().CPlusPlus) {
12322 // Equality comparison of a function pointer to a void pointer is invalid,
12323 // but we allow it as an extension.
12324 // FIXME: If we really want to allow this, should it be part of composite
12325 // pointer type computation so it works in conditionals too?
12326 if (!IsOrdered &&
12327 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12328 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12329 // This is a gcc extension compatibility comparison.
12330 // In a SFINAE context, we treat this as a hard error to maintain
12331 // conformance with the C++ standard.
12333 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12334
12335 if (isSFINAEContext())
12336 return QualType();
12337
12338 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12339 return computeResultTy();
12340 }
12341
12342 // C++ [expr.eq]p2:
12343 // If at least one operand is a pointer [...] bring them to their
12344 // composite pointer type.
12345 // C++ [expr.spaceship]p6
12346 // If at least one of the operands is of pointer type, [...] bring them
12347 // to their composite pointer type.
12348 // C++ [expr.rel]p2:
12349 // If both operands are pointers, [...] bring them to their composite
12350 // pointer type.
12351 // For <=>, the only valid non-pointer types are arrays and functions, and
12352 // we already decayed those, so this is really the same as the relational
12353 // comparison rule.
12354 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12355 (IsOrdered ? 2 : 1) &&
12356 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12357 RHSType->isObjCObjectPointerType()))) {
12358 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12359 return QualType();
12360 return computeResultTy();
12361 }
12362 } else if (LHSType->isPointerType() &&
12363 RHSType->isPointerType()) { // C99 6.5.8p2
12364 // All of the following pointer-related warnings are GCC extensions, except
12365 // when handling null pointer constants.
12366 QualType LCanPointeeTy =
12367 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12368 QualType RCanPointeeTy =
12369 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12370
12371 // C99 6.5.9p2 and C99 6.5.8p2
12372 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12373 RCanPointeeTy.getUnqualifiedType())) {
12374 if (IsRelational) {
12375 // Pointers both need to point to complete or incomplete types
12376 if ((LCanPointeeTy->isIncompleteType() !=
12377 RCanPointeeTy->isIncompleteType()) &&
12378 !getLangOpts().C11) {
12379 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12381 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12382 << RCanPointeeTy->isIncompleteType();
12383 }
12384 }
12385 } else if (!IsRelational &&
12386 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12387 // Valid unless comparison between non-null pointer and function pointer
12388 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12389 && !LHSIsNull && !RHSIsNull)
12391 /*isError*/false);
12392 } else {
12393 // Invalid
12394 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12395 }
12396 if (LCanPointeeTy != RCanPointeeTy) {
12397 // Treat NULL constant as a special case in OpenCL.
12398 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12399 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12400 Diag(Loc,
12401 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12402 << LHSType << RHSType << 0 /* comparison */
12403 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12404 }
12405 }
12406 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12407 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12408 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12409 : CK_BitCast;
12410 if (LHSIsNull && !RHSIsNull)
12411 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12412 else
12413 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12414 }
12415 return computeResultTy();
12416 }
12417
12418
12419 // C++ [expr.eq]p4:
12420 // Two operands of type std::nullptr_t or one operand of type
12421 // std::nullptr_t and the other a null pointer constant compare
12422 // equal.
12423 // C23 6.5.9p5:
12424 // If both operands have type nullptr_t or one operand has type nullptr_t
12425 // and the other is a null pointer constant, they compare equal if the
12426 // former is a null pointer.
12427 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12428 if (LHSType->isNullPtrType()) {
12429 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12430 return computeResultTy();
12431 }
12432 if (RHSType->isNullPtrType()) {
12433 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12434 return computeResultTy();
12435 }
12436 }
12437
12438 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12439 // C23 6.5.9p6:
12440 // Otherwise, at least one operand is a pointer. If one is a pointer and
12441 // the other is a null pointer constant or has type nullptr_t, they
12442 // compare equal
12443 if (LHSIsNull && RHSType->isPointerType()) {
12444 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12445 return computeResultTy();
12446 }
12447 if (RHSIsNull && LHSType->isPointerType()) {
12448 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12449 return computeResultTy();
12450 }
12451 }
12452
12453 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12454 // These aren't covered by the composite pointer type rules.
12455 if (!IsOrdered && RHSType->isNullPtrType() &&
12456 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12457 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12458 return computeResultTy();
12459 }
12460 if (!IsOrdered && LHSType->isNullPtrType() &&
12461 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12462 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12463 return computeResultTy();
12464 }
12465
12466 if (getLangOpts().CPlusPlus) {
12467 if (IsRelational &&
12468 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12469 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12470 // HACK: Relational comparison of nullptr_t against a pointer type is
12471 // invalid per DR583, but we allow it within std::less<> and friends,
12472 // since otherwise common uses of it break.
12473 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12474 // friends to have std::nullptr_t overload candidates.
12475 DeclContext *DC = CurContext;
12476 if (isa<FunctionDecl>(DC))
12477 DC = DC->getParent();
12478 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12479 if (CTSD->isInStdNamespace() &&
12480 llvm::StringSwitch<bool>(CTSD->getName())
12481 .Cases("less", "less_equal", "greater", "greater_equal", true)
12482 .Default(false)) {
12483 if (RHSType->isNullPtrType())
12484 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12485 else
12486 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12487 return computeResultTy();
12488 }
12489 }
12490 }
12491
12492 // C++ [expr.eq]p2:
12493 // If at least one operand is a pointer to member, [...] bring them to
12494 // their composite pointer type.
12495 if (!IsOrdered &&
12496 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12497 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12498 return QualType();
12499 else
12500 return computeResultTy();
12501 }
12502 }
12503
12504 // Handle block pointer types.
12505 if (!IsOrdered && LHSType->isBlockPointerType() &&
12506 RHSType->isBlockPointerType()) {
12507 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12508 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12509
12510 if (!LHSIsNull && !RHSIsNull &&
12511 !Context.typesAreCompatible(lpointee, rpointee)) {
12512 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12513 << LHSType << RHSType << LHS.get()->getSourceRange()
12514 << RHS.get()->getSourceRange();
12515 }
12516 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12517 return computeResultTy();
12518 }
12519
12520 // Allow block pointers to be compared with null pointer constants.
12521 if (!IsOrdered
12522 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12523 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12524 if (!LHSIsNull && !RHSIsNull) {
12525 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12527 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12528 ->getPointeeType()->isVoidType())))
12529 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12530 << LHSType << RHSType << LHS.get()->getSourceRange()
12531 << RHS.get()->getSourceRange();
12532 }
12533 if (LHSIsNull && !RHSIsNull)
12534 LHS = ImpCastExprToType(LHS.get(), RHSType,
12535 RHSType->isPointerType() ? CK_BitCast
12536 : CK_AnyPointerToBlockPointerCast);
12537 else
12538 RHS = ImpCastExprToType(RHS.get(), LHSType,
12539 LHSType->isPointerType() ? CK_BitCast
12540 : CK_AnyPointerToBlockPointerCast);
12541 return computeResultTy();
12542 }
12543
12544 if (LHSType->isObjCObjectPointerType() ||
12545 RHSType->isObjCObjectPointerType()) {
12546 const PointerType *LPT = LHSType->getAs<PointerType>();
12547 const PointerType *RPT = RHSType->getAs<PointerType>();
12548 if (LPT || RPT) {
12549 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12550 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12551
12552 if (!LPtrToVoid && !RPtrToVoid &&
12553 !Context.typesAreCompatible(LHSType, RHSType)) {
12554 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12555 /*isError*/false);
12556 }
12557 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12558 // the RHS, but we have test coverage for this behavior.
12559 // FIXME: Consider using convertPointersToCompositeType in C++.
12560 if (LHSIsNull && !RHSIsNull) {
12561 Expr *E = LHS.get();
12562 if (getLangOpts().ObjCAutoRefCount)
12563 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12565 LHS = ImpCastExprToType(E, RHSType,
12566 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12567 }
12568 else {
12569 Expr *E = RHS.get();
12570 if (getLangOpts().ObjCAutoRefCount)
12571 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12573 /*Diagnose=*/true,
12574 /*DiagnoseCFAudited=*/false, Opc);
12575 RHS = ImpCastExprToType(E, LHSType,
12576 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12577 }
12578 return computeResultTy();
12579 }
12580 if (LHSType->isObjCObjectPointerType() &&
12581 RHSType->isObjCObjectPointerType()) {
12582 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12583 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12584 /*isError*/false);
12586 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12587
12588 if (LHSIsNull && !RHSIsNull)
12589 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12590 else
12591 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12592 return computeResultTy();
12593 }
12594
12595 if (!IsOrdered && LHSType->isBlockPointerType() &&
12597 LHS = ImpCastExprToType(LHS.get(), RHSType,
12598 CK_BlockPointerToObjCPointerCast);
12599 return computeResultTy();
12600 } else if (!IsOrdered &&
12602 RHSType->isBlockPointerType()) {
12603 RHS = ImpCastExprToType(RHS.get(), LHSType,
12604 CK_BlockPointerToObjCPointerCast);
12605 return computeResultTy();
12606 }
12607 }
12608 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12609 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12610 unsigned DiagID = 0;
12611 bool isError = false;
12612 if (LangOpts.DebuggerSupport) {
12613 // Under a debugger, allow the comparison of pointers to integers,
12614 // since users tend to want to compare addresses.
12615 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12616 (RHSIsNull && RHSType->isIntegerType())) {
12617 if (IsOrdered) {
12618 isError = getLangOpts().CPlusPlus;
12619 DiagID =
12620 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12621 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12622 }
12623 } else if (getLangOpts().CPlusPlus) {
12624 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12625 isError = true;
12626 } else if (IsOrdered)
12627 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12628 else
12629 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12630
12631 if (DiagID) {
12632 Diag(Loc, DiagID)
12633 << LHSType << RHSType << LHS.get()->getSourceRange()
12634 << RHS.get()->getSourceRange();
12635 if (isError)
12636 return QualType();
12637 }
12638
12639 if (LHSType->isIntegerType())
12640 LHS = ImpCastExprToType(LHS.get(), RHSType,
12641 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12642 else
12643 RHS = ImpCastExprToType(RHS.get(), LHSType,
12644 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12645 return computeResultTy();
12646 }
12647
12648 // Handle block pointers.
12649 if (!IsOrdered && RHSIsNull
12650 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12651 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12652 return computeResultTy();
12653 }
12654 if (!IsOrdered && LHSIsNull
12655 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12656 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12657 return computeResultTy();
12658 }
12659
12660 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12661 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12662 return computeResultTy();
12663 }
12664
12665 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12666 return computeResultTy();
12667 }
12668
12669 if (LHSIsNull && RHSType->isQueueT()) {
12670 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12671 return computeResultTy();
12672 }
12673
12674 if (LHSType->isQueueT() && RHSIsNull) {
12675 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12676 return computeResultTy();
12677 }
12678 }
12679
12680 return InvalidOperands(Loc, LHS, RHS);
12681}
12682
12683// Return a signed ext_vector_type that is of identical size and number of
12684// elements. For floating point vectors, return an integer type of identical
12685// size and number of elements. In the non ext_vector_type case, search from
12686// the largest type to the smallest type to avoid cases where long long == long,
12687// where long gets picked over long long.
12689 const VectorType *VTy = V->castAs<VectorType>();
12690 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12691
12692 if (isa<ExtVectorType>(VTy)) {
12693 if (VTy->isExtVectorBoolType())
12695 if (TypeSize == Context.getTypeSize(Context.CharTy))
12697 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12699 if (TypeSize == Context.getTypeSize(Context.IntTy))
12701 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12703 if (TypeSize == Context.getTypeSize(Context.LongTy))
12705 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12706 "Unhandled vector element size in vector compare");
12708 }
12709
12710 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12713 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12716 if (TypeSize == Context.getTypeSize(Context.LongTy))
12719 if (TypeSize == Context.getTypeSize(Context.IntTy))
12722 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12725 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12726 "Unhandled vector element size in vector compare");
12729}
12730
12732 const BuiltinType *VTy = V->castAs<BuiltinType>();
12733 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12734
12735 const QualType ETy = V->getSveEltType(Context);
12736 const auto TypeSize = Context.getTypeSize(ETy);
12737
12738 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12739 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12740 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12741}
12742
12743/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12744/// operates on extended vector types. Instead of producing an IntTy result,
12745/// like a scalar comparison, a vector comparison produces a vector of integer
12746/// types.
12749 BinaryOperatorKind Opc) {
12750 if (Opc == BO_Cmp) {
12751 Diag(Loc, diag::err_three_way_vector_comparison);
12752 return QualType();
12753 }
12754
12755 // Check to make sure we're operating on vectors of the same type and width,
12756 // Allowing one side to be a scalar of element type.
12757 QualType vType =
12758 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12759 /*AllowBothBool*/ true,
12760 /*AllowBoolConversions*/ getLangOpts().ZVector,
12761 /*AllowBooleanOperation*/ true,
12762 /*ReportInvalid*/ true);
12763 if (vType.isNull())
12764 return vType;
12765
12766 QualType LHSType = LHS.get()->getType();
12767
12768 // Determine the return type of a vector compare. By default clang will return
12769 // a scalar for all vector compares except vector bool and vector pixel.
12770 // With the gcc compiler we will always return a vector type and with the xl
12771 // compiler we will always return a scalar type. This switch allows choosing
12772 // which behavior is prefered.
12773 if (getLangOpts().AltiVec) {
12774 switch (getLangOpts().getAltivecSrcCompat()) {
12776 // If AltiVec, the comparison results in a numeric type, i.e.
12777 // bool for C++, int for C
12778 if (vType->castAs<VectorType>()->getVectorKind() ==
12781 else
12782 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12783 break;
12785 // For GCC we always return the vector type.
12786 break;
12789 break;
12790 }
12791 }
12792
12793 // For non-floating point types, check for self-comparisons of the form
12794 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12795 // often indicate logic errors in the program.
12796 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12797
12798 // Check for comparisons of floating point operands using != and ==.
12799 if (LHSType->hasFloatingRepresentation()) {
12800 assert(RHS.get()->getType()->hasFloatingRepresentation());
12801 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12802 }
12803
12804 // Return a signed type for the vector.
12805 return GetSignedVectorType(vType);
12806}
12807
12809 ExprResult &RHS,
12811 BinaryOperatorKind Opc) {
12812 if (Opc == BO_Cmp) {
12813 Diag(Loc, diag::err_three_way_vector_comparison);
12814 return QualType();
12815 }
12816
12817 // Check to make sure we're operating on vectors of the same type and width,
12818 // Allowing one side to be a scalar of element type.
12820 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12821
12822 if (vType.isNull())
12823 return vType;
12824
12825 QualType LHSType = LHS.get()->getType();
12826
12827 // For non-floating point types, check for self-comparisons of the form
12828 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12829 // often indicate logic errors in the program.
12830 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12831
12832 // Check for comparisons of floating point operands using != and ==.
12833 if (LHSType->hasFloatingRepresentation()) {
12834 assert(RHS.get()->getType()->hasFloatingRepresentation());
12835 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12836 }
12837
12838 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12839 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12840
12841 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12842 RHSBuiltinTy->isSVEBool())
12843 return LHSType;
12844
12845 // Return a signed type for the vector.
12846 return GetSignedSizelessVectorType(vType);
12847}
12848
12849static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12850 const ExprResult &XorRHS,
12851 const SourceLocation Loc) {
12852 // Do not diagnose macros.
12853 if (Loc.isMacroID())
12854 return;
12855
12856 // Do not diagnose if both LHS and RHS are macros.
12857 if (XorLHS.get()->getExprLoc().isMacroID() &&
12858 XorRHS.get()->getExprLoc().isMacroID())
12859 return;
12860
12861 bool Negative = false;
12862 bool ExplicitPlus = false;
12863 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12864 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12865
12866 if (!LHSInt)
12867 return;
12868 if (!RHSInt) {
12869 // Check negative literals.
12870 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12871 UnaryOperatorKind Opc = UO->getOpcode();
12872 if (Opc != UO_Minus && Opc != UO_Plus)
12873 return;
12874 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12875 if (!RHSInt)
12876 return;
12877 Negative = (Opc == UO_Minus);
12878 ExplicitPlus = !Negative;
12879 } else {
12880 return;
12881 }
12882 }
12883
12884 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12885 llvm::APInt RightSideValue = RHSInt->getValue();
12886 if (LeftSideValue != 2 && LeftSideValue != 10)
12887 return;
12888
12889 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12890 return;
12891
12893 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12894 llvm::StringRef ExprStr =
12896
12897 CharSourceRange XorRange =
12899 llvm::StringRef XorStr =
12901 // Do not diagnose if xor keyword/macro is used.
12902 if (XorStr == "xor")
12903 return;
12904
12905 std::string LHSStr = std::string(Lexer::getSourceText(
12906 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12907 S.getSourceManager(), S.getLangOpts()));
12908 std::string RHSStr = std::string(Lexer::getSourceText(
12909 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12910 S.getSourceManager(), S.getLangOpts()));
12911
12912 if (Negative) {
12913 RightSideValue = -RightSideValue;
12914 RHSStr = "-" + RHSStr;
12915 } else if (ExplicitPlus) {
12916 RHSStr = "+" + RHSStr;
12917 }
12918
12919 StringRef LHSStrRef = LHSStr;
12920 StringRef RHSStrRef = RHSStr;
12921 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12922 // literals.
12923 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12924 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12925 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12926 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12927 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12928 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12929 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12930 return;
12931
12932 bool SuggestXor =
12933 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12934 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12935 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12936 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12937 std::string SuggestedExpr = "1 << " + RHSStr;
12938 bool Overflow = false;
12939 llvm::APInt One = (LeftSideValue - 1);
12940 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12941 if (Overflow) {
12942 if (RightSideIntValue < 64)
12943 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12944 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12945 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12946 else if (RightSideIntValue == 64)
12947 S.Diag(Loc, diag::warn_xor_used_as_pow)
12948 << ExprStr << toString(XorValue, 10, true);
12949 else
12950 return;
12951 } else {
12952 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12953 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12954 << toString(PowValue, 10, true)
12956 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12957 }
12958
12959 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12960 << ("0x2 ^ " + RHSStr) << SuggestXor;
12961 } else if (LeftSideValue == 10) {
12962 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12963 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12964 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12965 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12966 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12967 << ("0xA ^ " + RHSStr) << SuggestXor;
12968 }
12969}
12970
12973 // Ensure that either both operands are of the same vector type, or
12974 // one operand is of a vector type and the other is of its element type.
12975 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12976 /*AllowBothBool*/ true,
12977 /*AllowBoolConversions*/ false,
12978 /*AllowBooleanOperation*/ false,
12979 /*ReportInvalid*/ false);
12980 if (vType.isNull())
12981 return InvalidOperands(Loc, LHS, RHS);
12982 if (getLangOpts().OpenCL &&
12983 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12985 return InvalidOperands(Loc, LHS, RHS);
12986 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12987 // usage of the logical operators && and || with vectors in C. This
12988 // check could be notionally dropped.
12989 if (!getLangOpts().CPlusPlus &&
12990 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12991 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12992
12993 return GetSignedVectorType(LHS.get()->getType());
12994}
12995
12998 bool IsCompAssign) {
12999 if (!IsCompAssign) {
13001 if (LHS.isInvalid())
13002 return QualType();
13003 }
13005 if (RHS.isInvalid())
13006 return QualType();
13007
13008 // For conversion purposes, we ignore any qualifiers.
13009 // For example, "const float" and "float" are equivalent.
13010 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13011 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13012
13013 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13014 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13015 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13016
13017 if (Context.hasSameType(LHSType, RHSType))
13018 return Context.getCommonSugaredType(LHSType, RHSType);
13019
13020 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13021 // case we have to return InvalidOperands.
13022 ExprResult OriginalLHS = LHS;
13023 ExprResult OriginalRHS = RHS;
13024 if (LHSMatType && !RHSMatType) {
13025 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13026 if (!RHS.isInvalid())
13027 return LHSType;
13028
13029 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13030 }
13031
13032 if (!LHSMatType && RHSMatType) {
13033 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13034 if (!LHS.isInvalid())
13035 return RHSType;
13036 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13037 }
13038
13039 return InvalidOperands(Loc, LHS, RHS);
13040}
13041
13044 bool IsCompAssign) {
13045 if (!IsCompAssign) {
13047 if (LHS.isInvalid())
13048 return QualType();
13049 }
13051 if (RHS.isInvalid())
13052 return QualType();
13053
13054 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13055 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13056 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13057
13058 if (LHSMatType && RHSMatType) {
13059 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13060 return InvalidOperands(Loc, LHS, RHS);
13061
13062 if (Context.hasSameType(LHSMatType, RHSMatType))
13064 LHS.get()->getType().getUnqualifiedType(),
13065 RHS.get()->getType().getUnqualifiedType());
13066
13067 QualType LHSELTy = LHSMatType->getElementType(),
13068 RHSELTy = RHSMatType->getElementType();
13069 if (!Context.hasSameType(LHSELTy, RHSELTy))
13070 return InvalidOperands(Loc, LHS, RHS);
13071
13073 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13074 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13075 }
13076 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13077}
13078
13080 switch (Opc) {
13081 default:
13082 return false;
13083 case BO_And:
13084 case BO_AndAssign:
13085 case BO_Or:
13086 case BO_OrAssign:
13087 case BO_Xor:
13088 case BO_XorAssign:
13089 return true;
13090 }
13091}
13092
13095 BinaryOperatorKind Opc) {
13096 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13097
13098 bool IsCompAssign =
13099 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13100
13101 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13102
13103 if (LHS.get()->getType()->isVectorType() ||
13104 RHS.get()->getType()->isVectorType()) {
13105 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13107 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13108 /*AllowBothBool*/ true,
13109 /*AllowBoolConversions*/ getLangOpts().ZVector,
13110 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13111 /*ReportInvalid*/ true);
13112 return InvalidOperands(Loc, LHS, RHS);
13113 }
13114
13115 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13116 RHS.get()->getType()->isSveVLSBuiltinType()) {
13117 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13119 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13121 return InvalidOperands(Loc, LHS, RHS);
13122 }
13123
13124 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13125 RHS.get()->getType()->isSveVLSBuiltinType()) {
13126 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13128 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13130 return InvalidOperands(Loc, LHS, RHS);
13131 }
13132
13133 if (Opc == BO_And)
13134 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13135
13136 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13138 return InvalidOperands(Loc, LHS, RHS);
13139
13140 ExprResult LHSResult = LHS, RHSResult = RHS;
13142 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13143 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13144 return QualType();
13145 LHS = LHSResult.get();
13146 RHS = RHSResult.get();
13147
13148 if (Opc == BO_Xor)
13149 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13150
13151 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13152 return compType;
13153 return InvalidOperands(Loc, LHS, RHS);
13154}
13155
13156// C99 6.5.[13,14]
13159 BinaryOperatorKind Opc) {
13160 // Check vector operands differently.
13161 if (LHS.get()->getType()->isVectorType() ||
13162 RHS.get()->getType()->isVectorType())
13163 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13164
13165 bool EnumConstantInBoolContext = false;
13166 for (const ExprResult &HS : {LHS, RHS}) {
13167 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13168 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13169 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13170 EnumConstantInBoolContext = true;
13171 }
13172 }
13173
13174 if (EnumConstantInBoolContext)
13175 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13176
13177 // WebAssembly tables can't be used with logical operators.
13178 QualType LHSTy = LHS.get()->getType();
13179 QualType RHSTy = RHS.get()->getType();
13180 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13181 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13182 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13183 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13184 return InvalidOperands(Loc, LHS, RHS);
13185 }
13186
13187 // Diagnose cases where the user write a logical and/or but probably meant a
13188 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13189 // is a constant.
13190 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13191 !LHS.get()->getType()->isBooleanType() &&
13192 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13193 // Don't warn in macros or template instantiations.
13195 // If the RHS can be constant folded, and if it constant folds to something
13196 // that isn't 0 or 1 (which indicate a potential logical operation that
13197 // happened to fold to true/false) then warn.
13198 // Parens on the RHS are ignored.
13199 Expr::EvalResult EVResult;
13200 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13201 llvm::APSInt Result = EVResult.Val.getInt();
13202 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13203 !RHS.get()->getExprLoc().isMacroID()) ||
13204 (Result != 0 && Result != 1)) {
13205 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13206 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13207 // Suggest replacing the logical operator with the bitwise version
13208 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13209 << (Opc == BO_LAnd ? "&" : "|")
13212 Opc == BO_LAnd ? "&" : "|");
13213 if (Opc == BO_LAnd)
13214 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13215 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13218 RHS.get()->getEndLoc()));
13219 }
13220 }
13221 }
13222
13223 if (!Context.getLangOpts().CPlusPlus) {
13224 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13225 // not operate on the built-in scalar and vector float types.
13226 if (Context.getLangOpts().OpenCL &&
13227 Context.getLangOpts().OpenCLVersion < 120) {
13228 if (LHS.get()->getType()->isFloatingType() ||
13229 RHS.get()->getType()->isFloatingType())
13230 return InvalidOperands(Loc, LHS, RHS);
13231 }
13232
13233 LHS = UsualUnaryConversions(LHS.get());
13234 if (LHS.isInvalid())
13235 return QualType();
13236
13237 RHS = UsualUnaryConversions(RHS.get());
13238 if (RHS.isInvalid())
13239 return QualType();
13240
13241 if (!LHS.get()->getType()->isScalarType() ||
13242 !RHS.get()->getType()->isScalarType())
13243 return InvalidOperands(Loc, LHS, RHS);
13244
13245 return Context.IntTy;
13246 }
13247
13248 // The following is safe because we only use this method for
13249 // non-overloadable operands.
13250
13251 // C++ [expr.log.and]p1
13252 // C++ [expr.log.or]p1
13253 // The operands are both contextually converted to type bool.
13255 if (LHSRes.isInvalid())
13256 return InvalidOperands(Loc, LHS, RHS);
13257 LHS = LHSRes;
13258
13260 if (RHSRes.isInvalid())
13261 return InvalidOperands(Loc, LHS, RHS);
13262 RHS = RHSRes;
13263
13264 // C++ [expr.log.and]p2
13265 // C++ [expr.log.or]p2
13266 // The result is a bool.
13267 return Context.BoolTy;
13268}
13269
13270static bool IsReadonlyMessage(Expr *E, Sema &S) {
13271 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13272 if (!ME) return false;
13273 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13274 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13276 if (!Base) return false;
13277 return Base->getMethodDecl() != nullptr;
13278}
13279
13280/// Is the given expression (which must be 'const') a reference to a
13281/// variable which was originally non-const, but which has become
13282/// 'const' due to being captured within a block?
13285 assert(E->isLValue() && E->getType().isConstQualified());
13286 E = E->IgnoreParens();
13287
13288 // Must be a reference to a declaration from an enclosing scope.
13289 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13290 if (!DRE) return NCCK_None;
13292
13293 // The declaration must be a variable which is not declared 'const'.
13294 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13295 if (!var) return NCCK_None;
13296 if (var->getType().isConstQualified()) return NCCK_None;
13297 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13298
13299 // Decide whether the first capture was for a block or a lambda.
13300 DeclContext *DC = S.CurContext, *Prev = nullptr;
13301 // Decide whether the first capture was for a block or a lambda.
13302 while (DC) {
13303 // For init-capture, it is possible that the variable belongs to the
13304 // template pattern of the current context.
13305 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13306 if (var->isInitCapture() &&
13307 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13308 break;
13309 if (DC == var->getDeclContext())
13310 break;
13311 Prev = DC;
13312 DC = DC->getParent();
13313 }
13314 // Unless we have an init-capture, we've gone one step too far.
13315 if (!var->isInitCapture())
13316 DC = Prev;
13317 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13318}
13319
13320static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13321 Ty = Ty.getNonReferenceType();
13322 if (IsDereference && Ty->isPointerType())
13323 Ty = Ty->getPointeeType();
13324 return !Ty.isConstQualified();
13325}
13326
13327// Update err_typecheck_assign_const and note_typecheck_assign_const
13328// when this enum is changed.
13329enum {
13335 ConstUnknown, // Keep as last element
13336};
13337
13338/// Emit the "read-only variable not assignable" error and print notes to give
13339/// more information about why the variable is not assignable, such as pointing
13340/// to the declaration of a const variable, showing that a method is const, or
13341/// that the function is returning a const reference.
13342static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13344 SourceRange ExprRange = E->getSourceRange();
13345
13346 // Only emit one error on the first const found. All other consts will emit
13347 // a note to the error.
13348 bool DiagnosticEmitted = false;
13349
13350 // Track if the current expression is the result of a dereference, and if the
13351 // next checked expression is the result of a dereference.
13352 bool IsDereference = false;
13353 bool NextIsDereference = false;
13354
13355 // Loop to process MemberExpr chains.
13356 while (true) {
13357 IsDereference = NextIsDereference;
13358
13360 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13361 NextIsDereference = ME->isArrow();
13362 const ValueDecl *VD = ME->getMemberDecl();
13363 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13364 // Mutable fields can be modified even if the class is const.
13365 if (Field->isMutable()) {
13366 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13367 break;
13368 }
13369
13370 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13371 if (!DiagnosticEmitted) {
13372 S.Diag(Loc, diag::err_typecheck_assign_const)
13373 << ExprRange << ConstMember << false /*static*/ << Field
13374 << Field->getType();
13375 DiagnosticEmitted = true;
13376 }
13377 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13378 << ConstMember << false /*static*/ << Field << Field->getType()
13379 << Field->getSourceRange();
13380 }
13381 E = ME->getBase();
13382 continue;
13383 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13384 if (VDecl->getType().isConstQualified()) {
13385 if (!DiagnosticEmitted) {
13386 S.Diag(Loc, diag::err_typecheck_assign_const)
13387 << ExprRange << ConstMember << true /*static*/ << VDecl
13388 << VDecl->getType();
13389 DiagnosticEmitted = true;
13390 }
13391 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13392 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13393 << VDecl->getSourceRange();
13394 }
13395 // Static fields do not inherit constness from parents.
13396 break;
13397 }
13398 break; // End MemberExpr
13399 } else if (const ArraySubscriptExpr *ASE =
13400 dyn_cast<ArraySubscriptExpr>(E)) {
13401 E = ASE->getBase()->IgnoreParenImpCasts();
13402 continue;
13403 } else if (const ExtVectorElementExpr *EVE =
13404 dyn_cast<ExtVectorElementExpr>(E)) {
13405 E = EVE->getBase()->IgnoreParenImpCasts();
13406 continue;
13407 }
13408 break;
13409 }
13410
13411 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13412 // Function calls
13413 const FunctionDecl *FD = CE->getDirectCallee();
13414 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13415 if (!DiagnosticEmitted) {
13416 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13417 << ConstFunction << FD;
13418 DiagnosticEmitted = true;
13419 }
13421 diag::note_typecheck_assign_const)
13422 << ConstFunction << FD << FD->getReturnType()
13423 << FD->getReturnTypeSourceRange();
13424 }
13425 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13426 // Point to variable declaration.
13427 if (const ValueDecl *VD = DRE->getDecl()) {
13428 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13429 if (!DiagnosticEmitted) {
13430 S.Diag(Loc, diag::err_typecheck_assign_const)
13431 << ExprRange << ConstVariable << VD << VD->getType();
13432 DiagnosticEmitted = true;
13433 }
13434 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13435 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13436 }
13437 }
13438 } else if (isa<CXXThisExpr>(E)) {
13439 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13440 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13441 if (MD->isConst()) {
13442 if (!DiagnosticEmitted) {
13443 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13444 << ConstMethod << MD;
13445 DiagnosticEmitted = true;
13446 }
13447 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13448 << ConstMethod << MD << MD->getSourceRange();
13449 }
13450 }
13451 }
13452 }
13453
13454 if (DiagnosticEmitted)
13455 return;
13456
13457 // Can't determine a more specific message, so display the generic error.
13458 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13459}
13460
13466
13468 const RecordType *Ty,
13470 OriginalExprKind OEK,
13471 bool &DiagnosticEmitted) {
13472 std::vector<const RecordType *> RecordTypeList;
13473 RecordTypeList.push_back(Ty);
13474 unsigned NextToCheckIndex = 0;
13475 // We walk the record hierarchy breadth-first to ensure that we print
13476 // diagnostics in field nesting order.
13477 while (RecordTypeList.size() > NextToCheckIndex) {
13478 bool IsNested = NextToCheckIndex > 0;
13479 for (const FieldDecl *Field :
13480 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13481 // First, check every field for constness.
13482 QualType FieldTy = Field->getType();
13483 if (FieldTy.isConstQualified()) {
13484 if (!DiagnosticEmitted) {
13485 S.Diag(Loc, diag::err_typecheck_assign_const)
13486 << Range << NestedConstMember << OEK << VD
13487 << IsNested << Field;
13488 DiagnosticEmitted = true;
13489 }
13490 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13491 << NestedConstMember << IsNested << Field
13492 << FieldTy << Field->getSourceRange();
13493 }
13494
13495 // Then we append it to the list to check next in order.
13496 FieldTy = FieldTy.getCanonicalType();
13497 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13498 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13499 RecordTypeList.push_back(FieldRecTy);
13500 }
13501 }
13502 ++NextToCheckIndex;
13503 }
13504}
13505
13506/// Emit an error for the case where a record we are trying to assign to has a
13507/// const-qualified field somewhere in its hierarchy.
13508static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13510 QualType Ty = E->getType();
13511 assert(Ty->isRecordType() && "lvalue was not record?");
13513 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13514 bool DiagEmitted = false;
13515
13516 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13517 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13518 Range, OEK_Member, DiagEmitted);
13519 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13520 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13521 Range, OEK_Variable, DiagEmitted);
13522 else
13523 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13524 Range, OEK_LValue, DiagEmitted);
13525 if (!DiagEmitted)
13527}
13528
13529/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13530/// emit an error and return true. If so, return false.
13532 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13533
13535
13536 SourceLocation OrigLoc = Loc;
13538 &Loc);
13539 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13541 if (IsLV == Expr::MLV_Valid)
13542 return false;
13543
13544 unsigned DiagID = 0;
13545 bool NeedType = false;
13546 switch (IsLV) { // C99 6.5.16p2
13548 // Use a specialized diagnostic when we're assigning to an object
13549 // from an enclosing function or block.
13551 if (NCCK == NCCK_Block)
13552 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13553 else
13554 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13555 break;
13556 }
13557
13558 // In ARC, use some specialized diagnostics for occasions where we
13559 // infer 'const'. These are always pseudo-strong variables.
13560 if (S.getLangOpts().ObjCAutoRefCount) {
13561 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13562 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13563 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13564
13565 // Use the normal diagnostic if it's pseudo-__strong but the
13566 // user actually wrote 'const'.
13567 if (var->isARCPseudoStrong() &&
13568 (!var->getTypeSourceInfo() ||
13570 // There are three pseudo-strong cases:
13571 // - self
13572 ObjCMethodDecl *method = S.getCurMethodDecl();
13573 if (method && var == method->getSelfDecl()) {
13574 DiagID = method->isClassMethod()
13575 ? diag::err_typecheck_arc_assign_self_class_method
13576 : diag::err_typecheck_arc_assign_self;
13577
13578 // - Objective-C externally_retained attribute.
13579 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13580 isa<ParmVarDecl>(var)) {
13581 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13582
13583 // - fast enumeration variables
13584 } else {
13585 DiagID = diag::err_typecheck_arr_assign_enumeration;
13586 }
13587
13588 SourceRange Assign;
13589 if (Loc != OrigLoc)
13590 Assign = SourceRange(OrigLoc, OrigLoc);
13591 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13592 // We need to preserve the AST regardless, so migration tool
13593 // can do its job.
13594 return false;
13595 }
13596 }
13597 }
13598
13599 // If none of the special cases above are triggered, then this is a
13600 // simple const assignment.
13601 if (DiagID == 0) {
13603 return true;
13604 }
13605
13606 break;
13609 return true;
13612 return true;
13615 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13616 NeedType = true;
13617 break;
13619 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13620 NeedType = true;
13621 break;
13623 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13624 break;
13625 case Expr::MLV_Valid:
13626 llvm_unreachable("did not take early return for MLV_Valid");
13630 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13631 break;
13634 return S.RequireCompleteType(Loc, E->getType(),
13635 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13637 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13638 break;
13640 llvm_unreachable("readonly properties should be processed differently");
13642 DiagID = diag::err_readonly_message_assignment;
13643 break;
13645 DiagID = diag::err_no_subobject_property_setting;
13646 break;
13647 }
13648
13649 SourceRange Assign;
13650 if (Loc != OrigLoc)
13651 Assign = SourceRange(OrigLoc, OrigLoc);
13652 if (NeedType)
13653 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13654 else
13655 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13656 return true;
13657}
13658
13659static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13661 Sema &Sema) {
13663 return;
13665 return;
13666 if (Loc.isInvalid() || Loc.isMacroID())
13667 return;
13668 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13669 return;
13670
13671 // C / C++ fields
13672 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13673 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13674 if (ML && MR) {
13675 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13676 return;
13677 const ValueDecl *LHSDecl =
13678 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13679 const ValueDecl *RHSDecl =
13680 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13681 if (LHSDecl != RHSDecl)
13682 return;
13683 if (LHSDecl->getType().isVolatileQualified())
13684 return;
13685 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13686 if (RefTy->getPointeeType().isVolatileQualified())
13687 return;
13688
13689 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13690 }
13691
13692 // Objective-C instance variables
13693 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13694 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13695 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13696 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13697 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13698 if (RL && RR && RL->getDecl() == RR->getDecl())
13699 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13700 }
13701}
13702
13703// C99 6.5.16.1
13706 QualType CompoundType,
13707 BinaryOperatorKind Opc) {
13708 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13709
13710 // Verify that LHS is a modifiable lvalue, and emit error if not.
13711 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13712 return QualType();
13713
13714 QualType LHSType = LHSExpr->getType();
13715 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13716 CompoundType;
13717 // OpenCL v1.2 s6.1.1.1 p2:
13718 // The half data type can only be used to declare a pointer to a buffer that
13719 // contains half values
13720 if (getLangOpts().OpenCL &&
13721 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13722 LHSType->isHalfType()) {
13723 Diag(Loc, diag::err_opencl_half_load_store) << 1
13724 << LHSType.getUnqualifiedType();
13725 return QualType();
13726 }
13727
13728 // WebAssembly tables can't be used on RHS of an assignment expression.
13729 if (RHSType->isWebAssemblyTableType()) {
13730 Diag(Loc, diag::err_wasm_table_art) << 0;
13731 return QualType();
13732 }
13733
13734 AssignConvertType ConvTy;
13735 if (CompoundType.isNull()) {
13736 Expr *RHSCheck = RHS.get();
13737
13738 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13739
13740 QualType LHSTy(LHSType);
13741 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13742 if (RHS.isInvalid())
13743 return QualType();
13744 // Special case of NSObject attributes on c-style pointer types.
13745 if (ConvTy == IncompatiblePointer &&
13746 ((Context.isObjCNSObjectType(LHSType) &&
13747 RHSType->isObjCObjectPointerType()) ||
13748 (Context.isObjCNSObjectType(RHSType) &&
13749 LHSType->isObjCObjectPointerType())))
13750 ConvTy = Compatible;
13751
13752 if (ConvTy == Compatible &&
13753 LHSType->isObjCObjectType())
13754 Diag(Loc, diag::err_objc_object_assignment)
13755 << LHSType;
13756
13757 // If the RHS is a unary plus or minus, check to see if they = and + are
13758 // right next to each other. If so, the user may have typo'd "x =+ 4"
13759 // instead of "x += 4".
13760 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13761 RHSCheck = ICE->getSubExpr();
13762 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13763 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13764 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13765 // Only if the two operators are exactly adjacent.
13766 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13767 // And there is a space or other character before the subexpr of the
13768 // unary +/-. We don't want to warn on "x=-1".
13769 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13770 UO->getSubExpr()->getBeginLoc().isFileID()) {
13771 Diag(Loc, diag::warn_not_compound_assign)
13772 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13773 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13774 }
13775 }
13776
13777 if (ConvTy == Compatible) {
13778 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13779 // Warn about retain cycles where a block captures the LHS, but
13780 // not if the LHS is a simple variable into which the block is
13781 // being stored...unless that variable can be captured by reference!
13782 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13783 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13784 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13785 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13786 }
13787
13788 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13790 // It is safe to assign a weak reference into a strong variable.
13791 // Although this code can still have problems:
13792 // id x = self.weakProp;
13793 // id y = self.weakProp;
13794 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13795 // paths through the function. This should be revisited if
13796 // -Wrepeated-use-of-weak is made flow-sensitive.
13797 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13798 // variable, which will be valid for the current autorelease scope.
13799 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13800 RHS.get()->getBeginLoc()))
13802
13803 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13804 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13805 }
13806 }
13807 } else {
13808 // Compound assignment "x += y"
13809 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13810 }
13811
13812 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13813 RHS.get(), AA_Assigning))
13814 return QualType();
13815
13816 CheckForNullPointerDereference(*this, LHSExpr);
13817
13818 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13819 if (CompoundType.isNull()) {
13820 // C++2a [expr.ass]p5:
13821 // A simple-assignment whose left operand is of a volatile-qualified
13822 // type is deprecated unless the assignment is either a discarded-value
13823 // expression or an unevaluated operand
13824 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13825 }
13826 }
13827
13828 // C11 6.5.16p3: The type of an assignment expression is the type of the
13829 // left operand would have after lvalue conversion.
13830 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13831 // qualified type, the value has the unqualified version of the type of the
13832 // lvalue; additionally, if the lvalue has atomic type, the value has the
13833 // non-atomic version of the type of the lvalue.
13834 // C++ 5.17p1: the type of the assignment expression is that of its left
13835 // operand.
13836 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13837}
13838
13839// Scenarios to ignore if expression E is:
13840// 1. an explicit cast expression into void
13841// 2. a function call expression that returns void
13842static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13843 E = E->IgnoreParens();
13844
13845 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13846 if (CE->getCastKind() == CK_ToVoid) {
13847 return true;
13848 }
13849
13850 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13851 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13852 CE->getSubExpr()->getType()->isDependentType()) {
13853 return true;
13854 }
13855 }
13856
13857 if (const auto *CE = dyn_cast<CallExpr>(E))
13858 return CE->getCallReturnType(Context)->isVoidType();
13859 return false;
13860}
13861
13862// Look for instances where it is likely the comma operator is confused with
13863// another operator. There is an explicit list of acceptable expressions for
13864// the left hand side of the comma operator, otherwise emit a warning.
13866 // No warnings in macros
13867 if (Loc.isMacroID())
13868 return;
13869
13870 // Don't warn in template instantiations.
13872 return;
13873
13874 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13875 // instead, skip more than needed, then call back into here with the
13876 // CommaVisitor in SemaStmt.cpp.
13877 // The listed locations are the initialization and increment portions
13878 // of a for loop. The additional checks are on the condition of
13879 // if statements, do/while loops, and for loops.
13880 // Differences in scope flags for C89 mode requires the extra logic.
13881 const unsigned ForIncrementFlags =
13882 getLangOpts().C99 || getLangOpts().CPlusPlus
13885 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13886 const unsigned ScopeFlags = getCurScope()->getFlags();
13887 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13888 (ScopeFlags & ForInitFlags) == ForInitFlags)
13889 return;
13890
13891 // If there are multiple comma operators used together, get the RHS of the
13892 // of the comma operator as the LHS.
13893 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13894 if (BO->getOpcode() != BO_Comma)
13895 break;
13896 LHS = BO->getRHS();
13897 }
13898
13899 // Only allow some expressions on LHS to not warn.
13900 if (IgnoreCommaOperand(LHS, Context))
13901 return;
13902
13903 Diag(Loc, diag::warn_comma_operator);
13904 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13905 << LHS->getSourceRange()
13907 LangOpts.CPlusPlus ? "static_cast<void>("
13908 : "(void)(")
13910 ")");
13911}
13912
13913// C99 6.5.17
13916 LHS = S.CheckPlaceholderExpr(LHS.get());
13917 RHS = S.CheckPlaceholderExpr(RHS.get());
13918 if (LHS.isInvalid() || RHS.isInvalid())
13919 return QualType();
13920
13921 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13922 // operands, but not unary promotions.
13923 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13924
13925 // So we treat the LHS as a ignored value, and in C++ we allow the
13926 // containing site to determine what should be done with the RHS.
13927 LHS = S.IgnoredValueConversions(LHS.get());
13928 if (LHS.isInvalid())
13929 return QualType();
13930
13931 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13932
13933 if (!S.getLangOpts().CPlusPlus) {
13935 if (RHS.isInvalid())
13936 return QualType();
13937 if (!RHS.get()->getType()->isVoidType())
13938 S.RequireCompleteType(Loc, RHS.get()->getType(),
13939 diag::err_incomplete_type);
13940 }
13941
13942 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13943 S.DiagnoseCommaOperator(LHS.get(), Loc);
13944
13945 return RHS.get()->getType();
13946}
13947
13948/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13949/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13951 ExprValueKind &VK,
13952 ExprObjectKind &OK,
13953 SourceLocation OpLoc, bool IsInc,
13954 bool IsPrefix) {
13955 QualType ResType = Op->getType();
13956 // Atomic types can be used for increment / decrement where the non-atomic
13957 // versions can, so ignore the _Atomic() specifier for the purpose of
13958 // checking.
13959 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13960 ResType = ResAtomicType->getValueType();
13961
13962 assert(!ResType.isNull() && "no type for increment/decrement expression");
13963
13964 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13965 // Decrement of bool is not allowed.
13966 if (!IsInc) {
13967 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13968 return QualType();
13969 }
13970 // Increment of bool sets it to true, but is deprecated.
13971 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13972 : diag::warn_increment_bool)
13973 << Op->getSourceRange();
13974 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13975 // Error on enum increments and decrements in C++ mode
13976 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13977 return QualType();
13978 } else if (ResType->isRealType()) {
13979 // OK!
13980 } else if (ResType->isPointerType()) {
13981 // C99 6.5.2.4p2, 6.5.6p2
13982 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13983 return QualType();
13984 } else if (ResType->isObjCObjectPointerType()) {
13985 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13986 // Otherwise, we just need a complete type.
13987 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13988 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13989 return QualType();
13990 } else if (ResType->isAnyComplexType()) {
13991 // C99 does not support ++/-- on complex types, we allow as an extension.
13992 S.Diag(OpLoc, diag::ext_increment_complex)
13993 << IsInc << Op->getSourceRange();
13994 } else if (ResType->isPlaceholderType()) {
13996 if (PR.isInvalid()) return QualType();
13997 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13998 IsInc, IsPrefix);
13999 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14000 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14001 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14002 (ResType->castAs<VectorType>()->getVectorKind() !=
14004 // The z vector extensions allow ++ and -- for non-bool vectors.
14005 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14006 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14007 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14008 } else {
14009 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14010 << ResType << int(IsInc) << Op->getSourceRange();
14011 return QualType();
14012 }
14013 // At this point, we know we have a real, complex or pointer type.
14014 // Now make sure the operand is a modifiable lvalue.
14015 if (CheckForModifiableLvalue(Op, OpLoc, S))
14016 return QualType();
14017 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14018 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14019 // An operand with volatile-qualified type is deprecated
14020 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14021 << IsInc << ResType;
14022 }
14023 // In C++, a prefix increment is the same type as the operand. Otherwise
14024 // (in C or with postfix), the increment is the unqualified type of the
14025 // operand.
14026 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14027 VK = VK_LValue;
14028 OK = Op->getObjectKind();
14029 return ResType;
14030 } else {
14031 VK = VK_PRValue;
14032 return ResType.getUnqualifiedType();
14033 }
14034}
14035
14036/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14037/// This routine allows us to typecheck complex/recursive expressions
14038/// where the declaration is needed for type checking. We only need to
14039/// handle cases when the expression references a function designator
14040/// or is an lvalue. Here are some examples:
14041/// - &(x) => x
14042/// - &*****f => f for f a function designator.
14043/// - &s.xx => s
14044/// - &s.zz[1].yy -> s, if zz is an array
14045/// - *(x + 1) -> x, if x is an array
14046/// - &"123"[2] -> 0
14047/// - & __real__ x -> x
14048///
14049/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14050/// members.
14052 switch (E->getStmtClass()) {
14053 case Stmt::DeclRefExprClass:
14054 return cast<DeclRefExpr>(E)->getDecl();
14055 case Stmt::MemberExprClass:
14056 // If this is an arrow operator, the address is an offset from
14057 // the base's value, so the object the base refers to is
14058 // irrelevant.
14059 if (cast<MemberExpr>(E)->isArrow())
14060 return nullptr;
14061 // Otherwise, the expression refers to a part of the base
14062 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14063 case Stmt::ArraySubscriptExprClass: {
14064 // FIXME: This code shouldn't be necessary! We should catch the implicit
14065 // promotion of register arrays earlier.
14066 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14067 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14068 if (ICE->getSubExpr()->getType()->isArrayType())
14069 return getPrimaryDecl(ICE->getSubExpr());
14070 }
14071 return nullptr;
14072 }
14073 case Stmt::UnaryOperatorClass: {
14074 UnaryOperator *UO = cast<UnaryOperator>(E);
14075
14076 switch(UO->getOpcode()) {
14077 case UO_Real:
14078 case UO_Imag:
14079 case UO_Extension:
14080 return getPrimaryDecl(UO->getSubExpr());
14081 default:
14082 return nullptr;
14083 }
14084 }
14085 case Stmt::ParenExprClass:
14086 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14087 case Stmt::ImplicitCastExprClass:
14088 // If the result of an implicit cast is an l-value, we care about
14089 // the sub-expression; otherwise, the result here doesn't matter.
14090 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14091 case Stmt::CXXUuidofExprClass:
14092 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14093 default:
14094 return nullptr;
14095 }
14096}
14097
14098namespace {
14099enum {
14100 AO_Bit_Field = 0,
14101 AO_Vector_Element = 1,
14102 AO_Property_Expansion = 2,
14103 AO_Register_Variable = 3,
14104 AO_Matrix_Element = 4,
14105 AO_No_Error = 5
14106};
14107}
14108/// Diagnose invalid operand for address of operations.
14109///
14110/// \param Type The type of operand which cannot have its address taken.
14112 Expr *E, unsigned Type) {
14113 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14114}
14115
14117 const Expr *Op,
14118 const CXXMethodDecl *MD) {
14119 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14120
14121 if (Op != DRE)
14122 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14123 << Op->getSourceRange();
14124
14125 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14126 if (isa<CXXDestructorDecl>(MD))
14127 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14128 << DRE->getSourceRange();
14129
14130 if (DRE->getQualifier())
14131 return false;
14132
14133 if (MD->getParent()->getName().empty())
14134 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14135 << DRE->getSourceRange();
14136
14137 SmallString<32> Str;
14138 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14139 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14140 << DRE->getSourceRange()
14141 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14142}
14143
14144/// CheckAddressOfOperand - The operand of & must be either a function
14145/// designator or an lvalue designating an object. If it is an lvalue, the
14146/// object cannot be declared with storage class register or be a bit field.
14147/// Note: The usual conversions are *not* applied to the operand of the &
14148/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14149/// In C++, the operand might be an overloaded function name, in which case
14150/// we allow the '&' but retain the overloaded-function type.
14152 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14153 if (PTy->getKind() == BuiltinType::Overload) {
14154 Expr *E = OrigOp.get()->IgnoreParens();
14155 if (!isa<OverloadExpr>(E)) {
14156 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14157 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14158 << OrigOp.get()->getSourceRange();
14159 return QualType();
14160 }
14161
14162 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14163 if (isa<UnresolvedMemberExpr>(Ovl))
14165 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14166 << OrigOp.get()->getSourceRange();
14167 return QualType();
14168 }
14169
14170 return Context.OverloadTy;
14171 }
14172
14173 if (PTy->getKind() == BuiltinType::UnknownAny)
14174 return Context.UnknownAnyTy;
14175
14176 if (PTy->getKind() == BuiltinType::BoundMember) {
14177 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14178 << OrigOp.get()->getSourceRange();
14179 return QualType();
14180 }
14181
14182 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14183 if (OrigOp.isInvalid()) return QualType();
14184 }
14185
14186 if (OrigOp.get()->isTypeDependent())
14187 return Context.DependentTy;
14188
14189 assert(!OrigOp.get()->hasPlaceholderType());
14190
14191 // Make sure to ignore parentheses in subsequent checks
14192 Expr *op = OrigOp.get()->IgnoreParens();
14193
14194 // In OpenCL captures for blocks called as lambda functions
14195 // are located in the private address space. Blocks used in
14196 // enqueue_kernel can be located in a different address space
14197 // depending on a vendor implementation. Thus preventing
14198 // taking an address of the capture to avoid invalid AS casts.
14199 if (LangOpts.OpenCL) {
14200 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14201 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14202 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14203 return QualType();
14204 }
14205 }
14206
14207 if (getLangOpts().C99) {
14208 // Implement C99-only parts of addressof rules.
14209 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14210 if (uOp->getOpcode() == UO_Deref)
14211 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14212 // (assuming the deref expression is valid).
14213 return uOp->getSubExpr()->getType();
14214 }
14215 // Technically, there should be a check for array subscript
14216 // expressions here, but the result of one is always an lvalue anyway.
14217 }
14218 ValueDecl *dcl = getPrimaryDecl(op);
14219
14220 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14221 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14222 op->getBeginLoc()))
14223 return QualType();
14224
14226 unsigned AddressOfError = AO_No_Error;
14227
14228 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14229 bool sfinae = (bool)isSFINAEContext();
14230 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14231 : diag::ext_typecheck_addrof_temporary)
14232 << op->getType() << op->getSourceRange();
14233 if (sfinae)
14234 return QualType();
14235 // Materialize the temporary as an lvalue so that we can take its address.
14236 OrigOp = op =
14237 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14238 } else if (isa<ObjCSelectorExpr>(op)) {
14239 return Context.getPointerType(op->getType());
14240 } else if (lval == Expr::LV_MemberFunction) {
14241 // If it's an instance method, make a member pointer.
14242 // The expression must have exactly the form &A::foo.
14243
14244 // If the underlying expression isn't a decl ref, give up.
14245 if (!isa<DeclRefExpr>(op)) {
14246 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14247 << OrigOp.get()->getSourceRange();
14248 return QualType();
14249 }
14250 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14251 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14252
14253 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14254
14257 // Under the MS ABI, lock down the inheritance model now.
14259 (void)isCompleteType(OpLoc, MPTy);
14260 return MPTy;
14261 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14262 // C99 6.5.3.2p1
14263 // The operand must be either an l-value or a function designator
14264 if (!op->getType()->isFunctionType()) {
14265 // Use a special diagnostic for loads from property references.
14266 if (isa<PseudoObjectExpr>(op)) {
14267 AddressOfError = AO_Property_Expansion;
14268 } else {
14269 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14270 << op->getType() << op->getSourceRange();
14271 return QualType();
14272 }
14273 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14274 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14275 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14276 }
14277
14278 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14279 // The operand cannot be a bit-field
14280 AddressOfError = AO_Bit_Field;
14281 } else if (op->getObjectKind() == OK_VectorComponent) {
14282 // The operand cannot be an element of a vector
14283 AddressOfError = AO_Vector_Element;
14284 } else if (op->getObjectKind() == OK_MatrixComponent) {
14285 // The operand cannot be an element of a matrix.
14286 AddressOfError = AO_Matrix_Element;
14287 } else if (dcl) { // C99 6.5.3.2p1
14288 // We have an lvalue with a decl. Make sure the decl is not declared
14289 // with the register storage-class specifier.
14290 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14291 // in C++ it is not error to take address of a register
14292 // variable (c++03 7.1.1P3)
14293 if (vd->getStorageClass() == SC_Register &&
14295 AddressOfError = AO_Register_Variable;
14296 }
14297 } else if (isa<MSPropertyDecl>(dcl)) {
14298 AddressOfError = AO_Property_Expansion;
14299 } else if (isa<FunctionTemplateDecl>(dcl)) {
14300 return Context.OverloadTy;
14301 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14302 // Okay: we can take the address of a field.
14303 // Could be a pointer to member, though, if there is an explicit
14304 // scope qualifier for the class.
14305 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14306 DeclContext *Ctx = dcl->getDeclContext();
14307 if (Ctx && Ctx->isRecord()) {
14308 if (dcl->getType()->isReferenceType()) {
14309 Diag(OpLoc,
14310 diag::err_cannot_form_pointer_to_member_of_reference_type)
14311 << dcl->getDeclName() << dcl->getType();
14312 return QualType();
14313 }
14314
14315 // C++11 [expr.unary.op] p4:
14316 // A pointer to member is only formed when an explicit & is used and
14317 // its operand is a qualified-id not enclosed in parentheses.
14318 if (isa<ParenExpr>(OrigOp.get())) {
14319 SourceLocation LeftParenLoc = OrigOp.get()->getBeginLoc(),
14320 RightParenLoc = OrigOp.get()->getEndLoc();
14321
14322 Diag(LeftParenLoc,
14323 diag::err_form_ptr_to_member_from_parenthesized_expr)
14324 << SourceRange(OpLoc, RightParenLoc)
14325 << FixItHint::CreateRemoval(LeftParenLoc)
14326 << FixItHint::CreateRemoval(RightParenLoc);
14327
14328 // Continuing might lead to better error recovery.
14329 }
14330
14331 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14332 Ctx = Ctx->getParent();
14333
14335 op->getType(),
14336 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14337 // Under the MS ABI, lock down the inheritance model now.
14339 (void)isCompleteType(OpLoc, MPTy);
14340 return MPTy;
14341 }
14342 }
14345 llvm_unreachable("Unknown/unexpected decl type");
14346 }
14347
14348 if (AddressOfError != AO_No_Error) {
14349 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14350 return QualType();
14351 }
14352
14353 if (lval == Expr::LV_IncompleteVoidType) {
14354 // Taking the address of a void variable is technically illegal, but we
14355 // allow it in cases which are otherwise valid.
14356 // Example: "extern void x; void* y = &x;".
14357 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14358 }
14359
14360 // If the operand has type "type", the result has type "pointer to type".
14361 if (op->getType()->isObjCObjectType())
14363
14364 // Cannot take the address of WebAssembly references or tables.
14365 if (Context.getTargetInfo().getTriple().isWasm()) {
14366 QualType OpTy = op->getType();
14367 if (OpTy.isWebAssemblyReferenceType()) {
14368 Diag(OpLoc, diag::err_wasm_ca_reference)
14369 << 1 << OrigOp.get()->getSourceRange();
14370 return QualType();
14371 }
14372 if (OpTy->isWebAssemblyTableType()) {
14373 Diag(OpLoc, diag::err_wasm_table_pr)
14374 << 1 << OrigOp.get()->getSourceRange();
14375 return QualType();
14376 }
14377 }
14378
14379 CheckAddressOfPackedMember(op);
14380
14381 return Context.getPointerType(op->getType());
14382}
14383
14384static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14385 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14386 if (!DRE)
14387 return;
14388 const Decl *D = DRE->getDecl();
14389 if (!D)
14390 return;
14391 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14392 if (!Param)
14393 return;
14394 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14395 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14396 return;
14397 if (FunctionScopeInfo *FD = S.getCurFunction())
14398 FD->ModifiedNonNullParams.insert(Param);
14399}
14400
14401/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14403 SourceLocation OpLoc,
14404 bool IsAfterAmp = false) {
14405 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14406 if (ConvResult.isInvalid())
14407 return QualType();
14408 Op = ConvResult.get();
14409 QualType OpTy = Op->getType();
14411
14412 if (isa<CXXReinterpretCastExpr>(Op)) {
14413 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14414 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14415 Op->getSourceRange());
14416 }
14417
14418 if (const PointerType *PT = OpTy->getAs<PointerType>())
14419 {
14420 Result = PT->getPointeeType();
14421 }
14422 else if (const ObjCObjectPointerType *OPT =
14424 Result = OPT->getPointeeType();
14425 else {
14427 if (PR.isInvalid()) return QualType();
14428 if (PR.get() != Op)
14429 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14430 }
14431
14432 if (Result.isNull()) {
14433 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14434 << OpTy << Op->getSourceRange();
14435 return QualType();
14436 }
14437
14438 if (Result->isVoidType()) {
14439 // C++ [expr.unary.op]p1:
14440 // [...] the expression to which [the unary * operator] is applied shall
14441 // be a pointer to an object type, or a pointer to a function type
14442 LangOptions LO = S.getLangOpts();
14443 if (LO.CPlusPlus)
14444 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14445 << OpTy << Op->getSourceRange();
14446 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14447 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14448 << OpTy << Op->getSourceRange();
14449 }
14450
14451 // Dereferences are usually l-values...
14452 VK = VK_LValue;
14453
14454 // ...except that certain expressions are never l-values in C.
14455 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14456 VK = VK_PRValue;
14457
14458 return Result;
14459}
14460
14461BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14463 switch (Kind) {
14464 default: llvm_unreachable("Unknown binop!");
14465 case tok::periodstar: Opc = BO_PtrMemD; break;
14466 case tok::arrowstar: Opc = BO_PtrMemI; break;
14467 case tok::star: Opc = BO_Mul; break;
14468 case tok::slash: Opc = BO_Div; break;
14469 case tok::percent: Opc = BO_Rem; break;
14470 case tok::plus: Opc = BO_Add; break;
14471 case tok::minus: Opc = BO_Sub; break;
14472 case tok::lessless: Opc = BO_Shl; break;
14473 case tok::greatergreater: Opc = BO_Shr; break;
14474 case tok::lessequal: Opc = BO_LE; break;
14475 case tok::less: Opc = BO_LT; break;
14476 case tok::greaterequal: Opc = BO_GE; break;
14477 case tok::greater: Opc = BO_GT; break;
14478 case tok::exclaimequal: Opc = BO_NE; break;
14479 case tok::equalequal: Opc = BO_EQ; break;
14480 case tok::spaceship: Opc = BO_Cmp; break;
14481 case tok::amp: Opc = BO_And; break;
14482 case tok::caret: Opc = BO_Xor; break;
14483 case tok::pipe: Opc = BO_Or; break;
14484 case tok::ampamp: Opc = BO_LAnd; break;
14485 case tok::pipepipe: Opc = BO_LOr; break;
14486 case tok::equal: Opc = BO_Assign; break;
14487 case tok::starequal: Opc = BO_MulAssign; break;
14488 case tok::slashequal: Opc = BO_DivAssign; break;
14489 case tok::percentequal: Opc = BO_RemAssign; break;
14490 case tok::plusequal: Opc = BO_AddAssign; break;
14491 case tok::minusequal: Opc = BO_SubAssign; break;
14492 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14493 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14494 case tok::ampequal: Opc = BO_AndAssign; break;
14495 case tok::caretequal: Opc = BO_XorAssign; break;
14496 case tok::pipeequal: Opc = BO_OrAssign; break;
14497 case tok::comma: Opc = BO_Comma; break;
14498 }
14499 return Opc;
14500}
14501
14503 tok::TokenKind Kind) {
14505 switch (Kind) {
14506 default: llvm_unreachable("Unknown unary op!");
14507 case tok::plusplus: Opc = UO_PreInc; break;
14508 case tok::minusminus: Opc = UO_PreDec; break;
14509 case tok::amp: Opc = UO_AddrOf; break;
14510 case tok::star: Opc = UO_Deref; break;
14511 case tok::plus: Opc = UO_Plus; break;
14512 case tok::minus: Opc = UO_Minus; break;
14513 case tok::tilde: Opc = UO_Not; break;
14514 case tok::exclaim: Opc = UO_LNot; break;
14515 case tok::kw___real: Opc = UO_Real; break;
14516 case tok::kw___imag: Opc = UO_Imag; break;
14517 case tok::kw___extension__: Opc = UO_Extension; break;
14518 }
14519 return Opc;
14520}
14521
14522const FieldDecl *
14524 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14525 // common for setters.
14526 // struct A {
14527 // int X;
14528 // -void setX(int X) { X = X; }
14529 // +void setX(int X) { this->X = X; }
14530 // };
14531
14532 // Only consider parameters for self assignment fixes.
14533 if (!isa<ParmVarDecl>(SelfAssigned))
14534 return nullptr;
14535 const auto *Method =
14536 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14537 if (!Method)
14538 return nullptr;
14539
14540 const CXXRecordDecl *Parent = Method->getParent();
14541 // In theory this is fixable if the lambda explicitly captures this, but
14542 // that's added complexity that's rarely going to be used.
14543 if (Parent->isLambda())
14544 return nullptr;
14545
14546 // FIXME: Use an actual Lookup operation instead of just traversing fields
14547 // in order to get base class fields.
14548 auto Field =
14549 llvm::find_if(Parent->fields(),
14550 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14551 return F->getDeclName() == Name;
14552 });
14553 return (Field != Parent->field_end()) ? *Field : nullptr;
14554}
14555
14556/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14557/// This warning suppressed in the event of macro expansions.
14558static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14559 SourceLocation OpLoc, bool IsBuiltin) {
14561 return;
14562 if (S.isUnevaluatedContext())
14563 return;
14564 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14565 return;
14566 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14567 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14568 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14569 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14570 if (!LHSDeclRef || !RHSDeclRef ||
14571 LHSDeclRef->getLocation().isMacroID() ||
14572 RHSDeclRef->getLocation().isMacroID())
14573 return;
14574 const ValueDecl *LHSDecl =
14575 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14576 const ValueDecl *RHSDecl =
14577 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14578 if (LHSDecl != RHSDecl)
14579 return;
14580 if (LHSDecl->getType().isVolatileQualified())
14581 return;
14582 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14583 if (RefTy->getPointeeType().isVolatileQualified())
14584 return;
14585
14586 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14587 : diag::warn_self_assignment_overloaded)
14588 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14589 << RHSExpr->getSourceRange();
14590 if (const FieldDecl *SelfAssignField =
14592 Diag << 1 << SelfAssignField
14593 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14594 else
14595 Diag << 0;
14596}
14597
14598/// Check if a bitwise-& is performed on an Objective-C pointer. This
14599/// is usually indicative of introspection within the Objective-C pointer.
14601 SourceLocation OpLoc) {
14602 if (!S.getLangOpts().ObjC)
14603 return;
14604
14605 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14606 const Expr *LHS = L.get();
14607 const Expr *RHS = R.get();
14608
14610 ObjCPointerExpr = LHS;
14611 OtherExpr = RHS;
14612 }
14613 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14614 ObjCPointerExpr = RHS;
14615 OtherExpr = LHS;
14616 }
14617
14618 // This warning is deliberately made very specific to reduce false
14619 // positives with logic that uses '&' for hashing. This logic mainly
14620 // looks for code trying to introspect into tagged pointers, which
14621 // code should generally never do.
14622 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14623 unsigned Diag = diag::warn_objc_pointer_masking;
14624 // Determine if we are introspecting the result of performSelectorXXX.
14625 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14626 // Special case messages to -performSelector and friends, which
14627 // can return non-pointer values boxed in a pointer value.
14628 // Some clients may wish to silence warnings in this subcase.
14629 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14630 Selector S = ME->getSelector();
14631 StringRef SelArg0 = S.getNameForSlot(0);
14632 if (SelArg0.starts_with("performSelector"))
14633 Diag = diag::warn_objc_pointer_masking_performSelector;
14634 }
14635
14636 S.Diag(OpLoc, Diag)
14637 << ObjCPointerExpr->getSourceRange();
14638 }
14639}
14640
14642 if (!E)
14643 return nullptr;
14644 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14645 return DRE->getDecl();
14646 if (auto *ME = dyn_cast<MemberExpr>(E))
14647 return ME->getMemberDecl();
14648 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14649 return IRE->getDecl();
14650 return nullptr;
14651}
14652
14653// This helper function promotes a binary operator's operands (which are of a
14654// half vector type) to a vector of floats and then truncates the result to
14655// a vector of either half or short.
14657 BinaryOperatorKind Opc, QualType ResultTy,
14659 bool IsCompAssign, SourceLocation OpLoc,
14660 FPOptionsOverride FPFeatures) {
14661 auto &Context = S.getASTContext();
14662 assert((isVector(ResultTy, Context.HalfTy) ||
14663 isVector(ResultTy, Context.ShortTy)) &&
14664 "Result must be a vector of half or short");
14665 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14666 isVector(RHS.get()->getType(), Context.HalfTy) &&
14667 "both operands expected to be a half vector");
14668
14669 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14670 QualType BinOpResTy = RHS.get()->getType();
14671
14672 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14673 // change BinOpResTy to a vector of ints.
14674 if (isVector(ResultTy, Context.ShortTy))
14675 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14676
14677 if (IsCompAssign)
14678 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14679 ResultTy, VK, OK, OpLoc, FPFeatures,
14680 BinOpResTy, BinOpResTy);
14681
14682 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14683 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14684 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14685 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14686}
14687
14688static std::pair<ExprResult, ExprResult>
14690 Expr *RHSExpr) {
14691 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14692 if (!S.Context.isDependenceAllowed()) {
14693 // C cannot handle TypoExpr nodes on either side of a binop because it
14694 // doesn't handle dependent types properly, so make sure any TypoExprs have
14695 // been dealt with before checking the operands.
14696 LHS = S.CorrectDelayedTyposInExpr(LHS);
14698 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14699 [Opc, LHS](Expr *E) {
14700 if (Opc != BO_Assign)
14701 return ExprResult(E);
14702 // Avoid correcting the RHS to the same Expr as the LHS.
14703 Decl *D = getDeclFromExpr(E);
14704 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14705 });
14706 }
14707 return std::make_pair(LHS, RHS);
14708}
14709
14710/// Returns true if conversion between vectors of halfs and vectors of floats
14711/// is needed.
14712static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14713 Expr *E0, Expr *E1 = nullptr) {
14714 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14716 return false;
14717
14718 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14719 QualType Ty = E->IgnoreImplicit()->getType();
14720
14721 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14722 // to vectors of floats. Although the element type of the vectors is __fp16,
14723 // the vectors shouldn't be treated as storage-only types. See the
14724 // discussion here: https://reviews.llvm.org/rG825235c140e7
14725 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14726 if (VT->getVectorKind() == VectorKind::Neon)
14727 return false;
14728 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14729 }
14730 return false;
14731 };
14732
14733 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14734}
14735
14736/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14737/// operator @p Opc at location @c TokLoc. This routine only supports
14738/// built-in operations; ActOnBinOp handles overloaded operators.
14741 Expr *LHSExpr, Expr *RHSExpr) {
14742 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14743 // The syntax only allows initializer lists on the RHS of assignment,
14744 // so we don't need to worry about accepting invalid code for
14745 // non-assignment operators.
14746 // C++11 5.17p9:
14747 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14748 // of x = {} is x = T().
14750 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14751 InitializedEntity Entity =
14753 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14754 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14755 if (Init.isInvalid())
14756 return Init;
14757 RHSExpr = Init.get();
14758 }
14759
14760 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14761 QualType ResultTy; // Result type of the binary operator.
14762 // The following two variables are used for compound assignment operators
14763 QualType CompLHSTy; // Type of LHS after promotions for computation
14764 QualType CompResultTy; // Type of computation result
14767 bool ConvertHalfVec = false;
14768
14769 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14770 if (!LHS.isUsable() || !RHS.isUsable())
14771 return ExprError();
14772
14773 if (getLangOpts().OpenCL) {
14774 QualType LHSTy = LHSExpr->getType();
14775 QualType RHSTy = RHSExpr->getType();
14776 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14777 // the ATOMIC_VAR_INIT macro.
14778 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14779 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14780 if (BO_Assign == Opc)
14781 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14782 else
14783 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14784 return ExprError();
14785 }
14786
14787 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14788 // only with a builtin functions and therefore should be disallowed here.
14789 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14790 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14791 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14792 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14793 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14794 return ExprError();
14795 }
14796 }
14797
14798 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14799 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14800
14801 switch (Opc) {
14802 case BO_Assign:
14803 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14804 if (getLangOpts().CPlusPlus &&
14805 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14806 VK = LHS.get()->getValueKind();
14807 OK = LHS.get()->getObjectKind();
14808 }
14809 if (!ResultTy.isNull()) {
14810 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14811 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14812
14813 // Avoid copying a block to the heap if the block is assigned to a local
14814 // auto variable that is declared in the same scope as the block. This
14815 // optimization is unsafe if the local variable is declared in an outer
14816 // scope. For example:
14817 //
14818 // BlockTy b;
14819 // {
14820 // b = ^{...};
14821 // }
14822 // // It is unsafe to invoke the block here if it wasn't copied to the
14823 // // heap.
14824 // b();
14825
14826 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14827 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14828 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14829 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14830 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14831
14833 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14835 }
14836 RecordModifiableNonNullParam(*this, LHS.get());
14837 break;
14838 case BO_PtrMemD:
14839 case BO_PtrMemI:
14840 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14841 Opc == BO_PtrMemI);
14842 break;
14843 case BO_Mul:
14844 case BO_Div:
14845 ConvertHalfVec = true;
14846 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14847 Opc == BO_Div);
14848 break;
14849 case BO_Rem:
14850 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14851 break;
14852 case BO_Add:
14853 ConvertHalfVec = true;
14854 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14855 break;
14856 case BO_Sub:
14857 ConvertHalfVec = true;
14858 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14859 break;
14860 case BO_Shl:
14861 case BO_Shr:
14862 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14863 break;
14864 case BO_LE:
14865 case BO_LT:
14866 case BO_GE:
14867 case BO_GT:
14868 ConvertHalfVec = true;
14869 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14870
14871 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14872 BI && BI->isComparisonOp())
14873 Diag(OpLoc, diag::warn_consecutive_comparison);
14874
14875 break;
14876 case BO_EQ:
14877 case BO_NE:
14878 ConvertHalfVec = true;
14879 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14880 break;
14881 case BO_Cmp:
14882 ConvertHalfVec = true;
14883 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14884 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14885 break;
14886 case BO_And:
14887 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14888 [[fallthrough]];
14889 case BO_Xor:
14890 case BO_Or:
14891 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14892 break;
14893 case BO_LAnd:
14894 case BO_LOr:
14895 ConvertHalfVec = true;
14896 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14897 break;
14898 case BO_MulAssign:
14899 case BO_DivAssign:
14900 ConvertHalfVec = true;
14901 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14902 Opc == BO_DivAssign);
14903 CompLHSTy = CompResultTy;
14904 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14905 ResultTy =
14906 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14907 break;
14908 case BO_RemAssign:
14909 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14910 CompLHSTy = CompResultTy;
14911 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14912 ResultTy =
14913 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14914 break;
14915 case BO_AddAssign:
14916 ConvertHalfVec = true;
14917 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14918 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14919 ResultTy =
14920 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14921 break;
14922 case BO_SubAssign:
14923 ConvertHalfVec = true;
14924 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14925 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14926 ResultTy =
14927 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14928 break;
14929 case BO_ShlAssign:
14930 case BO_ShrAssign:
14931 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14932 CompLHSTy = CompResultTy;
14933 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14934 ResultTy =
14935 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14936 break;
14937 case BO_AndAssign:
14938 case BO_OrAssign: // fallthrough
14939 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14940 [[fallthrough]];
14941 case BO_XorAssign:
14942 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14943 CompLHSTy = CompResultTy;
14944 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14945 ResultTy =
14946 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14947 break;
14948 case BO_Comma:
14949 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14950 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14951 VK = RHS.get()->getValueKind();
14952 OK = RHS.get()->getObjectKind();
14953 }
14954 break;
14955 }
14956 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14957 return ExprError();
14958
14959 // Some of the binary operations require promoting operands of half vector to
14960 // float vectors and truncating the result back to half vector. For now, we do
14961 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14962 // arm64).
14963 assert(
14964 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14965 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14966 "both sides are half vectors or neither sides are");
14967 ConvertHalfVec =
14968 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14969
14970 // Check for array bounds violations for both sides of the BinaryOperator
14971 CheckArrayAccess(LHS.get());
14972 CheckArrayAccess(RHS.get());
14973
14974 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14975 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14976 &Context.Idents.get("object_setClass"),
14978 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14979 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14980 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14982 "object_setClass(")
14983 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14984 ",")
14985 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14986 }
14987 else
14988 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14989 }
14990 else if (const ObjCIvarRefExpr *OIRE =
14991 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14992 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14993
14994 // Opc is not a compound assignment if CompResultTy is null.
14995 if (CompResultTy.isNull()) {
14996 if (ConvertHalfVec)
14997 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14998 OpLoc, CurFPFeatureOverrides());
14999 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15000 VK, OK, OpLoc, CurFPFeatureOverrides());
15001 }
15002
15003 // Handle compound assignments.
15004 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15006 VK = VK_LValue;
15007 OK = LHS.get()->getObjectKind();
15008 }
15009
15010 // The LHS is not converted to the result type for fixed-point compound
15011 // assignment as the common type is computed on demand. Reset the CompLHSTy
15012 // to the LHS type we would have gotten after unary conversions.
15013 if (CompResultTy->isFixedPointType())
15014 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15015
15016 if (ConvertHalfVec)
15017 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15018 OpLoc, CurFPFeatureOverrides());
15019
15021 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15022 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15023}
15024
15025/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15026/// operators are mixed in a way that suggests that the programmer forgot that
15027/// comparison operators have higher precedence. The most typical example of
15028/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15030 SourceLocation OpLoc, Expr *LHSExpr,
15031 Expr *RHSExpr) {
15032 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15033 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15034
15035 // Check that one of the sides is a comparison operator and the other isn't.
15036 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15037 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15038 if (isLeftComp == isRightComp)
15039 return;
15040
15041 // Bitwise operations are sometimes used as eager logical ops.
15042 // Don't diagnose this.
15043 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15044 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15045 if (isLeftBitwise || isRightBitwise)
15046 return;
15047
15048 SourceRange DiagRange = isLeftComp
15049 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15050 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15051 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15052 SourceRange ParensRange =
15053 isLeftComp
15054 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15055 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15056
15057 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15058 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15059 SuggestParentheses(Self, OpLoc,
15060 Self.PDiag(diag::note_precedence_silence) << OpStr,
15061 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15062 SuggestParentheses(Self, OpLoc,
15063 Self.PDiag(diag::note_precedence_bitwise_first)
15065 ParensRange);
15066}
15067
15068/// It accepts a '&&' expr that is inside a '||' one.
15069/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15070/// in parentheses.
15071static void
15073 BinaryOperator *Bop) {
15074 assert(Bop->getOpcode() == BO_LAnd);
15075 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15076 << Bop->getSourceRange() << OpLoc;
15078 Self.PDiag(diag::note_precedence_silence)
15079 << Bop->getOpcodeStr(),
15080 Bop->getSourceRange());
15081}
15082
15083/// Look for '&&' in the left hand of a '||' expr.
15085 Expr *LHSExpr, Expr *RHSExpr) {
15086 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15087 if (Bop->getOpcode() == BO_LAnd) {
15088 // If it's "string_literal && a || b" don't warn since the precedence
15089 // doesn't matter.
15090 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15091 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15092 } else if (Bop->getOpcode() == BO_LOr) {
15093 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15094 // If it's "a || b && string_literal || c" we didn't warn earlier for
15095 // "a || b && string_literal", but warn now.
15096 if (RBop->getOpcode() == BO_LAnd &&
15097 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15098 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15099 }
15100 }
15101 }
15102}
15103
15104/// Look for '&&' in the right hand of a '||' expr.
15106 Expr *LHSExpr, Expr *RHSExpr) {
15107 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15108 if (Bop->getOpcode() == BO_LAnd) {
15109 // If it's "a || b && string_literal" don't warn since the precedence
15110 // doesn't matter.
15111 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15112 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15113 }
15114 }
15115}
15116
15117/// Look for bitwise op in the left or right hand of a bitwise op with
15118/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15119/// the '&' expression in parentheses.
15121 SourceLocation OpLoc, Expr *SubExpr) {
15122 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15123 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15124 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15125 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15126 << Bop->getSourceRange() << OpLoc;
15127 SuggestParentheses(S, Bop->getOperatorLoc(),
15128 S.PDiag(diag::note_precedence_silence)
15129 << Bop->getOpcodeStr(),
15130 Bop->getSourceRange());
15131 }
15132 }
15133}
15134
15136 Expr *SubExpr, StringRef Shift) {
15137 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15138 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15139 StringRef Op = Bop->getOpcodeStr();
15140 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15141 << Bop->getSourceRange() << OpLoc << Shift << Op;
15142 SuggestParentheses(S, Bop->getOperatorLoc(),
15143 S.PDiag(diag::note_precedence_silence) << Op,
15144 Bop->getSourceRange());
15145 }
15146 }
15147}
15148
15150 Expr *LHSExpr, Expr *RHSExpr) {
15151 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15152 if (!OCE)
15153 return;
15154
15155 FunctionDecl *FD = OCE->getDirectCallee();
15156 if (!FD || !FD->isOverloadedOperator())
15157 return;
15158
15160 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15161 return;
15162
15163 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15164 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15165 << (Kind == OO_LessLess);
15167 S.PDiag(diag::note_precedence_silence)
15168 << (Kind == OO_LessLess ? "<<" : ">>"),
15169 OCE->getSourceRange());
15171 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15172 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15173}
15174
15175/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15176/// precedence.
15178 SourceLocation OpLoc, Expr *LHSExpr,
15179 Expr *RHSExpr){
15180 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15182 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15183
15184 // Diagnose "arg1 & arg2 | arg3"
15185 if ((Opc == BO_Or || Opc == BO_Xor) &&
15186 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15187 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15188 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15189 }
15190
15191 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15192 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15193 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15194 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15195 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15196 }
15197
15198 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15199 || Opc == BO_Shr) {
15200 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15201 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15202 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15203 }
15204
15205 // Warn on overloaded shift operators and comparisons, such as:
15206 // cout << 5 == 4;
15208 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15209}
15210
15211// Binary Operators. 'Tok' is the token for the operator.
15213 tok::TokenKind Kind,
15214 Expr *LHSExpr, Expr *RHSExpr) {
15215 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15216 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15217 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15218
15219 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15220 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15221
15222 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15223}
15224
15226 UnresolvedSetImpl &Functions) {
15228 if (OverOp != OO_None && OverOp != OO_Equal)
15229 LookupOverloadedOperatorName(OverOp, S, Functions);
15230
15231 // In C++20 onwards, we may have a second operator to look up.
15232 if (getLangOpts().CPlusPlus20) {
15234 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15235 }
15236}
15237
15238/// Build an overloaded binary operator expression in the given scope.
15241 Expr *LHS, Expr *RHS) {
15242 switch (Opc) {
15243 case BO_Assign:
15244 // In the non-overloaded case, we warn about self-assignment (x = x) for
15245 // both simple assignment and certain compound assignments where algebra
15246 // tells us the operation yields a constant result. When the operator is
15247 // overloaded, we can't do the latter because we don't want to assume that
15248 // those algebraic identities still apply; for example, a path-building
15249 // library might use operator/= to append paths. But it's still reasonable
15250 // to assume that simple assignment is just moving/copying values around
15251 // and so self-assignment is likely a bug.
15252 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15253 [[fallthrough]];
15254 case BO_DivAssign:
15255 case BO_RemAssign:
15256 case BO_SubAssign:
15257 case BO_AndAssign:
15258 case BO_OrAssign:
15259 case BO_XorAssign:
15260 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15261 break;
15262 default:
15263 break;
15264 }
15265
15266 // Find all of the overloaded operators visible from this point.
15267 UnresolvedSet<16> Functions;
15268 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15269
15270 // Build the (potentially-overloaded, potentially-dependent)
15271 // binary operation.
15272 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15273}
15274
15277 Expr *LHSExpr, Expr *RHSExpr) {
15278 ExprResult LHS, RHS;
15279 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15280 if (!LHS.isUsable() || !RHS.isUsable())
15281 return ExprError();
15282 LHSExpr = LHS.get();
15283 RHSExpr = RHS.get();
15284
15285 // We want to end up calling one of checkPseudoObjectAssignment
15286 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15287 // both expressions are overloadable or either is type-dependent),
15288 // or CreateBuiltinBinOp (in any other case). We also want to get
15289 // any placeholder types out of the way.
15290
15291 // Handle pseudo-objects in the LHS.
15292 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15293 // Assignments with a pseudo-object l-value need special analysis.
15294 if (pty->getKind() == BuiltinType::PseudoObject &&
15296 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15297
15298 // Don't resolve overloads if the other type is overloadable.
15299 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15300 // We can't actually test that if we still have a placeholder,
15301 // though. Fortunately, none of the exceptions we see in that
15302 // code below are valid when the LHS is an overload set. Note
15303 // that an overload set can be dependently-typed, but it never
15304 // instantiates to having an overloadable type.
15305 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15306 if (resolvedRHS.isInvalid()) return ExprError();
15307 RHSExpr = resolvedRHS.get();
15308
15309 if (RHSExpr->isTypeDependent() ||
15310 RHSExpr->getType()->isOverloadableType())
15311 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15312 }
15313
15314 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15315 // template, diagnose the missing 'template' keyword instead of diagnosing
15316 // an invalid use of a bound member function.
15317 //
15318 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15319 // to C++1z [over.over]/1.4, but we already checked for that case above.
15320 if (Opc == BO_LT && inTemplateInstantiation() &&
15321 (pty->getKind() == BuiltinType::BoundMember ||
15322 pty->getKind() == BuiltinType::Overload)) {
15323 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15324 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15325 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15326 return isa<FunctionTemplateDecl>(ND);
15327 })) {
15328 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15329 : OE->getNameLoc(),
15330 diag::err_template_kw_missing)
15331 << OE->getName().getAsString() << "";
15332 return ExprError();
15333 }
15334 }
15335
15336 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15337 if (LHS.isInvalid()) return ExprError();
15338 LHSExpr = LHS.get();
15339 }
15340
15341 // Handle pseudo-objects in the RHS.
15342 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15343 // An overload in the RHS can potentially be resolved by the type
15344 // being assigned to.
15345 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15346 if (getLangOpts().CPlusPlus &&
15347 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15348 LHSExpr->getType()->isOverloadableType()))
15349 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15350
15351 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15352 }
15353
15354 // Don't resolve overloads if the other type is overloadable.
15355 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15356 LHSExpr->getType()->isOverloadableType())
15357 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15358
15359 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15360 if (!resolvedRHS.isUsable()) return ExprError();
15361 RHSExpr = resolvedRHS.get();
15362 }
15363
15364 if (getLangOpts().CPlusPlus) {
15365 // Otherwise, build an overloaded op if either expression is type-dependent
15366 // or has an overloadable type.
15367 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15368 LHSExpr->getType()->isOverloadableType() ||
15369 RHSExpr->getType()->isOverloadableType())
15370 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15371 }
15372
15373 if (getLangOpts().RecoveryAST &&
15374 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15375 assert(!getLangOpts().CPlusPlus);
15376 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15377 "Should only occur in error-recovery path.");
15379 // C [6.15.16] p3:
15380 // An assignment expression has the value of the left operand after the
15381 // assignment, but is not an lvalue.
15383 Context, LHSExpr, RHSExpr, Opc,
15385 OpLoc, CurFPFeatureOverrides());
15386 QualType ResultType;
15387 switch (Opc) {
15388 case BO_Assign:
15389 ResultType = LHSExpr->getType().getUnqualifiedType();
15390 break;
15391 case BO_LT:
15392 case BO_GT:
15393 case BO_LE:
15394 case BO_GE:
15395 case BO_EQ:
15396 case BO_NE:
15397 case BO_LAnd:
15398 case BO_LOr:
15399 // These operators have a fixed result type regardless of operands.
15400 ResultType = Context.IntTy;
15401 break;
15402 case BO_Comma:
15403 ResultType = RHSExpr->getType();
15404 break;
15405 default:
15406 ResultType = Context.DependentTy;
15407 break;
15408 }
15409 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15410 VK_PRValue, OK_Ordinary, OpLoc,
15412 }
15413
15414 // Build a built-in binary operation.
15415 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15416}
15417
15419 if (T.isNull() || T->isDependentType())
15420 return false;
15421
15422 if (!Ctx.isPromotableIntegerType(T))
15423 return true;
15424
15425 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15426}
15427
15429 UnaryOperatorKind Opc, Expr *InputExpr,
15430 bool IsAfterAmp) {
15431 ExprResult Input = InputExpr;
15434 QualType resultType;
15435 bool CanOverflow = false;
15436
15437 bool ConvertHalfVec = false;
15438 if (getLangOpts().OpenCL) {
15439 QualType Ty = InputExpr->getType();
15440 // The only legal unary operation for atomics is '&'.
15441 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15442 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15443 // only with a builtin functions and therefore should be disallowed here.
15444 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15445 || Ty->isBlockPointerType())) {
15446 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15447 << InputExpr->getType()
15448 << Input.get()->getSourceRange());
15449 }
15450 }
15451
15452 if (getLangOpts().HLSL && OpLoc.isValid()) {
15453 if (Opc == UO_AddrOf)
15454 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15455 if (Opc == UO_Deref)
15456 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15457 }
15458
15459 if (InputExpr->isTypeDependent() &&
15460 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15461 resultType = Context.DependentTy;
15462 } else {
15463 switch (Opc) {
15464 case UO_PreInc:
15465 case UO_PreDec:
15466 case UO_PostInc:
15467 case UO_PostDec:
15468 resultType =
15469 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15470 Opc == UO_PreInc || Opc == UO_PostInc,
15471 Opc == UO_PreInc || Opc == UO_PreDec);
15472 CanOverflow = isOverflowingIntegerType(Context, resultType);
15473 break;
15474 case UO_AddrOf:
15475 resultType = CheckAddressOfOperand(Input, OpLoc);
15476 CheckAddressOfNoDeref(InputExpr);
15477 RecordModifiableNonNullParam(*this, InputExpr);
15478 break;
15479 case UO_Deref: {
15481 if (Input.isInvalid())
15482 return ExprError();
15483 resultType =
15484 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15485 break;
15486 }
15487 case UO_Plus:
15488 case UO_Minus:
15489 CanOverflow = Opc == UO_Minus &&
15491 Input = UsualUnaryConversions(Input.get());
15492 if (Input.isInvalid())
15493 return ExprError();
15494 // Unary plus and minus require promoting an operand of half vector to a
15495 // float vector and truncating the result back to a half vector. For now,
15496 // we do this only when HalfArgsAndReturns is set (that is, when the
15497 // target is arm or arm64).
15498 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15499
15500 // If the operand is a half vector, promote it to a float vector.
15501 if (ConvertHalfVec)
15502 Input = convertVector(Input.get(), Context.FloatTy, *this);
15503 resultType = Input.get()->getType();
15504 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15505 break;
15506 else if (resultType->isVectorType() &&
15507 // The z vector extensions don't allow + or - with bool vectors.
15508 (!Context.getLangOpts().ZVector ||
15509 resultType->castAs<VectorType>()->getVectorKind() !=
15511 break;
15512 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15513 break;
15514 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15515 Opc == UO_Plus && resultType->isPointerType())
15516 break;
15517
15518 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15519 << resultType << Input.get()->getSourceRange());
15520
15521 case UO_Not: // bitwise complement
15522 Input = UsualUnaryConversions(Input.get());
15523 if (Input.isInvalid())
15524 return ExprError();
15525 resultType = Input.get()->getType();
15526 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15527 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15528 // C99 does not support '~' for complex conjugation.
15529 Diag(OpLoc, diag::ext_integer_complement_complex)
15530 << resultType << Input.get()->getSourceRange();
15531 else if (resultType->hasIntegerRepresentation())
15532 break;
15533 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15534 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15535 // on vector float types.
15536 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15537 if (!T->isIntegerType())
15538 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15539 << resultType << Input.get()->getSourceRange());
15540 } else {
15541 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15542 << resultType << Input.get()->getSourceRange());
15543 }
15544 break;
15545
15546 case UO_LNot: // logical negation
15547 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15549 if (Input.isInvalid())
15550 return ExprError();
15551 resultType = Input.get()->getType();
15552
15553 // Though we still have to promote half FP to float...
15554 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15555 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15556 .get();
15557 resultType = Context.FloatTy;
15558 }
15559
15560 // WebAsembly tables can't be used in unary expressions.
15561 if (resultType->isPointerType() &&
15563 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15564 << resultType << Input.get()->getSourceRange());
15565 }
15566
15567 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15568 // C99 6.5.3.3p1: ok, fallthrough;
15569 if (Context.getLangOpts().CPlusPlus) {
15570 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15571 // operand contextually converted to bool.
15572 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15573 ScalarTypeToBooleanCastKind(resultType));
15574 } else if (Context.getLangOpts().OpenCL &&
15575 Context.getLangOpts().OpenCLVersion < 120) {
15576 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15577 // operate on scalar float types.
15578 if (!resultType->isIntegerType() && !resultType->isPointerType())
15579 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15580 << resultType << Input.get()->getSourceRange());
15581 }
15582 } else if (resultType->isExtVectorType()) {
15583 if (Context.getLangOpts().OpenCL &&
15585 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15586 // operate on vector float types.
15587 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15588 if (!T->isIntegerType())
15589 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15590 << resultType << Input.get()->getSourceRange());
15591 }
15592 // Vector logical not returns the signed variant of the operand type.
15593 resultType = GetSignedVectorType(resultType);
15594 break;
15595 } else if (Context.getLangOpts().CPlusPlus &&
15596 resultType->isVectorType()) {
15597 const VectorType *VTy = resultType->castAs<VectorType>();
15598 if (VTy->getVectorKind() != VectorKind::Generic)
15599 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15600 << resultType << Input.get()->getSourceRange());
15601
15602 // Vector logical not returns the signed variant of the operand type.
15603 resultType = GetSignedVectorType(resultType);
15604 break;
15605 } else {
15606 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15607 << resultType << Input.get()->getSourceRange());
15608 }
15609
15610 // LNot always has type int. C99 6.5.3.3p5.
15611 // In C++, it's bool. C++ 5.3.1p8
15612 resultType = Context.getLogicalOperationType();
15613 break;
15614 case UO_Real:
15615 case UO_Imag:
15616 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15617 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15618 // ordinary complex l-values to ordinary l-values and all other values to
15619 // r-values.
15620 if (Input.isInvalid())
15621 return ExprError();
15622 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15623 if (Input.get()->isGLValue() &&
15624 Input.get()->getObjectKind() == OK_Ordinary)
15625 VK = Input.get()->getValueKind();
15626 } else if (!getLangOpts().CPlusPlus) {
15627 // In C, a volatile scalar is read by __imag. In C++, it is not.
15628 Input = DefaultLvalueConversion(Input.get());
15629 }
15630 break;
15631 case UO_Extension:
15632 resultType = Input.get()->getType();
15633 VK = Input.get()->getValueKind();
15634 OK = Input.get()->getObjectKind();
15635 break;
15636 case UO_Coawait:
15637 // It's unnecessary to represent the pass-through operator co_await in the
15638 // AST; just return the input expression instead.
15639 assert(!Input.get()->getType()->isDependentType() &&
15640 "the co_await expression must be non-dependant before "
15641 "building operator co_await");
15642 return Input;
15643 }
15644 }
15645 if (resultType.isNull() || Input.isInvalid())
15646 return ExprError();
15647
15648 // Check for array bounds violations in the operand of the UnaryOperator,
15649 // except for the '*' and '&' operators that have to be handled specially
15650 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15651 // that are explicitly defined as valid by the standard).
15652 if (Opc != UO_AddrOf && Opc != UO_Deref)
15653 CheckArrayAccess(Input.get());
15654
15655 auto *UO =
15656 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15657 OpLoc, CanOverflow, CurFPFeatureOverrides());
15658
15659 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15660 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15662 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15663
15664 // Convert the result back to a half vector.
15665 if (ConvertHalfVec)
15666 return convertVector(UO, Context.HalfTy, *this);
15667 return UO;
15668}
15669
15670/// Determine whether the given expression is a qualified member
15671/// access expression, of a form that could be turned into a pointer to member
15672/// with the address-of operator.
15674 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15675 if (!DRE->getQualifier())
15676 return false;
15677
15678 ValueDecl *VD = DRE->getDecl();
15679 if (!VD->isCXXClassMember())
15680 return false;
15681
15682 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15683 return true;
15684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15685 return Method->isImplicitObjectMemberFunction();
15686
15687 return false;
15688 }
15689
15690 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15691 if (!ULE->getQualifier())
15692 return false;
15693
15694 for (NamedDecl *D : ULE->decls()) {
15695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15696 if (Method->isImplicitObjectMemberFunction())
15697 return true;
15698 } else {
15699 // Overload set does not contain methods.
15700 break;
15701 }
15702 }
15703
15704 return false;
15705 }
15706
15707 return false;
15708}
15709
15711 UnaryOperatorKind Opc, Expr *Input,
15712 bool IsAfterAmp) {
15713 // First things first: handle placeholders so that the
15714 // overloaded-operator check considers the right type.
15715 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15716 // Increment and decrement of pseudo-object references.
15717 if (pty->getKind() == BuiltinType::PseudoObject &&
15719 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15720
15721 // extension is always a builtin operator.
15722 if (Opc == UO_Extension)
15723 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15724
15725 // & gets special logic for several kinds of placeholder.
15726 // The builtin code knows what to do.
15727 if (Opc == UO_AddrOf &&
15728 (pty->getKind() == BuiltinType::Overload ||
15729 pty->getKind() == BuiltinType::UnknownAny ||
15730 pty->getKind() == BuiltinType::BoundMember))
15731 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15732
15733 // Anything else needs to be handled now.
15735 if (Result.isInvalid()) return ExprError();
15736 Input = Result.get();
15737 }
15738
15739 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15741 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15742 // Find all of the overloaded operators visible from this point.
15743 UnresolvedSet<16> Functions;
15745 if (S && OverOp != OO_None)
15746 LookupOverloadedOperatorName(OverOp, S, Functions);
15747
15748 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15749 }
15750
15751 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15752}
15753
15754// Unary Operators. 'Tok' is the token for the operator.
15756 Expr *Input, bool IsAfterAmp) {
15757 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15758 IsAfterAmp);
15759}
15760
15761/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15763 LabelDecl *TheDecl) {
15764 TheDecl->markUsed(Context);
15765 // Create the AST node. The address of a label always has type 'void*'.
15766 auto *Res = new (Context) AddrLabelExpr(
15767 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15768
15769 if (getCurFunction())
15770 getCurFunction()->AddrLabels.push_back(Res);
15771
15772 return Res;
15773}
15774
15777 // Make sure we diagnose jumping into a statement expression.
15779}
15780
15782 // Note that function is also called by TreeTransform when leaving a
15783 // StmtExpr scope without rebuilding anything.
15784
15787}
15788
15790 SourceLocation RPLoc) {
15791 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15792}
15793
15795 SourceLocation RPLoc, unsigned TemplateDepth) {
15796 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15797 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15798
15801 assert(!Cleanup.exprNeedsCleanups() &&
15802 "cleanups within StmtExpr not correctly bound!");
15804
15805 // FIXME: there are a variety of strange constraints to enforce here, for
15806 // example, it is not possible to goto into a stmt expression apparently.
15807 // More semantic analysis is needed.
15808
15809 // If there are sub-stmts in the compound stmt, take the type of the last one
15810 // as the type of the stmtexpr.
15811 QualType Ty = Context.VoidTy;
15812 bool StmtExprMayBindToTemp = false;
15813 if (!Compound->body_empty()) {
15814 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15815 if (const auto *LastStmt =
15816 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15817 if (const Expr *Value = LastStmt->getExprStmt()) {
15818 StmtExprMayBindToTemp = true;
15819 Ty = Value->getType();
15820 }
15821 }
15822 }
15823
15824 // FIXME: Check that expression type is complete/non-abstract; statement
15825 // expressions are not lvalues.
15826 Expr *ResStmtExpr =
15827 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15828 if (StmtExprMayBindToTemp)
15829 return MaybeBindToTemporary(ResStmtExpr);
15830 return ResStmtExpr;
15831}
15832
15834 if (ER.isInvalid())
15835 return ExprError();
15836
15837 // Do function/array conversion on the last expression, but not
15838 // lvalue-to-rvalue. However, initialize an unqualified type.
15840 if (ER.isInvalid())
15841 return ExprError();
15842 Expr *E = ER.get();
15843
15844 if (E->isTypeDependent())
15845 return E;
15846
15847 // In ARC, if the final expression ends in a consume, splice
15848 // the consume out and bind it later. In the alternate case
15849 // (when dealing with a retainable type), the result
15850 // initialization will create a produce. In both cases the
15851 // result will be +1, and we'll need to balance that out with
15852 // a bind.
15853 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15854 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15855 return Cast->getSubExpr();
15856
15857 // FIXME: Provide a better location for the initialization.
15861 SourceLocation(), E);
15862}
15863
15865 TypeSourceInfo *TInfo,
15866 ArrayRef<OffsetOfComponent> Components,
15867 SourceLocation RParenLoc) {
15868 QualType ArgTy = TInfo->getType();
15869 bool Dependent = ArgTy->isDependentType();
15870 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15871
15872 // We must have at least one component that refers to the type, and the first
15873 // one is known to be a field designator. Verify that the ArgTy represents
15874 // a struct/union/class.
15875 if (!Dependent && !ArgTy->isRecordType())
15876 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15877 << ArgTy << TypeRange);
15878
15879 // Type must be complete per C99 7.17p3 because a declaring a variable
15880 // with an incomplete type would be ill-formed.
15881 if (!Dependent
15882 && RequireCompleteType(BuiltinLoc, ArgTy,
15883 diag::err_offsetof_incomplete_type, TypeRange))
15884 return ExprError();
15885
15886 bool DidWarnAboutNonPOD = false;
15887 QualType CurrentType = ArgTy;
15890 for (const OffsetOfComponent &OC : Components) {
15891 if (OC.isBrackets) {
15892 // Offset of an array sub-field. TODO: Should we allow vector elements?
15893 if (!CurrentType->isDependentType()) {
15894 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15895 if(!AT)
15896 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15897 << CurrentType);
15898 CurrentType = AT->getElementType();
15899 } else
15900 CurrentType = Context.DependentTy;
15901
15902 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15903 if (IdxRval.isInvalid())
15904 return ExprError();
15905 Expr *Idx = IdxRval.get();
15906
15907 // The expression must be an integral expression.
15908 // FIXME: An integral constant expression?
15909 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15910 !Idx->getType()->isIntegerType())
15911 return ExprError(
15912 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15913 << Idx->getSourceRange());
15914
15915 // Record this array index.
15916 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15917 Exprs.push_back(Idx);
15918 continue;
15919 }
15920
15921 // Offset of a field.
15922 if (CurrentType->isDependentType()) {
15923 // We have the offset of a field, but we can't look into the dependent
15924 // type. Just record the identifier of the field.
15925 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15926 CurrentType = Context.DependentTy;
15927 continue;
15928 }
15929
15930 // We need to have a complete type to look into.
15931 if (RequireCompleteType(OC.LocStart, CurrentType,
15932 diag::err_offsetof_incomplete_type))
15933 return ExprError();
15934
15935 // Look for the designated field.
15936 const RecordType *RC = CurrentType->getAs<RecordType>();
15937 if (!RC)
15938 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15939 << CurrentType);
15940 RecordDecl *RD = RC->getDecl();
15941
15942 // C++ [lib.support.types]p5:
15943 // The macro offsetof accepts a restricted set of type arguments in this
15944 // International Standard. type shall be a POD structure or a POD union
15945 // (clause 9).
15946 // C++11 [support.types]p4:
15947 // If type is not a standard-layout class (Clause 9), the results are
15948 // undefined.
15949 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15950 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15951 unsigned DiagID =
15952 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15953 : diag::ext_offsetof_non_pod_type;
15954
15955 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15956 Diag(BuiltinLoc, DiagID)
15957 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15958 DidWarnAboutNonPOD = true;
15959 }
15960 }
15961
15962 // Look for the field.
15963 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15964 LookupQualifiedName(R, RD);
15965 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15966 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15967 if (!MemberDecl) {
15968 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15969 MemberDecl = IndirectMemberDecl->getAnonField();
15970 }
15971
15972 if (!MemberDecl) {
15973 // Lookup could be ambiguous when looking up a placeholder variable
15974 // __builtin_offsetof(S, _).
15975 // In that case we would already have emitted a diagnostic
15976 if (!R.isAmbiguous())
15977 Diag(BuiltinLoc, diag::err_no_member)
15978 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15979 return ExprError();
15980 }
15981
15982 // C99 7.17p3:
15983 // (If the specified member is a bit-field, the behavior is undefined.)
15984 //
15985 // We diagnose this as an error.
15986 if (MemberDecl->isBitField()) {
15987 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15988 << MemberDecl->getDeclName()
15989 << SourceRange(BuiltinLoc, RParenLoc);
15990 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15991 return ExprError();
15992 }
15993
15994 RecordDecl *Parent = MemberDecl->getParent();
15995 if (IndirectMemberDecl)
15996 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15997
15998 // If the member was found in a base class, introduce OffsetOfNodes for
15999 // the base class indirections.
16000 CXXBasePaths Paths;
16001 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16002 Paths)) {
16003 if (Paths.getDetectedVirtual()) {
16004 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16005 << MemberDecl->getDeclName()
16006 << SourceRange(BuiltinLoc, RParenLoc);
16007 return ExprError();
16008 }
16009
16010 CXXBasePath &Path = Paths.front();
16011 for (const CXXBasePathElement &B : Path)
16012 Comps.push_back(OffsetOfNode(B.Base));
16013 }
16014
16015 if (IndirectMemberDecl) {
16016 for (auto *FI : IndirectMemberDecl->chain()) {
16017 assert(isa<FieldDecl>(FI));
16018 Comps.push_back(OffsetOfNode(OC.LocStart,
16019 cast<FieldDecl>(FI), OC.LocEnd));
16020 }
16021 } else
16022 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16023
16024 CurrentType = MemberDecl->getType().getNonReferenceType();
16025 }
16026
16027 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16028 Comps, Exprs, RParenLoc);
16029}
16030
16032 SourceLocation BuiltinLoc,
16034 ParsedType ParsedArgTy,
16035 ArrayRef<OffsetOfComponent> Components,
16036 SourceLocation RParenLoc) {
16037
16038 TypeSourceInfo *ArgTInfo;
16039 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16040 if (ArgTy.isNull())
16041 return ExprError();
16042
16043 if (!ArgTInfo)
16044 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16045
16046 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16047}
16048
16049
16051 Expr *CondExpr,
16052 Expr *LHSExpr, Expr *RHSExpr,
16053 SourceLocation RPLoc) {
16054 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16055
16058 QualType resType;
16059 bool CondIsTrue = false;
16060 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16061 resType = Context.DependentTy;
16062 } else {
16063 // The conditional expression is required to be a constant expression.
16064 llvm::APSInt condEval(32);
16066 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16067 if (CondICE.isInvalid())
16068 return ExprError();
16069 CondExpr = CondICE.get();
16070 CondIsTrue = condEval.getZExtValue();
16071
16072 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16073 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16074
16075 resType = ActiveExpr->getType();
16076 VK = ActiveExpr->getValueKind();
16077 OK = ActiveExpr->getObjectKind();
16078 }
16079
16080 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16081 resType, VK, OK, RPLoc, CondIsTrue);
16082}
16083
16084//===----------------------------------------------------------------------===//
16085// Clang Extensions.
16086//===----------------------------------------------------------------------===//
16087
16088/// ActOnBlockStart - This callback is invoked when a block literal is started.
16089void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16091
16092 if (LangOpts.CPlusPlus) {
16094 Decl *ManglingContextDecl;
16095 std::tie(MCtx, ManglingContextDecl) =
16096 getCurrentMangleNumberContext(Block->getDeclContext());
16097 if (MCtx) {
16098 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16099 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16100 }
16101 }
16102
16103 PushBlockScope(CurScope, Block);
16105 if (CurScope)
16106 PushDeclContext(CurScope, Block);
16107 else
16108 CurContext = Block;
16109
16111
16112 // Enter a new evaluation context to insulate the block from any
16113 // cleanups from the enclosing full-expression.
16116}
16117
16119 Scope *CurScope) {
16120 assert(ParamInfo.getIdentifier() == nullptr &&
16121 "block-id should have no identifier!");
16122 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16123 BlockScopeInfo *CurBlock = getCurBlock();
16124
16125 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16126 QualType T = Sig->getType();
16127
16128 // FIXME: We should allow unexpanded parameter packs here, but that would,
16129 // in turn, make the block expression contain unexpanded parameter packs.
16130 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16131 // Drop the parameters.
16133 EPI.HasTrailingReturn = false;
16134 EPI.TypeQuals.addConst();
16135 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16137 }
16138
16139 // GetTypeForDeclarator always produces a function type for a block
16140 // literal signature. Furthermore, it is always a FunctionProtoType
16141 // unless the function was written with a typedef.
16142 assert(T->isFunctionType() &&
16143 "GetTypeForDeclarator made a non-function block signature");
16144
16145 // Look for an explicit signature in that function type.
16146 FunctionProtoTypeLoc ExplicitSignature;
16147
16148 if ((ExplicitSignature = Sig->getTypeLoc()
16150
16151 // Check whether that explicit signature was synthesized by
16152 // GetTypeForDeclarator. If so, don't save that as part of the
16153 // written signature.
16154 if (ExplicitSignature.getLocalRangeBegin() ==
16155 ExplicitSignature.getLocalRangeEnd()) {
16156 // This would be much cheaper if we stored TypeLocs instead of
16157 // TypeSourceInfos.
16158 TypeLoc Result = ExplicitSignature.getReturnLoc();
16159 unsigned Size = Result.getFullDataSize();
16160 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16161 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16162
16163 ExplicitSignature = FunctionProtoTypeLoc();
16164 }
16165 }
16166
16167 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16168 CurBlock->FunctionType = T;
16169
16170 const auto *Fn = T->castAs<FunctionType>();
16171 QualType RetTy = Fn->getReturnType();
16172 bool isVariadic =
16173 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16174
16175 CurBlock->TheDecl->setIsVariadic(isVariadic);
16176
16177 // Context.DependentTy is used as a placeholder for a missing block
16178 // return type. TODO: what should we do with declarators like:
16179 // ^ * { ... }
16180 // If the answer is "apply template argument deduction"....
16181 if (RetTy != Context.DependentTy) {
16182 CurBlock->ReturnType = RetTy;
16183 CurBlock->TheDecl->setBlockMissingReturnType(false);
16184 CurBlock->HasImplicitReturnType = false;
16185 }
16186
16187 // Push block parameters from the declarator if we had them.
16189 if (ExplicitSignature) {
16190 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16191 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16192 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16193 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16194 // Diagnose this as an extension in C17 and earlier.
16195 if (!getLangOpts().C23)
16196 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16197 }
16198 Params.push_back(Param);
16199 }
16200
16201 // Fake up parameter variables if we have a typedef, like
16202 // ^ fntype { ... }
16203 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16204 for (const auto &I : Fn->param_types()) {
16206 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16207 Params.push_back(Param);
16208 }
16209 }
16210
16211 // Set the parameters on the block decl.
16212 if (!Params.empty()) {
16213 CurBlock->TheDecl->setParams(Params);
16215 /*CheckParameterNames=*/false);
16216 }
16217
16218 // Finally we can process decl attributes.
16219 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16220
16221 // Put the parameter variables in scope.
16222 for (auto *AI : CurBlock->TheDecl->parameters()) {
16223 AI->setOwningFunction(CurBlock->TheDecl);
16224
16225 // If this has an identifier, add it to the scope stack.
16226 if (AI->getIdentifier()) {
16227 CheckShadow(CurBlock->TheScope, AI);
16228
16229 PushOnScopeChains(AI, CurBlock->TheScope);
16230 }
16231
16232 if (AI->isInvalidDecl())
16233 CurBlock->TheDecl->setInvalidDecl();
16234 }
16235}
16236
16237/// ActOnBlockError - If there is an error parsing a block, this callback
16238/// is invoked to pop the information about the block from the action impl.
16239void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16240 // Leave the expression-evaluation context.
16243
16244 // Pop off CurBlock, handle nested blocks.
16247}
16248
16249/// ActOnBlockStmtExpr - This is called when the body of a block statement
16250/// literal was successfully completed. ^(int x){...}
16252 Stmt *Body, Scope *CurScope) {
16253 // If blocks are disabled, emit an error.
16254 if (!LangOpts.Blocks)
16255 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16256
16257 // Leave the expression-evaluation context.
16260 assert(!Cleanup.exprNeedsCleanups() &&
16261 "cleanups within block not correctly bound!");
16263
16264 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16265 BlockDecl *BD = BSI->TheDecl;
16266
16267 if (BSI->HasImplicitReturnType)
16269
16270 QualType RetTy = Context.VoidTy;
16271 if (!BSI->ReturnType.isNull())
16272 RetTy = BSI->ReturnType;
16273
16274 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16275 QualType BlockTy;
16276
16277 // If the user wrote a function type in some form, try to use that.
16278 if (!BSI->FunctionType.isNull()) {
16279 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16280
16281 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16282 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16283
16284 // Turn protoless block types into nullary block types.
16285 if (isa<FunctionNoProtoType>(FTy)) {
16287 EPI.ExtInfo = Ext;
16288 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16289
16290 // Otherwise, if we don't need to change anything about the function type,
16291 // preserve its sugar structure.
16292 } else if (FTy->getReturnType() == RetTy &&
16293 (!NoReturn || FTy->getNoReturnAttr())) {
16294 BlockTy = BSI->FunctionType;
16295
16296 // Otherwise, make the minimal modifications to the function type.
16297 } else {
16298 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16300 EPI.TypeQuals = Qualifiers();
16301 EPI.ExtInfo = Ext;
16302 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16303 }
16304
16305 // If we don't have a function type, just build one from nothing.
16306 } else {
16308 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16309 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16310 }
16311
16313 BlockTy = Context.getBlockPointerType(BlockTy);
16314
16315 // If needed, diagnose invalid gotos and switches in the block.
16316 if (getCurFunction()->NeedsScopeChecking() &&
16318 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16319
16320 BD->setBody(cast<CompoundStmt>(Body));
16321
16322 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16324
16325 // Try to apply the named return value optimization. We have to check again
16326 // if we can do this, though, because blocks keep return statements around
16327 // to deduce an implicit return type.
16328 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16329 !BD->isDependentContext())
16330 computeNRVO(Body, BSI);
16331
16336
16338
16339 // Set the captured variables on the block.
16341 for (Capture &Cap : BSI->Captures) {
16342 if (Cap.isInvalid() || Cap.isThisCapture())
16343 continue;
16344 // Cap.getVariable() is always a VarDecl because
16345 // blocks cannot capture structured bindings or other ValueDecl kinds.
16346 auto *Var = cast<VarDecl>(Cap.getVariable());
16347 Expr *CopyExpr = nullptr;
16348 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16349 if (const RecordType *Record =
16350 Cap.getCaptureType()->getAs<RecordType>()) {
16351 // The capture logic needs the destructor, so make sure we mark it.
16352 // Usually this is unnecessary because most local variables have
16353 // their destructors marked at declaration time, but parameters are
16354 // an exception because it's technically only the call site that
16355 // actually requires the destructor.
16356 if (isa<ParmVarDecl>(Var))
16358
16359 // Enter a separate potentially-evaluated context while building block
16360 // initializers to isolate their cleanups from those of the block
16361 // itself.
16362 // FIXME: Is this appropriate even when the block itself occurs in an
16363 // unevaluated operand?
16366
16368
16370 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16371
16372 // According to the blocks spec, the capture of a variable from
16373 // the stack requires a const copy constructor. This is not true
16374 // of the copy/move done to move a __block variable to the heap.
16375 if (!Result.isInvalid() &&
16376 !Result.get()->getType().isConstQualified()) {
16378 Result.get()->getType().withConst(),
16379 CK_NoOp, VK_LValue);
16380 }
16381
16382 if (!Result.isInvalid()) {
16384 InitializedEntity::InitializeBlock(Var->getLocation(),
16385 Cap.getCaptureType()),
16386 Loc, Result.get());
16387 }
16388
16389 // Build a full-expression copy expression if initialization
16390 // succeeded and used a non-trivial constructor. Recover from
16391 // errors by pretending that the copy isn't necessary.
16392 if (!Result.isInvalid() &&
16393 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16394 ->isTrivial()) {
16396 CopyExpr = Result.get();
16397 }
16398 }
16399 }
16400
16401 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16402 CopyExpr);
16403 Captures.push_back(NewCap);
16404 }
16405 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16406
16407 // Pop the block scope now but keep it alive to the end of this function.
16409 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16410
16411 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16412
16413 // If the block isn't obviously global, i.e. it captures anything at
16414 // all, then we need to do a few things in the surrounding context:
16415 if (Result->getBlockDecl()->hasCaptures()) {
16416 // First, this expression has a new cleanup object.
16417 ExprCleanupObjects.push_back(Result->getBlockDecl());
16419
16420 // It also gets a branch-protected scope if any of the captured
16421 // variables needs destruction.
16422 for (const auto &CI : Result->getBlockDecl()->captures()) {
16423 const VarDecl *var = CI.getVariable();
16424 if (var->getType().isDestructedType() != QualType::DK_none) {
16426 break;
16427 }
16428 }
16429 }
16430
16431 if (getCurFunction())
16432 getCurFunction()->addBlock(BD);
16433
16434 if (BD->isInvalidDecl())
16435 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16436 {Result}, Result->getType());
16437 return Result;
16438}
16439
16441 SourceLocation RPLoc) {
16442 TypeSourceInfo *TInfo;
16443 GetTypeFromParser(Ty, &TInfo);
16444 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16445}
16446
16448 Expr *E, TypeSourceInfo *TInfo,
16449 SourceLocation RPLoc) {
16450 Expr *OrigExpr = E;
16451 bool IsMS = false;
16452
16453 // CUDA device code does not support varargs.
16454 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16455 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16459 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16460 }
16461 }
16462
16463 // NVPTX does not support va_arg expression.
16464 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16465 Context.getTargetInfo().getTriple().isNVPTX())
16466 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16467
16468 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16469 // as Microsoft ABI on an actual Microsoft platform, where
16470 // __builtin_ms_va_list and __builtin_va_list are the same.)
16473 QualType MSVaListType = Context.getBuiltinMSVaListType();
16474 if (Context.hasSameType(MSVaListType, E->getType())) {
16475 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16476 return ExprError();
16477 IsMS = true;
16478 }
16479 }
16480
16481 // Get the va_list type
16482 QualType VaListType = Context.getBuiltinVaListType();
16483 if (!IsMS) {
16484 if (VaListType->isArrayType()) {
16485 // Deal with implicit array decay; for example, on x86-64,
16486 // va_list is an array, but it's supposed to decay to
16487 // a pointer for va_arg.
16488 VaListType = Context.getArrayDecayedType(VaListType);
16489 // Make sure the input expression also decays appropriately.
16491 if (Result.isInvalid())
16492 return ExprError();
16493 E = Result.get();
16494 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16495 // If va_list is a record type and we are compiling in C++ mode,
16496 // check the argument using reference binding.
16498 Context, Context.getLValueReferenceType(VaListType), false);
16500 if (Init.isInvalid())
16501 return ExprError();
16502 E = Init.getAs<Expr>();
16503 } else {
16504 // Otherwise, the va_list argument must be an l-value because
16505 // it is modified by va_arg.
16506 if (!E->isTypeDependent() &&
16507 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16508 return ExprError();
16509 }
16510 }
16511
16512 if (!IsMS && !E->isTypeDependent() &&
16513 !Context.hasSameType(VaListType, E->getType()))
16514 return ExprError(
16515 Diag(E->getBeginLoc(),
16516 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16517 << OrigExpr->getType() << E->getSourceRange());
16518
16519 if (!TInfo->getType()->isDependentType()) {
16520 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16521 diag::err_second_parameter_to_va_arg_incomplete,
16522 TInfo->getTypeLoc()))
16523 return ExprError();
16524
16526 TInfo->getType(),
16527 diag::err_second_parameter_to_va_arg_abstract,
16528 TInfo->getTypeLoc()))
16529 return ExprError();
16530
16531 if (!TInfo->getType().isPODType(Context)) {
16532 Diag(TInfo->getTypeLoc().getBeginLoc(),
16533 TInfo->getType()->isObjCLifetimeType()
16534 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16535 : diag::warn_second_parameter_to_va_arg_not_pod)
16536 << TInfo->getType()
16537 << TInfo->getTypeLoc().getSourceRange();
16538 }
16539
16540 // Check for va_arg where arguments of the given type will be promoted
16541 // (i.e. this va_arg is guaranteed to have undefined behavior).
16542 QualType PromoteType;
16543 if (Context.isPromotableIntegerType(TInfo->getType())) {
16544 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16545 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16546 // and C23 7.16.1.1p2 says, in part:
16547 // If type is not compatible with the type of the actual next argument
16548 // (as promoted according to the default argument promotions), the
16549 // behavior is undefined, except for the following cases:
16550 // - both types are pointers to qualified or unqualified versions of
16551 // compatible types;
16552 // - one type is compatible with a signed integer type, the other
16553 // type is compatible with the corresponding unsigned integer type,
16554 // and the value is representable in both types;
16555 // - one type is pointer to qualified or unqualified void and the
16556 // other is a pointer to a qualified or unqualified character type;
16557 // - or, the type of the next argument is nullptr_t and type is a
16558 // pointer type that has the same representation and alignment
16559 // requirements as a pointer to a character type.
16560 // Given that type compatibility is the primary requirement (ignoring
16561 // qualifications), you would think we could call typesAreCompatible()
16562 // directly to test this. However, in C++, that checks for *same type*,
16563 // which causes false positives when passing an enumeration type to
16564 // va_arg. Instead, get the underlying type of the enumeration and pass
16565 // that.
16566 QualType UnderlyingType = TInfo->getType();
16567 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16568 UnderlyingType = ET->getDecl()->getIntegerType();
16569 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16570 /*CompareUnqualified*/ true))
16571 PromoteType = QualType();
16572
16573 // If the types are still not compatible, we need to test whether the
16574 // promoted type and the underlying type are the same except for
16575 // signedness. Ask the AST for the correctly corresponding type and see
16576 // if that's compatible.
16577 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16578 PromoteType->isUnsignedIntegerType() !=
16579 UnderlyingType->isUnsignedIntegerType()) {
16580 UnderlyingType =
16581 UnderlyingType->isUnsignedIntegerType()
16582 ? Context.getCorrespondingSignedType(UnderlyingType)
16583 : Context.getCorrespondingUnsignedType(UnderlyingType);
16584 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16585 /*CompareUnqualified*/ true))
16586 PromoteType = QualType();
16587 }
16588 }
16589 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16590 PromoteType = Context.DoubleTy;
16591 if (!PromoteType.isNull())
16593 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16594 << TInfo->getType()
16595 << PromoteType
16596 << TInfo->getTypeLoc().getSourceRange());
16597 }
16598
16600 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16601}
16602
16604 // The type of __null will be int or long, depending on the size of
16605 // pointers on the target.
16606 QualType Ty;
16608 if (pw == Context.getTargetInfo().getIntWidth())
16609 Ty = Context.IntTy;
16610 else if (pw == Context.getTargetInfo().getLongWidth())
16611 Ty = Context.LongTy;
16612 else if (pw == Context.getTargetInfo().getLongLongWidth())
16613 Ty = Context.LongLongTy;
16614 else {
16615 llvm_unreachable("I don't know size of pointer!");
16616 }
16617
16618 return new (Context) GNUNullExpr(Ty, TokenLoc);
16619}
16620
16622 CXXRecordDecl *ImplDecl = nullptr;
16623
16624 // Fetch the std::source_location::__impl decl.
16625 if (NamespaceDecl *Std = S.getStdNamespace()) {
16626 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16628 if (S.LookupQualifiedName(ResultSL, Std)) {
16629 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16630 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16632 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16633 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16634 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16635 }
16636 }
16637 }
16638 }
16639
16640 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16641 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16642 return nullptr;
16643 }
16644
16645 // Verify that __impl is a trivial struct type, with no base classes, and with
16646 // only the four expected fields.
16647 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16648 ImplDecl->getNumBases() != 0) {
16649 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16650 return nullptr;
16651 }
16652
16653 unsigned Count = 0;
16654 for (FieldDecl *F : ImplDecl->fields()) {
16655 StringRef Name = F->getName();
16656
16657 if (Name == "_M_file_name") {
16658 if (F->getType() !=
16660 break;
16661 Count++;
16662 } else if (Name == "_M_function_name") {
16663 if (F->getType() !=
16665 break;
16666 Count++;
16667 } else if (Name == "_M_line") {
16668 if (!F->getType()->isIntegerType())
16669 break;
16670 Count++;
16671 } else if (Name == "_M_column") {
16672 if (!F->getType()->isIntegerType())
16673 break;
16674 Count++;
16675 } else {
16676 Count = 100; // invalid
16677 break;
16678 }
16679 }
16680 if (Count != 4) {
16681 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16682 return nullptr;
16683 }
16684
16685 return ImplDecl;
16686}
16687
16689 SourceLocation BuiltinLoc,
16690 SourceLocation RPLoc) {
16691 QualType ResultTy;
16692 switch (Kind) {
16698 ResultTy =
16700 break;
16701 }
16704 ResultTy = Context.UnsignedIntTy;
16705 break;
16709 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16711 return ExprError();
16712 }
16713 ResultTy = Context.getPointerType(
16715 break;
16716 }
16717
16718 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16719}
16720
16722 SourceLocation BuiltinLoc,
16723 SourceLocation RPLoc,
16724 DeclContext *ParentContext) {
16725 return new (Context)
16726 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16727}
16728
16730 const Expr *SrcExpr) {
16731 if (!DstType->isFunctionPointerType() ||
16732 !SrcExpr->getType()->isFunctionType())
16733 return false;
16734
16735 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16736 if (!DRE)
16737 return false;
16738
16739 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16740 if (!FD)
16741 return false;
16742
16744 /*Complain=*/true,
16745 SrcExpr->getBeginLoc());
16746}
16747
16750 QualType DstType, QualType SrcType,
16751 Expr *SrcExpr, AssignmentAction Action,
16752 bool *Complained) {
16753 if (Complained)
16754 *Complained = false;
16755
16756 // Decode the result (notice that AST's are still created for extensions).
16757 bool CheckInferredResultType = false;
16758 bool isInvalid = false;
16759 unsigned DiagKind = 0;
16760 ConversionFixItGenerator ConvHints;
16761 bool MayHaveConvFixit = false;
16762 bool MayHaveFunctionDiff = false;
16763 const ObjCInterfaceDecl *IFace = nullptr;
16764 const ObjCProtocolDecl *PDecl = nullptr;
16765
16766 switch (ConvTy) {
16767 case Compatible:
16768 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16769 return false;
16770
16771 case PointerToInt:
16772 if (getLangOpts().CPlusPlus) {
16773 DiagKind = diag::err_typecheck_convert_pointer_int;
16774 isInvalid = true;
16775 } else {
16776 DiagKind = diag::ext_typecheck_convert_pointer_int;
16777 }
16778 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16779 MayHaveConvFixit = true;
16780 break;
16781 case IntToPointer:
16782 if (getLangOpts().CPlusPlus) {
16783 DiagKind = diag::err_typecheck_convert_int_pointer;
16784 isInvalid = true;
16785 } else {
16786 DiagKind = diag::ext_typecheck_convert_int_pointer;
16787 }
16788 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16789 MayHaveConvFixit = true;
16790 break;
16792 DiagKind =
16793 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16794 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16795 MayHaveConvFixit = true;
16796 break;
16798 if (getLangOpts().CPlusPlus) {
16799 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16800 isInvalid = true;
16801 } else {
16802 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16803 }
16804 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16805 MayHaveConvFixit = true;
16806 break;
16808 if (Action == AA_Passing_CFAudited) {
16809 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16810 } else if (getLangOpts().CPlusPlus) {
16811 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16812 isInvalid = true;
16813 } else {
16814 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16815 }
16816 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16817 SrcType->isObjCObjectPointerType();
16818 if (CheckInferredResultType) {
16819 SrcType = SrcType.getUnqualifiedType();
16820 DstType = DstType.getUnqualifiedType();
16821 } else {
16822 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16823 }
16824 MayHaveConvFixit = true;
16825 break;
16827 if (getLangOpts().CPlusPlus) {
16828 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16829 isInvalid = true;
16830 } else {
16831 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16832 }
16833 break;
16835 if (getLangOpts().CPlusPlus) {
16836 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16837 isInvalid = true;
16838 } else {
16839 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16840 }
16841 break;
16843 // Perform array-to-pointer decay if necessary.
16844 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16845
16846 isInvalid = true;
16847
16848 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16849 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16850 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16851 DiagKind = diag::err_typecheck_incompatible_address_space;
16852 break;
16853 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16854 DiagKind = diag::err_typecheck_incompatible_ownership;
16855 break;
16856 }
16857
16858 llvm_unreachable("unknown error case for discarding qualifiers!");
16859 // fallthrough
16860 }
16862 // If the qualifiers lost were because we were applying the
16863 // (deprecated) C++ conversion from a string literal to a char*
16864 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16865 // Ideally, this check would be performed in
16866 // checkPointerTypesForAssignment. However, that would require a
16867 // bit of refactoring (so that the second argument is an
16868 // expression, rather than a type), which should be done as part
16869 // of a larger effort to fix checkPointerTypesForAssignment for
16870 // C++ semantics.
16871 if (getLangOpts().CPlusPlus &&
16873 return false;
16874 if (getLangOpts().CPlusPlus) {
16875 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16876 isInvalid = true;
16877 } else {
16878 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16879 }
16880
16881 break;
16883 if (getLangOpts().CPlusPlus) {
16884 isInvalid = true;
16885 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16886 } else {
16887 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16888 }
16889 break;
16891 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16892 isInvalid = true;
16893 break;
16894 case IntToBlockPointer:
16895 DiagKind = diag::err_int_to_block_pointer;
16896 isInvalid = true;
16897 break;
16899 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16900 isInvalid = true;
16901 break;
16903 if (SrcType->isObjCQualifiedIdType()) {
16904 const ObjCObjectPointerType *srcOPT =
16905 SrcType->castAs<ObjCObjectPointerType>();
16906 for (auto *srcProto : srcOPT->quals()) {
16907 PDecl = srcProto;
16908 break;
16909 }
16910 if (const ObjCInterfaceType *IFaceT =
16912 IFace = IFaceT->getDecl();
16913 }
16914 else if (DstType->isObjCQualifiedIdType()) {
16915 const ObjCObjectPointerType *dstOPT =
16916 DstType->castAs<ObjCObjectPointerType>();
16917 for (auto *dstProto : dstOPT->quals()) {
16918 PDecl = dstProto;
16919 break;
16920 }
16921 if (const ObjCInterfaceType *IFaceT =
16923 IFace = IFaceT->getDecl();
16924 }
16925 if (getLangOpts().CPlusPlus) {
16926 DiagKind = diag::err_incompatible_qualified_id;
16927 isInvalid = true;
16928 } else {
16929 DiagKind = diag::warn_incompatible_qualified_id;
16930 }
16931 break;
16932 }
16934 if (getLangOpts().CPlusPlus) {
16935 DiagKind = diag::err_incompatible_vectors;
16936 isInvalid = true;
16937 } else {
16938 DiagKind = diag::warn_incompatible_vectors;
16939 }
16940 break;
16942 DiagKind = diag::err_arc_weak_unavailable_assign;
16943 isInvalid = true;
16944 break;
16945 case Incompatible:
16946 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16947 if (Complained)
16948 *Complained = true;
16949 return true;
16950 }
16951
16952 DiagKind = diag::err_typecheck_convert_incompatible;
16953 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16954 MayHaveConvFixit = true;
16955 isInvalid = true;
16956 MayHaveFunctionDiff = true;
16957 break;
16958 }
16959
16960 QualType FirstType, SecondType;
16961 switch (Action) {
16962 case AA_Assigning:
16963 case AA_Initializing:
16964 // The destination type comes first.
16965 FirstType = DstType;
16966 SecondType = SrcType;
16967 break;
16968
16969 case AA_Returning:
16970 case AA_Passing:
16972 case AA_Converting:
16973 case AA_Sending:
16974 case AA_Casting:
16975 // The source type comes first.
16976 FirstType = SrcType;
16977 SecondType = DstType;
16978 break;
16979 }
16980
16981 PartialDiagnostic FDiag = PDiag(DiagKind);
16982 AssignmentAction ActionForDiag = Action;
16983 if (Action == AA_Passing_CFAudited)
16984 ActionForDiag = AA_Passing;
16985
16986 FDiag << FirstType << SecondType << ActionForDiag
16987 << SrcExpr->getSourceRange();
16988
16989 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16990 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16991 auto isPlainChar = [](const clang::Type *Type) {
16992 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16993 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16994 };
16995 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16996 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16997 }
16998
16999 // If we can fix the conversion, suggest the FixIts.
17000 if (!ConvHints.isNull()) {
17001 for (FixItHint &H : ConvHints.Hints)
17002 FDiag << H;
17003 }
17004
17005 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17006
17007 if (MayHaveFunctionDiff)
17008 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17009
17010 Diag(Loc, FDiag);
17011 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17012 DiagKind == diag::err_incompatible_qualified_id) &&
17013 PDecl && IFace && !IFace->hasDefinition())
17014 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17015 << IFace << PDecl;
17016
17017 if (SecondType == Context.OverloadTy)
17019 FirstType, /*TakingAddress=*/true);
17020
17021 if (CheckInferredResultType)
17023
17024 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17026
17027 if (Complained)
17028 *Complained = true;
17029 return isInvalid;
17030}
17031
17033 llvm::APSInt *Result,
17034 AllowFoldKind CanFold) {
17035 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17036 public:
17037 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17038 QualType T) override {
17039 return S.Diag(Loc, diag::err_ice_not_integral)
17040 << T << S.LangOpts.CPlusPlus;
17041 }
17042 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17043 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17044 }
17045 } Diagnoser;
17046
17047 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17048}
17049
17051 llvm::APSInt *Result,
17052 unsigned DiagID,
17053 AllowFoldKind CanFold) {
17054 class IDDiagnoser : public VerifyICEDiagnoser {
17055 unsigned DiagID;
17056
17057 public:
17058 IDDiagnoser(unsigned DiagID)
17059 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17060
17061 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17062 return S.Diag(Loc, DiagID);
17063 }
17064 } Diagnoser(DiagID);
17065
17066 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17067}
17068
17071 QualType T) {
17072 return diagnoseNotICE(S, Loc);
17073}
17074
17077 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17078}
17079
17082 VerifyICEDiagnoser &Diagnoser,
17083 AllowFoldKind CanFold) {
17084 SourceLocation DiagLoc = E->getBeginLoc();
17085
17086 if (getLangOpts().CPlusPlus11) {
17087 // C++11 [expr.const]p5:
17088 // If an expression of literal class type is used in a context where an
17089 // integral constant expression is required, then that class type shall
17090 // have a single non-explicit conversion function to an integral or
17091 // unscoped enumeration type
17092 ExprResult Converted;
17093 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17094 VerifyICEDiagnoser &BaseDiagnoser;
17095 public:
17096 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17097 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17098 BaseDiagnoser.Suppress, true),
17099 BaseDiagnoser(BaseDiagnoser) {}
17100
17101 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17102 QualType T) override {
17103 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17104 }
17105
17106 SemaDiagnosticBuilder diagnoseIncomplete(
17107 Sema &S, SourceLocation Loc, QualType T) override {
17108 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17109 }
17110
17111 SemaDiagnosticBuilder diagnoseExplicitConv(
17112 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17113 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17114 }
17115
17116 SemaDiagnosticBuilder noteExplicitConv(
17117 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17118 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17119 << ConvTy->isEnumeralType() << ConvTy;
17120 }
17121
17122 SemaDiagnosticBuilder diagnoseAmbiguous(
17123 Sema &S, SourceLocation Loc, QualType T) override {
17124 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17125 }
17126
17127 SemaDiagnosticBuilder noteAmbiguous(
17128 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17129 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17130 << ConvTy->isEnumeralType() << ConvTy;
17131 }
17132
17133 SemaDiagnosticBuilder diagnoseConversion(
17134 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17135 llvm_unreachable("conversion functions are permitted");
17136 }
17137 } ConvertDiagnoser(Diagnoser);
17138
17139 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17140 ConvertDiagnoser);
17141 if (Converted.isInvalid())
17142 return Converted;
17143 E = Converted.get();
17144 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17145 // don't try to evaluate it later. We also don't want to return the
17146 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17147 // this function will attempt to use 'Value'.
17148 if (isa<RecoveryExpr>(E))
17149 return ExprError();
17151 return ExprError();
17152 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17153 // An ICE must be of integral or unscoped enumeration type.
17154 if (!Diagnoser.Suppress)
17155 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17156 << E->getSourceRange();
17157 return ExprError();
17158 }
17159
17160 ExprResult RValueExpr = DefaultLvalueConversion(E);
17161 if (RValueExpr.isInvalid())
17162 return ExprError();
17163
17164 E = RValueExpr.get();
17165
17166 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17167 // in the non-ICE case.
17169 if (Result)
17171 if (!isa<ConstantExpr>(E))
17174 return E;
17175 }
17176
17177 Expr::EvalResult EvalResult;
17179 EvalResult.Diag = &Notes;
17180
17181 // Try to evaluate the expression, and produce diagnostics explaining why it's
17182 // not a constant expression as a side-effect.
17183 bool Folded =
17184 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17185 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17186
17187 if (!isa<ConstantExpr>(E))
17188 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17189
17190 // In C++11, we can rely on diagnostics being produced for any expression
17191 // which is not a constant expression. If no diagnostics were produced, then
17192 // this is a constant expression.
17193 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17194 if (Result)
17195 *Result = EvalResult.Val.getInt();
17196 return E;
17197 }
17198
17199 // If our only note is the usual "invalid subexpression" note, just point
17200 // the caret at its location rather than producing an essentially
17201 // redundant note.
17202 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17203 diag::note_invalid_subexpr_in_const_expr) {
17204 DiagLoc = Notes[0].first;
17205 Notes.clear();
17206 }
17207
17208 if (!Folded || !CanFold) {
17209 if (!Diagnoser.Suppress) {
17210 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17211 for (const PartialDiagnosticAt &Note : Notes)
17212 Diag(Note.first, Note.second);
17213 }
17214
17215 return ExprError();
17216 }
17217
17218 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17219 for (const PartialDiagnosticAt &Note : Notes)
17220 Diag(Note.first, Note.second);
17221
17222 if (Result)
17223 *Result = EvalResult.Val.getInt();
17224 return E;
17225}
17226
17227namespace {
17228 // Handle the case where we conclude a expression which we speculatively
17229 // considered to be unevaluated is actually evaluated.
17230 class TransformToPE : public TreeTransform<TransformToPE> {
17231 typedef TreeTransform<TransformToPE> BaseTransform;
17232
17233 public:
17234 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17235
17236 // Make sure we redo semantic analysis
17237 bool AlwaysRebuild() { return true; }
17238 bool ReplacingOriginal() { return true; }
17239
17240 // We need to special-case DeclRefExprs referring to FieldDecls which
17241 // are not part of a member pointer formation; normal TreeTransforming
17242 // doesn't catch this case because of the way we represent them in the AST.
17243 // FIXME: This is a bit ugly; is it really the best way to handle this
17244 // case?
17245 //
17246 // Error on DeclRefExprs referring to FieldDecls.
17247 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17248 if (isa<FieldDecl>(E->getDecl()) &&
17249 !SemaRef.isUnevaluatedContext())
17250 return SemaRef.Diag(E->getLocation(),
17251 diag::err_invalid_non_static_member_use)
17252 << E->getDecl() << E->getSourceRange();
17253
17254 return BaseTransform::TransformDeclRefExpr(E);
17255 }
17256
17257 // Exception: filter out member pointer formation
17258 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17259 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17260 return E;
17261
17262 return BaseTransform::TransformUnaryOperator(E);
17263 }
17264
17265 // The body of a lambda-expression is in a separate expression evaluation
17266 // context so never needs to be transformed.
17267 // FIXME: Ideally we wouldn't transform the closure type either, and would
17268 // just recreate the capture expressions and lambda expression.
17269 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17270 return SkipLambdaBody(E, Body);
17271 }
17272 };
17273}
17274
17276 assert(isUnevaluatedContext() &&
17277 "Should only transform unevaluated expressions");
17278 ExprEvalContexts.back().Context =
17279 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17281 return E;
17282 return TransformToPE(*this).TransformExpr(E);
17283}
17284
17286 assert(isUnevaluatedContext() &&
17287 "Should only transform unevaluated expressions");
17288 ExprEvalContexts.back().Context =
17289 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17291 return TInfo;
17292 return TransformToPE(*this).TransformType(TInfo);
17293}
17294
17295void
17297 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17299 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17300 LambdaContextDecl, ExprContext);
17301
17302 // Discarded statements and immediate contexts nested in other
17303 // discarded statements or immediate context are themselves
17304 // a discarded statement or an immediate context, respectively.
17305 ExprEvalContexts.back().InDiscardedStatement =
17307 .isDiscardedStatementContext();
17308
17309 // C++23 [expr.const]/p15
17310 // An expression or conversion is in an immediate function context if [...]
17311 // it is a subexpression of a manifestly constant-evaluated expression or
17312 // conversion.
17313 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
17314 ExprEvalContexts.back().InImmediateFunctionContext =
17315 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17316
17317 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17318 Prev.InImmediateEscalatingFunctionContext;
17319
17320 Cleanup.reset();
17321 if (!MaybeODRUseExprs.empty())
17322 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17323}
17324
17325void
17329 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17330 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17331}
17332
17333namespace {
17334
17335const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17336 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17337 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17338 if (E->getOpcode() == UO_Deref)
17339 return CheckPossibleDeref(S, E->getSubExpr());
17340 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17341 return CheckPossibleDeref(S, E->getBase());
17342 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17343 return CheckPossibleDeref(S, E->getBase());
17344 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17345 QualType Inner;
17346 QualType Ty = E->getType();
17347 if (const auto *Ptr = Ty->getAs<PointerType>())
17348 Inner = Ptr->getPointeeType();
17349 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17350 Inner = Arr->getElementType();
17351 else
17352 return nullptr;
17353
17354 if (Inner->hasAttr(attr::NoDeref))
17355 return E;
17356 }
17357 return nullptr;
17358}
17359
17360} // namespace
17361
17363 for (const Expr *E : Rec.PossibleDerefs) {
17364 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17365 if (DeclRef) {
17366 const ValueDecl *Decl = DeclRef->getDecl();
17367 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17368 << Decl->getName() << E->getSourceRange();
17369 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17370 } else {
17371 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17372 << E->getSourceRange();
17373 }
17374 }
17375 Rec.PossibleDerefs.clear();
17376}
17377
17378/// Check whether E, which is either a discarded-value expression or an
17379/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17380/// and if so, remove it from the list of volatile-qualified assignments that
17381/// we are going to warn are deprecated.
17384 return;
17385
17386 // Note: ignoring parens here is not justified by the standard rules, but
17387 // ignoring parentheses seems like a more reasonable approach, and this only
17388 // drives a deprecation warning so doesn't affect conformance.
17389 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17390 if (BO->getOpcode() == BO_Assign) {
17391 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17392 llvm::erase(LHSs, BO->getLHS());
17393 }
17394 }
17395}
17396
17398 assert(getLangOpts().CPlusPlus20 &&
17399 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17400 "Cannot mark an immediate escalating expression outside of an "
17401 "immediate escalating context");
17402 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17403 Call && Call->getCallee()) {
17404 if (auto *DeclRef =
17405 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17406 DeclRef->setIsImmediateEscalating(true);
17407 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17408 Ctr->setIsImmediateEscalating(true);
17409 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17410 DeclRef->setIsImmediateEscalating(true);
17411 } else {
17412 assert(false && "expected an immediately escalating expression");
17413 }
17415 FI->FoundImmediateEscalatingExpression = true;
17416}
17417
17419 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17420 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17423 return E;
17424
17425 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17426 /// It's OK if this fails; we'll also remove this in
17427 /// HandleImmediateInvocations, but catching it here allows us to avoid
17428 /// walking the AST looking for it in simple cases.
17429 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17430 if (auto *DeclRef =
17431 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17432 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17433
17434 // C++23 [expr.const]/p16
17435 // An expression or conversion is immediate-escalating if it is not initially
17436 // in an immediate function context and it is [...] an immediate invocation
17437 // that is not a constant expression and is not a subexpression of an
17438 // immediate invocation.
17439 APValue Cached;
17440 auto CheckConstantExpressionAndKeepResult = [&]() {
17442 Expr::EvalResult Eval;
17443 Eval.Diag = &Notes;
17444 bool Res = E.get()->EvaluateAsConstantExpr(
17445 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17446 if (Res && Notes.empty()) {
17447 Cached = std::move(Eval.Val);
17448 return true;
17449 }
17450 return false;
17451 };
17452
17453 if (!E.get()->isValueDependent() &&
17454 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17455 !CheckConstantExpressionAndKeepResult()) {
17457 return E;
17458 }
17459
17460 if (Cleanup.exprNeedsCleanups()) {
17461 // Since an immediate invocation is a full expression itself - it requires
17462 // an additional ExprWithCleanups node, but it can participate to a bigger
17463 // full expression which actually requires cleanups to be run after so
17464 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17465 // may discard cleanups for outer expression too early.
17466
17467 // Note that ExprWithCleanups created here must always have empty cleanup
17468 // objects:
17469 // - compound literals do not create cleanup objects in C++ and immediate
17470 // invocations are C++-only.
17471 // - blocks are not allowed inside constant expressions and compiler will
17472 // issue an error if they appear there.
17473 //
17474 // Hence, in correct code any cleanup objects created inside current
17475 // evaluation context must be outside the immediate invocation.
17478 }
17479
17481 getASTContext(), E.get(),
17482 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17483 getASTContext()),
17484 /*IsImmediateInvocation*/ true);
17485 if (Cached.hasValue())
17486 Res->MoveIntoResult(Cached, getASTContext());
17487 /// Value-dependent constant expressions should not be immediately
17488 /// evaluated until they are instantiated.
17489 if (!Res->isValueDependent())
17490 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17491 return Res;
17492}
17493
17497 Expr::EvalResult Eval;
17498 Eval.Diag = &Notes;
17499 ConstantExpr *CE = Candidate.getPointer();
17500 bool Result = CE->EvaluateAsConstantExpr(
17501 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17502 if (!Result || !Notes.empty()) {
17504 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17505 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17506 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17507 FunctionDecl *FD = nullptr;
17508 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17509 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17510 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17511 FD = Call->getConstructor();
17512 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17513 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17514
17515 assert(FD && FD->isImmediateFunction() &&
17516 "could not find an immediate function in this expression");
17517 if (FD->isInvalidDecl())
17518 return;
17519 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17520 << FD << FD->isConsteval();
17521 if (auto Context =
17523 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17524 << Context->Decl;
17525 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17526 }
17527 if (!FD->isConsteval())
17529 for (auto &Note : Notes)
17530 SemaRef.Diag(Note.first, Note.second);
17531 return;
17532 }
17534}
17535
17539 struct ComplexRemove : TreeTransform<ComplexRemove> {
17541 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17544 CurrentII;
17545 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17548 4>::reverse_iterator Current)
17549 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17550 void RemoveImmediateInvocation(ConstantExpr* E) {
17551 auto It = std::find_if(CurrentII, IISet.rend(),
17553 return Elem.getPointer() == E;
17554 });
17555 // It is possible that some subexpression of the current immediate
17556 // invocation was handled from another expression evaluation context. Do
17557 // not handle the current immediate invocation if some of its
17558 // subexpressions failed before.
17559 if (It == IISet.rend()) {
17560 if (SemaRef.FailedImmediateInvocations.contains(E))
17561 CurrentII->setInt(1);
17562 } else {
17563 It->setInt(1); // Mark as deleted
17564 }
17565 }
17566 ExprResult TransformConstantExpr(ConstantExpr *E) {
17567 if (!E->isImmediateInvocation())
17568 return Base::TransformConstantExpr(E);
17569 RemoveImmediateInvocation(E);
17570 return Base::TransformExpr(E->getSubExpr());
17571 }
17572 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17573 /// we need to remove its DeclRefExpr from the DRSet.
17574 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17575 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17576 return Base::TransformCXXOperatorCallExpr(E);
17577 }
17578 /// Base::TransformUserDefinedLiteral doesn't preserve the
17579 /// UserDefinedLiteral node.
17580 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17581 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17582 /// here.
17583 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17584 if (!Init)
17585 return Init;
17586 /// ConstantExpr are the first layer of implicit node to be removed so if
17587 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17588 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17589 if (CE->isImmediateInvocation())
17590 RemoveImmediateInvocation(CE);
17591 return Base::TransformInitializer(Init, NotCopyInit);
17592 }
17593 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17594 DRSet.erase(E);
17595 return E;
17596 }
17597 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17598 // Do not rebuild lambdas to avoid creating a new type.
17599 // Lambdas have already been processed inside their eval context.
17600 return E;
17601 }
17602 bool AlwaysRebuild() { return false; }
17603 bool ReplacingOriginal() { return true; }
17604 bool AllowSkippingCXXConstructExpr() {
17605 bool Res = AllowSkippingFirstCXXConstructExpr;
17606 AllowSkippingFirstCXXConstructExpr = true;
17607 return Res;
17608 }
17609 bool AllowSkippingFirstCXXConstructExpr = true;
17610 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17612
17613 /// CXXConstructExpr with a single argument are getting skipped by
17614 /// TreeTransform in some situtation because they could be implicit. This
17615 /// can only occur for the top-level CXXConstructExpr because it is used
17616 /// nowhere in the expression being transformed therefore will not be rebuilt.
17617 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17618 /// skipping the first CXXConstructExpr.
17619 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17620 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17621
17622 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17623 // The result may not be usable in case of previous compilation errors.
17624 // In this case evaluation of the expression may result in crash so just
17625 // don't do anything further with the result.
17626 if (Res.isUsable()) {
17628 It->getPointer()->setSubExpr(Res.get());
17629 }
17630}
17631
17632static void
17635 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17636 Rec.ReferenceToConsteval.size() == 0) ||
17638 return;
17639
17640 /// When we have more than 1 ImmediateInvocationCandidates or previously
17641 /// failed immediate invocations, we need to check for nested
17642 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17643 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17644 /// invocation.
17645 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17647
17648 /// Prevent sema calls during the tree transform from adding pointers that
17649 /// are already in the sets.
17650 llvm::SaveAndRestore DisableIITracking(
17652
17653 /// Prevent diagnostic during tree transfrom as they are duplicates
17655
17656 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17657 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17658 if (!It->getInt())
17660 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17661 Rec.ReferenceToConsteval.size()) {
17662 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17663 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17664 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17665 bool VisitDeclRefExpr(DeclRefExpr *E) {
17666 DRSet.erase(E);
17667 return DRSet.size();
17668 }
17669 } Visitor(Rec.ReferenceToConsteval);
17670 Visitor.TraverseStmt(
17671 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17672 }
17673 for (auto CE : Rec.ImmediateInvocationCandidates)
17674 if (!CE.getInt())
17676 for (auto *DR : Rec.ReferenceToConsteval) {
17677 // If the expression is immediate escalating, it is not an error;
17678 // The outer context itself becomes immediate and further errors,
17679 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17680 if (DR->isImmediateEscalating())
17681 continue;
17682 auto *FD = cast<FunctionDecl>(DR->getDecl());
17683 const NamedDecl *ND = FD;
17684 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17685 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17686 ND = MD->getParent();
17687
17688 // C++23 [expr.const]/p16
17689 // An expression or conversion is immediate-escalating if it is not
17690 // initially in an immediate function context and it is [...] a
17691 // potentially-evaluated id-expression that denotes an immediate function
17692 // that is not a subexpression of an immediate invocation.
17693 bool ImmediateEscalating = false;
17694 bool IsPotentiallyEvaluated =
17695 Rec.Context ==
17697 Rec.Context ==
17699 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17700 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17701
17703 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17704 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17705 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17706 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17707 if (auto Context =
17709 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17710 << Context->Decl;
17711 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17712 }
17713 if (FD->isImmediateEscalating() && !FD->isConsteval())
17715
17716 } else {
17718 }
17719 }
17720}
17721
17724 unsigned NumTypos = Rec.NumTypos;
17725
17726 if (!Rec.Lambdas.empty()) {
17728 if (!getLangOpts().CPlusPlus20 &&
17729 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17730 Rec.isUnevaluated() ||
17732 unsigned D;
17733 if (Rec.isUnevaluated()) {
17734 // C++11 [expr.prim.lambda]p2:
17735 // A lambda-expression shall not appear in an unevaluated operand
17736 // (Clause 5).
17737 D = diag::err_lambda_unevaluated_operand;
17738 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17739 // C++1y [expr.const]p2:
17740 // A conditional-expression e is a core constant expression unless the
17741 // evaluation of e, following the rules of the abstract machine, would
17742 // evaluate [...] a lambda-expression.
17743 D = diag::err_lambda_in_constant_expression;
17744 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17745 // C++17 [expr.prim.lamda]p2:
17746 // A lambda-expression shall not appear [...] in a template-argument.
17747 D = diag::err_lambda_in_invalid_context;
17748 } else
17749 llvm_unreachable("Couldn't infer lambda error message.");
17750
17751 for (const auto *L : Rec.Lambdas)
17752 Diag(L->getBeginLoc(), D);
17753 }
17754 }
17755
17756 // Append the collected materialized temporaries into previous context before
17757 // exit if the previous also is a lifetime extending context.
17758 auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
17760 PrevRecord.InLifetimeExtendingContext &&
17761 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17762 PrevRecord.ForRangeLifetimeExtendTemps.append(
17764 }
17765
17767 HandleImmediateInvocations(*this, Rec);
17768
17769 // Warn on any volatile-qualified simple-assignments that are not discarded-
17770 // value expressions nor unevaluated operands (those cases get removed from
17771 // this list by CheckUnusedVolatileAssignment).
17772 for (auto *BO : Rec.VolatileAssignmentLHSs)
17773 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17774 << BO->getType();
17775
17776 // When are coming out of an unevaluated context, clear out any
17777 // temporaries that we may have created as part of the evaluation of
17778 // the expression in that context: they aren't relevant because they
17779 // will never be constructed.
17780 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17782 ExprCleanupObjects.end());
17783 Cleanup = Rec.ParentCleanup;
17786 // Otherwise, merge the contexts together.
17787 } else {
17789 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17790 Rec.SavedMaybeODRUseExprs.end());
17791 }
17792
17793 // Pop the current expression evaluation context off the stack.
17794 ExprEvalContexts.pop_back();
17795
17796 // The global expression evaluation context record is never popped.
17797 ExprEvalContexts.back().NumTypos += NumTypos;
17798}
17799
17801 ExprCleanupObjects.erase(
17802 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17803 ExprCleanupObjects.end());
17804 Cleanup.reset();
17805 MaybeODRUseExprs.clear();
17806}
17807
17810 if (Result.isInvalid())
17811 return ExprError();
17812 E = Result.get();
17813 if (!E->getType()->isVariablyModifiedType())
17814 return E;
17816}
17817
17818/// Are we in a context that is potentially constant evaluated per C++20
17819/// [expr.const]p12?
17821 /// C++2a [expr.const]p12:
17822 // An expression or conversion is potentially constant evaluated if it is
17823 switch (SemaRef.ExprEvalContexts.back().Context) {
17826
17827 // -- a manifestly constant-evaluated expression,
17831 // -- a potentially-evaluated expression,
17833 // -- an immediate subexpression of a braced-init-list,
17834
17835 // -- [FIXME] an expression of the form & cast-expression that occurs
17836 // within a templated entity
17837 // -- a subexpression of one of the above that is not a subexpression of
17838 // a nested unevaluated operand.
17839 return true;
17840
17843 // Expressions in this context are never evaluated.
17844 return false;
17845 }
17846 llvm_unreachable("Invalid context");
17847}
17848
17849/// Return true if this function has a calling convention that requires mangling
17850/// in the size of the parameter pack.
17852 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17853 // we don't need parameter type sizes.
17854 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17855 if (!TT.isOSWindows() || !TT.isX86())
17856 return false;
17857
17858 // If this is C++ and this isn't an extern "C" function, parameters do not
17859 // need to be complete. In this case, C++ mangling will apply, which doesn't
17860 // use the size of the parameters.
17861 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17862 return false;
17863
17864 // Stdcall, fastcall, and vectorcall need this special treatment.
17865 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17866 switch (CC) {
17867 case CC_X86StdCall:
17868 case CC_X86FastCall:
17869 case CC_X86VectorCall:
17870 return true;
17871 default:
17872 break;
17873 }
17874 return false;
17875}
17876
17877/// Require that all of the parameter types of function be complete. Normally,
17878/// parameter types are only required to be complete when a function is called
17879/// or defined, but to mangle functions with certain calling conventions, the
17880/// mangler needs to know the size of the parameter list. In this situation,
17881/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17882/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17883/// result in a linker error. Clang doesn't implement this behavior, and instead
17884/// attempts to error at compile time.
17887 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17888 FunctionDecl *FD;
17889 ParmVarDecl *Param;
17890
17891 public:
17892 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17893 : FD(FD), Param(Param) {}
17894
17895 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17896 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17897 StringRef CCName;
17898 switch (CC) {
17899 case CC_X86StdCall:
17900 CCName = "stdcall";
17901 break;
17902 case CC_X86FastCall:
17903 CCName = "fastcall";
17904 break;
17905 case CC_X86VectorCall:
17906 CCName = "vectorcall";
17907 break;
17908 default:
17909 llvm_unreachable("CC does not need mangling");
17910 }
17911
17912 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17913 << Param->getDeclName() << FD->getDeclName() << CCName;
17914 }
17915 };
17916
17917 for (ParmVarDecl *Param : FD->parameters()) {
17918 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17919 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17920 }
17921}
17922
17923namespace {
17924enum class OdrUseContext {
17925 /// Declarations in this context are not odr-used.
17926 None,
17927 /// Declarations in this context are formally odr-used, but this is a
17928 /// dependent context.
17929 Dependent,
17930 /// Declarations in this context are odr-used but not actually used (yet).
17931 FormallyOdrUsed,
17932 /// Declarations in this context are used.
17933 Used
17934};
17935}
17936
17937/// Are we within a context in which references to resolved functions or to
17938/// variables result in odr-use?
17939static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17940 OdrUseContext Result;
17941
17942 switch (SemaRef.ExprEvalContexts.back().Context) {
17946 return OdrUseContext::None;
17947
17951 Result = OdrUseContext::Used;
17952 break;
17953
17955 Result = OdrUseContext::FormallyOdrUsed;
17956 break;
17957
17959 // A default argument formally results in odr-use, but doesn't actually
17960 // result in a use in any real sense until it itself is used.
17961 Result = OdrUseContext::FormallyOdrUsed;
17962 break;
17963 }
17964
17966 return OdrUseContext::Dependent;
17967
17968 return Result;
17969}
17970
17972 if (!Func->isConstexpr())
17973 return false;
17974
17975 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17976 return true;
17977 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17978 return CCD && CCD->getInheritedConstructor();
17979}
17980
17981/// Mark a function referenced, and check whether it is odr-used
17982/// (C++ [basic.def.odr]p2, C99 6.9p3)
17984 bool MightBeOdrUse) {
17985 assert(Func && "No function?");
17986
17987 Func->setReferenced();
17988
17989 // Recursive functions aren't really used until they're used from some other
17990 // context.
17991 bool IsRecursiveCall = CurContext == Func;
17992
17993 // C++11 [basic.def.odr]p3:
17994 // A function whose name appears as a potentially-evaluated expression is
17995 // odr-used if it is the unique lookup result or the selected member of a
17996 // set of overloaded functions [...].
17997 //
17998 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17999 // can just check that here.
18000 OdrUseContext OdrUse =
18001 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18002 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18003 OdrUse = OdrUseContext::FormallyOdrUsed;
18004
18005 // Trivial default constructors and destructors are never actually used.
18006 // FIXME: What about other special members?
18007 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18008 OdrUse == OdrUseContext::Used) {
18009 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18010 if (Constructor->isDefaultConstructor())
18011 OdrUse = OdrUseContext::FormallyOdrUsed;
18012 if (isa<CXXDestructorDecl>(Func))
18013 OdrUse = OdrUseContext::FormallyOdrUsed;
18014 }
18015
18016 // C++20 [expr.const]p12:
18017 // A function [...] is needed for constant evaluation if it is [...] a
18018 // constexpr function that is named by an expression that is potentially
18019 // constant evaluated
18020 bool NeededForConstantEvaluation =
18023
18024 // Determine whether we require a function definition to exist, per
18025 // C++11 [temp.inst]p3:
18026 // Unless a function template specialization has been explicitly
18027 // instantiated or explicitly specialized, the function template
18028 // specialization is implicitly instantiated when the specialization is
18029 // referenced in a context that requires a function definition to exist.
18030 // C++20 [temp.inst]p7:
18031 // The existence of a definition of a [...] function is considered to
18032 // affect the semantics of the program if the [...] function is needed for
18033 // constant evaluation by an expression
18034 // C++20 [basic.def.odr]p10:
18035 // Every program shall contain exactly one definition of every non-inline
18036 // function or variable that is odr-used in that program outside of a
18037 // discarded statement
18038 // C++20 [special]p1:
18039 // The implementation will implicitly define [defaulted special members]
18040 // if they are odr-used or needed for constant evaluation.
18041 //
18042 // Note that we skip the implicit instantiation of templates that are only
18043 // used in unused default arguments or by recursive calls to themselves.
18044 // This is formally non-conforming, but seems reasonable in practice.
18045 bool NeedDefinition =
18046 !IsRecursiveCall &&
18047 (OdrUse == OdrUseContext::Used ||
18048 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18049
18050 // C++14 [temp.expl.spec]p6:
18051 // If a template [...] is explicitly specialized then that specialization
18052 // shall be declared before the first use of that specialization that would
18053 // cause an implicit instantiation to take place, in every translation unit
18054 // in which such a use occurs
18055 if (NeedDefinition &&
18056 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18057 Func->getMemberSpecializationInfo()))
18059
18060 if (getLangOpts().CUDA)
18061 CUDA().CheckCall(Loc, Func);
18062
18063 // If we need a definition, try to create one.
18064 if (NeedDefinition && !Func->getBody()) {
18066 if (CXXConstructorDecl *Constructor =
18067 dyn_cast<CXXConstructorDecl>(Func)) {
18068 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18069 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18070 if (Constructor->isDefaultConstructor()) {
18071 if (Constructor->isTrivial() &&
18072 !Constructor->hasAttr<DLLExportAttr>())
18073 return;
18075 } else if (Constructor->isCopyConstructor()) {
18076 DefineImplicitCopyConstructor(Loc, Constructor);
18077 } else if (Constructor->isMoveConstructor()) {
18078 DefineImplicitMoveConstructor(Loc, Constructor);
18079 }
18080 } else if (Constructor->getInheritedConstructor()) {
18081 DefineInheritingConstructor(Loc, Constructor);
18082 }
18083 } else if (CXXDestructorDecl *Destructor =
18084 dyn_cast<CXXDestructorDecl>(Func)) {
18085 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18086 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18087 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18088 return;
18090 }
18091 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18092 MarkVTableUsed(Loc, Destructor->getParent());
18093 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18094 if (MethodDecl->isOverloadedOperator() &&
18095 MethodDecl->getOverloadedOperator() == OO_Equal) {
18096 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18097 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18098 if (MethodDecl->isCopyAssignmentOperator())
18099 DefineImplicitCopyAssignment(Loc, MethodDecl);
18100 else if (MethodDecl->isMoveAssignmentOperator())
18101 DefineImplicitMoveAssignment(Loc, MethodDecl);
18102 }
18103 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18104 MethodDecl->getParent()->isLambda()) {
18105 CXXConversionDecl *Conversion =
18106 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18107 if (Conversion->isLambdaToBlockPointerConversion())
18109 else
18111 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18112 MarkVTableUsed(Loc, MethodDecl->getParent());
18113 }
18114
18115 if (Func->isDefaulted() && !Func->isDeleted()) {
18119 }
18120
18121 // Implicit instantiation of function templates and member functions of
18122 // class templates.
18123 if (Func->isImplicitlyInstantiable()) {
18125 Func->getTemplateSpecializationKindForInstantiation();
18126 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18127 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18128 if (FirstInstantiation) {
18129 PointOfInstantiation = Loc;
18130 if (auto *MSI = Func->getMemberSpecializationInfo())
18131 MSI->setPointOfInstantiation(Loc);
18132 // FIXME: Notify listener.
18133 else
18134 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18135 } else if (TSK != TSK_ImplicitInstantiation) {
18136 // Use the point of use as the point of instantiation, instead of the
18137 // point of explicit instantiation (which we track as the actual point
18138 // of instantiation). This gives better backtraces in diagnostics.
18139 PointOfInstantiation = Loc;
18140 }
18141
18142 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18143 Func->isConstexpr()) {
18144 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18145 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18146 CodeSynthesisContexts.size())
18148 std::make_pair(Func, PointOfInstantiation));
18149 else if (Func->isConstexpr())
18150 // Do not defer instantiations of constexpr functions, to avoid the
18151 // expression evaluator needing to call back into Sema if it sees a
18152 // call to such a function.
18153 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18154 else {
18155 Func->setInstantiationIsPending(true);
18156 PendingInstantiations.push_back(
18157 std::make_pair(Func, PointOfInstantiation));
18158 // Notify the consumer that a function was implicitly instantiated.
18160 }
18161 }
18162 } else {
18163 // Walk redefinitions, as some of them may be instantiable.
18164 for (auto *i : Func->redecls()) {
18165 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18166 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18167 }
18168 }
18169 });
18170 }
18171
18172 // If a constructor was defined in the context of a default parameter
18173 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18174 // context), its initializers may not be referenced yet.
18175 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18177 *this,
18178 Constructor->isImmediateFunction()
18181 Constructor);
18182 for (CXXCtorInitializer *Init : Constructor->inits()) {
18183 if (Init->isInClassMemberInitializer())
18184 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18185 MarkDeclarationsReferencedInExpr(Init->getInit());
18186 });
18187 }
18188 }
18189
18190 // C++14 [except.spec]p17:
18191 // An exception-specification is considered to be needed when:
18192 // - the function is odr-used or, if it appears in an unevaluated operand,
18193 // would be odr-used if the expression were potentially-evaluated;
18194 //
18195 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18196 // function is a pure virtual function we're calling, and in that case the
18197 // function was selected by overload resolution and we need to resolve its
18198 // exception specification for a different reason.
18199 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18202
18203 // A callee could be called by a host function then by a device function.
18204 // If we only try recording once, we will miss recording the use on device
18205 // side. Therefore keep trying until it is recorded.
18206 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18209
18210 // If this is the first "real" use, act on that.
18211 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18212 // Keep track of used but undefined functions.
18213 if (!Func->isDefined()) {
18214 if (mightHaveNonExternalLinkage(Func))
18215 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18216 else if (Func->getMostRecentDecl()->isInlined() &&
18217 !LangOpts.GNUInline &&
18218 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18219 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18221 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18222 }
18223
18224 // Some x86 Windows calling conventions mangle the size of the parameter
18225 // pack into the name. Computing the size of the parameters requires the
18226 // parameter types to be complete. Check that now.
18229
18230 // In the MS C++ ABI, the compiler emits destructor variants where they are
18231 // used. If the destructor is used here but defined elsewhere, mark the
18232 // virtual base destructors referenced. If those virtual base destructors
18233 // are inline, this will ensure they are defined when emitting the complete
18234 // destructor variant. This checking may be redundant if the destructor is
18235 // provided later in this TU.
18237 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18238 CXXRecordDecl *Parent = Dtor->getParent();
18239 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18241 }
18242 }
18243
18244 Func->markUsed(Context);
18245 }
18246}
18247
18248/// Directly mark a variable odr-used. Given a choice, prefer to use
18249/// MarkVariableReferenced since it does additional checks and then
18250/// calls MarkVarDeclODRUsed.
18251/// If the variable must be captured:
18252/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18253/// - else capture it in the DeclContext that maps to the
18254/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18255static void
18257 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18258 // Keep track of used but undefined variables.
18259 // FIXME: We shouldn't suppress this warning for static data members.
18260 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18261 assert(Var && "expected a capturable variable");
18262
18264 (!Var->isExternallyVisible() || Var->isInline() ||
18266 !(Var->isStaticDataMember() && Var->hasInit())) {
18268 if (old.isInvalid())
18269 old = Loc;
18270 }
18271 QualType CaptureType, DeclRefType;
18272 if (SemaRef.LangOpts.OpenMP)
18275 /*EllipsisLoc*/ SourceLocation(),
18276 /*BuildAndDiagnose*/ true, CaptureType,
18277 DeclRefType, FunctionScopeIndexToStopAt);
18278
18279 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18280 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18281 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18282 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18283 if (VarTarget == SemaCUDA::CVT_Host &&
18284 (UserTarget == CUDAFunctionTarget::Device ||
18285 UserTarget == CUDAFunctionTarget::HostDevice ||
18286 UserTarget == CUDAFunctionTarget::Global)) {
18287 // Diagnose ODR-use of host global variables in device functions.
18288 // Reference of device global variables in host functions is allowed
18289 // through shadow variables therefore it is not diagnosed.
18290 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18291 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18292 << /*host*/ 2 << /*variable*/ 1 << Var
18293 << llvm::to_underlying(UserTarget);
18295 Var->getType().isConstQualified()
18296 ? diag::note_cuda_const_var_unpromoted
18297 : diag::note_cuda_host_var);
18298 }
18299 } else if (VarTarget == SemaCUDA::CVT_Device &&
18300 !Var->hasAttr<CUDASharedAttr>() &&
18301 (UserTarget == CUDAFunctionTarget::Host ||
18302 UserTarget == CUDAFunctionTarget::HostDevice)) {
18303 // Record a CUDA/HIP device side variable if it is ODR-used
18304 // by host code. This is done conservatively, when the variable is
18305 // referenced in any of the following contexts:
18306 // - a non-function context
18307 // - a host function
18308 // - a host device function
18309 // This makes the ODR-use of the device side variable by host code to
18310 // be visible in the device compilation for the compiler to be able to
18311 // emit template variables instantiated by host code only and to
18312 // externalize the static device side variable ODR-used by host code.
18313 if (!Var->hasExternalStorage())
18315 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18316 (!FD || (!FD->getDescribedFunctionTemplate() &&
18320 }
18321 }
18322
18323 V->markUsed(SemaRef.Context);
18324}
18325
18328 unsigned CapturingScopeIndex) {
18329 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18330}
18331
18333 ValueDecl *var) {
18334 DeclContext *VarDC = var->getDeclContext();
18335
18336 // If the parameter still belongs to the translation unit, then
18337 // we're actually just using one parameter in the declaration of
18338 // the next.
18339 if (isa<ParmVarDecl>(var) &&
18340 isa<TranslationUnitDecl>(VarDC))
18341 return;
18342
18343 // For C code, don't diagnose about capture if we're not actually in code
18344 // right now; it's impossible to write a non-constant expression outside of
18345 // function context, so we'll get other (more useful) diagnostics later.
18346 //
18347 // For C++, things get a bit more nasty... it would be nice to suppress this
18348 // diagnostic for certain cases like using a local variable in an array bound
18349 // for a member of a local class, but the correct predicate is not obvious.
18350 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18351 return;
18352
18353 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18354 unsigned ContextKind = 3; // unknown
18355 if (isa<CXXMethodDecl>(VarDC) &&
18356 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18357 ContextKind = 2;
18358 } else if (isa<FunctionDecl>(VarDC)) {
18359 ContextKind = 0;
18360 } else if (isa<BlockDecl>(VarDC)) {
18361 ContextKind = 1;
18362 }
18363
18364 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18365 << var << ValueKind << ContextKind << VarDC;
18366 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18367 << var;
18368
18369 // FIXME: Add additional diagnostic info about class etc. which prevents
18370 // capture.
18371}
18372
18374 ValueDecl *Var,
18375 bool &SubCapturesAreNested,
18376 QualType &CaptureType,
18377 QualType &DeclRefType) {
18378 // Check whether we've already captured it.
18379 if (CSI->CaptureMap.count(Var)) {
18380 // If we found a capture, any subcaptures are nested.
18381 SubCapturesAreNested = true;
18382
18383 // Retrieve the capture type for this variable.
18384 CaptureType = CSI->getCapture(Var).getCaptureType();
18385
18386 // Compute the type of an expression that refers to this variable.
18387 DeclRefType = CaptureType.getNonReferenceType();
18388
18389 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18390 // are mutable in the sense that user can change their value - they are
18391 // private instances of the captured declarations.
18392 const Capture &Cap = CSI->getCapture(Var);
18393 if (Cap.isCopyCapture() &&
18394 !(isa<LambdaScopeInfo>(CSI) &&
18395 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18396 !(isa<CapturedRegionScopeInfo>(CSI) &&
18397 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18398 DeclRefType.addConst();
18399 return true;
18400 }
18401 return false;
18402}
18403
18404// Only block literals, captured statements, and lambda expressions can
18405// capture; other scopes don't work.
18407 ValueDecl *Var,
18409 const bool Diagnose,
18410 Sema &S) {
18411 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18413
18414 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18415 if (Underlying) {
18416 if (Underlying->hasLocalStorage() && Diagnose)
18418 }
18419 return nullptr;
18420}
18421
18422// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18423// certain types of variables (unnamed, variably modified types etc.)
18424// so check for eligibility.
18426 SourceLocation Loc, const bool Diagnose,
18427 Sema &S) {
18428
18429 assert((isa<VarDecl, BindingDecl>(Var)) &&
18430 "Only variables and structured bindings can be captured");
18431
18432 bool IsBlock = isa<BlockScopeInfo>(CSI);
18433 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18434
18435 // Lambdas are not allowed to capture unnamed variables
18436 // (e.g. anonymous unions).
18437 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18438 // assuming that's the intent.
18439 if (IsLambda && !Var->getDeclName()) {
18440 if (Diagnose) {
18441 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18442 S.Diag(Var->getLocation(), diag::note_declared_at);
18443 }
18444 return false;
18445 }
18446
18447 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18448 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18449 if (Diagnose) {
18450 S.Diag(Loc, diag::err_ref_vm_type);
18451 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18452 }
18453 return false;
18454 }
18455 // Prohibit structs with flexible array members too.
18456 // We cannot capture what is in the tail end of the struct.
18457 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18458 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18459 if (Diagnose) {
18460 if (IsBlock)
18461 S.Diag(Loc, diag::err_ref_flexarray_type);
18462 else
18463 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18464 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18465 }
18466 return false;
18467 }
18468 }
18469 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18470 // Lambdas and captured statements are not allowed to capture __block
18471 // variables; they don't support the expected semantics.
18472 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18473 if (Diagnose) {
18474 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18475 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18476 }
18477 return false;
18478 }
18479 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18480 if (S.getLangOpts().OpenCL && IsBlock &&
18481 Var->getType()->isBlockPointerType()) {
18482 if (Diagnose)
18483 S.Diag(Loc, diag::err_opencl_block_ref_block);
18484 return false;
18485 }
18486
18487 if (isa<BindingDecl>(Var)) {
18488 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18489 if (Diagnose)
18491 return false;
18492 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18493 S.Diag(Loc, S.LangOpts.CPlusPlus20
18494 ? diag::warn_cxx17_compat_capture_binding
18495 : diag::ext_capture_binding)
18496 << Var;
18497 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18498 }
18499 }
18500
18501 return true;
18502}
18503
18504// Returns true if the capture by block was successful.
18506 SourceLocation Loc, const bool BuildAndDiagnose,
18507 QualType &CaptureType, QualType &DeclRefType,
18508 const bool Nested, Sema &S, bool Invalid) {
18509 bool ByRef = false;
18510
18511 // Blocks are not allowed to capture arrays, excepting OpenCL.
18512 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18513 // (decayed to pointers).
18514 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18515 if (BuildAndDiagnose) {
18516 S.Diag(Loc, diag::err_ref_array_type);
18517 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18518 Invalid = true;
18519 } else {
18520 return false;
18521 }
18522 }
18523
18524 // Forbid the block-capture of autoreleasing variables.
18525 if (!Invalid &&
18527 if (BuildAndDiagnose) {
18528 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18529 << /*block*/ 0;
18530 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18531 Invalid = true;
18532 } else {
18533 return false;
18534 }
18535 }
18536
18537 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18538 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18539 QualType PointeeTy = PT->getPointeeType();
18540
18541 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18543 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18544 if (BuildAndDiagnose) {
18545 SourceLocation VarLoc = Var->getLocation();
18546 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18547 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18548 }
18549 }
18550 }
18551
18552 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18553 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18554 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18555 // Block capture by reference does not change the capture or
18556 // declaration reference types.
18557 ByRef = true;
18558 } else {
18559 // Block capture by copy introduces 'const'.
18560 CaptureType = CaptureType.getNonReferenceType().withConst();
18561 DeclRefType = CaptureType;
18562 }
18563
18564 // Actually capture the variable.
18565 if (BuildAndDiagnose)
18566 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18567 CaptureType, Invalid);
18568
18569 return !Invalid;
18570}
18571
18572/// Capture the given variable in the captured region.
18575 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18576 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18577 bool IsTopScope, Sema &S, bool Invalid) {
18578 // By default, capture variables by reference.
18579 bool ByRef = true;
18580 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18581 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18582 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18583 // Using an LValue reference type is consistent with Lambdas (see below).
18584 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18585 bool HasConst = DeclRefType.isConstQualified();
18586 DeclRefType = DeclRefType.getUnqualifiedType();
18587 // Don't lose diagnostics about assignments to const.
18588 if (HasConst)
18589 DeclRefType.addConst();
18590 }
18591 // Do not capture firstprivates in tasks.
18592 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18593 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18594 return true;
18595 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18596 RSI->OpenMPCaptureLevel);
18597 }
18598
18599 if (ByRef)
18600 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18601 else
18602 CaptureType = DeclRefType;
18603
18604 // Actually capture the variable.
18605 if (BuildAndDiagnose)
18606 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18607 Loc, SourceLocation(), CaptureType, Invalid);
18608
18609 return !Invalid;
18610}
18611
18612/// Capture the given variable in the lambda.
18614 SourceLocation Loc, const bool BuildAndDiagnose,
18615 QualType &CaptureType, QualType &DeclRefType,
18616 const bool RefersToCapturedVariable,
18617 const Sema::TryCaptureKind Kind,
18618 SourceLocation EllipsisLoc, const bool IsTopScope,
18619 Sema &S, bool Invalid) {
18620 // Determine whether we are capturing by reference or by value.
18621 bool ByRef = false;
18622 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18623 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18624 } else {
18625 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18626 }
18627
18628 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18630 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18631 Invalid = true;
18632 }
18633
18634 // Compute the type of the field that will capture this variable.
18635 if (ByRef) {
18636 // C++11 [expr.prim.lambda]p15:
18637 // An entity is captured by reference if it is implicitly or
18638 // explicitly captured but not captured by copy. It is
18639 // unspecified whether additional unnamed non-static data
18640 // members are declared in the closure type for entities
18641 // captured by reference.
18642 //
18643 // FIXME: It is not clear whether we want to build an lvalue reference
18644 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18645 // to do the former, while EDG does the latter. Core issue 1249 will
18646 // clarify, but for now we follow GCC because it's a more permissive and
18647 // easily defensible position.
18648 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18649 } else {
18650 // C++11 [expr.prim.lambda]p14:
18651 // For each entity captured by copy, an unnamed non-static
18652 // data member is declared in the closure type. The
18653 // declaration order of these members is unspecified. The type
18654 // of such a data member is the type of the corresponding
18655 // captured entity if the entity is not a reference to an
18656 // object, or the referenced type otherwise. [Note: If the
18657 // captured entity is a reference to a function, the
18658 // corresponding data member is also a reference to a
18659 // function. - end note ]
18660 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18661 if (!RefType->getPointeeType()->isFunctionType())
18662 CaptureType = RefType->getPointeeType();
18663 }
18664
18665 // Forbid the lambda copy-capture of autoreleasing variables.
18666 if (!Invalid &&
18668 if (BuildAndDiagnose) {
18669 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18670 S.Diag(Var->getLocation(), diag::note_previous_decl)
18671 << Var->getDeclName();
18672 Invalid = true;
18673 } else {
18674 return false;
18675 }
18676 }
18677
18678 // Make sure that by-copy captures are of a complete and non-abstract type.
18679 if (!Invalid && BuildAndDiagnose) {
18680 if (!CaptureType->isDependentType() &&
18682 Loc, CaptureType,
18683 diag::err_capture_of_incomplete_or_sizeless_type,
18684 Var->getDeclName()))
18685 Invalid = true;
18686 else if (S.RequireNonAbstractType(Loc, CaptureType,
18687 diag::err_capture_of_abstract_type))
18688 Invalid = true;
18689 }
18690 }
18691
18692 // Compute the type of a reference to this captured variable.
18693 if (ByRef)
18694 DeclRefType = CaptureType.getNonReferenceType();
18695 else {
18696 // C++ [expr.prim.lambda]p5:
18697 // The closure type for a lambda-expression has a public inline
18698 // function call operator [...]. This function call operator is
18699 // declared const (9.3.1) if and only if the lambda-expression's
18700 // parameter-declaration-clause is not followed by mutable.
18701 DeclRefType = CaptureType.getNonReferenceType();
18702 bool Const = LSI->lambdaCaptureShouldBeConst();
18703 if (Const && !CaptureType->isReferenceType())
18704 DeclRefType.addConst();
18705 }
18706
18707 // Add the capture.
18708 if (BuildAndDiagnose)
18709 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18710 Loc, EllipsisLoc, CaptureType, Invalid);
18711
18712 return !Invalid;
18713}
18714
18716 const ASTContext &Context) {
18717 // Offer a Copy fix even if the type is dependent.
18718 if (Var->getType()->isDependentType())
18719 return true;
18721 if (T.isTriviallyCopyableType(Context))
18722 return true;
18723 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18724
18725 if (!(RD = RD->getDefinition()))
18726 return false;
18727 if (RD->hasSimpleCopyConstructor())
18728 return true;
18729 if (RD->hasUserDeclaredCopyConstructor())
18730 for (CXXConstructorDecl *Ctor : RD->ctors())
18731 if (Ctor->isCopyConstructor())
18732 return !Ctor->isDeleted();
18733 }
18734 return false;
18735}
18736
18737/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18738/// default capture. Fixes may be omitted if they aren't allowed by the
18739/// standard, for example we can't emit a default copy capture fix-it if we
18740/// already explicitly copy capture capture another variable.
18742 ValueDecl *Var) {
18744 // Don't offer Capture by copy of default capture by copy fixes if Var is
18745 // known not to be copy constructible.
18746 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18747
18748 SmallString<32> FixBuffer;
18749 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18750 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18751 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18752 if (ShouldOfferCopyFix) {
18753 // Offer fixes to insert an explicit capture for the variable.
18754 // [] -> [VarName]
18755 // [OtherCapture] -> [OtherCapture, VarName]
18756 FixBuffer.assign({Separator, Var->getName()});
18757 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18758 << Var << /*value*/ 0
18759 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18760 }
18761 // As above but capture by reference.
18762 FixBuffer.assign({Separator, "&", Var->getName()});
18763 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18764 << Var << /*reference*/ 1
18765 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18766 }
18767
18768 // Only try to offer default capture if there are no captures excluding this
18769 // and init captures.
18770 // [this]: OK.
18771 // [X = Y]: OK.
18772 // [&A, &B]: Don't offer.
18773 // [A, B]: Don't offer.
18774 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18775 return !C.isThisCapture() && !C.isInitCapture();
18776 }))
18777 return;
18778
18779 // The default capture specifiers, '=' or '&', must appear first in the
18780 // capture body.
18781 SourceLocation DefaultInsertLoc =
18783
18784 if (ShouldOfferCopyFix) {
18785 bool CanDefaultCopyCapture = true;
18786 // [=, *this] OK since c++17
18787 // [=, this] OK since c++20
18788 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18789 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18791 : false;
18792 // We can't use default capture by copy if any captures already specified
18793 // capture by copy.
18794 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18795 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18796 })) {
18797 FixBuffer.assign({"=", Separator});
18798 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18799 << /*value*/ 0
18800 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18801 }
18802 }
18803
18804 // We can't use default capture by reference if any captures already specified
18805 // capture by reference.
18806 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18807 return !C.isInitCapture() && C.isReferenceCapture() &&
18808 !C.isThisCapture();
18809 })) {
18810 FixBuffer.assign({"&", Separator});
18811 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18812 << /*reference*/ 1
18813 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18814 }
18815}
18816
18818 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18819 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18820 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18821 // An init-capture is notionally from the context surrounding its
18822 // declaration, but its parent DC is the lambda class.
18823 DeclContext *VarDC = Var->getDeclContext();
18824 DeclContext *DC = CurContext;
18825
18826 // tryCaptureVariable is called every time a DeclRef is formed,
18827 // it can therefore have non-negigible impact on performances.
18828 // For local variables and when there is no capturing scope,
18829 // we can bailout early.
18830 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18831 return true;
18832
18833 const auto *VD = dyn_cast<VarDecl>(Var);
18834 if (VD) {
18835 if (VD->isInitCapture())
18836 VarDC = VarDC->getParent();
18837 } else {
18839 }
18840 assert(VD && "Cannot capture a null variable");
18841
18842 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18843 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18844 // We need to sync up the Declaration Context with the
18845 // FunctionScopeIndexToStopAt
18846 if (FunctionScopeIndexToStopAt) {
18847 unsigned FSIndex = FunctionScopes.size() - 1;
18848 while (FSIndex != MaxFunctionScopesIndex) {
18850 --FSIndex;
18851 }
18852 }
18853
18854 // Capture global variables if it is required to use private copy of this
18855 // variable.
18856 bool IsGlobal = !VD->hasLocalStorage();
18857 if (IsGlobal && !(LangOpts.OpenMP &&
18858 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18859 MaxFunctionScopesIndex)))
18860 return true;
18861
18862 if (isa<VarDecl>(Var))
18863 Var = cast<VarDecl>(Var->getCanonicalDecl());
18864
18865 // Walk up the stack to determine whether we can capture the variable,
18866 // performing the "simple" checks that don't depend on type. We stop when
18867 // we've either hit the declared scope of the variable or find an existing
18868 // capture of that variable. We start from the innermost capturing-entity
18869 // (the DC) and ensure that all intervening capturing-entities
18870 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18871 // declcontext can either capture the variable or have already captured
18872 // the variable.
18873 CaptureType = Var->getType();
18874 DeclRefType = CaptureType.getNonReferenceType();
18875 bool Nested = false;
18876 bool Explicit = (Kind != TryCapture_Implicit);
18877 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18878 do {
18879
18880 LambdaScopeInfo *LSI = nullptr;
18881 if (!FunctionScopes.empty())
18882 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18883 FunctionScopes[FunctionScopesIndex]);
18884
18885 bool IsInScopeDeclarationContext =
18886 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18887
18888 if (LSI && !LSI->AfterParameterList) {
18889 // This allows capturing parameters from a default value which does not
18890 // seems correct
18891 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18892 return true;
18893 }
18894 // If the variable is declared in the current context, there is no need to
18895 // capture it.
18896 if (IsInScopeDeclarationContext &&
18897 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18898 return true;
18899
18900 // Only block literals, captured statements, and lambda expressions can
18901 // capture; other scopes don't work.
18902 DeclContext *ParentDC =
18903 !IsInScopeDeclarationContext
18904 ? DC->getParent()
18905 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18906 BuildAndDiagnose, *this);
18907 // We need to check for the parent *first* because, if we *have*
18908 // private-captured a global variable, we need to recursively capture it in
18909 // intermediate blocks, lambdas, etc.
18910 if (!ParentDC) {
18911 if (IsGlobal) {
18912 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18913 break;
18914 }
18915 return true;
18916 }
18917
18918 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18919 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18920
18921 // Check whether we've already captured it.
18922 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18923 DeclRefType)) {
18924 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18925 break;
18926 }
18927
18928 // When evaluating some attributes (like enable_if) we might refer to a
18929 // function parameter appertaining to the same declaration as that
18930 // attribute.
18931 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18932 Parm && Parm->getDeclContext() == DC)
18933 return true;
18934
18935 // If we are instantiating a generic lambda call operator body,
18936 // we do not want to capture new variables. What was captured
18937 // during either a lambdas transformation or initial parsing
18938 // should be used.
18940 if (BuildAndDiagnose) {
18941 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18943 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18944 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18945 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18946 buildLambdaCaptureFixit(*this, LSI, Var);
18947 } else
18949 }
18950 return true;
18951 }
18952
18953 // Try to capture variable-length arrays types.
18954 if (Var->getType()->isVariablyModifiedType()) {
18955 // We're going to walk down into the type and look for VLA
18956 // expressions.
18957 QualType QTy = Var->getType();
18958 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18959 QTy = PVD->getOriginalType();
18961 }
18962
18963 if (getLangOpts().OpenMP) {
18964 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18965 // OpenMP private variables should not be captured in outer scope, so
18966 // just break here. Similarly, global variables that are captured in a
18967 // target region should not be captured outside the scope of the region.
18968 if (RSI->CapRegionKind == CR_OpenMP) {
18969 // FIXME: We should support capturing structured bindings in OpenMP.
18970 if (isa<BindingDecl>(Var)) {
18971 if (BuildAndDiagnose) {
18972 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18973 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18974 }
18975 return true;
18976 }
18977 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18978 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18979 // If the variable is private (i.e. not captured) and has variably
18980 // modified type, we still need to capture the type for correct
18981 // codegen in all regions, associated with the construct. Currently,
18982 // it is captured in the innermost captured region only.
18983 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18984 Var->getType()->isVariablyModifiedType()) {
18985 QualType QTy = Var->getType();
18986 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18987 QTy = PVD->getOriginalType();
18988 for (int I = 1,
18989 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
18990 I < E; ++I) {
18991 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18992 FunctionScopes[FunctionScopesIndex - I]);
18993 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18994 "Wrong number of captured regions associated with the "
18995 "OpenMP construct.");
18996 captureVariablyModifiedType(Context, QTy, OuterRSI);
18997 }
18998 }
18999 bool IsTargetCap =
19000 IsOpenMPPrivateDecl != OMPC_private &&
19001 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19002 RSI->OpenMPCaptureLevel);
19003 // Do not capture global if it is not privatized in outer regions.
19004 bool IsGlobalCap =
19005 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19006 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19007
19008 // When we detect target captures we are looking from inside the
19009 // target region, therefore we need to propagate the capture from the
19010 // enclosing region. Therefore, the capture is not initially nested.
19011 if (IsTargetCap)
19012 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19013 RSI->OpenMPLevel);
19014
19015 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19016 (IsGlobal && !IsGlobalCap)) {
19017 Nested = !IsTargetCap;
19018 bool HasConst = DeclRefType.isConstQualified();
19019 DeclRefType = DeclRefType.getUnqualifiedType();
19020 // Don't lose diagnostics about assignments to const.
19021 if (HasConst)
19022 DeclRefType.addConst();
19023 CaptureType = Context.getLValueReferenceType(DeclRefType);
19024 break;
19025 }
19026 }
19027 }
19028 }
19029 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19030 // No capture-default, and this is not an explicit capture
19031 // so cannot capture this variable.
19032 if (BuildAndDiagnose) {
19033 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19034 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19035 auto *LSI = cast<LambdaScopeInfo>(CSI);
19036 if (LSI->Lambda) {
19037 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19038 buildLambdaCaptureFixit(*this, LSI, Var);
19039 }
19040 // FIXME: If we error out because an outer lambda can not implicitly
19041 // capture a variable that an inner lambda explicitly captures, we
19042 // should have the inner lambda do the explicit capture - because
19043 // it makes for cleaner diagnostics later. This would purely be done
19044 // so that the diagnostic does not misleadingly claim that a variable
19045 // can not be captured by a lambda implicitly even though it is captured
19046 // explicitly. Suggestion:
19047 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19048 // at the function head
19049 // - cache the StartingDeclContext - this must be a lambda
19050 // - captureInLambda in the innermost lambda the variable.
19051 }
19052 return true;
19053 }
19054 Explicit = false;
19055 FunctionScopesIndex--;
19056 if (IsInScopeDeclarationContext)
19057 DC = ParentDC;
19058 } while (!VarDC->Equals(DC));
19059
19060 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19061 // computing the type of the capture at each step, checking type-specific
19062 // requirements, and adding captures if requested.
19063 // If the variable had already been captured previously, we start capturing
19064 // at the lambda nested within that one.
19065 bool Invalid = false;
19066 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19067 ++I) {
19068 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19069
19070 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19071 // certain types of variables (unnamed, variably modified types etc.)
19072 // so check for eligibility.
19073 if (!Invalid)
19074 Invalid =
19075 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19076
19077 // After encountering an error, if we're actually supposed to capture, keep
19078 // capturing in nested contexts to suppress any follow-on diagnostics.
19079 if (Invalid && !BuildAndDiagnose)
19080 return true;
19081
19082 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19083 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19084 DeclRefType, Nested, *this, Invalid);
19085 Nested = true;
19086 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19088 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19089 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19090 Nested = true;
19091 } else {
19092 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19093 Invalid =
19094 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19095 DeclRefType, Nested, Kind, EllipsisLoc,
19096 /*IsTopScope*/ I == N - 1, *this, Invalid);
19097 Nested = true;
19098 }
19099
19100 if (Invalid && !BuildAndDiagnose)
19101 return true;
19102 }
19103 return Invalid;
19104}
19105
19107 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19108 QualType CaptureType;
19109 QualType DeclRefType;
19110 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19111 /*BuildAndDiagnose=*/true, CaptureType,
19112 DeclRefType, nullptr);
19113}
19114
19116 QualType CaptureType;
19117 QualType DeclRefType;
19119 /*BuildAndDiagnose=*/false, CaptureType,
19120 DeclRefType, nullptr);
19121}
19122
19124 QualType CaptureType;
19125 QualType DeclRefType;
19126
19127 // Determine whether we can capture this variable.
19129 /*BuildAndDiagnose=*/false, CaptureType,
19130 DeclRefType, nullptr))
19131 return QualType();
19132
19133 return DeclRefType;
19134}
19135
19136namespace {
19137// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19138// The produced TemplateArgumentListInfo* points to data stored within this
19139// object, so should only be used in contexts where the pointer will not be
19140// used after the CopiedTemplateArgs object is destroyed.
19141class CopiedTemplateArgs {
19142 bool HasArgs;
19143 TemplateArgumentListInfo TemplateArgStorage;
19144public:
19145 template<typename RefExpr>
19146 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19147 if (HasArgs)
19148 E->copyTemplateArgumentsInto(TemplateArgStorage);
19149 }
19150 operator TemplateArgumentListInfo*()
19151#ifdef __has_cpp_attribute
19152#if __has_cpp_attribute(clang::lifetimebound)
19153 [[clang::lifetimebound]]
19154#endif
19155#endif
19156 {
19157 return HasArgs ? &TemplateArgStorage : nullptr;
19158 }
19159};
19160}
19161
19162/// Walk the set of potential results of an expression and mark them all as
19163/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19164///
19165/// \return A new expression if we found any potential results, ExprEmpty() if
19166/// not, and ExprError() if we diagnosed an error.
19168 NonOdrUseReason NOUR) {
19169 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19170 // an object that satisfies the requirements for appearing in a
19171 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19172 // is immediately applied." This function handles the lvalue-to-rvalue
19173 // conversion part.
19174 //
19175 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19176 // transform it into the relevant kind of non-odr-use node and rebuild the
19177 // tree of nodes leading to it.
19178 //
19179 // This is a mini-TreeTransform that only transforms a restricted subset of
19180 // nodes (and only certain operands of them).
19181
19182 // Rebuild a subexpression.
19183 auto Rebuild = [&](Expr *Sub) {
19184 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19185 };
19186
19187 // Check whether a potential result satisfies the requirements of NOUR.
19188 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19189 // Any entity other than a VarDecl is always odr-used whenever it's named
19190 // in a potentially-evaluated expression.
19191 auto *VD = dyn_cast<VarDecl>(D);
19192 if (!VD)
19193 return true;
19194
19195 // C++2a [basic.def.odr]p4:
19196 // A variable x whose name appears as a potentially-evalauted expression
19197 // e is odr-used by e unless
19198 // -- x is a reference that is usable in constant expressions, or
19199 // -- x is a variable of non-reference type that is usable in constant
19200 // expressions and has no mutable subobjects, and e is an element of
19201 // the set of potential results of an expression of
19202 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19203 // conversion is applied, or
19204 // -- x is a variable of non-reference type, and e is an element of the
19205 // set of potential results of a discarded-value expression to which
19206 // the lvalue-to-rvalue conversion is not applied
19207 //
19208 // We check the first bullet and the "potentially-evaluated" condition in
19209 // BuildDeclRefExpr. We check the type requirements in the second bullet
19210 // in CheckLValueToRValueConversionOperand below.
19211 switch (NOUR) {
19212 case NOUR_None:
19213 case NOUR_Unevaluated:
19214 llvm_unreachable("unexpected non-odr-use-reason");
19215
19216 case NOUR_Constant:
19217 // Constant references were handled when they were built.
19218 if (VD->getType()->isReferenceType())
19219 return true;
19220 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19221 if (RD->hasMutableFields())
19222 return true;
19223 if (!VD->isUsableInConstantExpressions(S.Context))
19224 return true;
19225 break;
19226
19227 case NOUR_Discarded:
19228 if (VD->getType()->isReferenceType())
19229 return true;
19230 break;
19231 }
19232 return false;
19233 };
19234
19235 // Mark that this expression does not constitute an odr-use.
19236 auto MarkNotOdrUsed = [&] {
19237 S.MaybeODRUseExprs.remove(E);
19238 if (LambdaScopeInfo *LSI = S.getCurLambda())
19239 LSI->markVariableExprAsNonODRUsed(E);
19240 };
19241
19242 // C++2a [basic.def.odr]p2:
19243 // The set of potential results of an expression e is defined as follows:
19244 switch (E->getStmtClass()) {
19245 // -- If e is an id-expression, ...
19246 case Expr::DeclRefExprClass: {
19247 auto *DRE = cast<DeclRefExpr>(E);
19248 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19249 break;
19250
19251 // Rebuild as a non-odr-use DeclRefExpr.
19252 MarkNotOdrUsed();
19253 return DeclRefExpr::Create(
19254 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19255 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19256 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19257 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19258 }
19259
19260 case Expr::FunctionParmPackExprClass: {
19261 auto *FPPE = cast<FunctionParmPackExpr>(E);
19262 // If any of the declarations in the pack is odr-used, then the expression
19263 // as a whole constitutes an odr-use.
19264 for (VarDecl *D : *FPPE)
19265 if (IsPotentialResultOdrUsed(D))
19266 return ExprEmpty();
19267
19268 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19269 // nothing cares about whether we marked this as an odr-use, but it might
19270 // be useful for non-compiler tools.
19271 MarkNotOdrUsed();
19272 break;
19273 }
19274
19275 // -- If e is a subscripting operation with an array operand...
19276 case Expr::ArraySubscriptExprClass: {
19277 auto *ASE = cast<ArraySubscriptExpr>(E);
19278 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19279 if (!OldBase->getType()->isArrayType())
19280 break;
19281 ExprResult Base = Rebuild(OldBase);
19282 if (!Base.isUsable())
19283 return Base;
19284 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19285 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19286 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19287 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19288 ASE->getRBracketLoc());
19289 }
19290
19291 case Expr::MemberExprClass: {
19292 auto *ME = cast<MemberExpr>(E);
19293 // -- If e is a class member access expression [...] naming a non-static
19294 // data member...
19295 if (isa<FieldDecl>(ME->getMemberDecl())) {
19296 ExprResult Base = Rebuild(ME->getBase());
19297 if (!Base.isUsable())
19298 return Base;
19299 return MemberExpr::Create(
19300 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19301 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19302 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19303 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19304 ME->getObjectKind(), ME->isNonOdrUse());
19305 }
19306
19307 if (ME->getMemberDecl()->isCXXInstanceMember())
19308 break;
19309
19310 // -- If e is a class member access expression naming a static data member,
19311 // ...
19312 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19313 break;
19314
19315 // Rebuild as a non-odr-use MemberExpr.
19316 MarkNotOdrUsed();
19317 return MemberExpr::Create(
19318 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19319 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19320 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19321 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19322 }
19323
19324 case Expr::BinaryOperatorClass: {
19325 auto *BO = cast<BinaryOperator>(E);
19326 Expr *LHS = BO->getLHS();
19327 Expr *RHS = BO->getRHS();
19328 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19329 if (BO->getOpcode() == BO_PtrMemD) {
19330 ExprResult Sub = Rebuild(LHS);
19331 if (!Sub.isUsable())
19332 return Sub;
19333 BO->setLHS(Sub.get());
19334 // -- If e is a comma expression, ...
19335 } else if (BO->getOpcode() == BO_Comma) {
19336 ExprResult Sub = Rebuild(RHS);
19337 if (!Sub.isUsable())
19338 return Sub;
19339 BO->setRHS(Sub.get());
19340 } else {
19341 break;
19342 }
19343 return ExprResult(BO);
19344 }
19345
19346 // -- If e has the form (e1)...
19347 case Expr::ParenExprClass: {
19348 auto *PE = cast<ParenExpr>(E);
19349 ExprResult Sub = Rebuild(PE->getSubExpr());
19350 if (!Sub.isUsable())
19351 return Sub;
19352 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19353 }
19354
19355 // -- If e is a glvalue conditional expression, ...
19356 // We don't apply this to a binary conditional operator. FIXME: Should we?
19357 case Expr::ConditionalOperatorClass: {
19358 auto *CO = cast<ConditionalOperator>(E);
19359 ExprResult LHS = Rebuild(CO->getLHS());
19360 if (LHS.isInvalid())
19361 return ExprError();
19362 ExprResult RHS = Rebuild(CO->getRHS());
19363 if (RHS.isInvalid())
19364 return ExprError();
19365 if (!LHS.isUsable() && !RHS.isUsable())
19366 return ExprEmpty();
19367 if (!LHS.isUsable())
19368 LHS = CO->getLHS();
19369 if (!RHS.isUsable())
19370 RHS = CO->getRHS();
19371 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19372 CO->getCond(), LHS.get(), RHS.get());
19373 }
19374
19375 // [Clang extension]
19376 // -- If e has the form __extension__ e1...
19377 case Expr::UnaryOperatorClass: {
19378 auto *UO = cast<UnaryOperator>(E);
19379 if (UO->getOpcode() != UO_Extension)
19380 break;
19381 ExprResult Sub = Rebuild(UO->getSubExpr());
19382 if (!Sub.isUsable())
19383 return Sub;
19384 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19385 Sub.get());
19386 }
19387
19388 // [Clang extension]
19389 // -- If e has the form _Generic(...), the set of potential results is the
19390 // union of the sets of potential results of the associated expressions.
19391 case Expr::GenericSelectionExprClass: {
19392 auto *GSE = cast<GenericSelectionExpr>(E);
19393
19394 SmallVector<Expr *, 4> AssocExprs;
19395 bool AnyChanged = false;
19396 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19397 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19398 if (AssocExpr.isInvalid())
19399 return ExprError();
19400 if (AssocExpr.isUsable()) {
19401 AssocExprs.push_back(AssocExpr.get());
19402 AnyChanged = true;
19403 } else {
19404 AssocExprs.push_back(OrigAssocExpr);
19405 }
19406 }
19407
19408 void *ExOrTy = nullptr;
19409 bool IsExpr = GSE->isExprPredicate();
19410 if (IsExpr)
19411 ExOrTy = GSE->getControllingExpr();
19412 else
19413 ExOrTy = GSE->getControllingType();
19414 return AnyChanged ? S.CreateGenericSelectionExpr(
19415 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19416 GSE->getRParenLoc(), IsExpr, ExOrTy,
19417 GSE->getAssocTypeSourceInfos(), AssocExprs)
19418 : ExprEmpty();
19419 }
19420
19421 // [Clang extension]
19422 // -- If e has the form __builtin_choose_expr(...), the set of potential
19423 // results is the union of the sets of potential results of the
19424 // second and third subexpressions.
19425 case Expr::ChooseExprClass: {
19426 auto *CE = cast<ChooseExpr>(E);
19427
19428 ExprResult LHS = Rebuild(CE->getLHS());
19429 if (LHS.isInvalid())
19430 return ExprError();
19431
19432 ExprResult RHS = Rebuild(CE->getLHS());
19433 if (RHS.isInvalid())
19434 return ExprError();
19435
19436 if (!LHS.get() && !RHS.get())
19437 return ExprEmpty();
19438 if (!LHS.isUsable())
19439 LHS = CE->getLHS();
19440 if (!RHS.isUsable())
19441 RHS = CE->getRHS();
19442
19443 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19444 RHS.get(), CE->getRParenLoc());
19445 }
19446
19447 // Step through non-syntactic nodes.
19448 case Expr::ConstantExprClass: {
19449 auto *CE = cast<ConstantExpr>(E);
19450 ExprResult Sub = Rebuild(CE->getSubExpr());
19451 if (!Sub.isUsable())
19452 return Sub;
19453 return ConstantExpr::Create(S.Context, Sub.get());
19454 }
19455
19456 // We could mostly rely on the recursive rebuilding to rebuild implicit
19457 // casts, but not at the top level, so rebuild them here.
19458 case Expr::ImplicitCastExprClass: {
19459 auto *ICE = cast<ImplicitCastExpr>(E);
19460 // Only step through the narrow set of cast kinds we expect to encounter.
19461 // Anything else suggests we've left the region in which potential results
19462 // can be found.
19463 switch (ICE->getCastKind()) {
19464 case CK_NoOp:
19465 case CK_DerivedToBase:
19466 case CK_UncheckedDerivedToBase: {
19467 ExprResult Sub = Rebuild(ICE->getSubExpr());
19468 if (!Sub.isUsable())
19469 return Sub;
19470 CXXCastPath Path(ICE->path());
19471 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19472 ICE->getValueKind(), &Path);
19473 }
19474
19475 default:
19476 break;
19477 }
19478 break;
19479 }
19480
19481 default:
19482 break;
19483 }
19484
19485 // Can't traverse through this node. Nothing to do.
19486 return ExprEmpty();
19487}
19488
19490 // Check whether the operand is or contains an object of non-trivial C union
19491 // type.
19492 if (E->getType().isVolatileQualified() &&
19498
19499 // C++2a [basic.def.odr]p4:
19500 // [...] an expression of non-volatile-qualified non-class type to which
19501 // the lvalue-to-rvalue conversion is applied [...]
19502 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19503 return E;
19504
19507 if (Result.isInvalid())
19508 return ExprError();
19509 return Result.get() ? Result : E;
19510}
19511
19513 Res = CorrectDelayedTyposInExpr(Res);
19514
19515 if (!Res.isUsable())
19516 return Res;
19517
19518 // If a constant-expression is a reference to a variable where we delay
19519 // deciding whether it is an odr-use, just assume we will apply the
19520 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19521 // (a non-type template argument), we have special handling anyway.
19523}
19524
19526 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19527 // call.
19528 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19529 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19530
19531 for (Expr *E : LocalMaybeODRUseExprs) {
19532 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19533 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19534 DRE->getLocation(), *this);
19535 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19536 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19537 *this);
19538 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19539 for (VarDecl *VD : *FP)
19540 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19541 } else {
19542 llvm_unreachable("Unexpected expression");
19543 }
19544 }
19545
19546 assert(MaybeODRUseExprs.empty() &&
19547 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19548}
19549
19551 ValueDecl *Var, Expr *E) {
19553 if (!VD)
19554 return;
19555
19556 const bool RefersToEnclosingScope =
19557 (SemaRef.CurContext != VD->getDeclContext() &&
19559 if (RefersToEnclosingScope) {
19560 LambdaScopeInfo *const LSI =
19561 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19562 if (LSI && (!LSI->CallOperator ||
19563 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19564 // If a variable could potentially be odr-used, defer marking it so
19565 // until we finish analyzing the full expression for any
19566 // lvalue-to-rvalue
19567 // or discarded value conversions that would obviate odr-use.
19568 // Add it to the list of potential captures that will be analyzed
19569 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19570 // unless the variable is a reference that was initialized by a constant
19571 // expression (this will never need to be captured or odr-used).
19572 //
19573 // FIXME: We can simplify this a lot after implementing P0588R1.
19574 assert(E && "Capture variable should be used in an expression.");
19575 if (!Var->getType()->isReferenceType() ||
19578 }
19579 }
19580}
19581
19584 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19585 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19586 isa<FunctionParmPackExpr>(E)) &&
19587 "Invalid Expr argument to DoMarkVarDeclReferenced");
19588 Var->setReferenced();
19589
19590 if (Var->isInvalidDecl())
19591 return;
19592
19593 auto *MSI = Var->getMemberSpecializationInfo();
19596
19597 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19598 bool UsableInConstantExpr =
19600
19601 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19602 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19603 }
19604
19605 // C++20 [expr.const]p12:
19606 // A variable [...] is needed for constant evaluation if it is [...] a
19607 // variable whose name appears as a potentially constant evaluated
19608 // expression that is either a contexpr variable or is of non-volatile
19609 // const-qualified integral type or of reference type
19610 bool NeededForConstantEvaluation =
19611 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19612
19613 bool NeedDefinition =
19614 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19615
19616 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19617 "Can't instantiate a partial template specialization.");
19618
19619 // If this might be a member specialization of a static data member, check
19620 // the specialization is visible. We already did the checks for variable
19621 // template specializations when we created them.
19622 if (NeedDefinition && TSK != TSK_Undeclared &&
19623 !isa<VarTemplateSpecializationDecl>(Var))
19625
19626 // Perform implicit instantiation of static data members, static data member
19627 // templates of class templates, and variable template specializations. Delay
19628 // instantiations of variable templates, except for those that could be used
19629 // in a constant expression.
19630 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19631 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19632 // instantiation declaration if a variable is usable in a constant
19633 // expression (among other cases).
19634 bool TryInstantiating =
19636 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19637
19638 if (TryInstantiating) {
19639 SourceLocation PointOfInstantiation =
19640 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19641 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19642 if (FirstInstantiation) {
19643 PointOfInstantiation = Loc;
19644 if (MSI)
19645 MSI->setPointOfInstantiation(PointOfInstantiation);
19646 // FIXME: Notify listener.
19647 else
19648 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19649 }
19650
19651 if (UsableInConstantExpr) {
19652 // Do not defer instantiations of variables that could be used in a
19653 // constant expression.
19654 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19655 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19656 });
19657
19658 // Re-set the member to trigger a recomputation of the dependence bits
19659 // for the expression.
19660 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19661 DRE->setDecl(DRE->getDecl());
19662 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19663 ME->setMemberDecl(ME->getMemberDecl());
19664 } else if (FirstInstantiation) {
19666 .push_back(std::make_pair(Var, PointOfInstantiation));
19667 } else {
19668 bool Inserted = false;
19669 for (auto &I : SemaRef.SavedPendingInstantiations) {
19670 auto Iter = llvm::find_if(
19671 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19672 return P.first == Var;
19673 });
19674 if (Iter != I.end()) {
19676 I.erase(Iter);
19677 Inserted = true;
19678 break;
19679 }
19680 }
19681
19682 // FIXME: For a specialization of a variable template, we don't
19683 // distinguish between "declaration and type implicitly instantiated"
19684 // and "implicit instantiation of definition requested", so we have
19685 // no direct way to avoid enqueueing the pending instantiation
19686 // multiple times.
19687 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19689 .push_back(std::make_pair(Var, PointOfInstantiation));
19690 }
19691 }
19692 }
19693
19694 // C++2a [basic.def.odr]p4:
19695 // A variable x whose name appears as a potentially-evaluated expression e
19696 // is odr-used by e unless
19697 // -- x is a reference that is usable in constant expressions
19698 // -- x is a variable of non-reference type that is usable in constant
19699 // expressions and has no mutable subobjects [FIXME], and e is an
19700 // element of the set of potential results of an expression of
19701 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19702 // conversion is applied
19703 // -- x is a variable of non-reference type, and e is an element of the set
19704 // of potential results of a discarded-value expression to which the
19705 // lvalue-to-rvalue conversion is not applied [FIXME]
19706 //
19707 // We check the first part of the second bullet here, and
19708 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19709 // FIXME: To get the third bullet right, we need to delay this even for
19710 // variables that are not usable in constant expressions.
19711
19712 // If we already know this isn't an odr-use, there's nothing more to do.
19713 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19714 if (DRE->isNonOdrUse())
19715 return;
19716 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19717 if (ME->isNonOdrUse())
19718 return;
19719
19720 switch (OdrUse) {
19721 case OdrUseContext::None:
19722 // In some cases, a variable may not have been marked unevaluated, if it
19723 // appears in a defaukt initializer.
19724 assert((!E || isa<FunctionParmPackExpr>(E) ||
19726 "missing non-odr-use marking for unevaluated decl ref");
19727 break;
19728
19729 case OdrUseContext::FormallyOdrUsed:
19730 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19731 // behavior.
19732 break;
19733
19734 case OdrUseContext::Used:
19735 // If we might later find that this expression isn't actually an odr-use,
19736 // delay the marking.
19738 SemaRef.MaybeODRUseExprs.insert(E);
19739 else
19741 break;
19742
19743 case OdrUseContext::Dependent:
19744 // If this is a dependent context, we don't need to mark variables as
19745 // odr-used, but we may still need to track them for lambda capture.
19746 // FIXME: Do we also need to do this inside dependent typeid expressions
19747 // (which are modeled as unevaluated at this point)?
19749 break;
19750 }
19751}
19752
19754 BindingDecl *BD, Expr *E) {
19755 BD->setReferenced();
19756
19757 if (BD->isInvalidDecl())
19758 return;
19759
19760 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19761 if (OdrUse == OdrUseContext::Used) {
19762 QualType CaptureType, DeclRefType;
19764 /*EllipsisLoc*/ SourceLocation(),
19765 /*BuildAndDiagnose*/ true, CaptureType,
19766 DeclRefType,
19767 /*FunctionScopeIndexToStopAt*/ nullptr);
19768 } else if (OdrUse == OdrUseContext::Dependent) {
19770 }
19771}
19772
19773/// Mark a variable referenced, and check whether it is odr-used
19774/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19775/// used directly for normal expressions referring to VarDecl.
19777 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19778}
19779
19780// C++ [temp.dep.expr]p3:
19781// An id-expression is type-dependent if it contains:
19782// - an identifier associated by name lookup with an entity captured by copy
19783// in a lambda-expression that has an explicit object parameter whose type
19784// is dependent ([dcl.fct]),
19786 Sema &SemaRef, ValueDecl *D, Expr *E) {
19787 auto *ID = dyn_cast<DeclRefExpr>(E);
19788 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19789 return;
19790
19791 // If any enclosing lambda with a dependent explicit object parameter either
19792 // explicitly captures the variable by value, or has a capture default of '='
19793 // and does not capture the variable by reference, then the type of the DRE
19794 // is dependent on the type of that lambda's explicit object parameter.
19795 auto IsDependent = [&]() {
19796 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19797 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19798 if (!LSI)
19799 continue;
19800
19801 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19802 LSI->AfterParameterList)
19803 return false;
19804
19805 const auto *MD = LSI->CallOperator;
19806 if (MD->getType().isNull())
19807 continue;
19808
19809 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19810 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19811 !Ty->getParamType(0)->isDependentType())
19812 continue;
19813
19814 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19815 if (C->isCopyCapture())
19816 return true;
19817 continue;
19818 }
19819
19820 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19821 return true;
19822 }
19823 return false;
19824 }();
19825
19826 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19827 IsDependent, SemaRef.getASTContext());
19828}
19829
19830static void
19832 bool MightBeOdrUse,
19833 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19836
19837 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19839 if (SemaRef.getLangOpts().CPlusPlus)
19841 Var, E);
19842 return;
19843 }
19844
19845 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19847 if (SemaRef.getLangOpts().CPlusPlus)
19849 Decl, E);
19850 return;
19851 }
19852 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19853
19854 // If this is a call to a method via a cast, also mark the method in the
19855 // derived class used in case codegen can devirtualize the call.
19856 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19857 if (!ME)
19858 return;
19859 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19860 if (!MD)
19861 return;
19862 // Only attempt to devirtualize if this is truly a virtual call.
19863 bool IsVirtualCall = MD->isVirtual() &&
19865 if (!IsVirtualCall)
19866 return;
19867
19868 // If it's possible to devirtualize the call, mark the called function
19869 // referenced.
19871 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19872 if (DM)
19873 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19874}
19875
19876/// Perform reference-marking and odr-use handling for a DeclRefExpr.
19877///
19878/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19879/// handled with care if the DeclRefExpr is not newly-created.
19881 // TODO: update this with DR# once a defect report is filed.
19882 // C++11 defect. The address of a pure member should not be an ODR use, even
19883 // if it's a qualified reference.
19884 bool OdrUse = true;
19885 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19886 if (Method->isVirtual() &&
19887 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19888 OdrUse = false;
19889
19890 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19894 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19895 !FD->isDependentContext())
19896 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19897 }
19898 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19900}
19901
19902/// Perform reference-marking and odr-use handling for a MemberExpr.
19904 // C++11 [basic.def.odr]p2:
19905 // A non-overloaded function whose name appears as a potentially-evaluated
19906 // expression or a member of a set of candidate functions, if selected by
19907 // overload resolution when referred to from a potentially-evaluated
19908 // expression, is odr-used, unless it is a pure virtual function and its
19909 // name is not explicitly qualified.
19910 bool MightBeOdrUse = true;
19912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19913 if (Method->isPureVirtual())
19914 MightBeOdrUse = false;
19915 }
19917 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19918 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19920}
19921
19922/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19924 for (VarDecl *VD : *E)
19925 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19927}
19928
19929/// Perform marking for a reference to an arbitrary declaration. It
19930/// marks the declaration referenced, and performs odr-use checking for
19931/// functions and variables. This method should not be used when building a
19932/// normal expression which refers to a variable.
19934 bool MightBeOdrUse) {
19935 if (MightBeOdrUse) {
19936 if (auto *VD = dyn_cast<VarDecl>(D)) {
19938 return;
19939 }
19940 }
19941 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19942 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19943 return;
19944 }
19945 D->setReferenced();
19946}
19947
19948namespace {
19949 // Mark all of the declarations used by a type as referenced.
19950 // FIXME: Not fully implemented yet! We need to have a better understanding
19951 // of when we're entering a context we should not recurse into.
19952 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19953 // TreeTransforms rebuilding the type in a new context. Rather than
19954 // duplicating the TreeTransform logic, we should consider reusing it here.
19955 // Currently that causes problems when rebuilding LambdaExprs.
19956 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19957 Sema &S;
19959
19960 public:
19962
19963 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19964
19965 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19966 };
19967}
19968
19969bool MarkReferencedDecls::TraverseTemplateArgument(
19970 const TemplateArgument &Arg) {
19971 {
19972 // A non-type template argument is a constant-evaluated context.
19976 if (Decl *D = Arg.getAsDecl())
19977 S.MarkAnyDeclReferenced(Loc, D, true);
19978 } else if (Arg.getKind() == TemplateArgument::Expression) {
19980 }
19981 }
19982
19983 return Inherited::TraverseTemplateArgument(Arg);
19984}
19985
19987 MarkReferencedDecls Marker(*this, Loc);
19988 Marker.TraverseType(T);
19989}
19990
19991namespace {
19992/// Helper class that marks all of the declarations referenced by
19993/// potentially-evaluated subexpressions as "referenced".
19994class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19995public:
19996 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19997 bool SkipLocalVariables;
19999
20000 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20002 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20003
20004 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20005 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20006 }
20007
20008 void Visit(Expr *E) {
20009 if (llvm::is_contained(StopAt, E))
20010 return;
20011 Inherited::Visit(E);
20012 }
20013
20014 void VisitConstantExpr(ConstantExpr *E) {
20015 // Don't mark declarations within a ConstantExpression, as this expression
20016 // will be evaluated and folded to a value.
20017 }
20018
20019 void VisitDeclRefExpr(DeclRefExpr *E) {
20020 // If we were asked not to visit local variables, don't.
20021 if (SkipLocalVariables) {
20022 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20023 if (VD->hasLocalStorage())
20024 return;
20025 }
20026
20027 // FIXME: This can trigger the instantiation of the initializer of a
20028 // variable, which can cause the expression to become value-dependent
20029 // or error-dependent. Do we need to propagate the new dependence bits?
20031 }
20032
20033 void VisitMemberExpr(MemberExpr *E) {
20035 Visit(E->getBase());
20036 }
20037};
20038} // namespace
20039
20040/// Mark any declarations that appear within this expression or any
20041/// potentially-evaluated subexpressions as "referenced".
20042///
20043/// \param SkipLocalVariables If true, don't mark local variables as
20044/// 'referenced'.
20045/// \param StopAt Subexpressions that we shouldn't recurse into.
20047 bool SkipLocalVariables,
20048 ArrayRef<const Expr*> StopAt) {
20049 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20050}
20051
20052/// Emit a diagnostic when statements are reachable.
20053/// FIXME: check for reachability even in expressions for which we don't build a
20054/// CFG (eg, in the initializer of a global or in a constant expression).
20055/// For example,
20056/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20058 const PartialDiagnostic &PD) {
20059 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20060 if (!FunctionScopes.empty())
20061 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20063 return true;
20064 }
20065
20066 // The initializer of a constexpr variable or of the first declaration of a
20067 // static data member is not syntactically a constant evaluated constant,
20068 // but nonetheless is always required to be a constant expression, so we
20069 // can skip diagnosing.
20070 // FIXME: Using the mangling context here is a hack.
20071 if (auto *VD = dyn_cast_or_null<VarDecl>(
20072 ExprEvalContexts.back().ManglingContextDecl)) {
20073 if (VD->isConstexpr() ||
20074 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20075 return false;
20076 // FIXME: For any other kind of variable, we should build a CFG for its
20077 // initializer and check whether the context in question is reachable.
20078 }
20079
20080 Diag(Loc, PD);
20081 return true;
20082}
20083
20084/// Emit a diagnostic that describes an effect on the run-time behavior
20085/// of the program being compiled.
20086///
20087/// This routine emits the given diagnostic when the code currently being
20088/// type-checked is "potentially evaluated", meaning that there is a
20089/// possibility that the code will actually be executable. Code in sizeof()
20090/// expressions, code used only during overload resolution, etc., are not
20091/// potentially evaluated. This routine will suppress such diagnostics or,
20092/// in the absolutely nutty case of potentially potentially evaluated
20093/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20094/// later.
20095///
20096/// This routine should be used for all diagnostics that describe the run-time
20097/// behavior of a program, such as passing a non-POD value through an ellipsis.
20098/// Failure to do so will likely result in spurious diagnostics or failures
20099/// during overload resolution or within sizeof/alignof/typeof/typeid.
20101 const PartialDiagnostic &PD) {
20102
20103 if (ExprEvalContexts.back().isDiscardedStatementContext())
20104 return false;
20105
20106 switch (ExprEvalContexts.back().Context) {
20111 // The argument will never be evaluated, so don't complain.
20112 break;
20113
20116 // Relevant diagnostics should be produced by constant evaluation.
20117 break;
20118
20121 return DiagIfReachable(Loc, Stmts, PD);
20122 }
20123
20124 return false;
20125}
20126
20128 const PartialDiagnostic &PD) {
20129 return DiagRuntimeBehavior(
20130 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20131}
20132
20134 CallExpr *CE, FunctionDecl *FD) {
20135 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20136 return false;
20137
20138 // If we're inside a decltype's expression, don't check for a valid return
20139 // type or construct temporaries until we know whether this is the last call.
20140 if (ExprEvalContexts.back().ExprContext ==
20142 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20143 return false;
20144 }
20145
20146 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20147 FunctionDecl *FD;
20148 CallExpr *CE;
20149
20150 public:
20151 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20152 : FD(FD), CE(CE) { }
20153
20154 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20155 if (!FD) {
20156 S.Diag(Loc, diag::err_call_incomplete_return)
20157 << T << CE->getSourceRange();
20158 return;
20159 }
20160
20161 S.Diag(Loc, diag::err_call_function_incomplete_return)
20162 << CE->getSourceRange() << FD << T;
20163 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20164 << FD->getDeclName();
20165 }
20166 } Diagnoser(FD, CE);
20167
20168 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20169 return true;
20170
20171 return false;
20172}
20173
20174// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20175// will prevent this condition from triggering, which is what we want.
20178
20179 unsigned diagnostic = diag::warn_condition_is_assignment;
20180 bool IsOrAssign = false;
20181
20182 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20183 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20184 return;
20185
20186 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20187
20188 // Greylist some idioms by putting them into a warning subcategory.
20189 if (ObjCMessageExpr *ME
20190 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20191 Selector Sel = ME->getSelector();
20192
20193 // self = [<foo> init...]
20194 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20195 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20196
20197 // <foo> = [<bar> nextObject]
20198 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20199 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20200 }
20201
20202 Loc = Op->getOperatorLoc();
20203 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20204 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20205 return;
20206
20207 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20208 Loc = Op->getOperatorLoc();
20209 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20210 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20211 else {
20212 // Not an assignment.
20213 return;
20214 }
20215
20216 Diag(Loc, diagnostic) << E->getSourceRange();
20217
20220 Diag(Loc, diag::note_condition_assign_silence)
20222 << FixItHint::CreateInsertion(Close, ")");
20223
20224 if (IsOrAssign)
20225 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20227 else
20228 Diag(Loc, diag::note_condition_assign_to_comparison)
20230}
20231
20232/// Redundant parentheses over an equality comparison can indicate
20233/// that the user intended an assignment used as condition.
20235 // Don't warn if the parens came from a macro.
20236 SourceLocation parenLoc = ParenE->getBeginLoc();
20237 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20238 return;
20239 // Don't warn for dependent expressions.
20240 if (ParenE->isTypeDependent())
20241 return;
20242
20243 Expr *E = ParenE->IgnoreParens();
20244
20245 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20246 if (opE->getOpcode() == BO_EQ &&
20247 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20248 == Expr::MLV_Valid) {
20249 SourceLocation Loc = opE->getOperatorLoc();
20250
20251 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20252 SourceRange ParenERange = ParenE->getSourceRange();
20253 Diag(Loc, diag::note_equality_comparison_silence)
20254 << FixItHint::CreateRemoval(ParenERange.getBegin())
20255 << FixItHint::CreateRemoval(ParenERange.getEnd());
20256 Diag(Loc, diag::note_equality_comparison_to_assign)
20258 }
20259}
20260
20262 bool IsConstexpr) {
20264 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20266
20267 ExprResult result = CheckPlaceholderExpr(E);
20268 if (result.isInvalid()) return ExprError();
20269 E = result.get();
20270
20271 if (!E->isTypeDependent()) {
20272 if (getLangOpts().CPlusPlus)
20273 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20274
20276 if (ERes.isInvalid())
20277 return ExprError();
20278 E = ERes.get();
20279
20280 QualType T = E->getType();
20281 if (!T->isScalarType()) { // C99 6.8.4.1p1
20282 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20283 << T << E->getSourceRange();
20284 return ExprError();
20285 }
20286 CheckBoolLikeConversion(E, Loc);
20287 }
20288
20289 return E;
20290}
20291
20293 Expr *SubExpr, ConditionKind CK,
20294 bool MissingOK) {
20295 // MissingOK indicates whether having no condition expression is valid
20296 // (for loop) or invalid (e.g. while loop).
20297 if (!SubExpr)
20298 return MissingOK ? ConditionResult() : ConditionError();
20299
20300 ExprResult Cond;
20301 switch (CK) {
20303 Cond = CheckBooleanCondition(Loc, SubExpr);
20304 break;
20305
20307 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20308 break;
20309
20311 Cond = CheckSwitchCondition(Loc, SubExpr);
20312 break;
20313 }
20314 if (Cond.isInvalid()) {
20315 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20316 {SubExpr}, PreferredConditionType(CK));
20317 if (!Cond.get())
20318 return ConditionError();
20319 }
20320 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20322 if (!FullExpr.get())
20323 return ConditionError();
20324
20325 return ConditionResult(*this, nullptr, FullExpr,
20327}
20328
20329namespace {
20330 /// A visitor for rebuilding a call to an __unknown_any expression
20331 /// to have an appropriate type.
20332 struct RebuildUnknownAnyFunction
20333 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20334
20335 Sema &S;
20336
20337 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20338
20339 ExprResult VisitStmt(Stmt *S) {
20340 llvm_unreachable("unexpected statement!");
20341 }
20342
20343 ExprResult VisitExpr(Expr *E) {
20344 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20345 << E->getSourceRange();
20346 return ExprError();
20347 }
20348
20349 /// Rebuild an expression which simply semantically wraps another
20350 /// expression which it shares the type and value kind of.
20351 template <class T> ExprResult rebuildSugarExpr(T *E) {
20352 ExprResult SubResult = Visit(E->getSubExpr());
20353 if (SubResult.isInvalid()) return ExprError();
20354
20355 Expr *SubExpr = SubResult.get();
20356 E->setSubExpr(SubExpr);
20357 E->setType(SubExpr->getType());
20358 E->setValueKind(SubExpr->getValueKind());
20359 assert(E->getObjectKind() == OK_Ordinary);
20360 return E;
20361 }
20362
20363 ExprResult VisitParenExpr(ParenExpr *E) {
20364 return rebuildSugarExpr(E);
20365 }
20366
20367 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20368 return rebuildSugarExpr(E);
20369 }
20370
20371 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20372 ExprResult SubResult = Visit(E->getSubExpr());
20373 if (SubResult.isInvalid()) return ExprError();
20374
20375 Expr *SubExpr = SubResult.get();
20376 E->setSubExpr(SubExpr);
20377 E->setType(S.Context.getPointerType(SubExpr->getType()));
20378 assert(E->isPRValue());
20379 assert(E->getObjectKind() == OK_Ordinary);
20380 return E;
20381 }
20382
20383 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20384 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20385
20386 E->setType(VD->getType());
20387
20388 assert(E->isPRValue());
20389 if (S.getLangOpts().CPlusPlus &&
20390 !(isa<CXXMethodDecl>(VD) &&
20391 cast<CXXMethodDecl>(VD)->isInstance()))
20393
20394 return E;
20395 }
20396
20397 ExprResult VisitMemberExpr(MemberExpr *E) {
20398 return resolveDecl(E, E->getMemberDecl());
20399 }
20400
20401 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20402 return resolveDecl(E, E->getDecl());
20403 }
20404 };
20405}
20406
20407/// Given a function expression of unknown-any type, try to rebuild it
20408/// to have a function type.
20410 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20411 if (Result.isInvalid()) return ExprError();
20412 return S.DefaultFunctionArrayConversion(Result.get());
20413}
20414
20415namespace {
20416 /// A visitor for rebuilding an expression of type __unknown_anytype
20417 /// into one which resolves the type directly on the referring
20418 /// expression. Strict preservation of the original source
20419 /// structure is not a goal.
20420 struct RebuildUnknownAnyExpr
20421 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20422
20423 Sema &S;
20424
20425 /// The current destination type.
20426 QualType DestType;
20427
20428 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20429 : S(S), DestType(CastType) {}
20430
20431 ExprResult VisitStmt(Stmt *S) {
20432 llvm_unreachable("unexpected statement!");
20433 }
20434
20435 ExprResult VisitExpr(Expr *E) {
20436 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20437 << E->getSourceRange();
20438 return ExprError();
20439 }
20440
20441 ExprResult VisitCallExpr(CallExpr *E);
20442 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20443
20444 /// Rebuild an expression which simply semantically wraps another
20445 /// expression which it shares the type and value kind of.
20446 template <class T> ExprResult rebuildSugarExpr(T *E) {
20447 ExprResult SubResult = Visit(E->getSubExpr());
20448 if (SubResult.isInvalid()) return ExprError();
20449 Expr *SubExpr = SubResult.get();
20450 E->setSubExpr(SubExpr);
20451 E->setType(SubExpr->getType());
20452 E->setValueKind(SubExpr->getValueKind());
20453 assert(E->getObjectKind() == OK_Ordinary);
20454 return E;
20455 }
20456
20457 ExprResult VisitParenExpr(ParenExpr *E) {
20458 return rebuildSugarExpr(E);
20459 }
20460
20461 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20462 return rebuildSugarExpr(E);
20463 }
20464
20465 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20466 const PointerType *Ptr = DestType->getAs<PointerType>();
20467 if (!Ptr) {
20468 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20469 << E->getSourceRange();
20470 return ExprError();
20471 }
20472
20473 if (isa<CallExpr>(E->getSubExpr())) {
20474 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20475 << E->getSourceRange();
20476 return ExprError();
20477 }
20478
20479 assert(E->isPRValue());
20480 assert(E->getObjectKind() == OK_Ordinary);
20481 E->setType(DestType);
20482
20483 // Build the sub-expression as if it were an object of the pointee type.
20484 DestType = Ptr->getPointeeType();
20485 ExprResult SubResult = Visit(E->getSubExpr());
20486 if (SubResult.isInvalid()) return ExprError();
20487 E->setSubExpr(SubResult.get());
20488 return E;
20489 }
20490
20491 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20492
20493 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20494
20495 ExprResult VisitMemberExpr(MemberExpr *E) {
20496 return resolveDecl(E, E->getMemberDecl());
20497 }
20498
20499 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20500 return resolveDecl(E, E->getDecl());
20501 }
20502 };
20503}
20504
20505/// Rebuilds a call expression which yielded __unknown_anytype.
20506ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20507 Expr *CalleeExpr = E->getCallee();
20508
20509 enum FnKind {
20510 FK_MemberFunction,
20511 FK_FunctionPointer,
20512 FK_BlockPointer
20513 };
20514
20515 FnKind Kind;
20516 QualType CalleeType = CalleeExpr->getType();
20517 if (CalleeType == S.Context.BoundMemberTy) {
20518 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20519 Kind = FK_MemberFunction;
20520 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20521 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20522 CalleeType = Ptr->getPointeeType();
20523 Kind = FK_FunctionPointer;
20524 } else {
20525 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20526 Kind = FK_BlockPointer;
20527 }
20528 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20529
20530 // Verify that this is a legal result type of a function.
20531 if (DestType->isArrayType() || DestType->isFunctionType()) {
20532 unsigned diagID = diag::err_func_returning_array_function;
20533 if (Kind == FK_BlockPointer)
20534 diagID = diag::err_block_returning_array_function;
20535
20536 S.Diag(E->getExprLoc(), diagID)
20537 << DestType->isFunctionType() << DestType;
20538 return ExprError();
20539 }
20540
20541 // Otherwise, go ahead and set DestType as the call's result.
20542 E->setType(DestType.getNonLValueExprType(S.Context));
20544 assert(E->getObjectKind() == OK_Ordinary);
20545
20546 // Rebuild the function type, replacing the result type with DestType.
20547 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20548 if (Proto) {
20549 // __unknown_anytype(...) is a special case used by the debugger when
20550 // it has no idea what a function's signature is.
20551 //
20552 // We want to build this call essentially under the K&R
20553 // unprototyped rules, but making a FunctionNoProtoType in C++
20554 // would foul up all sorts of assumptions. However, we cannot
20555 // simply pass all arguments as variadic arguments, nor can we
20556 // portably just call the function under a non-variadic type; see
20557 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20558 // However, it turns out that in practice it is generally safe to
20559 // call a function declared as "A foo(B,C,D);" under the prototype
20560 // "A foo(B,C,D,...);". The only known exception is with the
20561 // Windows ABI, where any variadic function is implicitly cdecl
20562 // regardless of its normal CC. Therefore we change the parameter
20563 // types to match the types of the arguments.
20564 //
20565 // This is a hack, but it is far superior to moving the
20566 // corresponding target-specific code from IR-gen to Sema/AST.
20567
20568 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20569 SmallVector<QualType, 8> ArgTypes;
20570 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20571 ArgTypes.reserve(E->getNumArgs());
20572 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20573 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20574 }
20575 ParamTypes = ArgTypes;
20576 }
20577 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20578 Proto->getExtProtoInfo());
20579 } else {
20580 DestType = S.Context.getFunctionNoProtoType(DestType,
20581 FnType->getExtInfo());
20582 }
20583
20584 // Rebuild the appropriate pointer-to-function type.
20585 switch (Kind) {
20586 case FK_MemberFunction:
20587 // Nothing to do.
20588 break;
20589
20590 case FK_FunctionPointer:
20591 DestType = S.Context.getPointerType(DestType);
20592 break;
20593
20594 case FK_BlockPointer:
20595 DestType = S.Context.getBlockPointerType(DestType);
20596 break;
20597 }
20598
20599 // Finally, we can recurse.
20600 ExprResult CalleeResult = Visit(CalleeExpr);
20601 if (!CalleeResult.isUsable()) return ExprError();
20602 E->setCallee(CalleeResult.get());
20603
20604 // Bind a temporary if necessary.
20605 return S.MaybeBindToTemporary(E);
20606}
20607
20608ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20609 // Verify that this is a legal result type of a call.
20610 if (DestType->isArrayType() || DestType->isFunctionType()) {
20611 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20612 << DestType->isFunctionType() << DestType;
20613 return ExprError();
20614 }
20615
20616 // Rewrite the method result type if available.
20617 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20618 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20619 Method->setReturnType(DestType);
20620 }
20621
20622 // Change the type of the message.
20623 E->setType(DestType.getNonReferenceType());
20625
20626 return S.MaybeBindToTemporary(E);
20627}
20628
20629ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20630 // The only case we should ever see here is a function-to-pointer decay.
20631 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20632 assert(E->isPRValue());
20633 assert(E->getObjectKind() == OK_Ordinary);
20634
20635 E->setType(DestType);
20636
20637 // Rebuild the sub-expression as the pointee (function) type.
20638 DestType = DestType->castAs<PointerType>()->getPointeeType();
20639
20640 ExprResult Result = Visit(E->getSubExpr());
20641 if (!Result.isUsable()) return ExprError();
20642
20643 E->setSubExpr(Result.get());
20644 return E;
20645 } else if (E->getCastKind() == CK_LValueToRValue) {
20646 assert(E->isPRValue());
20647 assert(E->getObjectKind() == OK_Ordinary);
20648
20649 assert(isa<BlockPointerType>(E->getType()));
20650
20651 E->setType(DestType);
20652
20653 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20654 DestType = S.Context.getLValueReferenceType(DestType);
20655
20656 ExprResult Result = Visit(E->getSubExpr());
20657 if (!Result.isUsable()) return ExprError();
20658
20659 E->setSubExpr(Result.get());
20660 return E;
20661 } else {
20662 llvm_unreachable("Unhandled cast type!");
20663 }
20664}
20665
20666ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20667 ExprValueKind ValueKind = VK_LValue;
20668 QualType Type = DestType;
20669
20670 // We know how to make this work for certain kinds of decls:
20671
20672 // - functions
20673 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20674 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20675 DestType = Ptr->getPointeeType();
20676 ExprResult Result = resolveDecl(E, VD);
20677 if (Result.isInvalid()) return ExprError();
20678 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20679 VK_PRValue);
20680 }
20681
20682 if (!Type->isFunctionType()) {
20683 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20684 << VD << E->getSourceRange();
20685 return ExprError();
20686 }
20687 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20688 // We must match the FunctionDecl's type to the hack introduced in
20689 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20690 // type. See the lengthy commentary in that routine.
20691 QualType FDT = FD->getType();
20692 const FunctionType *FnType = FDT->castAs<FunctionType>();
20693 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20694 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20695 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20696 SourceLocation Loc = FD->getLocation();
20698 S.Context, FD->getDeclContext(), Loc, Loc,
20699 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20701 false /*isInlineSpecified*/, FD->hasPrototype(),
20702 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20703
20704 if (FD->getQualifier())
20705 NewFD->setQualifierInfo(FD->getQualifierLoc());
20706
20708 for (const auto &AI : FT->param_types()) {
20709 ParmVarDecl *Param =
20711 Param->setScopeInfo(0, Params.size());
20712 Params.push_back(Param);
20713 }
20714 NewFD->setParams(Params);
20715 DRE->setDecl(NewFD);
20716 VD = DRE->getDecl();
20717 }
20718 }
20719
20720 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20721 if (MD->isInstance()) {
20722 ValueKind = VK_PRValue;
20724 }
20725
20726 // Function references aren't l-values in C.
20727 if (!S.getLangOpts().CPlusPlus)
20728 ValueKind = VK_PRValue;
20729
20730 // - variables
20731 } else if (isa<VarDecl>(VD)) {
20732 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20733 Type = RefTy->getPointeeType();
20734 } else if (Type->isFunctionType()) {
20735 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20736 << VD << E->getSourceRange();
20737 return ExprError();
20738 }
20739
20740 // - nothing else
20741 } else {
20742 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20743 << VD << E->getSourceRange();
20744 return ExprError();
20745 }
20746
20747 // Modifying the declaration like this is friendly to IR-gen but
20748 // also really dangerous.
20749 VD->setType(DestType);
20750 E->setType(Type);
20751 E->setValueKind(ValueKind);
20752 return E;
20753}
20754
20755/// Check a cast of an unknown-any type. We intentionally only
20756/// trigger this for C-style casts.
20759 ExprValueKind &VK, CXXCastPath &Path) {
20760 // The type we're casting to must be either void or complete.
20761 if (!CastType->isVoidType() &&
20763 diag::err_typecheck_cast_to_incomplete))
20764 return ExprError();
20765
20766 // Rewrite the casted expression from scratch.
20767 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20768 if (!result.isUsable()) return ExprError();
20769
20770 CastExpr = result.get();
20771 VK = CastExpr->getValueKind();
20772 CastKind = CK_NoOp;
20773
20774 return CastExpr;
20775}
20776
20778 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20779}
20780
20782 Expr *arg, QualType &paramType) {
20783 // If the syntactic form of the argument is not an explicit cast of
20784 // any sort, just do default argument promotion.
20785 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20786 if (!castArg) {
20788 if (result.isInvalid()) return ExprError();
20789 paramType = result.get()->getType();
20790 return result;
20791 }
20792
20793 // Otherwise, use the type that was written in the explicit cast.
20794 assert(!arg->hasPlaceholderType());
20795 paramType = castArg->getTypeAsWritten();
20796
20797 // Copy-initialize a parameter of that type.
20798 InitializedEntity entity =
20800 /*consumed*/ false);
20801 return PerformCopyInitialization(entity, callLoc, arg);
20802}
20803
20805 Expr *orig = E;
20806 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20807 while (true) {
20808 E = E->IgnoreParenImpCasts();
20809 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20810 E = call->getCallee();
20811 diagID = diag::err_uncasted_call_of_unknown_any;
20812 } else {
20813 break;
20814 }
20815 }
20816
20817 SourceLocation loc;
20818 NamedDecl *d;
20819 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20820 loc = ref->getLocation();
20821 d = ref->getDecl();
20822 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20823 loc = mem->getMemberLoc();
20824 d = mem->getMemberDecl();
20825 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20826 diagID = diag::err_uncasted_call_of_unknown_any;
20827 loc = msg->getSelectorStartLoc();
20828 d = msg->getMethodDecl();
20829 if (!d) {
20830 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20831 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20832 << orig->getSourceRange();
20833 return ExprError();
20834 }
20835 } else {
20836 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20837 << E->getSourceRange();
20838 return ExprError();
20839 }
20840
20841 S.Diag(loc, diagID) << d << orig->getSourceRange();
20842
20843 // Never recoverable.
20844 return ExprError();
20845}
20846
20847/// Check for operands with placeholder types and complain if found.
20848/// Returns ExprError() if there was an error and no recovery was possible.
20851 // C cannot handle TypoExpr nodes on either side of a binop because it
20852 // doesn't handle dependent types properly, so make sure any TypoExprs have
20853 // been dealt with before checking the operands.
20855 if (!Result.isUsable()) return ExprError();
20856 E = Result.get();
20857 }
20858
20859 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20860 if (!placeholderType) return E;
20861
20862 switch (placeholderType->getKind()) {
20863 case BuiltinType::UnresolvedTemplate: {
20864 auto *ULE = cast<UnresolvedLookupExpr>(E);
20865 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20866 // There's only one FoundDecl for UnresolvedTemplate type. See
20867 // BuildTemplateIdExpr.
20868 NamedDecl *Temp = *ULE->decls_begin();
20869 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20870
20871 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20872 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20873 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20874 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20875 else
20876 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20877 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20878 << IsTypeAliasTemplateDecl;
20879 Diag(Temp->getLocation(), diag::note_referenced_type_template)
20880 << IsTypeAliasTemplateDecl;
20881
20882 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20883 }
20884
20885 // Overloaded expressions.
20886 case BuiltinType::Overload: {
20887 // Try to resolve a single function template specialization.
20888 // This is obligatory.
20889 ExprResult Result = E;
20891 return Result;
20892
20893 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20894 // leaves Result unchanged on failure.
20895 Result = E;
20897 return Result;
20898
20899 // If that failed, try to recover with a call.
20900 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20901 /*complain*/ true);
20902 return Result;
20903 }
20904
20905 // Bound member functions.
20906 case BuiltinType::BoundMember: {
20907 ExprResult result = E;
20908 const Expr *BME = E->IgnoreParens();
20909 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20910 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20911 if (isa<CXXPseudoDestructorExpr>(BME)) {
20912 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20913 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20914 if (ME->getMemberNameInfo().getName().getNameKind() ==
20916 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20917 }
20918 tryToRecoverWithCall(result, PD,
20919 /*complain*/ true);
20920 return result;
20921 }
20922
20923 // ARC unbridged casts.
20924 case BuiltinType::ARCUnbridgedCast: {
20925 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20926 ObjC().diagnoseARCUnbridgedCast(realCast);
20927 return realCast;
20928 }
20929
20930 // Expressions of unknown type.
20931 case BuiltinType::UnknownAny:
20932 return diagnoseUnknownAnyExpr(*this, E);
20933
20934 // Pseudo-objects.
20935 case BuiltinType::PseudoObject:
20936 return checkPseudoObjectRValue(E);
20937
20938 case BuiltinType::BuiltinFn: {
20939 // Accept __noop without parens by implicitly converting it to a call expr.
20940 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20941 if (DRE) {
20942 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20943 unsigned BuiltinID = FD->getBuiltinID();
20944 if (BuiltinID == Builtin::BI__noop) {
20945 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20946 CK_BuiltinFnToFnPtr)
20947 .get();
20948 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20951 }
20952
20953 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20954 // Any use of these other than a direct call is ill-formed as of C++20,
20955 // because they are not addressable functions. In earlier language
20956 // modes, warn and force an instantiation of the real body.
20957 Diag(E->getBeginLoc(),
20959 ? diag::err_use_of_unaddressable_function
20960 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20961 if (FD->isImplicitlyInstantiable()) {
20962 // Require a definition here because a normal attempt at
20963 // instantiation for a builtin will be ignored, and we won't try
20964 // again later. We assume that the definition of the template
20965 // precedes this use.
20967 /*Recursive=*/false,
20968 /*DefinitionRequired=*/true,
20969 /*AtEndOfTU=*/false);
20970 }
20971 // Produce a properly-typed reference to the function.
20972 CXXScopeSpec SS;
20973 SS.Adopt(DRE->getQualifierLoc());
20974 TemplateArgumentListInfo TemplateArgs;
20975 DRE->copyTemplateArgumentsInto(TemplateArgs);
20976 return BuildDeclRefExpr(
20977 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20978 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20979 DRE->getTemplateKeywordLoc(),
20980 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20981 }
20982 }
20983
20984 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20985 return ExprError();
20986 }
20987
20988 case BuiltinType::IncompleteMatrixIdx:
20989 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20990 ->getRowIdx()
20991 ->getBeginLoc(),
20992 diag::err_matrix_incomplete_index);
20993 return ExprError();
20994
20995 // Expressions of unknown type.
20996 case BuiltinType::ArraySection:
20997 Diag(E->getBeginLoc(), diag::err_array_section_use)
20998 << cast<ArraySectionExpr>(E)->isOMPArraySection();
20999 return ExprError();
21000
21001 // Expressions of unknown type.
21002 case BuiltinType::OMPArrayShaping:
21003 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21004
21005 case BuiltinType::OMPIterator:
21006 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21007
21008 // Everything else should be impossible.
21009#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21010 case BuiltinType::Id:
21011#include "clang/Basic/OpenCLImageTypes.def"
21012#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21013 case BuiltinType::Id:
21014#include "clang/Basic/OpenCLExtensionTypes.def"
21015#define SVE_TYPE(Name, Id, SingletonId) \
21016 case BuiltinType::Id:
21017#include "clang/Basic/AArch64SVEACLETypes.def"
21018#define PPC_VECTOR_TYPE(Name, Id, Size) \
21019 case BuiltinType::Id:
21020#include "clang/Basic/PPCTypes.def"
21021#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21022#include "clang/Basic/RISCVVTypes.def"
21023#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21024#include "clang/Basic/WebAssemblyReferenceTypes.def"
21025#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21026#define PLACEHOLDER_TYPE(Id, SingletonId)
21027#include "clang/AST/BuiltinTypes.def"
21028 break;
21029 }
21030
21031 llvm_unreachable("invalid placeholder type!");
21032}
21033
21035 if (E->isTypeDependent())
21036 return true;
21038 return E->getType()->isIntegralOrEnumerationType();
21039 return false;
21040}
21041
21043 ArrayRef<Expr *> SubExprs, QualType T) {
21044 if (!Context.getLangOpts().RecoveryAST)
21045 return ExprError();
21046
21047 if (isSFINAEContext())
21048 return ExprError();
21049
21050 if (T.isNull() || T->isUndeducedType() ||
21051 !Context.getLangOpts().RecoveryASTType)
21052 // We don't know the concrete type, fallback to dependent type.
21054
21055 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21056}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3285
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:50
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:48
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9217
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17633
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:1946
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:15239
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:10099
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:18573
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10841
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:15029
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6173
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10760
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:8784
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:3241
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8238
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:8444
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:11789
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10805
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11739
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2229
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14502
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:17971
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13283
@ NCCK_Block
Definition: SemaExpr.cpp:13283
@ NCCK_None
Definition: SemaExpr.cpp:13283
@ NCCK_Lambda
Definition: SemaExpr.cpp:13283
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:9993
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:9266
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6097
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:2653
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19785
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18425
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16729
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:8688
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1930
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16621
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13842
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4811
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12141
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14402
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4411
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8763
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17820
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:14558
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:10926
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8081
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19582
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3266
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8047
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11831
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6444
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13467
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19831
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:10040
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19550
@ ConstMethod
Definition: SemaExpr.cpp:13333
@ ConstUnknown
Definition: SemaExpr.cpp:13335
@ ConstVariable
Definition: SemaExpr.cpp:13331
@ NestedConstMember
Definition: SemaExpr.cpp:13334
@ ConstMember
Definition: SemaExpr.cpp:13332
@ ConstFunction
Definition: SemaExpr.cpp:13330
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14384
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17494
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12016
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:8718
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:14656
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1316
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6334
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:9654
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:8362
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8068
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10772
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14641
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4868
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8993
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17536
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:15120
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:2375
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:13950
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8307
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:8416
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10599
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11845
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:4281
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10647
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3565
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5810
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:145
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11278
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4203
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9166
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:1273
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18256
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:10956
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13531
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14051
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:161
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:17851
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:11640
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15177
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14111
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:1366
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4882
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:10143
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:18613
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15084
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:570
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8818
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:17939
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:13342
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3695
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13320
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18373
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10819
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4233
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11473
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12059
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20804
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:1938
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8482
OriginalExprKind
Definition: SemaExpr.cpp:13461
@ OEK_Variable
Definition: SemaExpr.cpp:13462
@ OEK_LValue
Definition: SemaExpr.cpp:13464
@ OEK_Member
Definition: SemaExpr.cpp:13463
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:18505
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:1223
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10747
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:11379
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18332
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1298
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10563
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13270
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:18741
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6403
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9014
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4221
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15105
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4901
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:1498
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11007
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6361
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1412
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4263
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10789
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:8277
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11977
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12849
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8396
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8703
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:1117
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14689
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:14600
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:595
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:20409
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:1192
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11692
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1145
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:6261
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19753
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1906
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:106
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:1459
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1168
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13914
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18715
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10737
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11629
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:14712
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11679
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13284
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:8212
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15149
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15135
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11669
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15072
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4477
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:10061
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18406
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15418
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13659
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13079
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:19167
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17885
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11272
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:10873
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7548
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
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:2768
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:1122
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 getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
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:2119
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:2133
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:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
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 getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h: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:1591
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...
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>.
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:1171
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
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:1163
CanQualType PseudoObjectTy
Definition: ASTContext.h:1122
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
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:2321
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1167
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
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:2341
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
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:1878
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
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:1569
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:1130
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2360
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:1794
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:2000
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:2345
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:3518
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3532
QualType getElementType() const
Definition: Type.h:3530
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:5659
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
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:4786
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:4500
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4494
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5229
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4576
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4633
void setIsVariadic(bool value)
Definition: Decl.h:4570
SourceLocation getCaretLocation() const
Definition: Decl.h:4567
void setBody(CompoundStmt *B)
Definition: Decl.h:4574
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4580
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5240
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5416
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3349
This class is used for builtin types like 'int'.
Definition: Type.h:2981
bool isSVEBool() const
Definition: Type.h:3052
Kind getKind() const
Definition: Type.h:3023
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:1542
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
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:74
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
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:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
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:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
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:3086
QualType getElementType() const
Definition: Type.h:3096
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:4808
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:3556
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3612
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3632
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:4167
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4188
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4185
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:1282
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
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:1938
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1585
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1964
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:1233
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
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:725
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
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:1900
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
bool isInvalidType() const
Definition: DeclSpec.h:2714
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
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:5575
EnumDecl * getDecl() const
Definition: Type.h:5582
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:3923
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:4175
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:4061
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
bool isFPConstrained() const
Definition: LangOptions.h:843
RoundingMode getRoundingMode() const
Definition: LangOptions.h:849
Represents a member of a struct/union/class.
Definition: Decl.h:3057
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3148
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3218
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
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:2706
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:2830
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2405
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:2160
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2842
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2444
size_t param_size() const
Definition: Decl.h:2699
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:2790
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4630
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4660
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
QualType desugar() const
Definition: Type.h:5123
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5101
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4915
bool isParamConsumed(unsigned I) const
Definition: Type.h:5115
unsigned getNumParams() const
Definition: Type.h:4889
QualType getParamType(unsigned i) const
Definition: Type.h:4891
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4896
ArrayRef< QualType > param_types() const
Definition: Type.h:5044
Declaration of a template function.
Definition: DeclTemplate.h:957
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:4367
bool getCmseNSCall() const
Definition: Type.h:4417
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4441
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
ExtInfo getExtInfo() const
Definition: Type.h:4585
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4581
QualType getReturnType() const
Definition: Type.h:4573
bool getCmseNSCallAttr() const
Definition: Type.h:4583
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4597
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:4475
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:3341
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:8601
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:1950
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
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
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:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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:4131
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4145
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:637
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,...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
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:6952
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
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
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition: Type.h:7008
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1788
qual_range quals() const
Definition: Type.h:7127
Represents a class type in Objective C.
Definition: Type.h:6754
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:2978
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
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:4728
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:3139
QualType getPointeeType() const
Definition: Type.h:3149
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:7443
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7448
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:7506
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
@ DK_nontrivial_c_struct
Definition: Type.h:1523
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2823
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:7541
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:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
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:7500
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
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:2582
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:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2841
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:7567
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7480
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1619
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:7416
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:2574
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7391
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:7494
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:4168
field_range fields() const
Definition: Decl.h:4374
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5109
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:3380
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:262
@ 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
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 ...
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: SemaObjC.h:841
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
Definition: SemaObjC.cpp:1256
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1157
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:578
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:6478
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9449
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5708
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17070
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17076
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
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:14523
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6350
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:6235
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10157
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:688
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:2478
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15755
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:6298
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3689
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15428
bool isValidRVVBitcast(QualType srcType, QualType destType)
Are the two types RVV-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7594
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:6205
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:15230
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:6291
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:7328
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
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:424
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19512
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13157
VariadicCallType
Definition: Sema.h:2004
@ VariadicDoesNotApply
Definition: Sema.h:2009
@ VariadicFunction
Definition: Sema.h:2005
@ VariadicMethod
Definition: Sema.h:2007
@ VariadicConstructor
Definition: Sema.h:2008
@ VariadicBlock
Definition: Sema.h:2006
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7086
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
@ NTCUC_CompoundLiteral
Definition: Sema.h:2996
@ NTCUC_Assignment
Definition: Sema.h:2994
@ NTCUC_FunctionReturn
Definition: Sema.h:2986
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3000
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:7622
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:2353
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15775
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:17362
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15781
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:1563
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12168
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:16461
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:804
SemaCUDA & CUDA()
Definition: Sema.h:993
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17296
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:20261
ConditionKind
Definition: Sema.h:5830
@ 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:2694
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:797
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:2251
Preprocessor & getPreprocessor() const
Definition: Sema.h:516
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2113
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12731
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:6367
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3629
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:6279
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:18326
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:17081
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6709
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:10235
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:1422
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7573
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.
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:20046
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15794
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:16447
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:798
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:1048
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13865
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5088
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2005
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7716
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14151
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15217
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1058
ASTContext & Context
Definition: Sema.h:848
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:6192
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2691
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:9930
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:20057
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11565
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:2947
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
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:7983
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:21034
SemaObjC & ObjC()
Definition: Sema.h:1003
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:12996
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:2641
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:5722
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19525
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
bool isImmediateFunctionContext() const
Definition: Sema.h:6217
ASTContext & getASTContext() const
Definition: Sema.h:517
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:776
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:15710
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:18817
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:19776
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15225
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:17722
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9673
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:881
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3577
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6236
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3185
bool isBoundsAttrContext() const
Definition: Sema.h:5137
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:7100
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15762
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4444
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7999
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:13042
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:2208
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:16050
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:1677
AssumedTemplateKind
Definition: Sema.h:8767
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1975
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:519
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:638
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:6250
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:225
FPOptions & getCurFPFeatures()
Definition: Sema.h:512
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:6361
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20292
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
@ UPPC_Block
Block expression.
Definition: Sema.h:10769
const LangOptions & getLangOpts() const
Definition: Sema.h:510
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:12195
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:7341
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12971
SemaOpenACC & OpenACC()
Definition: Sema.h:1008
ReuseLambdaContextDecl_t
Definition: Sema.h:5194
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:6683
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17397
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2256
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:19923
Preprocessor & PP
Definition: Sema.h:847
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11017
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5766
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:6507
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14116
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16721
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4803
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:7611
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:846
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15864
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2366
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:6775
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17418
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8564
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4757
SemaHLSL & HLSL()
Definition: Sema.h:998
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:17382
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
@ 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:72
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19933
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:9957
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:5149
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4783
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:9316
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:10439
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:946
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15673
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:3341
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3730
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10485
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:9725
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:1664
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5146
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:2085
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:652
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3273
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:6221
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7326
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:1645
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:16239
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7757
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2322
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8545
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:20757
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:9473
@ VAK_Invalid
Definition: Sema.h:5982
@ VAK_Valid
Definition: Sema.h:5978
@ VAK_ValidInCXX11
Definition: Sema.h:5979
@ VAK_MSVCUndefined
Definition: Sema.h:5981
@ VAK_Undefined
Definition: Sema.h:5980
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5870
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10448
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16603
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:8008
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:19986
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6213
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:6020
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:6064
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:6030
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:6088
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:6093
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:6080
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6059
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6038
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:6097
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6022
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:6049
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6101
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:6034
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:6043
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6055
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:6076
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:6070
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:6026
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:6084
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:8461
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:5863
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:5865
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:5873
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:5867
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:5871
@ ACK_Comparison
A comparison.
Definition: Sema.h:5869
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19880
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4194
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16688
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:4983
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20849
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17275
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:10402
SourceManager & getSourceManager() const
Definition: Sema.h:515
TryCaptureKind
Definition: Sema.h:5236
@ TryCapture_Implicit
Definition: Sema.h:5237
@ TryCapture_ExplicitByRef
Definition: Sema.h:5239
AssignmentAction
Definition: Sema.h:5157
@ AA_Returning
Definition: Sema.h:5160
@ AA_Passing_CFAudited
Definition: Sema.h:5165
@ AA_Initializing
Definition: Sema.h:5162
@ AA_Converting
Definition: Sema.h:5161
@ AA_Assigning
Definition: Sema.h:5158
@ AA_Passing
Definition: Sema.h:5159
@ AA_Casting
Definition: Sema.h:5164
@ AA_Sending
Definition: Sema.h:5163
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6742
ExprResult checkPseudoObjectRValue(Expr *E)
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4467
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:8872
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:12747
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10660
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19489
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13704
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
@ NTCUK_Destruct
Definition: Sema.h:3012
@ NTCUK_Copy
Definition: Sema.h:3013
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:20127
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5569
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:7642
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:7688
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:6268
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2144
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:4981
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:228
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:8301
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:2060
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11584
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15212
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:7790
@ CTK_ErrorRecovery
Definition: Sema.h:7529
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2307
bool isConstantEvaluatedContext() const
Definition: Sema.h:1861
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:3157
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12616
ASTConsumer & Consumer
Definition: Sema.h:849
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3391
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:5153
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:887
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10431
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5211
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3625
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:12688
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:8496
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:4925
@ 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:2043
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:6734
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4697
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5678
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:20133
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4304
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16440
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5791
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8831
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:820
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:20777
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:19123
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7825
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:6203
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17800
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19115
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1330
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7737
SourceManager & SourceMgr
Definition: Sema.h:851
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4788
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7898
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:2416
DiagnosticsEngine & Diags
Definition: Sema.h:850
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:511
FPOptions CurFPFeatures
Definition: Sema.h:844
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:528
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:7672
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5643
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20176
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
Definition: SemaDecl.cpp:1337
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13093
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4787
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15789
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:1001
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6115
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12808
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8976
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:13162
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:16251
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:19903
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:16748
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:17983
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15833
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4848
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:5993
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:280
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20234
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:21042
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15275
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3764
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3053
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7300
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16089
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4921
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:14739
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9251
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:6474
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:4771
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:5939
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:7342
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:7348
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:7340
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:7345
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:7356
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:7352
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16118
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10699
@ 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:10427
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:2805
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:15867
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:13414
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11132
static ConditionResult ConditionError()
Definition: Sema.h:5817
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:6761
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:20781
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:5855
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16031
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2298
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5773
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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:2704
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17808
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7232
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:6227
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:5439
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:6652
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:5096
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:3687
bool isUnion() const
Definition: Decl.h:3790
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3808
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:218
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:672
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:992
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:472
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
IntType getSizeType() const
Definition: TargetInfo.h:371
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1561
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1654
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:1033
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:869
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1472
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:3390
const Type * getTypeForDecl() const
Definition: Decl.h:3414
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3417
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:7330
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:7341
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:2400
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:7966
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isObjCBuiltinType() const
Definition: Type.h:7795
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:1888
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8083
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:730
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:7881
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:667
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8063
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:2010
bool isVoidPointerType() const
Definition: Type.cpp:655
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:688
bool isArrayType() const
Definition: Type.h:7678
bool isCharType() const
Definition: Type.cpp:2078
bool isFunctionPointerType() const
Definition: Type.h:7646
bool isArithmeticType() const
Definition: Type.cpp:2270
bool isConstantMatrixType() const
Definition: Type.h:7736
bool isPointerType() const
Definition: Type.h:7612
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2461
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
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:7986
bool isEnumeralType() const
Definition: Type.h:7710
bool isScalarType() const
Definition: Type.h:8004
bool isVariableArrayType() const
Definition: Type.h:7690
bool isSizelessBuiltinType() const
Definition: Type.cpp:2422
bool isClkEventT() const
Definition: Type.h:7817
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2488
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
bool isObjCQualifiedIdType() const
Definition: Type.h:7765
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2225
bool isExtVectorType() const
Definition: Type.h:7722
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2114
bool isExtVectorBoolType() const
Definition: Type.h:7726
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2526
bool isImageType() const
Definition: Type.h:7829
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7899
bool isPipeType() const
Definition: Type.h:7836
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2661
bool isBitIntType() const
Definition: Type.h:7840
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7874
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7702
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAnyComplexType() const
Definition: Type.h:7714
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7958
bool isHalfType() const
Definition: Type.h:7909
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7974
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:2285
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7887
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2175
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2445
bool isQueueT() const
Definition: Type.h:7821
bool isMemberPointerType() const
Definition: Type.h:7660
bool isAtomicType() const
Definition: Type.h:7757
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8046
bool isObjCIdType() const
Definition: Type.h:7777
bool isMatrixType() const
Definition: Type.h:7732
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isComplexIntegerType() const
Definition: Type.cpp:673
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2071
bool isObjCObjectType() const
Definition: Type.h:7748
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4808
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4898
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2247
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:8000
bool isVectorType() const
Definition: Type.h:7718
bool isObjCQualifiedClassType() const
Definition: Type.h:7771
bool isObjCClassType() const
Definition: Type.h:7783
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2475
ScalarTypeKind
Definition: Type.h:2626
@ STK_FloatingComplex
Definition: Type.h:2635
@ STK_Floating
Definition: Type.h:2633
@ STK_BlockPointer
Definition: Type.h:2628
@ STK_Bool
Definition: Type.h:2631
@ STK_ObjCObjectPointer
Definition: Type.h:2629
@ STK_FixedPoint
Definition: Type.h:2636
@ STK_IntegralComplex
Definition: Type.h:2634
@ STK_CPointer
Definition: Type.h:2627
@ STK_Integral
Definition: Type.h:2632
@ STK_MemberPointer
Definition: Type.h:2630
bool isFloatingType() const
Definition: Type.cpp:2238
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:2185
bool isAnyPointerType() const
Definition: Type.h:7616
bool isRealType() const
Definition: Type.cpp:2261
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSamplerT() const
Definition: Type.h:7809
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4625
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2457
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:4843
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:1025
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3197
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:3936
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:5365
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:3747
Expr * getSizeExpr() const
Definition: Type.h:3766
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
VectorKind getVectorKind() const
Definition: Type.h:3989
QualType getElementType() const
Definition: Type.h:3983
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:132
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
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
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h: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:26
#define bool
Definition: stdbool.h:24
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5566
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5553
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5561
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5560
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5546
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5511
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5517
const ASTContext & Context
Definition: SemaExpr.cpp:5505
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5538
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5542
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5527
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5509
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5506
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:4735
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4736
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:9737
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:4987
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:5021
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:5067
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:5026
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:5034
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:5030
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:5040
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:5006
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:5044
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:4992
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:5000
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:4989
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:4996
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6305
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:153