Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
clang 20.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
18#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
43#include "clang/Sema/DeclSpec.h"
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Overload.h"
51#include "clang/Sema/Scope.h"
53#include "clang/Sema/SemaCUDA.h"
55#include "clang/Sema/SemaHLSL.h"
57#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/ConvertUTF.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/TypeSize.h"
68#include <optional>
69
70using namespace clang;
71using namespace sema;
72
73bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars.count(D))
76 return false;
77
78 // See if this is a deleted function.
79 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80 if (FD->isDeleted())
81 return false;
82
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87 return false;
88
89 // See if this is an aligned allocation/deallocation function that is
90 // unavailable.
91 if (TreatUnavailableAsInvalid &&
93 return false;
94 }
95
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99 return false;
100
101 if (isa<UnresolvedUsingIfExistsDecl>(D))
102 return false;
103
104 return true;
105}
106
108 // Warn if this is used but marked unused.
109 if (const auto *A = D->getAttr<UnusedAttr>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115 if (DC && !DC->hasAttr<UnusedAttr>())
116 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117 }
118 }
119}
120
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.
180 if (D->getFormalLinkage() != Linkage::Internal)
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
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver,
221 bool SkipTrailingRequiresClause) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else {
267 StringLiteral *Msg = FD->getDeletedMessage();
268 Diag(Loc, diag::err_deleted_function_use)
269 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
270 }
272 return true;
273 }
274
275 // [expr.prim.id]p4
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
279 //
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
282 // definition.
283 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction;
285 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
303 return true;
304
305 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
306 return true;
307
308 }
309
310 if (auto *Concept = dyn_cast<ConceptDecl>(D);
312 return true;
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 return true;
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
730
733
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
737 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
739
740 // C11 6.3.2.1p2:
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
744 T = Atomic->getValueType().getUnqualifiedType();
745 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
746 nullptr, VK_PRValue, FPOptionsOverride());
747 }
748
749 return Res;
750}
751
754 if (Res.isInvalid())
755 return ExprError();
756 Res = DefaultLvalueConversion(Res.get());
757 if (Res.isInvalid())
758 return ExprError();
759 return Res;
760}
761
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
785 // First, convert to an r-value.
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
808 // Widen the expression to double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
817 // Widen the expression to long double.
818 return Ty->isComplexType()
821 CK_FloatingComplexCast)
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
931 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
932
933 return E;
934}
935
937 if (Ty->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
941 // is ill-formed.
942 //
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty->isVoidType())
947 return VAK_Invalid;
948
949 if (Ty->isObjCObjectType())
950 return VAK_Invalid;
951 return VAK_Valid;
952 }
953
955 return VAK_Invalid;
956
957 if (Context.getTargetInfo().getTriple().isWasm() &&
959 return VAK_Invalid;
960 }
961
962 if (Ty.isCXX98PODType(Context))
963 return VAK_Valid;
964
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
972 if (!Record->hasNonTrivialCopyConstructor() &&
973 !Record->hasNonTrivialMoveConstructor() &&
974 !Record->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11;
976
977 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
978 return VAK_Valid;
979
980 if (Ty->isObjCObjectType())
981 return VAK_Invalid;
982
984 return VAK_Valid;
985
986 if (getLangOpts().MSVCCompat)
987 return VAK_MSVCUndefined;
988
990 return VAK_Valid;
991
992 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
993 // permitted to reject them. We should consider doing so.
994 return VAK_Undefined;
995}
996
998 // Don't allow one to pass an Objective-C interface to a vararg.
999 const QualType &Ty = E->getType();
1000 VarArgKind VAK = isValidVarArgType(Ty);
1001
1002 // Complain about passing non-POD types through varargs.
1003 switch (VAK) {
1004 case VAK_ValidInCXX11:
1006 E->getBeginLoc(), nullptr,
1007 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1008 [[fallthrough]];
1009 case VAK_Valid:
1010 if (Ty->isRecordType()) {
1011 // This is unlikely to be what the user intended. If the class has a
1012 // 'c_str' member function, the user probably meant to call that.
1013 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1014 PDiag(diag::warn_pass_class_arg_to_vararg)
1015 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1016 }
1017 break;
1018
1019 case VAK_Undefined:
1020 case VAK_MSVCUndefined:
1021 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1022 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1023 << getLangOpts().CPlusPlus11 << Ty << CT);
1024 break;
1025
1026 case VAK_Invalid:
1028 Diag(E->getBeginLoc(),
1029 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1030 << Ty << CT;
1031 else if (Ty->isObjCObjectType())
1032 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1033 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1034 << Ty << CT);
1035 else
1036 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1037 << isa<InitListExpr>(E) << Ty << CT;
1038 break;
1039 }
1040}
1041
1043 FunctionDecl *FDecl) {
1044 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1045 // Strip the unbridged-cast placeholder expression off, if applicable.
1046 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1047 (CT == VariadicMethod ||
1048 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1050
1051 // Otherwise, do normal placeholder checking.
1052 } else {
1054 if (ExprRes.isInvalid())
1055 return ExprError();
1056 E = ExprRes.get();
1057 }
1058 }
1059
1061 if (ExprRes.isInvalid())
1062 return ExprError();
1063
1064 // Copy blocks to the heap.
1065 if (ExprRes.get()->getType()->isBlockPointerType())
1066 maybeExtendBlockObject(ExprRes);
1067
1068 E = ExprRes.get();
1069
1070 // Diagnostics regarding non-POD argument types are
1071 // emitted along with format string checking in Sema::CheckFunctionCall().
1073 // Turn this into a trap.
1074 CXXScopeSpec SS;
1075 SourceLocation TemplateKWLoc;
1076 UnqualifiedId Name;
1077 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1078 E->getBeginLoc());
1079 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1080 /*HasTrailingLParen=*/true,
1081 /*IsAddressOfOperand=*/false);
1082 if (TrapFn.isInvalid())
1083 return ExprError();
1084
1085 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1086 E->getEndLoc());
1087 if (Call.isInvalid())
1088 return ExprError();
1089
1090 ExprResult Comma =
1091 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1092 if (Comma.isInvalid())
1093 return ExprError();
1094 return Comma.get();
1095 }
1096
1097 if (!getLangOpts().CPlusPlus &&
1099 diag::err_call_incomplete_argument))
1100 return ExprError();
1101
1102 return E;
1103}
1104
1105/// Convert complex integers to complex floats and real integers to
1106/// real floats as required for complex arithmetic. Helper function of
1107/// UsualArithmeticConversions()
1108///
1109/// \return false if the integer expression is an integer type and is
1110/// successfully converted to the (complex) float type.
1112 ExprResult &ComplexExpr,
1113 QualType IntTy,
1114 QualType ComplexTy,
1115 bool SkipCast) {
1116 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1117 if (SkipCast) return false;
1118 if (IntTy->isIntegerType()) {
1119 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1120 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1121 } else {
1122 assert(IntTy->isComplexIntegerType());
1123 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1124 CK_IntegralComplexToFloatingComplex);
1125 }
1126 return false;
1127}
1128
1129// This handles complex/complex, complex/float, or float/complex.
1130// When both operands are complex, the shorter operand is converted to the
1131// type of the longer, and that is the type of the result. This corresponds
1132// to what is done when combining two real floating-point operands.
1133// The fun begins when size promotion occur across type domains.
1134// From H&S 6.3.4: When one operand is complex and the other is a real
1135// floating-point type, the less precise type is converted, within it's
1136// real or complex domain, to the precision of the other type. For example,
1137// when combining a "long double" with a "double _Complex", the
1138// "double _Complex" is promoted to "long double _Complex".
1140 QualType ShorterType,
1141 QualType LongerType,
1142 bool PromotePrecision) {
1143 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1145 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1146
1147 if (PromotePrecision) {
1148 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1149 Shorter =
1150 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1151 } else {
1152 if (LongerIsComplex)
1153 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1154 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1155 }
1156 }
1157 return Result;
1158}
1159
1160/// Handle arithmetic conversion with complex types. Helper function of
1161/// UsualArithmeticConversions()
1163 ExprResult &RHS, QualType LHSType,
1164 QualType RHSType, bool IsCompAssign) {
1165 // Handle (complex) integer types.
1166 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1167 /*SkipCast=*/false))
1168 return LHSType;
1169 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1170 /*SkipCast=*/IsCompAssign))
1171 return RHSType;
1172
1173 // Compute the rank of the two types, regardless of whether they are complex.
1174 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1175 if (Order < 0)
1176 // Promote the precision of the LHS if not an assignment.
1177 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1178 /*PromotePrecision=*/!IsCompAssign);
1179 // Promote the precision of the RHS unless it is already the same as the LHS.
1180 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1181 /*PromotePrecision=*/Order > 0);
1182}
1183
1184/// Handle arithmetic conversion from integer to float. Helper function
1185/// of UsualArithmeticConversions()
1187 ExprResult &IntExpr,
1188 QualType FloatTy, QualType IntTy,
1189 bool ConvertFloat, bool ConvertInt) {
1190 if (IntTy->isIntegerType()) {
1191 if (ConvertInt)
1192 // Convert intExpr to the lhs floating point type.
1193 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1194 CK_IntegralToFloating);
1195 return FloatTy;
1196 }
1197
1198 // Convert both sides to the appropriate complex float.
1199 assert(IntTy->isComplexIntegerType());
1200 QualType result = S.Context.getComplexType(FloatTy);
1201
1202 // _Complex int -> _Complex float
1203 if (ConvertInt)
1204 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1205 CK_IntegralComplexToFloatingComplex);
1206
1207 // float -> _Complex float
1208 if (ConvertFloat)
1209 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1210 CK_FloatingRealToComplex);
1211
1212 return result;
1213}
1214
1215/// Handle arithmethic conversion with floating point types. Helper
1216/// function of UsualArithmeticConversions()
1218 ExprResult &RHS, QualType LHSType,
1219 QualType RHSType, bool IsCompAssign) {
1220 bool LHSFloat = LHSType->isRealFloatingType();
1221 bool RHSFloat = RHSType->isRealFloatingType();
1222
1223 // N1169 4.1.4: If one of the operands has a floating type and the other
1224 // operand has a fixed-point type, the fixed-point operand
1225 // is converted to the floating type [...]
1226 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1227 if (LHSFloat)
1228 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1229 else if (!IsCompAssign)
1230 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1231 return LHSFloat ? LHSType : RHSType;
1232 }
1233
1234 // If we have two real floating types, convert the smaller operand
1235 // to the bigger result.
1236 if (LHSFloat && RHSFloat) {
1237 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1238 if (order > 0) {
1239 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1240 return LHSType;
1241 }
1242
1243 assert(order < 0 && "illegal float comparison");
1244 if (!IsCompAssign)
1245 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1246 return RHSType;
1247 }
1248
1249 if (LHSFloat) {
1250 // Half FP has to be promoted to float unless it is natively supported
1251 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1252 LHSType = S.Context.FloatTy;
1253
1254 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1255 /*ConvertFloat=*/!IsCompAssign,
1256 /*ConvertInt=*/ true);
1257 }
1258 assert(RHSFloat);
1259 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1260 /*ConvertFloat=*/ true,
1261 /*ConvertInt=*/!IsCompAssign);
1262}
1263
1264/// Diagnose attempts to convert between __float128, __ibm128 and
1265/// long double if there is no support for such conversion.
1266/// Helper function of UsualArithmeticConversions().
1267static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1268 QualType RHSType) {
1269 // No issue if either is not a floating point type.
1270 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1271 return false;
1272
1273 // No issue if both have the same 128-bit float semantics.
1274 auto *LHSComplex = LHSType->getAs<ComplexType>();
1275 auto *RHSComplex = RHSType->getAs<ComplexType>();
1276
1277 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1278 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1279
1280 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1281 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1282
1283 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1284 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1285 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1286 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1287 return false;
1288
1289 return true;
1290}
1291
1292typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1293
1294namespace {
1295/// These helper callbacks are placed in an anonymous namespace to
1296/// permit their use as function template parameters.
1297ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1298 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1299}
1300
1301ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1303 CK_IntegralComplexCast);
1304}
1305}
1306
1307/// Handle integer arithmetic conversions. Helper function of
1308/// UsualArithmeticConversions()
1309template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1311 ExprResult &RHS, QualType LHSType,
1312 QualType RHSType, bool IsCompAssign) {
1313 // The rules for this case are in C99 6.3.1.8
1314 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1315 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1316 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1317 if (LHSSigned == RHSSigned) {
1318 // Same signedness; use the higher-ranked type
1319 if (order >= 0) {
1320 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1321 return LHSType;
1322 } else if (!IsCompAssign)
1323 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1324 return RHSType;
1325 } else if (order != (LHSSigned ? 1 : -1)) {
1326 // The unsigned type has greater than or equal rank to the
1327 // signed type, so use the unsigned type
1328 if (RHSSigned) {
1329 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1330 return LHSType;
1331 } else if (!IsCompAssign)
1332 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1333 return RHSType;
1334 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1335 // The two types are different widths; if we are here, that
1336 // means the signed type is larger than the unsigned type, so
1337 // use the signed type.
1338 if (LHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else {
1345 // The signed type is higher-ranked than the unsigned type,
1346 // but isn't actually any bigger (like unsigned int and long
1347 // on most 32-bit systems). Use the unsigned type corresponding
1348 // to the signed type.
1349 QualType result =
1350 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1351 RHS = (*doRHSCast)(S, RHS.get(), result);
1352 if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), result);
1354 return result;
1355 }
1356}
1357
1358/// Handle conversions with GCC complex int extension. Helper function
1359/// of UsualArithmeticConversions()
1361 ExprResult &RHS, QualType LHSType,
1362 QualType RHSType,
1363 bool IsCompAssign) {
1364 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1365 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1366
1367 if (LHSComplexInt && RHSComplexInt) {
1368 QualType LHSEltType = LHSComplexInt->getElementType();
1369 QualType RHSEltType = RHSComplexInt->getElementType();
1370 QualType ScalarType =
1371 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1372 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1373
1374 return S.Context.getComplexType(ScalarType);
1375 }
1376
1377 if (LHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType ScalarType =
1380 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1381 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1383 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1384 CK_IntegralRealToComplex);
1385
1386 return ComplexType;
1387 }
1388
1389 assert(RHSComplexInt);
1390
1391 QualType RHSEltType = RHSComplexInt->getElementType();
1392 QualType ScalarType =
1393 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1394 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1396
1397 if (!IsCompAssign)
1398 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1399 CK_IntegralRealToComplex);
1400 return ComplexType;
1401}
1402
1403/// Return the rank of a given fixed point or integer type. The value itself
1404/// doesn't matter, but the values must be increasing with proper increasing
1405/// rank as described in N1169 4.1.1.
1406static unsigned GetFixedPointRank(QualType Ty) {
1407 const auto *BTy = Ty->getAs<BuiltinType>();
1408 assert(BTy && "Expected a builtin type.");
1409
1410 switch (BTy->getKind()) {
1411 case BuiltinType::ShortFract:
1412 case BuiltinType::UShortFract:
1413 case BuiltinType::SatShortFract:
1414 case BuiltinType::SatUShortFract:
1415 return 1;
1416 case BuiltinType::Fract:
1417 case BuiltinType::UFract:
1418 case BuiltinType::SatFract:
1419 case BuiltinType::SatUFract:
1420 return 2;
1421 case BuiltinType::LongFract:
1422 case BuiltinType::ULongFract:
1423 case BuiltinType::SatLongFract:
1424 case BuiltinType::SatULongFract:
1425 return 3;
1426 case BuiltinType::ShortAccum:
1427 case BuiltinType::UShortAccum:
1428 case BuiltinType::SatShortAccum:
1429 case BuiltinType::SatUShortAccum:
1430 return 4;
1431 case BuiltinType::Accum:
1432 case BuiltinType::UAccum:
1433 case BuiltinType::SatAccum:
1434 case BuiltinType::SatUAccum:
1435 return 5;
1436 case BuiltinType::LongAccum:
1437 case BuiltinType::ULongAccum:
1438 case BuiltinType::SatLongAccum:
1439 case BuiltinType::SatULongAccum:
1440 return 6;
1441 default:
1442 if (BTy->isInteger())
1443 return 0;
1444 llvm_unreachable("Unexpected fixed point or integer type");
1445 }
1446}
1447
1448/// handleFixedPointConversion - Fixed point operations between fixed
1449/// point types and integers or other fixed point types do not fall under
1450/// usual arithmetic conversion since these conversions could result in loss
1451/// of precsision (N1169 4.1.4). These operations should be calculated with
1452/// the full precision of their result type (N1169 4.1.6.2.1).
1454 QualType RHSTy) {
1455 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1456 "Expected at least one of the operands to be a fixed point type");
1457 assert((LHSTy->isFixedPointOrIntegerType() ||
1458 RHSTy->isFixedPointOrIntegerType()) &&
1459 "Special fixed point arithmetic operation conversions are only "
1460 "applied to ints or other fixed point types");
1461
1462 // If one operand has signed fixed-point type and the other operand has
1463 // unsigned fixed-point type, then the unsigned fixed-point operand is
1464 // converted to its corresponding signed fixed-point type and the resulting
1465 // type is the type of the converted operand.
1466 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1468 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1470
1471 // The result type is the type with the highest rank, whereby a fixed-point
1472 // conversion rank is always greater than an integer conversion rank; if the
1473 // type of either of the operands is a saturating fixedpoint type, the result
1474 // type shall be the saturating fixed-point type corresponding to the type
1475 // with the highest rank; the resulting value is converted (taking into
1476 // account rounding and overflow) to the precision of the resulting type.
1477 // Same ranks between signed and unsigned types are resolved earlier, so both
1478 // types are either signed or both unsigned at this point.
1479 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1480 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1481
1482 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1483
1485 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1486
1487 return ResultTy;
1488}
1489
1490/// Check that the usual arithmetic conversions can be performed on this pair of
1491/// expressions that might be of enumeration type.
1494 Sema::ArithConvKind ACK) {
1495 // C++2a [expr.arith.conv]p1:
1496 // If one operand is of enumeration type and the other operand is of a
1497 // different enumeration type or a floating-point type, this behavior is
1498 // deprecated ([depr.arith.conv.enum]).
1499 //
1500 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1501 // Eventually we will presumably reject these cases (in C++23 onwards?).
1503 R = RHS->getEnumCoercedType(S.Context);
1504 bool LEnum = L->isUnscopedEnumerationType(),
1505 REnum = R->isUnscopedEnumerationType();
1506 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1507 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1508 (REnum && L->isFloatingType())) {
1509 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1510 ? diag::err_arith_conv_enum_float_cxx26
1511 : S.getLangOpts().CPlusPlus20
1512 ? diag::warn_arith_conv_enum_float_cxx20
1513 : diag::warn_arith_conv_enum_float)
1514 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1515 << L << R;
1516 } else if (!IsCompAssign && LEnum && REnum &&
1518 unsigned DiagID;
1519 // In C++ 26, usual arithmetic conversions between 2 different enum types
1520 // are ill-formed.
1521 if (S.getLangOpts().CPlusPlus26)
1522 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1523 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1524 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1525 // If either enumeration type is unnamed, it's less likely that the
1526 // user cares about this, but this situation is still deprecated in
1527 // C++2a. Use a different warning group.
1528 DiagID = S.getLangOpts().CPlusPlus20
1529 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1530 : diag::warn_arith_conv_mixed_anon_enum_types;
1531 } else if (ACK == Sema::ACK_Conditional) {
1532 // Conditional expressions are separated out because they have
1533 // historically had a different warning flag.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_conditional_mixed_enum_types_cxx20
1536 : diag::warn_conditional_mixed_enum_types;
1537 } else if (ACK == Sema::ACK_Comparison) {
1538 // Comparison expressions are separated out because they have
1539 // historically had a different warning flag.
1540 DiagID = S.getLangOpts().CPlusPlus20
1541 ? diag::warn_comparison_mixed_enum_types_cxx20
1542 : diag::warn_comparison_mixed_enum_types;
1543 } else {
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_enum_types;
1547 }
1548 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1549 << (int)ACK << L << R;
1550 }
1551}
1552
1553/// UsualArithmeticConversions - Performs various conversions that are common to
1554/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1555/// routine returns the first non-arithmetic type found. The client is
1556/// responsible for emitting appropriate error diagnostics.
1559 ArithConvKind ACK) {
1560 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1561
1562 if (ACK != ACK_CompAssign) {
1563 LHS = UsualUnaryConversions(LHS.get());
1564 if (LHS.isInvalid())
1565 return QualType();
1566 }
1567
1568 RHS = UsualUnaryConversions(RHS.get());
1569 if (RHS.isInvalid())
1570 return QualType();
1571
1572 // For conversion purposes, we ignore any qualifiers.
1573 // For example, "const float" and "float" are equivalent.
1574 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1575 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1576
1577 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1578 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1579 LHSType = AtomicLHS->getValueType();
1580
1581 // If both types are identical, no conversion is needed.
1582 if (Context.hasSameType(LHSType, RHSType))
1583 return Context.getCommonSugaredType(LHSType, RHSType);
1584
1585 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1586 // The caller can deal with this (e.g. pointer + int).
1587 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1588 return QualType();
1589
1590 // Apply unary and bitfield promotions to the LHS's type.
1591 QualType LHSUnpromotedType = LHSType;
1592 if (Context.isPromotableIntegerType(LHSType))
1593 LHSType = Context.getPromotedIntegerType(LHSType);
1594 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1595 if (!LHSBitfieldPromoteTy.isNull())
1596 LHSType = LHSBitfieldPromoteTy;
1597 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1598 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1599
1600 // If both types are identical, no conversion is needed.
1601 if (Context.hasSameType(LHSType, RHSType))
1602 return Context.getCommonSugaredType(LHSType, RHSType);
1603
1604 // At this point, we have two different arithmetic types.
1605
1606 // Diagnose attempts to convert between __ibm128, __float128 and long double
1607 // where such conversions currently can't be handled.
1608 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1609 return QualType();
1610
1611 // Handle complex types first (C99 6.3.1.8p1).
1612 if (LHSType->isComplexType() || RHSType->isComplexType())
1613 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1614 ACK == ACK_CompAssign);
1615
1616 // Now handle "real" floating types (i.e. float, double, long double).
1617 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1618 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1619 ACK == ACK_CompAssign);
1620
1621 // Handle GCC complex int extension.
1622 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1623 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1624 ACK == ACK_CompAssign);
1625
1626 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1627 return handleFixedPointConversion(*this, LHSType, RHSType);
1628
1629 // Finally, we have two differing integer types.
1630 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1631 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// Semantic Analysis for various Expression Types
1636//===----------------------------------------------------------------------===//
1637
1638
1640 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1641 bool PredicateIsExpr, void *ControllingExprOrType,
1642 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1643 unsigned NumAssocs = ArgTypes.size();
1644 assert(NumAssocs == ArgExprs.size());
1645
1646 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1647 for (unsigned i = 0; i < NumAssocs; ++i) {
1648 if (ArgTypes[i])
1649 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1650 else
1651 Types[i] = nullptr;
1652 }
1653
1654 // If we have a controlling type, we need to convert it from a parsed type
1655 // into a semantic type and then pass that along.
1656 if (!PredicateIsExpr) {
1657 TypeSourceInfo *ControllingType;
1658 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1659 &ControllingType);
1660 assert(ControllingType && "couldn't get the type out of the parser");
1661 ControllingExprOrType = ControllingType;
1662 }
1663
1665 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1666 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1667 delete [] Types;
1668 return ER;
1669}
1670
1672 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1673 bool PredicateIsExpr, void *ControllingExprOrType,
1675 unsigned NumAssocs = Types.size();
1676 assert(NumAssocs == Exprs.size());
1677 assert(ControllingExprOrType &&
1678 "Must have either a controlling expression or a controlling type");
1679
1680 Expr *ControllingExpr = nullptr;
1681 TypeSourceInfo *ControllingType = nullptr;
1682 if (PredicateIsExpr) {
1683 // Decay and strip qualifiers for the controlling expression type, and
1684 // handle placeholder type replacement. See committee discussion from WG14
1685 // DR423.
1689 reinterpret_cast<Expr *>(ControllingExprOrType));
1690 if (R.isInvalid())
1691 return ExprError();
1692 ControllingExpr = R.get();
1693 } else {
1694 // The extension form uses the type directly rather than converting it.
1695 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1696 if (!ControllingType)
1697 return ExprError();
1698 }
1699
1700 bool TypeErrorFound = false,
1701 IsResultDependent = ControllingExpr
1702 ? ControllingExpr->isTypeDependent()
1703 : ControllingType->getType()->isDependentType(),
1704 ContainsUnexpandedParameterPack =
1705 ControllingExpr
1706 ? ControllingExpr->containsUnexpandedParameterPack()
1707 : ControllingType->getType()->containsUnexpandedParameterPack();
1708
1709 // The controlling expression is an unevaluated operand, so side effects are
1710 // likely unintended.
1711 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1712 ControllingExpr->HasSideEffects(Context, false))
1713 Diag(ControllingExpr->getExprLoc(),
1714 diag::warn_side_effects_unevaluated_context);
1715
1716 for (unsigned i = 0; i < NumAssocs; ++i) {
1717 if (Exprs[i]->containsUnexpandedParameterPack())
1718 ContainsUnexpandedParameterPack = true;
1719
1720 if (Types[i]) {
1721 if (Types[i]->getType()->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]->getType()->isDependentType()) {
1725 IsResultDependent = true;
1726 } else {
1727 // We relax the restriction on use of incomplete types and non-object
1728 // types with the type-based extension of _Generic. Allowing incomplete
1729 // objects means those can be used as "tags" for a type-safe way to map
1730 // to a value. Similarly, matching on function types rather than
1731 // function pointer types can be useful. However, the restriction on VM
1732 // types makes sense to retain as there are open questions about how
1733 // the selection can be made at compile time.
1734 //
1735 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1736 // complete object type other than a variably modified type."
1737 unsigned D = 0;
1738 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1739 D = diag::err_assoc_type_incomplete;
1740 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1741 D = diag::err_assoc_type_nonobject;
1742 else if (Types[i]->getType()->isVariablyModifiedType())
1743 D = diag::err_assoc_type_variably_modified;
1744 else if (ControllingExpr) {
1745 // Because the controlling expression undergoes lvalue conversion,
1746 // array conversion, and function conversion, an association which is
1747 // of array type, function type, or is qualified can never be
1748 // reached. We will warn about this so users are less surprised by
1749 // the unreachable association. However, we don't have to handle
1750 // function types; that's not an object type, so it's handled above.
1751 //
1752 // The logic is somewhat different for C++ because C++ has different
1753 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1754 // If T is a non-class type, the type of the prvalue is the cv-
1755 // unqualified version of T. Otherwise, the type of the prvalue is T.
1756 // The result of these rules is that all qualified types in an
1757 // association in C are unreachable, and in C++, only qualified non-
1758 // class types are unreachable.
1759 //
1760 // NB: this does not apply when the first operand is a type rather
1761 // than an expression, because the type form does not undergo
1762 // conversion.
1763 unsigned Reason = 0;
1764 QualType QT = Types[i]->getType();
1765 if (QT->isArrayType())
1766 Reason = 1;
1767 else if (QT.hasQualifiers() &&
1768 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1769 Reason = 2;
1770
1771 if (Reason)
1772 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1773 diag::warn_unreachable_association)
1774 << QT << (Reason - 1);
1775 }
1776
1777 if (D != 0) {
1778 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1779 << Types[i]->getTypeLoc().getSourceRange()
1780 << Types[i]->getType();
1781 TypeErrorFound = true;
1782 }
1783
1784 // C11 6.5.1.1p2 "No two generic associations in the same generic
1785 // selection shall specify compatible types."
1786 for (unsigned j = i+1; j < NumAssocs; ++j)
1787 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1788 Context.typesAreCompatible(Types[i]->getType(),
1789 Types[j]->getType())) {
1790 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1791 diag::err_assoc_compatible_types)
1792 << Types[j]->getTypeLoc().getSourceRange()
1793 << Types[j]->getType()
1794 << Types[i]->getType();
1795 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1796 diag::note_compat_assoc)
1797 << Types[i]->getTypeLoc().getSourceRange()
1798 << Types[i]->getType();
1799 TypeErrorFound = true;
1800 }
1801 }
1802 }
1803 }
1804 if (TypeErrorFound)
1805 return ExprError();
1806
1807 // If we determined that the generic selection is result-dependent, don't
1808 // try to compute the result expression.
1809 if (IsResultDependent) {
1810 if (ControllingExpr)
1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1812 Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1815 Exprs, DefaultLoc, RParenLoc,
1816 ContainsUnexpandedParameterPack);
1817 }
1818
1819 SmallVector<unsigned, 1> CompatIndices;
1820 unsigned DefaultIndex = -1U;
1821 // Look at the canonical type of the controlling expression in case it was a
1822 // deduced type like __auto_type. However, when issuing diagnostics, use the
1823 // type the user wrote in source rather than the canonical one.
1824 for (unsigned i = 0; i < NumAssocs; ++i) {
1825 if (!Types[i])
1826 DefaultIndex = i;
1827 else if (ControllingExpr &&
1829 ControllingExpr->getType().getCanonicalType(),
1830 Types[i]->getType()))
1831 CompatIndices.push_back(i);
1832 else if (ControllingType &&
1834 ControllingType->getType().getCanonicalType(),
1835 Types[i]->getType()))
1836 CompatIndices.push_back(i);
1837 }
1838
1839 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1840 TypeSourceInfo *ControllingType) {
1841 // We strip parens here because the controlling expression is typically
1842 // parenthesized in macro definitions.
1843 if (ControllingExpr)
1844 ControllingExpr = ControllingExpr->IgnoreParens();
1845
1846 SourceRange SR = ControllingExpr
1847 ? ControllingExpr->getSourceRange()
1848 : ControllingType->getTypeLoc().getSourceRange();
1849 QualType QT = ControllingExpr ? ControllingExpr->getType()
1850 : ControllingType->getType();
1851
1852 return std::make_pair(SR, QT);
1853 };
1854
1855 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1856 // type compatible with at most one of the types named in its generic
1857 // association list."
1858 if (CompatIndices.size() > 1) {
1859 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1860 SourceRange SR = P.first;
1861 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1862 << SR << P.second << (unsigned)CompatIndices.size();
1863 for (unsigned I : CompatIndices) {
1864 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1865 diag::note_compat_assoc)
1866 << Types[I]->getTypeLoc().getSourceRange()
1867 << Types[I]->getType();
1868 }
1869 return ExprError();
1870 }
1871
1872 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1873 // its controlling expression shall have type compatible with exactly one of
1874 // the types named in its generic association list."
1875 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1876 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1877 SourceRange SR = P.first;
1878 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1879 return ExprError();
1880 }
1881
1882 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1883 // type name that is compatible with the type of the controlling expression,
1884 // then the result expression of the generic selection is the expression
1885 // in that generic association. Otherwise, the result expression of the
1886 // generic selection is the expression in the default generic association."
1887 unsigned ResultIndex =
1888 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1889
1890 if (ControllingExpr) {
1892 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1893 ContainsUnexpandedParameterPack, ResultIndex);
1894 }
1896 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898}
1899
1901 switch (Kind) {
1902 default:
1903 llvm_unreachable("unexpected TokenKind");
1904 case tok::kw___func__:
1905 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1906 case tok::kw___FUNCTION__:
1908 case tok::kw___FUNCDNAME__:
1909 return PredefinedIdentKind::FuncDName; // [MS]
1910 case tok::kw___FUNCSIG__:
1911 return PredefinedIdentKind::FuncSig; // [MS]
1912 case tok::kw_L__FUNCTION__:
1913 return PredefinedIdentKind::LFunction; // [MS]
1914 case tok::kw_L__FUNCSIG__:
1915 return PredefinedIdentKind::LFuncSig; // [MS]
1916 case tok::kw___PRETTY_FUNCTION__:
1918 }
1919}
1920
1921/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1922/// to determine the value of a PredefinedExpr. This can be either a
1923/// block, lambda, captured statement, function, otherwise a nullptr.
1925 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1926 DC = DC->getParent();
1927 return cast_or_null<Decl>(DC);
1928}
1929
1930/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1931/// location of the token and the offset of the ud-suffix within it.
1933 unsigned Offset) {
1934 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1935 S.getLangOpts());
1936}
1937
1938/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1939/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1941 IdentifierInfo *UDSuffix,
1942 SourceLocation UDSuffixLoc,
1943 ArrayRef<Expr*> Args,
1944 SourceLocation LitEndLoc) {
1945 assert(Args.size() <= 2 && "too many arguments for literal operator");
1946
1947 QualType ArgTy[2];
1948 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1949 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1950 if (ArgTy[ArgIdx]->isArrayType())
1951 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1952 }
1953
1954 DeclarationName OpName =
1956 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1957 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1958
1959 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1960 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1961 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1962 /*AllowStringTemplatePack*/ false,
1963 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1964 return ExprError();
1965
1966 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1967}
1968
1970 // StringToks needs backing storage as it doesn't hold array elements itself
1971 std::vector<Token> ExpandedToks;
1972 if (getLangOpts().MicrosoftExt)
1973 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1974
1975 StringLiteralParser Literal(StringToks, PP,
1977 if (Literal.hadError)
1978 return ExprError();
1979
1980 SmallVector<SourceLocation, 4> StringTokLocs;
1981 for (const Token &Tok : StringToks)
1982 StringTokLocs.push_back(Tok.getLocation());
1983
1985 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1986 &StringTokLocs[0], StringTokLocs.size());
1987
1988 if (!Literal.getUDSuffix().empty()) {
1989 SourceLocation UDSuffixLoc =
1990 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1991 Literal.getUDSuffixOffset());
1992 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1993 }
1994
1995 return Lit;
1996}
1997
1998std::vector<Token>
2000 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2001 // local macros that expand to string literals that may be concatenated.
2002 // These macros are expanded here (in Sema), because StringLiteralParser
2003 // (in Lex) doesn't know the enclosing function (because it hasn't been
2004 // parsed yet).
2005 assert(getLangOpts().MicrosoftExt);
2006
2007 // Note: Although function local macros are defined only inside functions,
2008 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2009 // expansion of macros into empty string literals without additional checks.
2010 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2011 if (!CurrentDecl)
2012 CurrentDecl = Context.getTranslationUnitDecl();
2013
2014 std::vector<Token> ExpandedToks;
2015 ExpandedToks.reserve(Toks.size());
2016 for (const Token &Tok : Toks) {
2017 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2018 assert(tok::isStringLiteral(Tok.getKind()));
2019 ExpandedToks.emplace_back(Tok);
2020 continue;
2021 }
2022 if (isa<TranslationUnitDecl>(CurrentDecl))
2023 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2024 // Stringify predefined expression
2025 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2026 << Tok.getKind();
2027 SmallString<64> Str;
2028 llvm::raw_svector_ostream OS(Str);
2029 Token &Exp = ExpandedToks.emplace_back();
2030 Exp.startToken();
2031 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2032 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2033 OS << 'L';
2034 Exp.setKind(tok::wide_string_literal);
2035 } else {
2036 Exp.setKind(tok::string_literal);
2037 }
2038 OS << '"'
2040 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2041 << '"';
2042 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2043 }
2044 return ExpandedToks;
2045}
2046
2049 assert(!StringToks.empty() && "Must have at least one string!");
2050
2051 // StringToks needs backing storage as it doesn't hold array elements itself
2052 std::vector<Token> ExpandedToks;
2053 if (getLangOpts().MicrosoftExt)
2054 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2055
2056 StringLiteralParser Literal(StringToks, PP);
2057 if (Literal.hadError)
2058 return ExprError();
2059
2060 SmallVector<SourceLocation, 4> StringTokLocs;
2061 for (const Token &Tok : StringToks)
2062 StringTokLocs.push_back(Tok.getLocation());
2063
2064 QualType CharTy = Context.CharTy;
2066 if (Literal.isWide()) {
2067 CharTy = Context.getWideCharType();
2069 } else if (Literal.isUTF8()) {
2070 if (getLangOpts().Char8)
2071 CharTy = Context.Char8Ty;
2072 else if (getLangOpts().C23)
2073 CharTy = Context.UnsignedCharTy;
2075 } else if (Literal.isUTF16()) {
2076 CharTy = Context.Char16Ty;
2078 } else if (Literal.isUTF32()) {
2079 CharTy = Context.Char32Ty;
2081 } else if (Literal.isPascal()) {
2082 CharTy = Context.UnsignedCharTy;
2083 }
2084
2085 // Warn on u8 string literals before C++20 and C23, whose type
2086 // was an array of char before but becomes an array of char8_t.
2087 // In C++20, it cannot be used where a pointer to char is expected.
2088 // In C23, it might have an unexpected value if char was signed.
2089 if (Kind == StringLiteralKind::UTF8 &&
2091 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2092 : !getLangOpts().C23)) {
2093 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2094 ? diag::warn_cxx20_compat_utf8_string
2095 : diag::warn_c23_compat_utf8_string);
2096
2097 // Create removals for all 'u8' prefixes in the string literal(s). This
2098 // ensures C++20/C23 compatibility (but may change the program behavior when
2099 // built by non-Clang compilers for which the execution character set is
2100 // not always UTF-8).
2101 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2102 SourceLocation RemovalDiagLoc;
2103 for (const Token &Tok : StringToks) {
2104 if (Tok.getKind() == tok::utf8_string_literal) {
2105 if (RemovalDiagLoc.isInvalid())
2106 RemovalDiagLoc = Tok.getLocation();
2108 Tok.getLocation(),
2109 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2111 }
2112 }
2113 Diag(RemovalDiagLoc, RemovalDiag);
2114 }
2115
2116 QualType StrTy =
2117 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2118
2119 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2120 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2121 Kind, Literal.Pascal, StrTy,
2122 &StringTokLocs[0],
2123 StringTokLocs.size());
2124 if (Literal.getUDSuffix().empty())
2125 return Lit;
2126
2127 // We're building a user-defined literal.
2128 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2129 SourceLocation UDSuffixLoc =
2130 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2131 Literal.getUDSuffixOffset());
2132
2133 // Make sure we're allowed user-defined literals here.
2134 if (!UDLScope)
2135 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2136
2137 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2138 // operator "" X (str, len)
2139 QualType SizeType = Context.getSizeType();
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 QualType ArgTy[] = {
2147 Context.getArrayDecayedType(StrTy), SizeType
2148 };
2149
2150 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2151 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2152 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2153 /*AllowStringTemplatePack*/ true,
2154 /*DiagnoseMissing*/ true, Lit)) {
2155
2156 case LOLR_Cooked: {
2157 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2158 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2159 StringTokLocs[0]);
2160 Expr *Args[] = { Lit, LenArg };
2161
2162 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2163 }
2164
2165 case LOLR_Template: {
2166 TemplateArgumentListInfo ExplicitArgs;
2167 TemplateArgument Arg(Lit);
2168 TemplateArgumentLocInfo ArgInfo(Lit);
2169 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2170 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2171 &ExplicitArgs);
2172 }
2173
2175 TemplateArgumentListInfo ExplicitArgs;
2176
2177 unsigned CharBits = Context.getIntWidth(CharTy);
2178 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2179 llvm::APSInt Value(CharBits, CharIsUnsigned);
2180
2181 TemplateArgument TypeArg(CharTy);
2183 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2184
2185 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2186 Value = Lit->getCodeUnit(I);
2187 TemplateArgument Arg(Context, Value, CharTy);
2189 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2190 }
2191 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2192 &ExplicitArgs);
2193 }
2194 case LOLR_Raw:
2196 llvm_unreachable("unexpected literal operator lookup result");
2197 case LOLR_Error:
2198 return ExprError();
2199 }
2200 llvm_unreachable("unexpected literal operator lookup result");
2201}
2202
2206 const CXXScopeSpec *SS) {
2207 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2208 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2209}
2210
2213 const DeclarationNameInfo &NameInfo,
2214 const CXXScopeSpec *SS, NamedDecl *FoundD,
2215 SourceLocation TemplateKWLoc,
2216 const TemplateArgumentListInfo *TemplateArgs) {
2219 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2220 TemplateArgs);
2221}
2222
2223// CUDA/HIP: Check whether a captured reference variable is referencing a
2224// host variable in a device or host device lambda.
2226 VarDecl *VD) {
2227 if (!S.getLangOpts().CUDA || !VD->hasInit())
2228 return false;
2229 assert(VD->getType()->isReferenceType());
2230
2231 // Check whether the reference variable is referencing a host variable.
2232 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2233 if (!DRE)
2234 return false;
2235 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2236 if (!Referee || !Referee->hasGlobalStorage() ||
2237 Referee->hasAttr<CUDADeviceAttr>())
2238 return false;
2239
2240 // Check whether the current function is a device or host device lambda.
2241 // Check whether the reference variable is a capture by getDeclContext()
2242 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2243 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2244 if (MD && MD->getParent()->isLambda() &&
2245 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2246 VD->getDeclContext() != MD)
2247 return true;
2248
2249 return false;
2250}
2251
2253 // A declaration named in an unevaluated operand never constitutes an odr-use.
2255 return NOUR_Unevaluated;
2256
2257 // C++2a [basic.def.odr]p4:
2258 // A variable x whose name appears as a potentially-evaluated expression e
2259 // is odr-used by e unless [...] x is a reference that is usable in
2260 // constant expressions.
2261 // CUDA/HIP:
2262 // If a reference variable referencing a host variable is captured in a
2263 // device or host device lambda, the value of the referee must be copied
2264 // to the capture and the reference variable must be treated as odr-use
2265 // since the value of the referee is not known at compile time and must
2266 // be loaded from the captured.
2267 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268 if (VD->getType()->isReferenceType() &&
2269 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2271 VD->isUsableInConstantExpressions(Context))
2272 return NOUR_Constant;
2273 }
2274
2275 // All remaining non-variable cases constitute an odr-use. For variables, we
2276 // need to wait and see how the expression is used.
2277 return NOUR_None;
2278}
2279
2282 const DeclarationNameInfo &NameInfo,
2283 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2284 SourceLocation TemplateKWLoc,
2285 const TemplateArgumentListInfo *TemplateArgs) {
2286 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2287 NeedToCaptureVariable(D, NameInfo.getLoc());
2288
2290 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2291 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2293
2294 // C++ [except.spec]p17:
2295 // An exception-specification is considered to be needed when:
2296 // - in an expression, the function is the unique lookup result or
2297 // the selected member of a set of overloaded functions.
2298 //
2299 // We delay doing this until after we've built the function reference and
2300 // marked it as used so that:
2301 // a) if the function is defaulted, we get errors from defining it before /
2302 // instead of errors from computing its exception specification, and
2303 // b) if the function is a defaulted comparison, we can use the body we
2304 // build when defining it as input to the exception specification
2305 // computation rather than computing a new body.
2306 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2307 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2308 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2310 }
2311 }
2312
2313 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2315 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2317
2318 const auto *FD = dyn_cast<FieldDecl>(D);
2319 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2320 FD = IFD->getAnonField();
2321 if (FD) {
2322 UnusedPrivateFields.remove(FD);
2323 // Just in case we're building an illegal pointer-to-member.
2324 if (FD->isBitField())
2326 }
2327
2328 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2329 // designates a bit-field.
2330 if (const auto *BD = dyn_cast<BindingDecl>(D))
2331 if (const auto *BE = BD->getBinding())
2332 E->setObjectKind(BE->getObjectKind());
2333
2334 return E;
2335}
2336
2337void
2340 DeclarationNameInfo &NameInfo,
2341 const TemplateArgumentListInfo *&TemplateArgs) {
2342 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2343 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2344 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2345
2346 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2347 Id.TemplateId->NumArgs);
2348 translateTemplateArguments(TemplateArgsPtr, Buffer);
2349
2350 TemplateName TName = Id.TemplateId->Template.get();
2351 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2352 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2353 TemplateArgs = &Buffer;
2354 } else {
2355 NameInfo = GetNameFromUnqualifiedId(Id);
2356 TemplateArgs = nullptr;
2357 }
2358}
2359
2361 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2363 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2364 DeclContext *Ctx =
2365 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2366 if (!TC) {
2367 // Emit a special diagnostic for failed member lookups.
2368 // FIXME: computing the declaration context might fail here (?)
2369 if (Ctx)
2370 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2371 << SS.getRange();
2372 else
2373 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2374 return;
2375 }
2376
2377 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2378 bool DroppedSpecifier =
2379 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2380 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2381 ? diag::note_implicit_param_decl
2382 : diag::note_previous_decl;
2383 if (!Ctx)
2384 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2385 SemaRef.PDiag(NoteID));
2386 else
2387 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2388 << Typo << Ctx << DroppedSpecifier
2389 << SS.getRange(),
2390 SemaRef.PDiag(NoteID));
2391}
2392
2394 // During a default argument instantiation the CurContext points
2395 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2396 // function parameter list, hence add an explicit check.
2397 bool isDefaultArgument =
2398 !CodeSynthesisContexts.empty() &&
2399 CodeSynthesisContexts.back().Kind ==
2401 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2402 bool isInstance = CurMethod && CurMethod->isInstance() &&
2403 R.getNamingClass() == CurMethod->getParent() &&
2404 !isDefaultArgument;
2405
2406 // There are two ways we can find a class-scope declaration during template
2407 // instantiation that we did not find in the template definition: if it is a
2408 // member of a dependent base class, or if it is declared after the point of
2409 // use in the same class. Distinguish these by comparing the class in which
2410 // the member was found to the naming class of the lookup.
2411 unsigned DiagID = diag::err_found_in_dependent_base;
2412 unsigned NoteID = diag::note_member_declared_at;
2414 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2415 : diag::err_found_later_in_class;
2416 } else if (getLangOpts().MSVCCompat) {
2417 DiagID = diag::ext_found_in_dependent_base;
2418 NoteID = diag::note_dependent_member_use;
2419 }
2420
2421 if (isInstance) {
2422 // Give a code modification hint to insert 'this->'.
2423 Diag(R.getNameLoc(), DiagID)
2424 << R.getLookupName()
2425 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2427 } else {
2428 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2429 // they're not shadowed).
2430 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2431 }
2432
2433 for (const NamedDecl *D : R)
2434 Diag(D->getLocation(), NoteID);
2435
2436 // Return true if we are inside a default argument instantiation
2437 // and the found name refers to an instance member function, otherwise
2438 // the caller will try to create an implicit member call and this is wrong
2439 // for default arguments.
2440 //
2441 // FIXME: Is this special case necessary? We could allow the caller to
2442 // diagnose this.
2443 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2444 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2445 return true;
2446 }
2447
2448 // Tell the callee to try to recover.
2449 return false;
2450}
2451
2454 TemplateArgumentListInfo *ExplicitTemplateArgs,
2455 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2456 TypoExpr **Out) {
2457 DeclarationName Name = R.getLookupName();
2458
2459 unsigned diagnostic = diag::err_undeclared_var_use;
2460 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2461 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2462 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2463 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2464 diagnostic = diag::err_undeclared_use;
2465 diagnostic_suggest = diag::err_undeclared_use_suggest;
2466 }
2467
2468 // If the original lookup was an unqualified lookup, fake an
2469 // unqualified lookup. This is useful when (for example) the
2470 // original lookup would not have found something because it was a
2471 // dependent name.
2472 DeclContext *DC =
2473 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2474 while (DC) {
2475 if (isa<CXXRecordDecl>(DC)) {
2476 if (ExplicitTemplateArgs) {
2478 R, S, SS, Context.getRecordType(cast<CXXRecordDecl>(DC)),
2479 /*EnteringContext*/ false, TemplateNameIsRequired,
2480 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2481 return true;
2482 } else {
2483 LookupQualifiedName(R, DC);
2484 }
2485
2486 if (!R.empty()) {
2487 // Don't give errors about ambiguities in this lookup.
2489
2490 // If there's a best viable function among the results, only mention
2491 // that one in the notes.
2492 OverloadCandidateSet Candidates(R.getNameLoc(),
2494 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2496 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2497 OR_Success) {
2498 R.clear();
2499 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2500 R.resolveKind();
2501 }
2502
2504 }
2505
2506 R.clear();
2507 }
2508
2509 DC = DC->getLookupParent();
2510 }
2511
2512 // We didn't find anything, so try to correct for a typo.
2513 TypoCorrection Corrected;
2514 if (S && Out) {
2515 SourceLocation TypoLoc = R.getNameLoc();
2516 assert(!ExplicitTemplateArgs &&
2517 "Diagnosing an empty lookup with explicit template args!");
2518 *Out = CorrectTypoDelayed(
2519 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2520 [=](const TypoCorrection &TC) {
2521 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2522 diagnostic, diagnostic_suggest);
2523 },
2524 nullptr, CTK_ErrorRecovery, LookupCtx);
2525 if (*Out)
2526 return true;
2527 } else if (S && (Corrected =
2529 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2530 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2531 bool DroppedSpecifier =
2532 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2533 R.setLookupName(Corrected.getCorrection());
2534
2535 bool AcceptableWithRecovery = false;
2536 bool AcceptableWithoutRecovery = false;
2537 NamedDecl *ND = Corrected.getFoundDecl();
2538 if (ND) {
2539 if (Corrected.isOverloaded()) {
2543 for (NamedDecl *CD : Corrected) {
2544 if (FunctionTemplateDecl *FTD =
2545 dyn_cast<FunctionTemplateDecl>(CD))
2547 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2548 Args, OCS);
2549 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2550 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2552 Args, OCS);
2553 }
2554 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2555 case OR_Success:
2556 ND = Best->FoundDecl;
2557 Corrected.setCorrectionDecl(ND);
2558 break;
2559 default:
2560 // FIXME: Arbitrarily pick the first declaration for the note.
2561 Corrected.setCorrectionDecl(ND);
2562 break;
2563 }
2564 }
2565 R.addDecl(ND);
2566 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2567 CXXRecordDecl *Record = nullptr;
2568 if (Corrected.getCorrectionSpecifier()) {
2569 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2570 Record = Ty->getAsCXXRecordDecl();
2571 }
2572 if (!Record)
2573 Record = cast<CXXRecordDecl>(
2576 }
2577
2578 auto *UnderlyingND = ND->getUnderlyingDecl();
2579 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2580 isa<FunctionTemplateDecl>(UnderlyingND);
2581 // FIXME: If we ended up with a typo for a type name or
2582 // Objective-C class name, we're in trouble because the parser
2583 // is in the wrong place to recover. Suggest the typo
2584 // correction, but don't make it a fix-it since we're not going
2585 // to recover well anyway.
2586 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2587 getAsTypeTemplateDecl(UnderlyingND) ||
2588 isa<ObjCInterfaceDecl>(UnderlyingND);
2589 } else {
2590 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2591 // because we aren't able to recover.
2592 AcceptableWithoutRecovery = true;
2593 }
2594
2595 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2596 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2597 ? diag::note_implicit_param_decl
2598 : diag::note_previous_decl;
2599 if (SS.isEmpty())
2600 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2601 PDiag(NoteID), AcceptableWithRecovery);
2602 else
2603 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2604 << Name << computeDeclContext(SS, false)
2605 << DroppedSpecifier << SS.getRange(),
2606 PDiag(NoteID), AcceptableWithRecovery);
2607
2608 // Tell the callee whether to try to recover.
2609 return !AcceptableWithRecovery;
2610 }
2611 }
2612 R.clear();
2613
2614 // Emit a special diagnostic for failed member lookups.
2615 // FIXME: computing the declaration context might fail here (?)
2616 if (!SS.isEmpty()) {
2617 Diag(R.getNameLoc(), diag::err_no_member)
2618 << Name << computeDeclContext(SS, false)
2619 << SS.getRange();
2620 return true;
2621 }
2622
2623 // Give up, we can't recover.
2624 Diag(R.getNameLoc(), diagnostic) << Name;
2625 return true;
2626}
2627
2628/// In Microsoft mode, if we are inside a template class whose parent class has
2629/// dependent base classes, and we can't resolve an unqualified identifier, then
2630/// assume the identifier is a member of a dependent base class. We can only
2631/// recover successfully in static methods, instance methods, and other contexts
2632/// where 'this' is available. This doesn't precisely match MSVC's
2633/// instantiation model, but it's close enough.
2634static Expr *
2636 DeclarationNameInfo &NameInfo,
2637 SourceLocation TemplateKWLoc,
2638 const TemplateArgumentListInfo *TemplateArgs) {
2639 // Only try to recover from lookup into dependent bases in static methods or
2640 // contexts where 'this' is available.
2641 QualType ThisType = S.getCurrentThisType();
2642 const CXXRecordDecl *RD = nullptr;
2643 if (!ThisType.isNull())
2644 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2645 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2646 RD = MD->getParent();
2647 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2648 return nullptr;
2649
2650 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2651 // is available, suggest inserting 'this->' as a fixit.
2652 SourceLocation Loc = NameInfo.getLoc();
2653 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2654 DB << NameInfo.getName() << RD;
2655
2656 if (!ThisType.isNull()) {
2657 DB << FixItHint::CreateInsertion(Loc, "this->");
2659 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2660 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2661 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2662 }
2663
2664 // Synthesize a fake NNS that points to the derived class. This will
2665 // perform name lookup during template instantiation.
2666 CXXScopeSpec SS;
2667 auto *NNS =
2668 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2669 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2671 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2672 TemplateArgs);
2673}
2674
2677 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2678 bool HasTrailingLParen, bool IsAddressOfOperand,
2680 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2681 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2682 "cannot be direct & operand and have a trailing lparen");
2683 if (SS.isInvalid())
2684 return ExprError();
2685
2686 TemplateArgumentListInfo TemplateArgsBuffer;
2687
2688 // Decompose the UnqualifiedId into the following data.
2689 DeclarationNameInfo NameInfo;
2690 const TemplateArgumentListInfo *TemplateArgs;
2691 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2692
2693 DeclarationName Name = NameInfo.getName();
2694 IdentifierInfo *II = Name.getAsIdentifierInfo();
2695 SourceLocation NameLoc = NameInfo.getLoc();
2696
2697 if (II && II->isEditorPlaceholder()) {
2698 // FIXME: When typed placeholders are supported we can create a typed
2699 // placeholder expression node.
2700 return ExprError();
2701 }
2702
2703 // This specially handles arguments of attributes appertains to a type of C
2704 // struct field such that the name lookup within a struct finds the member
2705 // name, which is not the case for other contexts in C.
2706 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2707 // See if this is reference to a field of struct.
2708 LookupResult R(*this, NameInfo, LookupMemberName);
2709 // LookupName handles a name lookup from within anonymous struct.
2710 if (LookupName(R, S)) {
2711 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2712 QualType type = VD->getType().getNonReferenceType();
2713 // This will eventually be translated into MemberExpr upon
2714 // the use of instantiated struct fields.
2715 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2716 }
2717 }
2718 }
2719
2720 // Perform the required lookup.
2721 LookupResult R(*this, NameInfo,
2725 if (TemplateKWLoc.isValid() || TemplateArgs) {
2726 // Lookup the template name again to correctly establish the context in
2727 // which it was found. This is really unfortunate as we already did the
2728 // lookup to determine that it was a template name in the first place. If
2729 // this becomes a performance hit, we can work harder to preserve those
2730 // results until we get here but it's likely not worth it.
2731 AssumedTemplateKind AssumedTemplate;
2732 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2733 /*EnteringContext=*/false, TemplateKWLoc,
2734 &AssumedTemplate))
2735 return ExprError();
2736
2738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2739 IsAddressOfOperand, TemplateArgs);
2740 } else {
2741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2742 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2743 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2744
2745 // If the result might be in a dependent base class, this is a dependent
2746 // id-expression.
2748 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2749 IsAddressOfOperand, TemplateArgs);
2750
2751 // If this reference is in an Objective-C method, then we need to do
2752 // some special Objective-C lookup, too.
2753 if (IvarLookupFollowUp) {
2754 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2755 if (E.isInvalid())
2756 return ExprError();
2757
2758 if (Expr *Ex = E.getAs<Expr>())
2759 return Ex;
2760 }
2761 }
2762
2763 if (R.isAmbiguous())
2764 return ExprError();
2765
2766 // This could be an implicitly declared function reference if the language
2767 // mode allows it as a feature.
2768 if (R.empty() && HasTrailingLParen && II &&
2769 getLangOpts().implicitFunctionsAllowed()) {
2770 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2771 if (D) R.addDecl(D);
2772 }
2773
2774 // Determine whether this name might be a candidate for
2775 // argument-dependent lookup.
2776 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2777
2778 if (R.empty() && !ADL) {
2779 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2780 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2781 TemplateKWLoc, TemplateArgs))
2782 return E;
2783 }
2784
2785 // Don't diagnose an empty lookup for inline assembly.
2786 if (IsInlineAsmIdentifier)
2787 return ExprError();
2788
2789 // If this name wasn't predeclared and if this is not a function
2790 // call, diagnose the problem.
2791 TypoExpr *TE = nullptr;
2792 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2793 : nullptr);
2794 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2795 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2796 "Typo correction callback misconfigured");
2797 if (CCC) {
2798 // Make sure the callback knows what the typo being diagnosed is.
2799 CCC->setTypoName(II);
2800 if (SS.isValid())
2801 CCC->setTypoNNS(SS.getScopeRep());
2802 }
2803 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2804 // a template name, but we happen to have always already looked up the name
2805 // before we get here if it must be a template name.
2806 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2807 {}, nullptr, &TE)) {
2808 if (TE && KeywordReplacement) {
2809 auto &State = getTypoExprState(TE);
2810 auto BestTC = State.Consumer->getNextCorrection();
2811 if (BestTC.isKeyword()) {
2812 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2813 if (State.DiagHandler)
2814 State.DiagHandler(BestTC);
2815 KeywordReplacement->startToken();
2816 KeywordReplacement->setKind(II->getTokenID());
2817 KeywordReplacement->setIdentifierInfo(II);
2818 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2819 // Clean up the state associated with the TypoExpr, since it has
2820 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2821 clearDelayedTypo(TE);
2822 // Signal that a correction to a keyword was performed by returning a
2823 // valid-but-null ExprResult.
2824 return (Expr*)nullptr;
2825 }
2826 State.Consumer->resetCorrectionStream();
2827 }
2828 return TE ? TE : ExprError();
2829 }
2830
2831 assert(!R.empty() &&
2832 "DiagnoseEmptyLookup returned false but added no results");
2833
2834 // If we found an Objective-C instance variable, let
2835 // LookupInObjCMethod build the appropriate expression to
2836 // reference the ivar.
2837 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2838 R.clear();
2839 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2840 // In a hopelessly buggy code, Objective-C instance variable
2841 // lookup fails and no expression will be built to reference it.
2842 if (!E.isInvalid() && !E.get())
2843 return ExprError();
2844 return E;
2845 }
2846 }
2847
2848 // This is guaranteed from this point on.
2849 assert(!R.empty() || ADL);
2850
2851 // Check whether this might be a C++ implicit instance member access.
2852 // C++ [class.mfct.non-static]p3:
2853 // When an id-expression that is not part of a class member access
2854 // syntax and not used to form a pointer to member is used in the
2855 // body of a non-static member function of class X, if name lookup
2856 // resolves the name in the id-expression to a non-static non-type
2857 // member of some class C, the id-expression is transformed into a
2858 // class member access expression using (*this) as the
2859 // postfix-expression to the left of the . operator.
2860 //
2861 // But we don't actually need to do this for '&' operands if R
2862 // resolved to a function or overloaded function set, because the
2863 // expression is ill-formed if it actually works out to be a
2864 // non-static member function:
2865 //
2866 // C++ [expr.ref]p4:
2867 // Otherwise, if E1.E2 refers to a non-static member function. . .
2868 // [t]he expression can be used only as the left-hand operand of a
2869 // member function call.
2870 //
2871 // There are other safeguards against such uses, but it's important
2872 // to get this right here so that we don't end up making a
2873 // spuriously dependent expression if we're inside a dependent
2874 // instance method.
2875 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2876 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2877 S);
2878
2879 if (TemplateArgs || TemplateKWLoc.isValid()) {
2880
2881 // In C++1y, if this is a variable template id, then check it
2882 // in BuildTemplateIdExpr().
2883 // The single lookup result must be a variable template declaration.
2884 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2885 Id.TemplateId->Kind == TNK_Var_template) {
2886 assert(R.getAsSingle<VarTemplateDecl>() &&
2887 "There should only be one declaration found.");
2888 }
2889
2890 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2891 }
2892
2893 return BuildDeclarationNameExpr(SS, R, ADL);
2894}
2895
2897 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2898 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2899 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2900 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2901
2902 if (R.isAmbiguous())
2903 return ExprError();
2904
2906 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2907 NameInfo, /*TemplateArgs=*/nullptr);
2908
2909 if (R.empty()) {
2910 // Don't diagnose problems with invalid record decl, the secondary no_member
2911 // diagnostic during template instantiation is likely bogus, e.g. if a class
2912 // is invalid because it's derived from an invalid base class, then missing
2913 // members were likely supposed to be inherited.
2915 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2916 if (CD->isInvalidDecl())
2917 return ExprError();
2918 Diag(NameInfo.getLoc(), diag::err_no_member)
2919 << NameInfo.getName() << DC << SS.getRange();
2920 return ExprError();
2921 }
2922
2923 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2924 // Diagnose a missing typename if this resolved unambiguously to a type in
2925 // a dependent context. If we can recover with a type, downgrade this to
2926 // a warning in Microsoft compatibility mode.
2927 unsigned DiagID = diag::err_typename_missing;
2928 if (RecoveryTSI && getLangOpts().MSVCCompat)
2929 DiagID = diag::ext_typename_missing;
2931 auto D = Diag(Loc, DiagID);
2932 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2933 << SourceRange(Loc, NameInfo.getEndLoc());
2934
2935 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2936 // context.
2937 if (!RecoveryTSI)
2938 return ExprError();
2939
2940 // Only issue the fixit if we're prepared to recover.
2941 D << FixItHint::CreateInsertion(Loc, "typename ");
2942
2943 // Recover by pretending this was an elaborated type.
2945 TypeLocBuilder TLB;
2946 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2947
2952
2953 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2954
2955 return ExprEmpty();
2956 }
2957
2958 // If necessary, build an implicit class member access.
2959 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2961 /*TemplateKWLoc=*/SourceLocation(),
2962 R, /*TemplateArgs=*/nullptr,
2963 /*S=*/nullptr);
2964
2965 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2966}
2967
2970 NestedNameSpecifier *Qualifier,
2971 NamedDecl *FoundDecl,
2972 NamedDecl *Member) {
2973 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2974 if (!RD)
2975 return From;
2976
2977 QualType DestRecordType;
2978 QualType DestType;
2979 QualType FromRecordType;
2980 QualType FromType = From->getType();
2981 bool PointerConversions = false;
2982 if (isa<FieldDecl>(Member)) {
2983 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2984 auto FromPtrType = FromType->getAs<PointerType>();
2985 DestRecordType = Context.getAddrSpaceQualType(
2986 DestRecordType, FromPtrType
2987 ? FromType->getPointeeType().getAddressSpace()
2988 : FromType.getAddressSpace());
2989
2990 if (FromPtrType) {
2991 DestType = Context.getPointerType(DestRecordType);
2992 FromRecordType = FromPtrType->getPointeeType();
2993 PointerConversions = true;
2994 } else {
2995 DestType = DestRecordType;
2996 FromRecordType = FromType;
2997 }
2998 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2999 if (!Method->isImplicitObjectMemberFunction())
3000 return From;
3001
3002 DestType = Method->getThisType().getNonReferenceType();
3003 DestRecordType = Method->getFunctionObjectParameterType();
3004
3005 if (FromType->getAs<PointerType>()) {
3006 FromRecordType = FromType->getPointeeType();
3007 PointerConversions = true;
3008 } else {
3009 FromRecordType = FromType;
3010 DestType = DestRecordType;
3011 }
3012
3013 LangAS FromAS = FromRecordType.getAddressSpace();
3014 LangAS DestAS = DestRecordType.getAddressSpace();
3015 if (FromAS != DestAS) {
3016 QualType FromRecordTypeWithoutAS =
3017 Context.removeAddrSpaceQualType(FromRecordType);
3018 QualType FromTypeWithDestAS =
3019 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3020 if (PointerConversions)
3021 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3022 From = ImpCastExprToType(From, FromTypeWithDestAS,
3023 CK_AddressSpaceConversion, From->getValueKind())
3024 .get();
3025 }
3026 } else {
3027 // No conversion necessary.
3028 return From;
3029 }
3030
3031 if (DestType->isDependentType() || FromType->isDependentType())
3032 return From;
3033
3034 // If the unqualified types are the same, no conversion is necessary.
3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3036 return From;
3037
3038 SourceRange FromRange = From->getSourceRange();
3039 SourceLocation FromLoc = FromRange.getBegin();
3040
3041 ExprValueKind VK = From->getValueKind();
3042
3043 // C++ [class.member.lookup]p8:
3044 // [...] Ambiguities can often be resolved by qualifying a name with its
3045 // class name.
3046 //
3047 // If the member was a qualified name and the qualified referred to a
3048 // specific base subobject type, we'll cast to that intermediate type
3049 // first and then to the object in which the member is declared. That allows
3050 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3051 //
3052 // class Base { public: int x; };
3053 // class Derived1 : public Base { };
3054 // class Derived2 : public Base { };
3055 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3056 //
3057 // void VeryDerived::f() {
3058 // x = 17; // error: ambiguous base subobjects
3059 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3060 // }
3061 if (Qualifier && Qualifier->getAsType()) {
3062 QualType QType = QualType(Qualifier->getAsType(), 0);
3063 assert(QType->isRecordType() && "lookup done with non-record type");
3064
3065 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3066
3067 // In C++98, the qualifier type doesn't actually have to be a base
3068 // type of the object type, in which case we just ignore it.
3069 // Otherwise build the appropriate casts.
3070 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3071 CXXCastPath BasePath;
3072 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3073 FromLoc, FromRange, &BasePath))
3074 return ExprError();
3075
3076 if (PointerConversions)
3077 QType = Context.getPointerType(QType);
3078 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3079 VK, &BasePath).get();
3080
3081 FromType = QType;
3082 FromRecordType = QRecordType;
3083
3084 // If the qualifier type was the same as the destination type,
3085 // we're done.
3086 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3087 return From;
3088 }
3089 }
3090
3091 CXXCastPath BasePath;
3092 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3093 FromLoc, FromRange, &BasePath,
3094 /*IgnoreAccess=*/true))
3095 return ExprError();
3096
3097 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3098 VK, &BasePath);
3099}
3100
3102 const LookupResult &R,
3103 bool HasTrailingLParen) {
3104 // Only when used directly as the postfix-expression of a call.
3105 if (!HasTrailingLParen)
3106 return false;
3107
3108 // Never if a scope specifier was provided.
3109 if (SS.isNotEmpty())
3110 return false;
3111
3112 // Only in C++ or ObjC++.
3113 if (!getLangOpts().CPlusPlus)
3114 return false;
3115
3116 // Turn off ADL when we find certain kinds of declarations during
3117 // normal lookup:
3118 for (const NamedDecl *D : R) {
3119 // C++0x [basic.lookup.argdep]p3:
3120 // -- a declaration of a class member
3121 // Since using decls preserve this property, we check this on the
3122 // original decl.
3123 if (D->isCXXClassMember())
3124 return false;
3125
3126 // C++0x [basic.lookup.argdep]p3:
3127 // -- a block-scope function declaration that is not a
3128 // using-declaration
3129 // NOTE: we also trigger this for function templates (in fact, we
3130 // don't check the decl type at all, since all other decl types
3131 // turn off ADL anyway).
3132 if (isa<UsingShadowDecl>(D))
3133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135 return false;
3136
3137 // C++0x [basic.lookup.argdep]p3:
3138 // -- a declaration that is neither a function or a function
3139 // template
3140 // And also for builtin functions.
3141 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3142 // But also builtin functions.
3143 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3144 return false;
3145 } else if (!isa<FunctionTemplateDecl>(D))
3146 return false;
3147 }
3148
3149 return true;
3150}
3151
3152
3153/// Diagnoses obvious problems with the use of the given declaration
3154/// as an expression. This is only actually called for lookups that
3155/// were not overloaded, and it doesn't promise that the declaration
3156/// will in fact be used.
3158 bool AcceptInvalid) {
3159 if (D->isInvalidDecl() && !AcceptInvalid)
3160 return true;
3161
3162 if (isa<TypedefNameDecl>(D)) {
3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3164 return true;
3165 }
3166
3167 if (isa<ObjCInterfaceDecl>(D)) {
3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3169 return true;
3170 }
3171
3172 if (isa<NamespaceDecl>(D)) {
3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3174 return true;
3175 }
3176
3177 return false;
3178}
3179
3180// Certain multiversion types should be treated as overloaded even when there is
3181// only one result.
3183 assert(R.isSingleResult() && "Expected only a single result");
3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3185 return FD &&
3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3187}
3188
3190 LookupResult &R, bool NeedsADL,
3191 bool AcceptInvalidDecl) {
3192 // If this is a single, fully-resolved result and we don't need ADL,
3193 // just build an ordinary singleton decl ref.
3194 if (!NeedsADL && R.isSingleResult() &&
3198 R.getRepresentativeDecl(), nullptr,
3199 AcceptInvalidDecl);
3200
3201 // We only need to check the declaration if there's exactly one
3202 // result, because in the overloaded case the results can only be
3203 // functions and function templates.
3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3206 AcceptInvalidDecl))
3207 return ExprError();
3208
3209 // Otherwise, just build an unresolved lookup expression. Suppress
3210 // any lookup-related diagnostics; we'll hash these out later, when
3211 // we've picked a target.
3213
3216 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3217 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3218
3219 return ULE;
3220}
3221
3223 SourceLocation loc,
3224 ValueDecl *var);
3225
3227 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3228 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3229 bool AcceptInvalidDecl) {
3230 assert(D && "Cannot refer to a NULL declaration");
3231 assert(!isa<FunctionTemplateDecl>(D) &&
3232 "Cannot refer unambiguously to a function template");
3233
3234 SourceLocation Loc = NameInfo.getLoc();
3235 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3236 // Recovery from invalid cases (e.g. D is an invalid Decl).
3237 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3238 // diagnostics, as invalid decls use int as a fallback type.
3239 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3240 }
3241
3242 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3243 // Specifically diagnose references to class templates that are missing
3244 // a template argument list.
3245 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3246 return ExprError();
3247 }
3248
3249 // Make sure that we're referring to a value.
3250 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3251 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3252 Diag(D->getLocation(), diag::note_declared_at);
3253 return ExprError();
3254 }
3255
3256 // Check whether this declaration can be used. Note that we suppress
3257 // this check when we're going to perform argument-dependent lookup
3258 // on this function name, because this might not be the function
3259 // that overload resolution actually selects.
3260 if (DiagnoseUseOfDecl(D, Loc))
3261 return ExprError();
3262
3263 auto *VD = cast<ValueDecl>(D);
3264
3265 // Only create DeclRefExpr's for valid Decl's.
3266 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3267 return ExprError();
3268
3269 // Handle members of anonymous structs and unions. If we got here,
3270 // and the reference is to a class member indirect field, then this
3271 // must be the subject of a pointer-to-member expression.
3272 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3273 IndirectField && !IndirectField->isCXXClassMember())
3275 IndirectField);
3276
3277 QualType type = VD->getType();
3278 if (type.isNull())
3279 return ExprError();
3280 ExprValueKind valueKind = VK_PRValue;
3281
3282 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3283 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3284 // is expanded by some outer '...' in the context of the use.
3285 type = type.getNonPackExpansionType();
3286
3287 switch (D->getKind()) {
3288 // Ignore all the non-ValueDecl kinds.
3289#define ABSTRACT_DECL(kind)
3290#define VALUE(type, base)
3291#define DECL(type, base) case Decl::type:
3292#include "clang/AST/DeclNodes.inc"
3293 llvm_unreachable("invalid value decl kind");
3294
3295 // These shouldn't make it here.
3296 case Decl::ObjCAtDefsField:
3297 llvm_unreachable("forming non-member reference to ivar?");
3298
3299 // Enum constants are always r-values and never references.
3300 // Unresolved using declarations are dependent.
3301 case Decl::EnumConstant:
3302 case Decl::UnresolvedUsingValue:
3303 case Decl::OMPDeclareReduction:
3304 case Decl::OMPDeclareMapper:
3305 valueKind = VK_PRValue;
3306 break;
3307
3308 // Fields and indirect fields that got here must be for
3309 // pointer-to-member expressions; we just call them l-values for
3310 // internal consistency, because this subexpression doesn't really
3311 // exist in the high-level semantics.
3312 case Decl::Field:
3313 case Decl::IndirectField:
3314 case Decl::ObjCIvar:
3315 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3316 "building reference to field in C?");
3317
3318 // These can't have reference type in well-formed programs, but
3319 // for internal consistency we do this anyway.
3320 type = type.getNonReferenceType();
3321 valueKind = VK_LValue;
3322 break;
3323
3324 // Non-type template parameters are either l-values or r-values
3325 // depending on the type.
3326 case Decl::NonTypeTemplateParm: {
3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3328 type = reftype->getPointeeType();
3329 valueKind = VK_LValue; // even if the parameter is an r-value reference
3330 break;
3331 }
3332
3333 // [expr.prim.id.unqual]p2:
3334 // If the entity is a template parameter object for a template
3335 // parameter of type T, the type of the expression is const T.
3336 // [...] The expression is an lvalue if the entity is a [...] template
3337 // parameter object.
3338 if (type->isRecordType()) {
3339 type = type.getUnqualifiedType().withConst();
3340 valueKind = VK_LValue;
3341 break;
3342 }
3343
3344 // For non-references, we need to strip qualifiers just in case
3345 // the template parameter was declared as 'const int' or whatever.
3346 valueKind = VK_PRValue;
3347 type = type.getUnqualifiedType();
3348 break;
3349 }
3350
3351 case Decl::Var:
3352 case Decl::VarTemplateSpecialization:
3353 case Decl::VarTemplatePartialSpecialization:
3354 case Decl::Decomposition:
3355 case Decl::Binding:
3356 case Decl::OMPCapturedExpr:
3357 // In C, "extern void blah;" is valid and is an r-value.
3358 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3359 type->isVoidType()) {
3360 valueKind = VK_PRValue;
3361 break;
3362 }
3363 [[fallthrough]];
3364
3365 case Decl::ImplicitParam:
3366 case Decl::ParmVar: {
3367 // These are always l-values.
3368 valueKind = VK_LValue;
3369 type = type.getNonReferenceType();
3370
3371 // FIXME: Does the addition of const really only apply in
3372 // potentially-evaluated contexts? Since the variable isn't actually
3373 // captured in an unevaluated context, it seems that the answer is no.
3374 if (!isUnevaluatedContext()) {
3375 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3376 if (!CapturedType.isNull())
3377 type = CapturedType;
3378 }
3379 break;
3380 }
3381
3382 case Decl::Function: {
3383 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3386 valueKind = VK_PRValue;
3387 break;
3388 }
3389 }
3390
3391 const FunctionType *fty = type->castAs<FunctionType>();
3392
3393 // If we're referring to a function with an __unknown_anytype
3394 // result type, make the entire expression __unknown_anytype.
3395 if (fty->getReturnType() == Context.UnknownAnyTy) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400
3401 // Functions are l-values in C++.
3402 if (getLangOpts().CPlusPlus) {
3403 valueKind = VK_LValue;
3404 break;
3405 }
3406
3407 // C99 DR 316 says that, if a function type comes from a
3408 // function definition (without a prototype), that type is only
3409 // used for checking compatibility. Therefore, when referencing
3410 // the function, we pretend that we don't have the full function
3411 // type.
3412 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3414 fty->getExtInfo());
3415
3416 // Functions are r-values in C.
3417 valueKind = VK_PRValue;
3418 break;
3419 }
3420
3421 case Decl::CXXDeductionGuide:
3422 llvm_unreachable("building reference to deduction guide");
3423
3424 case Decl::MSProperty:
3425 case Decl::MSGuid:
3426 case Decl::TemplateParamObject:
3427 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3428 // capture in OpenMP, or duplicated between host and device?
3429 valueKind = VK_LValue;
3430 break;
3431
3432 case Decl::UnnamedGlobalConstant:
3433 valueKind = VK_LValue;
3434 break;
3435
3436 case Decl::CXXMethod:
3437 // If we're referring to a method with an __unknown_anytype
3438 // result type, make the entire expression __unknown_anytype.
3439 // This should only be possible with a type written directly.
3440 if (const FunctionProtoType *proto =
3441 dyn_cast<FunctionProtoType>(VD->getType()))
3442 if (proto->getReturnType() == Context.UnknownAnyTy) {
3444 valueKind = VK_PRValue;
3445 break;
3446 }
3447
3448 // C++ methods are l-values if static, r-values if non-static.
3449 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3450 valueKind = VK_LValue;
3451 break;
3452 }
3453 [[fallthrough]];
3454
3455 case Decl::CXXConversion:
3456 case Decl::CXXDestructor:
3457 case Decl::CXXConstructor:
3458 valueKind = VK_PRValue;
3459 break;
3460 }
3461
3462 auto *E =
3463 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3464 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3465 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3466 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3467 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3468 // diagnostics).
3469 if (VD->isInvalidDecl() && E)
3470 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3471 return E;
3472}
3473
3474static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3476 Target.resize(CharByteWidth * (Source.size() + 1));
3477 char *ResultPtr = &Target[0];
3478 const llvm::UTF8 *ErrorPtr;
3479 bool success =
3480 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3481 (void)success;
3482 assert(success);
3483 Target.resize(ResultPtr - &Target[0]);
3484}
3485
3488 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3489 if (!currentDecl) {
3490 Diag(Loc, diag::ext_predef_outside_function);
3491 currentDecl = Context.getTranslationUnitDecl();
3492 }
3493
3494 QualType ResTy;
3495 StringLiteral *SL = nullptr;
3496 if (cast<DeclContext>(currentDecl)->isDependentContext())
3497 ResTy = Context.DependentTy;
3498 else {
3499 // Pre-defined identifiers are of type char[x], where x is the length of
3500 // the string.
3501 bool ForceElaboratedPrinting =
3502 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3503 auto Str =
3504 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3505 unsigned Length = Str.length();
3506
3507 llvm::APInt LengthI(32, Length + 1);
3510 ResTy =
3512 SmallString<32> RawChars;
3514 Str, RawChars);
3515 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3517 /*IndexTypeQuals*/ 0);
3519 /*Pascal*/ false, ResTy, Loc);
3520 } else {
3522 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3524 /*IndexTypeQuals*/ 0);
3526 /*Pascal*/ false, ResTy, Loc);
3527 }
3528 }
3529
3530 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3531 SL);
3532}
3533
3536}
3537
3539 SmallString<16> CharBuffer;
3540 bool Invalid = false;
3541 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3542 if (Invalid)
3543 return ExprError();
3544
3545 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3546 PP, Tok.getKind());
3547 if (Literal.hadError())
3548 return ExprError();
3549
3550 QualType Ty;
3551 if (Literal.isWide())
3552 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3553 else if (Literal.isUTF8() && getLangOpts().C23)
3554 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3555 else if (Literal.isUTF8() && getLangOpts().Char8)
3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3557 else if (Literal.isUTF16())
3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3559 else if (Literal.isUTF32())
3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3563 else
3564 Ty = Context.CharTy; // 'x' -> char in C++;
3565 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3566
3568 if (Literal.isWide())
3570 else if (Literal.isUTF16())
3572 else if (Literal.isUTF32())
3574 else if (Literal.isUTF8())
3576
3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3578 Tok.getLocation());
3579
3580 if (Literal.getUDSuffix().empty())
3581 return Lit;
3582
3583 // We're building a user-defined literal.
3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3585 SourceLocation UDSuffixLoc =
3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3587
3588 // Make sure we're allowed user-defined literals here.
3589 if (!UDLScope)
3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3591
3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3593 // operator "" X (ch)
3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3595 Lit, Tok.getLocation());
3596}
3597
3599 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3601 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3602 Context.IntTy, Loc);
3603}
3604
3607 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3608
3609 using llvm::APFloat;
3610 APFloat Val(Format);
3611
3612 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3613 if (RM == llvm::RoundingMode::Dynamic)
3614 RM = llvm::RoundingMode::NearestTiesToEven;
3615 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3616
3617 // Overflow is always an error, but underflow is only an error if
3618 // we underflowed to zero (APFloat reports denormals as underflow).
3619 if ((result & APFloat::opOverflow) ||
3620 ((result & APFloat::opUnderflow) && Val.isZero())) {
3621 unsigned diagnostic;
3622 SmallString<20> buffer;
3623 if (result & APFloat::opOverflow) {
3624 diagnostic = diag::warn_float_overflow;
3625 APFloat::getLargest(Format).toString(buffer);
3626 } else {
3627 diagnostic = diag::warn_float_underflow;
3628 APFloat::getSmallest(Format).toString(buffer);
3629 }
3630
3631 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3632 }
3633
3634 bool isExact = (result == APFloat::opOK);
3635 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3636}
3637
3639 assert(E && "Invalid expression");
3640
3641 if (E->isValueDependent())
3642 return false;
3643
3644 QualType QT = E->getType();
3645 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3647 return true;
3648 }
3649
3650 llvm::APSInt ValueAPS;
3652
3653 if (R.isInvalid())
3654 return true;
3655
3656 // GCC allows the value of unroll count to be 0.
3657 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3658 // "The values of 0 and 1 block any unrolling of the loop."
3659 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3660 // '#pragma unroll' cases.
3661 bool ValueIsPositive =
3662 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3663 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3664 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3665 << toString(ValueAPS, 10) << ValueIsPositive;
3666 return true;
3667 }
3668
3669 return false;
3670}
3671
3673 // Fast path for a single digit (which is quite common). A single digit
3674 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3675 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3676 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3677 return ActOnIntegerConstant(Tok.getLocation(), Val);
3678 }
3679
3680 SmallString<128> SpellingBuffer;
3681 // NumericLiteralParser wants to overread by one character. Add padding to
3682 // the buffer in case the token is copied to the buffer. If getSpelling()
3683 // returns a StringRef to the memory buffer, it should have a null char at
3684 // the EOF, so it is also safe.
3685 SpellingBuffer.resize(Tok.getLength() + 1);
3686
3687 // Get the spelling of the token, which eliminates trigraphs, etc.
3688 bool Invalid = false;
3689 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3690 if (Invalid)
3691 return ExprError();
3692
3693 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3696 if (Literal.hadError)
3697 return ExprError();
3698
3699 if (Literal.hasUDSuffix()) {
3700 // We're building a user-defined literal.
3701 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3702 SourceLocation UDSuffixLoc =
3703 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3704
3705 // Make sure we're allowed user-defined literals here.
3706 if (!UDLScope)
3707 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3708
3709 QualType CookedTy;
3710 if (Literal.isFloatingLiteral()) {
3711 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3712 // long double, the literal is treated as a call of the form
3713 // operator "" X (f L)
3714 CookedTy = Context.LongDoubleTy;
3715 } else {
3716 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3717 // unsigned long long, the literal is treated as a call of the form
3718 // operator "" X (n ULL)
3719 CookedTy = Context.UnsignedLongLongTy;
3720 }
3721
3722 DeclarationName OpName =
3724 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3725 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3726
3727 SourceLocation TokLoc = Tok.getLocation();
3728
3729 // Perform literal operator lookup to determine if we're building a raw
3730 // literal or a cooked one.
3731 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3732 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3733 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3734 /*AllowStringTemplatePack*/ false,
3735 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3737 // Lookup failure for imaginary constants isn't fatal, there's still the
3738 // GNU extension producing _Complex types.
3739 break;
3740 case LOLR_Error:
3741 return ExprError();
3742 case LOLR_Cooked: {
3743 Expr *Lit;
3744 if (Literal.isFloatingLiteral()) {
3745 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3746 } else {
3747 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3748 if (Literal.GetIntegerValue(ResultVal))
3749 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3750 << /* Unsigned */ 1;
3751 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3752 Tok.getLocation());
3753 }
3754 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3755 }
3756
3757 case LOLR_Raw: {
3758 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3759 // literal is treated as a call of the form
3760 // operator "" X ("n")
3761 unsigned Length = Literal.getUDSuffixOffset();
3764 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3765 Expr *Lit =
3766 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3768 /*Pascal*/ false, StrTy, &TokLoc, 1);
3769 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3770 }
3771
3772 case LOLR_Template: {
3773 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3774 // template), L is treated as a call fo the form
3775 // operator "" X <'c1', 'c2', ... 'ck'>()
3776 // where n is the source character sequence c1 c2 ... ck.
3777 TemplateArgumentListInfo ExplicitArgs;
3778 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3779 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3780 llvm::APSInt Value(CharBits, CharIsUnsigned);
3781 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3782 Value = TokSpelling[I];
3785 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3786 }
3787 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3788 }
3790 llvm_unreachable("unexpected literal operator lookup result");
3791 }
3792 }
3793
3794 Expr *Res;
3795
3796 if (Literal.isFixedPointLiteral()) {
3797 QualType Ty;
3798
3799 if (Literal.isAccum) {
3800 if (Literal.isHalf) {
3801 Ty = Context.ShortAccumTy;
3802 } else if (Literal.isLong) {
3803 Ty = Context.LongAccumTy;
3804 } else {
3805 Ty = Context.AccumTy;
3806 }
3807 } else if (Literal.isFract) {
3808 if (Literal.isHalf) {
3809 Ty = Context.ShortFractTy;
3810 } else if (Literal.isLong) {
3811 Ty = Context.LongFractTy;
3812 } else {
3813 Ty = Context.FractTy;
3814 }
3815 }
3816
3817 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3818
3819 bool isSigned = !Literal.isUnsigned;
3820 unsigned scale = Context.getFixedPointScale(Ty);
3821 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3822
3823 llvm::APInt Val(bit_width, 0, isSigned);
3824 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3825 bool ValIsZero = Val.isZero() && !Overflowed;
3826
3827 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3828 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3829 // Clause 6.4.4 - The value of a constant shall be in the range of
3830 // representable values for its type, with exception for constants of a
3831 // fract type with a value of exactly 1; such a constant shall denote
3832 // the maximal value for the type.
3833 --Val;
3834 else if (Val.ugt(MaxVal) || Overflowed)
3835 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3836
3838 Tok.getLocation(), scale);
3839 } else if (Literal.isFloatingLiteral()) {
3840 QualType Ty;
3841 if (Literal.isHalf){
3842 if (getLangOpts().HLSL ||
3843 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3844 Ty = Context.HalfTy;
3845 else {
3846 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3847 return ExprError();
3848 }
3849 } else if (Literal.isFloat)
3850 Ty = Context.FloatTy;
3851 else if (Literal.isLong)
3853 else if (Literal.isFloat16)
3854 Ty = Context.Float16Ty;
3855 else if (Literal.isFloat128)
3856 Ty = Context.Float128Ty;
3857 else if (getLangOpts().HLSL)
3858 Ty = Context.FloatTy;
3859 else
3860 Ty = Context.DoubleTy;
3861
3862 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3863
3864 if (Ty == Context.DoubleTy) {
3865 if (getLangOpts().SinglePrecisionConstants) {
3866 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3867 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3868 }
3869 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3870 "cl_khr_fp64", getLangOpts())) {
3871 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3872 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 }
3877 } else if (!Literal.isIntegerLiteral()) {
3878 return ExprError();
3879 } else {
3880 QualType Ty;
3881
3882 // 'z/uz' literals are a C++23 feature.
3883 if (Literal.isSizeT)
3886 ? diag::warn_cxx20_compat_size_t_suffix
3887 : diag::ext_cxx23_size_t_suffix
3888 : diag::err_cxx23_size_t_suffix);
3889
3890 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3891 // but we do not currently support the suffix in C++ mode because it's not
3892 // entirely clear whether WG21 will prefer this suffix to return a library
3893 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3894 // literals are a C++ extension.
3895 if (Literal.isBitInt)
3896 PP.Diag(Tok.getLocation(),
3897 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3898 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3899 : diag::ext_c23_bitint_suffix);
3900
3901 // Get the value in the widest-possible width. What is "widest" depends on
3902 // whether the literal is a bit-precise integer or not. For a bit-precise
3903 // integer type, try to scan the source to determine how many bits are
3904 // needed to represent the value. This may seem a bit expensive, but trying
3905 // to get the integer value from an overly-wide APInt is *extremely*
3906 // expensive, so the naive approach of assuming
3907 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3908 unsigned BitsNeeded =
3909 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3910 Literal.getLiteralDigits(), Literal.getRadix())
3912 llvm::APInt ResultVal(BitsNeeded, 0);
3913
3914 if (Literal.GetIntegerValue(ResultVal)) {
3915 // If this value didn't fit into uintmax_t, error and force to ull.
3916 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3917 << /* Unsigned */ 1;
3919 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3920 "long long is not intmax_t?");
3921 } else {
3922 // If this value fits into a ULL, try to figure out what else it fits into
3923 // according to the rules of C99 6.4.4.1p5.
3924
3925 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3926 // be an unsigned int.
3927 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3928
3929 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3930 // suffix for portability of code with C++, but both `l` and `ll` are
3931 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3932 // same.
3933 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3934 Literal.isLong = true;
3935 Literal.isLongLong = false;
3936 }
3937
3938 // Check from smallest to largest, picking the smallest type we can.
3939 unsigned Width = 0;
3940
3941 // Microsoft specific integer suffixes are explicitly sized.
3942 if (Literal.MicrosoftInteger) {
3943 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3944 Width = 8;
3945 Ty = Context.CharTy;
3946 } else {
3947 Width = Literal.MicrosoftInteger;
3948 Ty = Context.getIntTypeForBitwidth(Width,
3949 /*Signed=*/!Literal.isUnsigned);
3950 }
3951 }
3952
3953 // Bit-precise integer literals are automagically-sized based on the
3954 // width required by the literal.
3955 if (Literal.isBitInt) {
3956 // The signed version has one more bit for the sign value. There are no
3957 // zero-width bit-precise integers, even if the literal value is 0.
3958 Width = std::max(ResultVal.getActiveBits(), 1u) +
3959 (Literal.isUnsigned ? 0u : 1u);
3960
3961 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3962 // and reset the type to the largest supported width.
3963 unsigned int MaxBitIntWidth =
3965 if (Width > MaxBitIntWidth) {
3966 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3967 << Literal.isUnsigned;
3968 Width = MaxBitIntWidth;
3969 }
3970
3971 // Reset the result value to the smaller APInt and select the correct
3972 // type to be used. Note, we zext even for signed values because the
3973 // literal itself is always an unsigned value (a preceeding - is a
3974 // unary operator, not part of the literal).
3975 ResultVal = ResultVal.zextOrTrunc(Width);
3976 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3977 }
3978
3979 // Check C++23 size_t literals.
3980 if (Literal.isSizeT) {
3981 assert(!Literal.MicrosoftInteger &&
3982 "size_t literals can't be Microsoft literals");
3983 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3985
3986 // Does it fit in size_t?
3987 if (ResultVal.isIntN(SizeTSize)) {
3988 // Does it fit in ssize_t?
3989 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3991 else if (AllowUnsigned)
3992 Ty = Context.getSizeType();
3993 Width = SizeTSize;
3994 }
3995 }
3996
3997 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3998 !Literal.isSizeT) {
3999 // Are int/unsigned possibilities?
4000 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4001
4002 // Does it fit in a unsigned int?
4003 if (ResultVal.isIntN(IntSize)) {
4004 // Does it fit in a signed int?
4005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4006 Ty = Context.IntTy;
4007 else if (AllowUnsigned)
4009 Width = IntSize;
4010 }
4011 }
4012
4013 // Are long/unsigned long possibilities?
4014 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4015 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4016
4017 // Does it fit in a unsigned long?
4018 if (ResultVal.isIntN(LongSize)) {
4019 // Does it fit in a signed long?
4020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4021 Ty = Context.LongTy;
4022 else if (AllowUnsigned)
4024 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4025 // is compatible.
4026 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4027 const unsigned LongLongSize =
4029 Diag(Tok.getLocation(),
4031 ? Literal.isLong
4032 ? diag::warn_old_implicitly_unsigned_long_cxx
4033 : /*C++98 UB*/ diag::
4034 ext_old_implicitly_unsigned_long_cxx
4035 : diag::warn_old_implicitly_unsigned_long)
4036 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4037 : /*will be ill-formed*/ 1);
4039 }
4040 Width = LongSize;
4041 }
4042 }
4043
4044 // Check long long if needed.
4045 if (Ty.isNull() && !Literal.isSizeT) {
4046 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4047
4048 // Does it fit in a unsigned long long?
4049 if (ResultVal.isIntN(LongLongSize)) {
4050 // Does it fit in a signed long long?
4051 // To be compatible with MSVC, hex integer literals ending with the
4052 // LL or i64 suffix are always signed in Microsoft mode.
4053 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4054 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4055 Ty = Context.LongLongTy;
4056 else if (AllowUnsigned)
4058 Width = LongLongSize;
4059
4060 // 'long long' is a C99 or C++11 feature, whether the literal
4061 // explicitly specified 'long long' or we needed the extra width.
4062 if (getLangOpts().CPlusPlus)
4063 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4064 ? diag::warn_cxx98_compat_longlong
4065 : diag::ext_cxx11_longlong);
4066 else if (!getLangOpts().C99)
4067 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4068 }
4069 }
4070
4071 // If we still couldn't decide a type, we either have 'size_t' literal
4072 // that is out of range, or a decimal literal that does not fit in a
4073 // signed long long and has no U suffix.
4074 if (Ty.isNull()) {
4075 if (Literal.isSizeT)
4076 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4077 << Literal.isUnsigned;
4078 else
4079 Diag(Tok.getLocation(),
4080 diag::ext_integer_literal_too_large_for_signed);
4083 }
4084
4085 if (ResultVal.getBitWidth() != Width)
4086 ResultVal = ResultVal.trunc(Width);
4087 }
4088 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4089 }
4090
4091 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4092 if (Literal.isImaginary) {
4093 Res = new (Context) ImaginaryLiteral(Res,
4095
4096 // In C++, this is a GNU extension. In C, it's a C2y extension.
4097 unsigned DiagId;
4098 if (getLangOpts().CPlusPlus)
4099 DiagId = diag::ext_gnu_imaginary_constant;
4100 else if (getLangOpts().C2y)
4101 DiagId = diag::warn_c23_compat_imaginary_constant;
4102 else
4103 DiagId = diag::ext_c2y_imaginary_constant;
4104 Diag(Tok.getLocation(), DiagId);
4105 }
4106 return Res;
4107}
4108
4110 assert(E && "ActOnParenExpr() missing expr");
4111 QualType ExprTy = E->getType();
4112 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4113 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4114 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4115 return new (Context) ParenExpr(L, R, E);
4116}
4117
4120 SourceRange ArgRange) {
4121 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4122 // scalar or vector data type argument..."
4123 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4124 // type (C99 6.2.5p18) or void.
4125 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4126 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4127 << T << ArgRange;
4128 return true;
4129 }
4130
4131 assert((T->isVoidType() || !T->isIncompleteType()) &&
4132 "Scalar types should always be complete");
4133 return false;
4134}
4135
4138 SourceRange ArgRange) {
4139 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4140 if (!T->isVectorType() && !T->isSizelessVectorType())
4141 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4142 << ""
4143 << "__builtin_vectorelements" << T << ArgRange;
4144
4145 return false;
4146}
4147
4150 SourceRange ArgRange) {
4151 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4152 return true;
4153
4154 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4156 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4157 return true;
4158 }
4159
4160 return false;
4161}
4162
4165 SourceRange ArgRange,
4166 UnaryExprOrTypeTrait TraitKind) {
4167 // Invalid types must be hard errors for SFINAE in C++.
4168 if (S.LangOpts.CPlusPlus)
4169 return true;
4170
4171 // C99 6.5.3.4p1:
4172 if (T->isFunctionType() &&
4173 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4174 TraitKind == UETT_PreferredAlignOf)) {
4175 // sizeof(function)/alignof(function) is allowed as an extension.
4176 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4177 << getTraitSpelling(TraitKind) << ArgRange;
4178 return false;
4179 }
4180
4181 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4182 // this is an error (OpenCL v1.1 s6.3.k)
4183 if (T->isVoidType()) {
4184 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4185 : diag::ext_sizeof_alignof_void_type;
4186 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4187 return false;
4188 }
4189
4190 return true;
4191}
4192
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4198 // runtime doesn't allow it.
4200 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4201 << T << (TraitKind == UETT_SizeOf)
4202 << ArgRange;
4203 return true;
4204 }
4205
4206 return false;
4207}
4208
4209/// Check whether E is a pointer from a decayed array type (the decayed
4210/// pointer type is equal to T) and emit a warning if it is.
4212 const Expr *E) {
4213 // Don't warn if the operation changed the type.
4214 if (T != E->getType())
4215 return;
4216
4217 // Now look for array decays.
4218 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4219 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4220 return;
4221
4222 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4223 << ICE->getType()
4224 << ICE->getSubExpr()->getType();
4225}
4226
4228 UnaryExprOrTypeTrait ExprKind) {
4229 QualType ExprTy = E->getType();
4230 assert(!ExprTy->isReferenceType());
4231
4232 bool IsUnevaluatedOperand =
4233 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4234 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4235 ExprKind == UETT_VecStep);
4236 if (IsUnevaluatedOperand) {
4238 if (Result.isInvalid())
4239 return true;
4240 E = Result.get();
4241 }
4242
4243 // The operand for sizeof and alignof is in an unevaluated expression context,
4244 // so side effects could result in unintended consequences.
4245 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4246 // used to build SFINAE gadgets.
4247 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4248 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4250 !E->getType()->isVariableArrayType() &&
4251 E->HasSideEffects(Context, false))
4252 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4253
4254 if (ExprKind == UETT_VecStep)
4255 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4256 E->getSourceRange());
4257
4258 if (ExprKind == UETT_VectorElements)
4259 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4260 E->getSourceRange());
4261
4262 // Explicitly list some types as extensions.
4263 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange(), ExprKind))
4265 return false;
4266
4267 // WebAssembly tables are always illegal operands to unary expressions and
4268 // type traits.
4269 if (Context.getTargetInfo().getTriple().isWasm() &&
4271 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4272 << getTraitSpelling(ExprKind);
4273 return true;
4274 }
4275
4276 // 'alignof' applied to an expression only requires the base element type of
4277 // the expression to be complete. 'sizeof' requires the expression's type to
4278 // be complete (and will attempt to complete it if it's an array of unknown
4279 // bound).
4280 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4283 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 } else {
4288 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4289 getTraitSpelling(ExprKind), E->getSourceRange()))
4290 return true;
4291 }
4292
4293 // Completing the expression's type may have changed it.
4294 ExprTy = E->getType();
4295 assert(!ExprTy->isReferenceType());
4296
4297 if (ExprTy->isFunctionType()) {
4298 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4299 << getTraitSpelling(ExprKind) << E->getSourceRange();
4300 return true;
4301 }
4302
4303 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4304 E->getSourceRange(), ExprKind))
4305 return true;
4306
4307 if (ExprKind == UETT_SizeOf) {
4308 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4309 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4310 QualType OType = PVD->getOriginalType();
4311 QualType Type = PVD->getType();
4312 if (Type->isPointerType() && OType->isArrayType()) {
4313 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4314 << Type << OType;
4315 Diag(PVD->getLocation(), diag::note_declared_at);
4316 }
4317 }
4318 }
4319
4320 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4321 // decays into a pointer and returns an unintended result. This is most
4322 // likely a typo for "sizeof(array) op x".
4323 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4324 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4325 BO->getLHS());
4326 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4327 BO->getRHS());
4328 }
4329 }
4330
4331 return false;
4332}
4333
4334static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4335 // Cannot know anything else if the expression is dependent.
4336 if (E->isTypeDependent())
4337 return false;
4338
4339 if (E->getObjectKind() == OK_BitField) {
4340 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4341 << 1 << E->getSourceRange();
4342 return true;
4343 }
4344
4345 ValueDecl *D = nullptr;
4346 Expr *Inner = E->IgnoreParens();
4347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4348 D = DRE->getDecl();
4349 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4350 D = ME->getMemberDecl();
4351 }
4352
4353 // If it's a field, require the containing struct to have a
4354 // complete definition so that we can compute the layout.
4355 //
4356 // This can happen in C++11 onwards, either by naming the member
4357 // in a way that is not transformed into a member access expression
4358 // (in an unevaluated operand, for instance), or by naming the member
4359 // in a trailing-return-type.
4360 //
4361 // For the record, since __alignof__ on expressions is a GCC
4362 // extension, GCC seems to permit this but always gives the
4363 // nonsensical answer 0.
4364 //
4365 // We don't really need the layout here --- we could instead just
4366 // directly check for all the appropriate alignment-lowing
4367 // attributes --- but that would require duplicating a lot of
4368 // logic that just isn't worth duplicating for such a marginal
4369 // use-case.
4370 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4371 // Fast path this check, since we at least know the record has a
4372 // definition if we can find a member of it.
4373 if (!FD->getParent()->isCompleteDefinition()) {
4374 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4375 << E->getSourceRange();
4376 return true;
4377 }
4378
4379 // Otherwise, if it's a field, and the field doesn't have
4380 // reference type, then it must have a complete type (or be a
4381 // flexible array member, which we explicitly want to
4382 // white-list anyway), which makes the following checks trivial.
4383 if (!FD->getType()->isReferenceType())
4384 return false;
4385 }
4386
4387 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4388}
4389
4391 E = E->IgnoreParens();
4392
4393 // Cannot know anything else if the expression is dependent.
4394 if (E->isTypeDependent())
4395 return false;
4396
4397 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4398}
4399
4401 CapturingScopeInfo *CSI) {
4402 assert(T->isVariablyModifiedType());
4403 assert(CSI != nullptr);
4404
4405 // We're going to walk down into the type and look for VLA expressions.
4406 do {
4407 const Type *Ty = T.getTypePtr();
4408 switch (Ty->getTypeClass()) {
4409#define TYPE(Class, Base)
4410#define ABSTRACT_TYPE(Class, Base)
4411#define NON_CANONICAL_TYPE(Class, Base)
4412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4414#include "clang/AST/TypeNodes.inc"
4415 T = QualType();
4416 break;
4417 // These types are never variably-modified.
4418 case Type::Builtin:
4419 case Type::Complex:
4420 case Type::Vector:
4421 case Type::ExtVector:
4422 case Type::ConstantMatrix:
4423 case Type::Record:
4424 case Type::Enum:
4425 case Type::TemplateSpecialization:
4426 case Type::ObjCObject:
4427 case Type::ObjCInterface:
4428 case Type::ObjCObjectPointer:
4429 case Type::ObjCTypeParam:
4430 case Type::Pipe:
4431 case Type::BitInt:
4432 llvm_unreachable("type class is never variably-modified!");
4433 case Type::Elaborated:
4434 T = cast<ElaboratedType>(Ty)->getNamedType();
4435 break;
4436 case Type::Adjusted:
4437 T = cast<AdjustedType>(Ty)->getOriginalType();
4438 break;
4439 case Type::Decayed:
4440 T = cast<DecayedType>(Ty)->getPointeeType();
4441 break;
4442 case Type::ArrayParameter:
4443 T = cast<ArrayParameterType>(Ty)->getElementType();
4444 break;
4445 case Type::Pointer:
4446 T = cast<PointerType>(Ty)->getPointeeType();
4447 break;
4448 case Type::BlockPointer:
4449 T = cast<BlockPointerType>(Ty)->getPointeeType();
4450 break;
4451 case Type::LValueReference:
4452 case Type::RValueReference:
4453 T = cast<ReferenceType>(Ty)->getPointeeType();
4454 break;
4455 case Type::MemberPointer:
4456 T = cast<MemberPointerType>(Ty)->getPointeeType();
4457 break;
4458 case Type::ConstantArray:
4459 case Type::IncompleteArray:
4460 // Losing element qualification here is fine.
4461 T = cast<ArrayType>(Ty)->getElementType();
4462 break;
4463 case Type::VariableArray: {
4464 // Losing element qualification here is fine.
4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4466
4467 // Unknown size indication requires no size computation.
4468 // Otherwise, evaluate and record it.
4469 auto Size = VAT->getSizeExpr();
4470 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4473
4474 T = VAT->getElementType();
4475 break;
4476 }
4477 case Type::FunctionProto:
4478 case Type::FunctionNoProto:
4479 T = cast<FunctionType>(Ty)->getReturnType();
4480 break;
4481 case Type::Paren:
4482 case Type::TypeOf:
4483 case Type::UnaryTransform:
4484 case Type::Attributed:
4485 case Type::BTFTagAttributed:
4486 case Type::HLSLAttributedResource:
4487 case Type::SubstTemplateTypeParm:
4488 case Type::MacroQualified:
4489 case Type::CountAttributed:
4490 // Keep walking after single level desugaring.
4491 T = T.getSingleStepDesugaredType(Context);
4492 break;
4493 case Type::Typedef:
4494 T = cast<TypedefType>(Ty)->desugar();
4495 break;
4496 case Type::Decltype:
4497 T = cast<DecltypeType>(Ty)->desugar();
4498 break;
4499 case Type::PackIndexing:
4500 T = cast<PackIndexingType>(Ty)->desugar();
4501 break;
4502 case Type::Using:
4503 T = cast<UsingType>(Ty)->desugar();
4504 break;
4505 case Type::Auto:
4506 case Type::DeducedTemplateSpecialization:
4507 T = cast<DeducedType>(Ty)->getDeducedType();
4508 break;
4509 case Type::TypeOfExpr:
4510 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4511 break;
4512 case Type::Atomic:
4513 T = cast<AtomicType>(Ty)->getValueType();
4514 break;
4515 }
4516 } while (!T.isNull() && T->isVariablyModifiedType());
4517}
4518
4520 SourceLocation OpLoc,
4521 SourceRange ExprRange,
4522 UnaryExprOrTypeTrait ExprKind,
4523 StringRef KWName) {
4524 if (ExprType->isDependentType())
4525 return false;
4526
4527 // C++ [expr.sizeof]p2:
4528 // When applied to a reference or a reference type, the result
4529 // is the size of the referenced type.
4530 // C++11 [expr.alignof]p3:
4531 // When alignof is applied to a reference type, the result
4532 // shall be the alignment of the referenced type.
4533 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4534 ExprType = Ref->getPointeeType();
4535
4536 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4537 // When alignof or _Alignof is applied to an array type, the result
4538 // is the alignment of the element type.
4539 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4540 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4541 // If the trait is 'alignof' in C before C2y, the ability to apply the
4542 // trait to an incomplete array is an extension.
4543 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4544 ExprType->isIncompleteArrayType())
4545 Diag(OpLoc, getLangOpts().C2y
4546 ? diag::warn_c2y_compat_alignof_incomplete_array
4547 : diag::ext_c2y_alignof_incomplete_array);
4548 ExprType = Context.getBaseElementType(ExprType);
4549 }
4550
4551 if (ExprKind == UETT_VecStep)
4552 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4553
4554 if (ExprKind == UETT_VectorElements)
4555 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4556 ExprRange);
4557
4558 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4559 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4560 ExprRange);
4561
4562 // Explicitly list some types as extensions.
4563 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4564 ExprKind))
4565 return false;
4566
4568 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4569 KWName, ExprRange))
4570 return true;
4571
4572 if (ExprType->isFunctionType()) {
4573 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4574 return true;
4575 }
4576
4577 // WebAssembly tables are always illegal operands to unary expressions and
4578 // type traits.
4579 if (Context.getTargetInfo().getTriple().isWasm() &&
4580 ExprType->isWebAssemblyTableType()) {
4581 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4582 << getTraitSpelling(ExprKind);
4583 return true;
4584 }
4585
4586 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4587 ExprKind))
4588 return true;
4589
4590 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4591 if (auto *TT = ExprType->getAs<TypedefType>()) {
4592 for (auto I = FunctionScopes.rbegin(),
4593 E = std::prev(FunctionScopes.rend());
4594 I != E; ++I) {
4595 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4596 if (CSI == nullptr)
4597 break;
4598 DeclContext *DC = nullptr;
4599 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4600 DC = LSI->CallOperator;
4601 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4602 DC = CRSI->TheCapturedDecl;
4603 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4604 DC = BSI->TheDecl;
4605 if (DC) {
4606 if (DC->containsDecl(TT->getDecl()))
4607 break;
4608 captureVariablyModifiedType(Context, ExprType, CSI);
4609 }
4610 }
4611 }
4612 }
4613
4614 return false;
4615}
4616
4618 SourceLocation OpLoc,
4619 UnaryExprOrTypeTrait ExprKind,
4620 SourceRange R) {
4621 if (!TInfo)
4622 return ExprError();
4623
4624 QualType T = TInfo->getType();
4625
4626 if (!T->isDependentType() &&
4627 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4628 getTraitSpelling(ExprKind)))
4629 return ExprError();
4630
4631 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4632 // properly deal with VLAs in nested calls of sizeof and typeof.
4633 if (currentEvaluationContext().isUnevaluated() &&
4634 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4635 ExprKind == UETT_SizeOf && TInfo->getType()->isVariablyModifiedType())
4636 TInfo = TransformToPotentiallyEvaluated(TInfo);
4637
4638 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4639 return new (Context) UnaryExprOrTypeTraitExpr(
4640 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4641}
4642
4645 UnaryExprOrTypeTrait ExprKind) {
4647 if (PE.isInvalid())
4648 return ExprError();
4649
4650 E = PE.get();
4651
4652 // Verify that the operand is valid.
4653 bool isInvalid = false;
4654 if (E->isTypeDependent()) {
4655 // Delay type-checking for type-dependent expressions.
4656 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4657 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4658 } else if (ExprKind == UETT_VecStep) {
4660 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4661 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4662 isInvalid = true;
4663 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4664 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4665 isInvalid = true;
4666 } else if (ExprKind == UETT_VectorElements) {
4667 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4668 } else {
4670 }
4671
4672 if (isInvalid)
4673 return ExprError();
4674
4675 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4677 if (PE.isInvalid()) return ExprError();
4678 E = PE.get();
4679 }
4680
4681 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4682 return new (Context) UnaryExprOrTypeTraitExpr(
4683 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4684}
4685
4688 UnaryExprOrTypeTrait ExprKind, bool IsType,
4689 void *TyOrEx, SourceRange ArgRange) {
4690 // If error parsing type, ignore.
4691 if (!TyOrEx) return ExprError();
4692
4693 if (IsType) {
4694 TypeSourceInfo *TInfo;
4695 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4696 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4697 }
4698
4699 Expr *ArgEx = (Expr *)TyOrEx;
4700 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4701 return Result;
4702}
4703
4705 SourceLocation OpLoc, SourceRange R) {
4706 if (!TInfo)
4707 return true;
4708 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4709 UETT_AlignOf, KWName);
4710}
4711
4713 SourceLocation OpLoc, SourceRange R) {
4714 TypeSourceInfo *TInfo;
4716 &TInfo);
4717 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4718}
4719
4721 bool IsReal) {
4722 if (V.get()->isTypeDependent())
4723 return S.Context.DependentTy;
4724
4725 // _Real and _Imag are only l-values for normal l-values.
4726 if (V.get()->getObjectKind() != OK_Ordinary) {
4727 V = S.DefaultLvalueConversion(V.get());
4728 if (V.isInvalid())
4729 return QualType();
4730 }
4731
4732 // These operators return the element type of a complex type.
4733 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4734 return CT->getElementType();
4735
4736 // Otherwise they pass through real integer and floating point types here.
4737 if (V.get()->getType()->isArithmeticType())
4738 return V.get()->getType();
4739
4740 // Test for placeholders.
4741 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4742 if (PR.isInvalid()) return QualType();
4743 if (PR.get() != V.get()) {
4744 V = PR;
4745 return CheckRealImagOperand(S, V, Loc, IsReal);
4746 }
4747
4748 // Reject anything else.
4749 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4750 << (IsReal ? "__real" : "__imag");
4751 return QualType();
4752}
4753
4754
4755
4758 tok::TokenKind Kind, Expr *Input) {
4760 switch (Kind) {
4761 default: llvm_unreachable("Unknown unary op!");
4762 case tok::plusplus: Opc = UO_PostInc; break;
4763 case tok::minusminus: Opc = UO_PostDec; break;
4764 }
4765
4766 // Since this might is a postfix expression, get rid of ParenListExprs.
4768 if (Result.isInvalid()) return ExprError();
4769 Input = Result.get();
4770
4771 return BuildUnaryOp(S, OpLoc, Opc, Input);
4772}
4773
4774/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4775///
4776/// \return true on error
4778 SourceLocation opLoc,
4779 Expr *op) {
4780 assert(op->getType()->isObjCObjectPointerType());
4782 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4783 return false;
4784
4785 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4787 << op->getSourceRange();
4788 return true;
4789}
4790
4792 auto *BaseNoParens = Base->IgnoreParens();
4793 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4794 return MSProp->getPropertyDecl()->getType()->isArrayType();
4795 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4796}
4797
4798// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4799// Typically this is DependentTy, but can sometimes be more precise.
4800//
4801// There are cases when we could determine a non-dependent type:
4802// - LHS and RHS may have non-dependent types despite being type-dependent
4803// (e.g. unbounded array static members of the current instantiation)
4804// - one may be a dependent-sized array with known element type
4805// - one may be a dependent-typed valid index (enum in current instantiation)
4806//
4807// We *always* return a dependent type, in such cases it is DependentTy.
4808// This avoids creating type-dependent expressions with non-dependent types.
4809// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4811 const ASTContext &Ctx) {
4812 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4813 QualType LTy = LHS->getType(), RTy = RHS->getType();
4815 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4816 if (const PointerType *PT = LTy->getAs<PointerType>())
4817 Result = PT->getPointeeType();
4818 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4819 Result = AT->getElementType();
4820 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4821 if (const PointerType *PT = RTy->getAs<PointerType>())
4822 Result = PT->getPointeeType();
4823 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4824 Result = AT->getElementType();
4825 }
4826 // Ensure we return a dependent type.
4827 return Result->isDependentType() ? Result : Ctx.DependentTy;
4828}
4829
4831 SourceLocation lbLoc,
4832 MultiExprArg ArgExprs,
4833 SourceLocation rbLoc) {
4834
4835 if (base && !base->getType().isNull() &&
4836 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4837 auto *AS = cast<ArraySectionExpr>(base);
4838 if (AS->isOMPArraySection())
4840 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4841 /*Length*/ nullptr,
4842 /*Stride=*/nullptr, rbLoc);
4843
4844 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4845 SourceLocation(), /*Length*/ nullptr,
4846 rbLoc);
4847 }
4848
4849 // Since this might be a postfix expression, get rid of ParenListExprs.
4850 if (isa<ParenListExpr>(base)) {
4852 if (result.isInvalid())
4853 return ExprError();
4854 base = result.get();
4855 }
4856
4857 // Check if base and idx form a MatrixSubscriptExpr.
4858 //
4859 // Helper to check for comma expressions, which are not allowed as indices for
4860 // matrix subscript expressions.
4861 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4862 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4863 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4864 << SourceRange(base->getBeginLoc(), rbLoc);
4865 return true;
4866 }
4867 return false;
4868 };
4869 // The matrix subscript operator ([][])is considered a single operator.
4870 // Separating the index expressions by parenthesis is not allowed.
4871 if (base && !base->getType().isNull() &&
4872 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4873 !isa<MatrixSubscriptExpr>(base)) {
4874 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4875 << SourceRange(base->getBeginLoc(), rbLoc);
4876 return ExprError();
4877 }
4878 // If the base is a MatrixSubscriptExpr, try to create a new
4879 // MatrixSubscriptExpr.
4880 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4881 if (matSubscriptE) {
4882 assert(ArgExprs.size() == 1);
4883 if (CheckAndReportCommaError(ArgExprs.front()))
4884 return ExprError();
4885
4886 assert(matSubscriptE->isIncomplete() &&
4887 "base has to be an incomplete matrix subscript");
4888 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4889 matSubscriptE->getRowIdx(),
4890 ArgExprs.front(), rbLoc);
4891 }
4892 if (base->getType()->isWebAssemblyTableType()) {
4893 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4894 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4895 return ExprError();
4896 }
4897
4898 CheckInvalidBuiltinCountedByRef(base, ArraySubscriptKind);
4899
4900 // Handle any non-overload placeholder types in the base and index
4901 // expressions. We can't handle overloads here because the other
4902 // operand might be an overloadable type, in which case the overload
4903 // resolution for the operator overload should get the first crack
4904 // at the overload.
4905 bool IsMSPropertySubscript = false;
4906 if (base->getType()->isNonOverloadPlaceholderType()) {
4907 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4908 if (!IsMSPropertySubscript) {
4909 ExprResult result = CheckPlaceholderExpr(base);
4910 if (result.isInvalid())
4911 return ExprError();
4912 base = result.get();
4913 }
4914 }
4915
4916 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4917 if (base->getType()->isMatrixType()) {
4918 assert(ArgExprs.size() == 1);
4919 if (CheckAndReportCommaError(ArgExprs.front()))
4920 return ExprError();
4921
4922 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4923 rbLoc);
4924 }
4925
4926 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4927 Expr *idx = ArgExprs[0];
4928 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4929 (isa<CXXOperatorCallExpr>(idx) &&
4930 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4931 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4932 << SourceRange(base->getBeginLoc(), rbLoc);
4933 }
4934 }
4935
4936 if (ArgExprs.size() == 1 &&
4937 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4938 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4939 if (result.isInvalid())
4940 return ExprError();
4941 ArgExprs[0] = result.get();
4942 } else {
4943 if (CheckArgsForPlaceholders(ArgExprs))
4944 return ExprError();
4945 }
4946
4947 // Build an unanalyzed expression if either operand is type-dependent.
4948 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4949 (base->isTypeDependent() ||
4951 !isa<PackExpansionExpr>(ArgExprs[0])) {
4952 return new (Context) ArraySubscriptExpr(
4953 base, ArgExprs.front(),
4954 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4955 VK_LValue, OK_Ordinary, rbLoc);
4956 }
4957
4958 // MSDN, property (C++)
4959 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4960 // This attribute can also be used in the declaration of an empty array in a
4961 // class or structure definition. For example:
4962 // __declspec(property(get=GetX, put=PutX)) int x[];
4963 // The above statement indicates that x[] can be used with one or more array
4964 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4965 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4966 if (IsMSPropertySubscript) {
4967 assert(ArgExprs.size() == 1);
4968 // Build MS property subscript expression if base is MS property reference
4969 // or MS property subscript.
4970 return new (Context)
4971 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4972 VK_LValue, OK_Ordinary, rbLoc);
4973 }
4974
4975 // Use C++ overloaded-operator rules if either operand has record
4976 // type. The spec says to do this if either type is *overloadable*,
4977 // but enum types can't declare subscript operators or conversion
4978 // operators, so there's nothing interesting for overload resolution
4979 // to do if there aren't any record types involved.
4980 //
4981 // ObjC pointers have their own subscripting logic that is not tied
4982 // to overload resolution and so should not take this path.
4983 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4984 ((base->getType()->isRecordType() ||
4985 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4986 ArgExprs[0]->getType()->isRecordType())))) {
4987 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4988 }
4989
4990 ExprResult Res =
4991 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4992
4993 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4994 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4995
4996 return Res;
4997}
4998
5001 InitializationKind Kind =
5003 InitializationSequence InitSeq(*this, Entity, Kind, E);
5004 return InitSeq.Perform(*this, Entity, Kind, E);
5005}
5006
5008 Expr *ColumnIdx,
5009 SourceLocation RBLoc) {
5011 if (BaseR.isInvalid())
5012 return BaseR;
5013 Base = BaseR.get();
5014
5015 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5016 if (RowR.isInvalid())
5017 return RowR;
5018 RowIdx = RowR.get();
5019
5020 if (!ColumnIdx)
5021 return new (Context) MatrixSubscriptExpr(
5022 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5023
5024 // Build an unanalyzed expression if any of the operands is type-dependent.
5025 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5026 ColumnIdx->isTypeDependent())
5027 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5028 Context.DependentTy, RBLoc);
5029
5030 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5031 if (ColumnR.isInvalid())
5032 return ColumnR;
5033 ColumnIdx = ColumnR.get();
5034
5035 // Check that IndexExpr is an integer expression. If it is a constant
5036 // expression, check that it is less than Dim (= the number of elements in the
5037 // corresponding dimension).
5038 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5039 bool IsColumnIdx) -> Expr * {
5040 if (!IndexExpr->getType()->isIntegerType() &&
5041 !IndexExpr->isTypeDependent()) {
5042 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5043 << IsColumnIdx;
5044 return nullptr;
5045 }
5046
5047 if (std::optional<llvm::APSInt> Idx =
5048 IndexExpr->getIntegerConstantExpr(Context)) {
5049 if ((*Idx < 0 || *Idx >= Dim)) {
5050 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5051 << IsColumnIdx << Dim;
5052 return nullptr;
5053 }
5054 }
5055
5056 ExprResult ConvExpr = IndexExpr;
5057 assert(!ConvExpr.isInvalid() &&
5058 "should be able to convert any integer type to size type");
5059 return ConvExpr.get();
5060 };
5061
5062 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5063 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5064 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5065 if (!RowIdx || !ColumnIdx)
5066 return ExprError();
5067
5068 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5069 MTy->getElementType(), RBLoc);
5070}
5071
5072void Sema::CheckAddressOfNoDeref(const Expr *E) {
5073 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5074 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5075
5076 // For expressions like `&(*s).b`, the base is recorded and what should be
5077 // checked.
5078 const MemberExpr *Member = nullptr;
5079 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5080 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5081
5082 LastRecord.PossibleDerefs.erase(StrippedExpr);
5083}
5084
5085void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5087 return;
5088
5089 QualType ResultTy = E->getType();
5090 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5091
5092 // Bail if the element is an array since it is not memory access.
5093 if (isa<ArrayType>(ResultTy))
5094 return;
5095
5096 if (ResultTy->hasAttr(attr::NoDeref)) {
5097 LastRecord.PossibleDerefs.insert(E);
5098 return;
5099 }
5100
5101 // Check if the base type is a pointer to a member access of a struct
5102 // marked with noderef.
5103 const Expr *Base = E->getBase();
5104 QualType BaseTy = Base->getType();
5105 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5106 // Not a pointer access
5107 return;
5108
5109 const MemberExpr *Member = nullptr;
5110 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5111 Member->isArrow())
5112 Base = Member->getBase();
5113
5114 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5115 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5116 LastRecord.PossibleDerefs.insert(E);
5117 }
5118}
5119
5122 Expr *Idx, SourceLocation RLoc) {
5123 Expr *LHSExp = Base;
5124 Expr *RHSExp = Idx;
5125
5128
5129 // Per C++ core issue 1213, the result is an xvalue if either operand is
5130 // a non-lvalue array, and an lvalue otherwise.
5131 if (getLangOpts().CPlusPlus11) {
5132 for (auto *Op : {LHSExp, RHSExp}) {
5133 Op = Op->IgnoreImplicit();
5134 if (Op->getType()->isArrayType() && !Op->isLValue())
5135 VK = VK_XValue;
5136 }
5137 }
5138
5139 // Perform default conversions.
5140 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5142 if (Result.isInvalid())
5143 return ExprError();
5144 LHSExp = Result.get();
5145 }
5147 if (Result.isInvalid())
5148 return ExprError();
5149 RHSExp = Result.get();
5150
5151 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5152
5153 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5154 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5155 // in the subscript position. As a result, we need to derive the array base
5156 // and index from the expression types.
5157 Expr *BaseExpr, *IndexExpr;
5158 QualType ResultType;
5159 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5160 BaseExpr = LHSExp;
5161 IndexExpr = RHSExp;
5162 ResultType =
5164 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5165 BaseExpr = LHSExp;
5166 IndexExpr = RHSExp;
5167 ResultType = PTy->getPointeeType();
5168 } else if (const ObjCObjectPointerType *PTy =
5169 LHSTy->getAs<ObjCObjectPointerType>()) {
5170 BaseExpr = LHSExp;
5171 IndexExpr = RHSExp;
5172
5173 // Use custom logic if this should be the pseudo-object subscript
5174 // expression.
5176 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5177 nullptr, nullptr);
5178
5179 ResultType = PTy->getPointeeType();
5180 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5181 // Handle the uncommon case of "123[Ptr]".
5182 BaseExpr = RHSExp;
5183 IndexExpr = LHSExp;
5184 ResultType = PTy->getPointeeType();
5185 } else if (const ObjCObjectPointerType *PTy =
5186 RHSTy->getAs<ObjCObjectPointerType>()) {
5187 // Handle the uncommon case of "123[Ptr]".
5188 BaseExpr = RHSExp;
5189 IndexExpr = LHSExp;
5190 ResultType = PTy->getPointeeType();
5192 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5193 << ResultType << BaseExpr->getSourceRange();
5194 return ExprError();
5195 }
5196 } else if (LHSTy->isSubscriptableVectorType()) {
5197 if (LHSTy->isBuiltinType() &&
5198 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5199 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5200 if (BTy->isSVEBool())
5201 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5202 << LHSExp->getSourceRange()
5203 << RHSExp->getSourceRange());
5204 ResultType = BTy->getSveEltType(Context);
5205 } else {
5206 const VectorType *VTy = LHSTy->getAs<VectorType>();
5207 ResultType = VTy->getElementType();
5208 }
5209 BaseExpr = LHSExp; // vectors: V[123]
5210 IndexExpr = RHSExp;
5211 // We apply C++ DR1213 to vector subscripting too.
5212 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5213 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5214 if (Materialized.isInvalid())
5215 return ExprError();
5216 LHSExp = Materialized.get();
5217 }
5218 VK = LHSExp->getValueKind();
5219 if (VK != VK_PRValue)
5220 OK = OK_VectorComponent;
5221
5222 QualType BaseType = BaseExpr->getType();
5223 Qualifiers BaseQuals = BaseType.getQualifiers();
5224 Qualifiers MemberQuals = ResultType.getQualifiers();
5225 Qualifiers Combined = BaseQuals + MemberQuals;
5226 if (Combined != MemberQuals)
5227 ResultType = Context.getQualifiedType(ResultType, Combined);
5228 } else if (LHSTy->isArrayType()) {
5229 // If we see an array that wasn't promoted by
5230 // DefaultFunctionArrayLvalueConversion, it must be an array that
5231 // wasn't promoted because of the C90 rule that doesn't
5232 // allow promoting non-lvalue arrays. Warn, then
5233 // force the promotion here.
5234 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5235 << LHSExp->getSourceRange();
5236 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5237 CK_ArrayToPointerDecay).get();
5238 LHSTy = LHSExp->getType();
5239
5240 BaseExpr = LHSExp;
5241 IndexExpr = RHSExp;
5242 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5243 } else if (RHSTy->isArrayType()) {
5244 // Same as previous, except for 123[f().a] case
5245 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5246 << RHSExp->getSourceRange();
5247 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5248 CK_ArrayToPointerDecay).get();
5249 RHSTy = RHSExp->getType();
5250
5251 BaseExpr = RHSExp;
5252 IndexExpr = LHSExp;
5253 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5254 } else {
5255 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5256 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5257 }
5258 // C99 6.5.2.1p1
5259 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5260 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5261 << IndexExpr->getSourceRange());
5262
5263 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5264 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5265 !IndexExpr->isTypeDependent()) {
5266 std::optional<llvm::APSInt> IntegerContantExpr =
5268 if (!IntegerContantExpr.has_value() ||
5269 IntegerContantExpr.value().isNegative())
5270 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5271 }
5272
5273 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5274 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5275 // type. Note that Functions are not objects, and that (in C99 parlance)
5276 // incomplete types are not object types.
5277 if (ResultType->isFunctionType()) {
5278 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5279 << ResultType << BaseExpr->getSourceRange();
5280 return ExprError();
5281 }
5282
5283 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5284 // GNU extension: subscripting on pointer to void
5285 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5286 << BaseExpr->getSourceRange();
5287
5288 // C forbids expressions of unqualified void type from being l-values.
5289 // See IsCForbiddenLValueType.
5290 if (!ResultType.hasQualifiers())
5291 VK = VK_PRValue;
5292 } else if (!ResultType->isDependentType() &&
5293 !ResultType.isWebAssemblyReferenceType() &&
5295 LLoc, ResultType,
5296 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5297 return ExprError();
5298
5299 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5300 !ResultType.isCForbiddenLValueType());
5301
5303 FunctionScopes.size() > 1) {
5304 if (auto *TT =
5305 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5306 for (auto I = FunctionScopes.rbegin(),
5307 E = std::prev(FunctionScopes.rend());
5308 I != E; ++I) {
5309 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5310 if (CSI == nullptr)
5311 break;
5312 DeclContext *DC = nullptr;
5313 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5314 DC = LSI->CallOperator;
5315 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5316 DC = CRSI->TheCapturedDecl;
5317 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5318 DC = BSI->TheDecl;
5319 if (DC) {
5320 if (DC->containsDecl(TT->getDecl()))
5321 break;
5323 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5324 }
5325 }
5326 }
5327 }
5328
5329 return new (Context)
5330 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5331}
5332
5334 ParmVarDecl *Param, Expr *RewrittenInit,
5335 bool SkipImmediateInvocations) {
5336 if (Param->hasUnparsedDefaultArg()) {
5337 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5338 // If we've already cleared out the location for the default argument,
5339 // that means we're parsing it right now.
5340 if (!UnparsedDefaultArgLocs.count(Param)) {
5341 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5342 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5343 Param->setInvalidDecl();
5344 return true;
5345 }
5346
5347 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5348 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5350 diag::note_default_argument_declared_here);
5351 return true;
5352 }
5353
5354 if (Param->hasUninstantiatedDefaultArg()) {
5355 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5356 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5357 return true;
5358 }
5359
5360 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5361 assert(Init && "default argument but no initializer?");
5362
5363 // If the default expression creates temporaries, we need to
5364 // push them to the current stack of expression temporaries so they'll
5365 // be properly destroyed.
5366 // FIXME: We should really be rebuilding the default argument with new
5367 // bound temporaries; see the comment in PR5810.
5368 // We don't need to do that with block decls, though, because
5369 // blocks in default argument expression can never capture anything.
5370 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5371 // Set the "needs cleanups" bit regardless of whether there are
5372 // any explicit objects.
5373 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5374 // Append all the objects to the cleanup list. Right now, this
5375 // should always be a no-op, because blocks in default argument
5376 // expressions should never be able to capture anything.
5377 assert(!InitWithCleanup->getNumObjects() &&
5378 "default argument expression has capturing blocks?");
5379 }
5380 // C++ [expr.const]p15.1:
5381 // An expression or conversion is in an immediate function context if it is
5382 // potentially evaluated and [...] its innermost enclosing non-block scope
5383 // is a function parameter scope of an immediate function.
5385 *this,
5389 Param);
5390 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5391 SkipImmediateInvocations;
5392 runWithSufficientStackSpace(CallLoc, [&] {
5393 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5394 });
5395 return false;
5396}
5397
5400 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5401 ShouldVisitImplicitCode = true;
5402 }
5403
5404 bool HasImmediateCalls = false;
5405
5406 bool VisitCallExpr(CallExpr *E) override {
5407 if (const FunctionDecl *FD = E->getDirectCallee())
5408 HasImmediateCalls |= FD->isImmediateFunction();
5410 }
5411
5413 if (const FunctionDecl *FD = E->getConstructor())
5414 HasImmediateCalls |= FD->isImmediateFunction();
5416 }
5417
5418 // SourceLocExpr are not immediate invocations
5419 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5420 // need to be rebuilt so that they refer to the correct SourceLocation and
5421 // DeclContext.
5423 HasImmediateCalls = true;
5425 }
5426
5427 // A nested lambda might have parameters with immediate invocations
5428 // in their default arguments.
5429 // The compound statement is not visited (as it does not constitute a
5430 // subexpression).
5431 // FIXME: We should consider visiting and transforming captures
5432 // with init expressions.
5433 bool VisitLambdaExpr(LambdaExpr *E) override {
5434 return VisitCXXMethodDecl(E->getCallOperator());
5435 }
5436
5438 return TraverseStmt(E->getExpr());
5439 }
5440
5442 return TraverseStmt(E->getExpr());
5443 }
5444};
5445
5447 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5449 : TreeTransform(SemaRef) {}
5450
5451 bool AlwaysRebuild() { return true; }
5452
5453 // Lambda can only have immediate invocations in the default
5454 // args of their parameters, which is transformed upon calling the closure.
5455 // The body is not a subexpression, so we have nothing to do.
5456 // FIXME: Immediate calls in capture initializers should be transformed.
5459
5460 // Make sure we don't rebuild the this pointer as it would
5461 // cause it to incorrectly point it to the outermost class
5462 // in the case of nested struct initialization.
5464
5465 // Rewrite to source location to refer to the context in which they are used.
5467 DeclContext *DC = E->getParentContext();
5468 if (DC == SemaRef.CurContext)
5469 return E;
5470
5471 // FIXME: During instantiation, because the rebuild of defaults arguments
5472 // is not always done in the context of the template instantiator,
5473 // we run the risk of producing a dependent source location
5474 // that would never be rebuilt.
5475 // This usually happens during overload resolution, or in contexts
5476 // where the value of the source location does not matter.
5477 // However, we should find a better way to deal with source location
5478 // of function templates.
5479 if (!SemaRef.CurrentInstantiationScope ||
5480 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5481 DC = SemaRef.CurContext;
5482
5483 return getDerived().RebuildSourceLocExpr(
5484 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5485 }
5486};
5487
5489 FunctionDecl *FD, ParmVarDecl *Param,
5490 Expr *Init) {
5491 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5492
5493 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5494 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5495 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5496 InitializationContext =
5498 if (!InitializationContext.has_value())
5499 InitializationContext.emplace(CallLoc, Param, CurContext);
5500
5501 if (!Init && !Param->hasUnparsedDefaultArg()) {
5502 // Mark that we are replacing a default argument first.
5503 // If we are instantiating a template we won't have to
5504 // retransform immediate calls.
5505 // C++ [expr.const]p15.1:
5506 // An expression or conversion is in an immediate function context if it
5507 // is potentially evaluated and [...] its innermost enclosing non-block
5508 // scope is a function parameter scope of an immediate function.
5510 *this,
5514 Param);
5515
5516 if (Param->hasUninstantiatedDefaultArg()) {
5517 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5518 return ExprError();
5519 }
5520 // CWG2631
5521 // An immediate invocation that is not evaluated where it appears is
5522 // evaluated and checked for whether it is a constant expression at the
5523 // point where the enclosing initializer is used in a function call.
5525 if (!NestedDefaultChecking)
5526 V.TraverseDecl(Param);
5527
5528 // Rewrite the call argument that was created from the corresponding
5529 // parameter's default argument.
5530 if (V.HasImmediateCalls ||
5531 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5532 if (V.HasImmediateCalls)
5533 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5534 CallLoc, Param, CurContext};
5535 // Pass down lifetime extending flag, and collect temporaries in
5536 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5540 ExprResult Res;
5541 runWithSufficientStackSpace(CallLoc, [&] {
5542 Res = Immediate.TransformInitializer(Param->getInit(),
5543 /*NotCopy=*/false);
5544 });
5545 if (Res.isInvalid())
5546 return ExprError();
5547 Res = ConvertParamDefaultArgument(Param, Res.get(),
5548 Res.get()->getBeginLoc());
5549 if (Res.isInvalid())
5550 return ExprError();
5551 Init = Res.get();
5552 }
5553 }
5554
5556 CallLoc, FD, Param, Init,
5557 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5558 return ExprError();
5559
5560 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5561 Init, InitializationContext->Context);
5562}
5563
5565 FieldDecl *Field) {
5566 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5567 return Pattern;
5568 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5569 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5571 ClassPattern->lookup(Field->getDeclName());
5572 auto Rng = llvm::make_filter_range(
5573 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5574 if (Rng.empty())
5575 return nullptr;
5576 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5577 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5578 // && "Duplicated instantiation pattern for field decl");
5579 return cast<FieldDecl>(*Rng.begin());
5580}
5581
5583 assert(Field->hasInClassInitializer());
5584
5585 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5586
5587 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5588
5589 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5590 InitializationContext =
5592 if (!InitializationContext.has_value())
5593 InitializationContext.emplace(Loc, Field, CurContext);
5594
5595 Expr *Init = nullptr;
5596
5597 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5598 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5601
5602 if (!Field->getInClassInitializer()) {
5603 // Maybe we haven't instantiated the in-class initializer. Go check the
5604 // pattern FieldDecl to see if it has one.
5605 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5606 FieldDecl *Pattern =
5608 assert(Pattern && "We must have set the Pattern!");
5609 if (!Pattern->hasInClassInitializer() ||
5610 InstantiateInClassInitializer(Loc, Field, Pattern,
5612 Field->setInvalidDecl();
5613 return ExprError();
5614 }
5615 }
5616 }
5617
5618 // CWG2631
5619 // An immediate invocation that is not evaluated where it appears is
5620 // evaluated and checked for whether it is a constant expression at the
5621 // point where the enclosing initializer is used in a [...] a constructor
5622 // definition, or an aggregate initialization.
5624 if (!NestedDefaultChecking)
5625 V.TraverseDecl(Field);
5626
5627 // CWG1815
5628 // Support lifetime extension of temporary created by aggregate
5629 // initialization using a default member initializer. We should rebuild
5630 // the initializer in a lifetime extension context if the initializer
5631 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5632 // extension code recurses into the default initializer and does lifetime
5633 // extension when warranted.
5634 bool ContainsAnyTemporaries =
5635 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5636 if (Field->getInClassInitializer() &&
5637 !Field->getInClassInitializer()->containsErrors() &&
5638 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5639 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5640 CurContext};
5641 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5642 NestedDefaultChecking;
5643 // Pass down lifetime extending flag, and collect temporaries in
5644 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5648 ExprResult Res;
5650 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5651 /*CXXDirectInit=*/false);
5652 });
5653 if (!Res.isInvalid())
5654 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5655 if (Res.isInvalid()) {
5656 Field->setInvalidDecl();
5657 return ExprError();
5658 }
5659 Init = Res.get();
5660 }
5661
5662 if (Field->getInClassInitializer()) {
5663 Expr *E = Init ? Init : Field->getInClassInitializer();
5664 if (!NestedDefaultChecking)
5666 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5667 });
5670 // C++11 [class.base.init]p7:
5671 // The initialization of each base and member constitutes a
5672 // full-expression.
5673 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5674 if (Res.isInvalid()) {
5675 Field->setInvalidDecl();
5676 return ExprError();
5677 }
5678 Init = Res.get();
5679
5680 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5681 Field, InitializationContext->Context,
5682 Init);
5683 }
5684
5685 // DR1351:
5686 // If the brace-or-equal-initializer of a non-static data member
5687 // invokes a defaulted default constructor of its class or of an
5688 // enclosing class in a potentially evaluated subexpression, the
5689 // program is ill-formed.
5690 //
5691 // This resolution is unworkable: the exception specification of the
5692 // default constructor can be needed in an unevaluated context, in
5693 // particular, in the operand of a noexcept-expression, and we can be
5694 // unable to compute an exception specification for an enclosed class.
5695 //
5696 // Any attempt to resolve the exception specification of a defaulted default
5697 // constructor before the initializer is lexically complete will ultimately
5698 // come here at which point we can diagnose it.
5699 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5700 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5701 << OutermostClass << Field;
5702 Diag(Field->getEndLoc(),
5703 diag::note_default_member_initializer_not_yet_parsed);
5704 // Recover by marking the field invalid, unless we're in a SFINAE context.
5705 if (!isSFINAEContext())
5706 Field->setInvalidDecl();
5707 return ExprError();
5708}
5709
5712 Expr *Fn) {
5713 if (Proto && Proto->isVariadic()) {
5714 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5715 return VariadicConstructor;
5716 else if (Fn && Fn->getType()->isBlockPointerType())
5717 return VariadicBlock;
5718 else if (FDecl) {
5719 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5720 if (Method->isInstance())
5721 return VariadicMethod;
5722 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5723 return VariadicMethod;
5724 return VariadicFunction;
5725 }
5726 return VariadicDoesNotApply;
5727}
5728
5729namespace {
5730class FunctionCallCCC final : public FunctionCallFilterCCC {
5731public:
5732 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5733 unsigned NumArgs, MemberExpr *ME)
5734 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5735 FunctionName(FuncName) {}
5736
5737 bool ValidateCandidate(const TypoCorrection &candidate) override {
5738 if (!candidate.getCorrectionSpecifier() ||
5739 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5740 return false;
5741 }
5742
5744 }
5745
5746 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5747 return std::make_unique<FunctionCallCCC>(*this);
5748 }
5749
5750private:
5751 const IdentifierInfo *const FunctionName;
5752};
5753}
5754
5756 FunctionDecl *FDecl,
5757 ArrayRef<Expr *> Args) {
5758 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5759 DeclarationName FuncName = FDecl->getDeclName();
5760 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5761
5762 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5763 if (TypoCorrection Corrected = S.CorrectTypo(
5765 S.getScopeForContext(S.CurContext), nullptr, CCC,
5767 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5768 if (Corrected.isOverloaded()) {
5771 for (NamedDecl *CD : Corrected) {
5772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5774 OCS);
5775 }
5776 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5777 case OR_Success:
5778 ND = Best->FoundDecl;
5779 Corrected.setCorrectionDecl(ND);
5780 break;
5781 default:
5782 break;
5783 }
5784 }
5785 ND = ND->getUnderlyingDecl();
5786 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5787 return Corrected;
5788 }
5789 }
5790 return TypoCorrection();
5791}
5792
5793// [C++26][[expr.unary.op]/p4
5794// A pointer to member is only formed when an explicit &
5795// is used and its operand is a qualified-id not enclosed in parentheses.
5797 if (!isa<ParenExpr>(Fn))
5798 return false;
5799
5800 Fn = Fn->IgnoreParens();
5801
5802 auto *UO = dyn_cast<UnaryOperator>(Fn);
5803 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5804 return false;
5805 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5806 return DRE->hasQualifier();
5807 }
5808 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5809 return OVL->getQualifier();
5810 return false;
5811}
5812
5813bool
5815 FunctionDecl *FDecl,
5816 const FunctionProtoType *Proto,
5817 ArrayRef<Expr *> Args,
5818 SourceLocation RParenLoc,
5819 bool IsExecConfig) {
5820 // Bail out early if calling a builtin with custom typechecking.
5821 if (FDecl)
5822 if (unsigned ID = FDecl->getBuiltinID())
5824 return false;
5825
5826 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5827 // assignment, to the types of the corresponding parameter, ...
5828
5829 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5830 bool HasExplicitObjectParameter =
5831 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5832 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5833 unsigned NumParams = Proto->getNumParams();
5834 bool Invalid = false;
5835 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5836 unsigned FnKind = Fn->getType()->isBlockPointerType()
5837 ? 1 /* block */
5838 : (IsExecConfig ? 3 /* kernel function (exec config) */
5839 : 0 /* function */);
5840
5841 // If too few arguments are available (and we don't have default
5842 // arguments for the remaining parameters), don't make the call.
5843 if (Args.size() < NumParams) {
5844 if (Args.size() < MinArgs) {
5845 TypoCorrection TC;
5846 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5847 unsigned diag_id =
5848 MinArgs == NumParams && !Proto->isVariadic()
5849 ? diag::err_typecheck_call_too_few_args_suggest
5850 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5852 TC, PDiag(diag_id)
5853 << FnKind << MinArgs - ExplicitObjectParameterOffset
5854 << static_cast<unsigned>(Args.size()) -
5855 ExplicitObjectParameterOffset
5856 << HasExplicitObjectParameter << TC.getCorrectionRange());
5857 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5858 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5859 ->getDeclName())
5860 Diag(RParenLoc,
5861 MinArgs == NumParams && !Proto->isVariadic()
5862 ? diag::err_typecheck_call_too_few_args_one
5863 : diag::err_typecheck_call_too_few_args_at_least_one)
5864 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5865 << HasExplicitObjectParameter << Fn->getSourceRange();
5866 else
5867 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5868 ? diag::err_typecheck_call_too_few_args
5869 : diag::err_typecheck_call_too_few_args_at_least)
5870 << FnKind << MinArgs - ExplicitObjectParameterOffset
5871 << static_cast<unsigned>(Args.size()) -
5872 ExplicitObjectParameterOffset
5873 << HasExplicitObjectParameter << Fn->getSourceRange();
5874
5875 // Emit the location of the prototype.
5876 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5877 Diag(FDecl->getLocation(), diag::note_callee_decl)
5878 << FDecl << FDecl->getParametersSourceRange();
5879
5880 return true;
5881 }
5882 // We reserve space for the default arguments when we create
5883 // the call expression, before calling ConvertArgumentsForCall.
5884 assert((Call->getNumArgs() == NumParams) &&
5885 "We should have reserved space for the default arguments before!");
5886 }
5887
5888 // If too many are passed and not variadic, error on the extras and drop
5889 // them.
5890 if (Args.size() > NumParams) {
5891 if (!Proto->isVariadic()) {
5892 TypoCorrection TC;
5893 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5894 unsigned diag_id =
5895 MinArgs == NumParams && !Proto->isVariadic()
5896 ? diag::err_typecheck_call_too_many_args_suggest
5897 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5899 TC, PDiag(diag_id)
5900 << FnKind << NumParams - ExplicitObjectParameterOffset
5901 << static_cast<unsigned>(Args.size()) -
5902 ExplicitObjectParameterOffset
5903 << HasExplicitObjectParameter << TC.getCorrectionRange());
5904 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5905 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5906 ->getDeclName())
5907 Diag(Args[NumParams]->getBeginLoc(),
5908 MinArgs == NumParams
5909 ? diag::err_typecheck_call_too_many_args_one
5910 : diag::err_typecheck_call_too_many_args_at_most_one)
5911 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5912 << static_cast<unsigned>(Args.size()) -
5913 ExplicitObjectParameterOffset
5914 << HasExplicitObjectParameter << Fn->getSourceRange()
5915 << SourceRange(Args[NumParams]->getBeginLoc(),
5916 Args.back()->getEndLoc());
5917 else
5918 Diag(Args[NumParams]->getBeginLoc(),
5919 MinArgs == NumParams
5920 ? diag::err_typecheck_call_too_many_args
5921 : diag::err_typecheck_call_too_many_args_at_most)
5922 << FnKind << NumParams - ExplicitObjectParameterOffset
5923 << static_cast<unsigned>(Args.size()) -
5924 ExplicitObjectParameterOffset
5925 << HasExplicitObjectParameter << Fn->getSourceRange()
5926 << SourceRange(Args[NumParams]->getBeginLoc(),
5927 Args.back()->getEndLoc());
5928
5929 // Emit the location of the prototype.
5930 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5931 Diag(FDecl->getLocation(), diag::note_callee_decl)
5932 << FDecl << FDecl->getParametersSourceRange();
5933
5934 // This deletes the extra arguments.
5935 Call->shrinkNumArgs(NumParams);
5936 return true;
5937 }
5938 }
5939 SmallVector<Expr *, 8> AllArgs;
5940 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5941
5942 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
5943 AllArgs, CallType);
5944 if (Invalid)
5945 return true;
5946 unsigned TotalNumArgs = AllArgs.size();
5947 for (unsigned i = 0; i < TotalNumArgs; ++i)
5948 Call->setArg(i, AllArgs[i]);
5949
5950 Call->computeDependence();
5951 return false;
5952}
5953
5955 const FunctionProtoType *Proto,
5956 unsigned FirstParam, ArrayRef<Expr *> Args,
5957 SmallVectorImpl<Expr *> &AllArgs,
5958 VariadicCallType CallType, bool AllowExplicit,
5959 bool IsListInitialization) {
5960 unsigned NumParams = Proto->getNumParams();
5961 bool Invalid = false;
5962 size_t ArgIx = 0;
5963 // Continue to check argument types (even if we have too few/many args).
5964 for (unsigned i = FirstParam; i < NumParams; i++) {
5965 QualType ProtoArgType = Proto->getParamType(i);
5966
5967 Expr *Arg;
5968 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5969 if (ArgIx < Args.size()) {
5970 Arg = Args[ArgIx++];
5971
5972 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5973 diag::err_call_incomplete_argument, Arg))
5974 return true;
5975
5976 // Strip the unbridged-cast placeholder expression off, if applicable.
5977 bool CFAudited = false;
5978 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5979 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5980 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5981 Arg = ObjC().stripARCUnbridgedCast(Arg);
5982 else if (getLangOpts().ObjCAutoRefCount &&
5983 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5984 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5985 CFAudited = true;
5986
5987 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5988 ProtoArgType->isBlockPointerType())
5989 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5990 BE->getBlockDecl()->setDoesNotEscape();
5991 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
5993 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
5994 if (ArgExpr.isInvalid())
5995 return true;
5996 Arg = ArgExpr.getAs<Expr>();
5997 }
5998
5999 InitializedEntity Entity =
6001 ProtoArgType)
6003 Context, ProtoArgType, Proto->isParamConsumed(i));
6004
6005 // Remember that parameter belongs to a CF audited API.
6006 if (CFAudited)
6007 Entity.setParameterCFAudited();
6008
6010 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6011 if (ArgE.isInvalid())
6012 return true;
6013
6014 Arg = ArgE.getAs<Expr>();
6015 } else {
6016 assert(Param && "can't use default arguments without a known callee");
6017
6018 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6019 if (ArgExpr.isInvalid())
6020 return true;
6021
6022 Arg = ArgExpr.getAs<Expr>();
6023 }
6024
6025 // Check for array bounds violations for each argument to the call. This
6026 // check only triggers warnings when the argument isn't a more complex Expr
6027 // with its own checking, such as a BinaryOperator.
6028 CheckArrayAccess(Arg);
6029
6030 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6031 CheckStaticArrayArgument(CallLoc, Param, Arg);
6032
6033 AllArgs.push_back(Arg);
6034 }
6035
6036 // If this is a variadic call, handle args passed through "...".
6037 if (CallType != VariadicDoesNotApply) {
6038 // Assume that extern "C" functions with variadic arguments that
6039 // return __unknown_anytype aren't *really* variadic.
6040 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6041 FDecl->isExternC()) {
6042 for (Expr *A : Args.slice(ArgIx)) {
6043 QualType paramType; // ignored
6044 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6045 Invalid |= arg.isInvalid();
6046 AllArgs.push_back(arg.get());
6047 }
6048
6049 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6050 } else {
6051 for (Expr *A : Args.slice(ArgIx)) {
6052 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6053 Invalid |= Arg.isInvalid();
6054 AllArgs.push_back(Arg.get());
6055 }
6056 }
6057
6058 // Check for array bounds violations.
6059 for (Expr *A : Args.slice(ArgIx))
6060 CheckArrayAccess(A);
6061 }
6062 return Invalid;
6063}
6064
6066 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6067 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6068 TL = DTL.getOriginalLoc();
6069 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6070 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6071 << ATL.getLocalSourceRange();
6072}
6073
6074void
6076 ParmVarDecl *Param,
6077 const Expr *ArgExpr) {
6078 // Static array parameters are not supported in C++.
6079 if (!Param || getLangOpts().CPlusPlus)
6080 return;
6081
6082 QualType OrigTy = Param->getOriginalType();
6083
6084 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6085 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6086 return;
6087
6088 if (ArgExpr->isNullPointerConstant(Context,
6090 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6091 DiagnoseCalleeStaticArrayParam(*this, Param);
6092 return;
6093 }
6094
6095 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6096 if (!CAT)
6097 return;
6098
6099 const ConstantArrayType *ArgCAT =
6101 if (!ArgCAT)
6102 return;
6103
6104 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6105 ArgCAT->getElementType())) {
6106 if (ArgCAT->getSize().ult(CAT->getSize())) {
6107 Diag(CallLoc, diag::warn_static_array_too_small)
6108 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6109 << (unsigned)CAT->getZExtSize() << 0;
6110 DiagnoseCalleeStaticArrayParam(*this, Param);
6111 }
6112 return;
6113 }
6114
6115 std::optional<CharUnits> ArgSize =
6117 std::optional<CharUnits> ParmSize =
6119 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6120 Diag(CallLoc, diag::warn_static_array_too_small)
6121 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6122 << (unsigned)ParmSize->getQuantity() << 1;
6123 DiagnoseCalleeStaticArrayParam(*this, Param);
6124 }
6125}
6126
6127/// Given a function expression of unknown-any type, try to rebuild it
6128/// to have a function type.
6130
6131/// Is the given type a placeholder that we need to lower out
6132/// immediately during argument processing?
6134 // Placeholders are never sugared.
6135 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6136 if (!placeholder) return false;
6137
6138 switch (placeholder->getKind()) {
6139 // Ignore all the non-placeholder types.
6140#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6141 case BuiltinType::Id:
6142#include "clang/Basic/OpenCLImageTypes.def"
6143#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6144 case BuiltinType::Id:
6145#include "clang/Basic/OpenCLExtensionTypes.def"
6146 // In practice we'll never use this, since all SVE types are sugared
6147 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6148#define SVE_TYPE(Name, Id, SingletonId) \
6149 case BuiltinType::Id:
6150#include "clang/Basic/AArch64SVEACLETypes.def"
6151#define PPC_VECTOR_TYPE(Name, Id, Size) \
6152 case BuiltinType::Id:
6153#include "clang/Basic/PPCTypes.def"
6154#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6155#include "clang/Basic/RISCVVTypes.def"
6156#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6157#include "clang/Basic/WebAssemblyReferenceTypes.def"
6158#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6159#include "clang/Basic/AMDGPUTypes.def"
6160#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6161#include "clang/Basic/HLSLIntangibleTypes.def"
6162#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6163#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6164#include "clang/AST/BuiltinTypes.def"
6165 return false;
6166
6167 case BuiltinType::UnresolvedTemplate:
6168 // We cannot lower out overload sets; they might validly be resolved
6169 // by the call machinery.
6170 case BuiltinType::Overload:
6171 return false;
6172
6173 // Unbridged casts in ARC can be handled in some call positions and
6174 // should be left in place.
6175 case BuiltinType::ARCUnbridgedCast:
6176 return false;
6177
6178 // Pseudo-objects should be converted as soon as possible.
6179 case BuiltinType::PseudoObject:
6180 return true;
6181
6182 // The debugger mode could theoretically but currently does not try
6183 // to resolve unknown-typed arguments based on known parameter types.
6184 case BuiltinType::UnknownAny:
6185 return true;
6186
6187 // These are always invalid as call arguments and should be reported.
6188 case BuiltinType::BoundMember:
6189 case BuiltinType::BuiltinFn:
6190 case BuiltinType::IncompleteMatrixIdx:
6191 case BuiltinType::ArraySection:
6192 case BuiltinType::OMPArrayShaping:
6193 case BuiltinType::OMPIterator:
6194 return true;
6195
6196 }
6197 llvm_unreachable("bad builtin type kind");
6198}
6199
6201 // Apply this processing to all the arguments at once instead of
6202 // dying at the first failure.
6203 bool hasInvalid = false;
6204 for (size_t i = 0, e = args.size(); i != e; i++) {
6205 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6206 ExprResult result = CheckPlaceholderExpr(args[i]);
6207 if (result.isInvalid()) hasInvalid = true;
6208 else args[i] = result.get();
6209 }
6210 }
6211 return hasInvalid;
6212}
6213
6214/// If a builtin function has a pointer argument with no explicit address
6215/// space, then it should be able to accept a pointer to any address
6216/// space as input. In order to do this, we need to replace the
6217/// standard builtin declaration with one that uses the same address space
6218/// as the call.
6219///
6220/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6221/// it does not contain any pointer arguments without
6222/// an address space qualifer. Otherwise the rewritten
6223/// FunctionDecl is returned.
6224/// TODO: Handle pointer return types.
6226 FunctionDecl *FDecl,
6227 MultiExprArg ArgExprs) {
6228
6229 QualType DeclType = FDecl->getType();
6230 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6231
6232 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6233 ArgExprs.size() < FT->getNumParams())
6234 return nullptr;
6235
6236 bool NeedsNewDecl = false;
6237 unsigned i = 0;
6238 SmallVector<QualType, 8> OverloadParams;
6239
6240 for (QualType ParamType : FT->param_types()) {
6241
6242 // Convert array arguments to pointer to simplify type lookup.
6243 ExprResult ArgRes =
6245 if (ArgRes.isInvalid())
6246 return nullptr;
6247 Expr *Arg = ArgRes.get();
6248 QualType ArgType = Arg->getType();
6249 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6250 !ArgType->isPointerType() ||
6251 !ArgType->getPointeeType().hasAddressSpace() ||
6253 OverloadParams.push_back(ParamType);
6254 continue;
6255 }
6256
6257 QualType PointeeType = ParamType->getPointeeType();
6258 if (PointeeType.hasAddressSpace())
6259 continue;
6260
6261 NeedsNewDecl = true;
6262 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6263
6264 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6265 OverloadParams.push_back(Context.getPointerType(PointeeType));
6266 }
6267
6268 if (!NeedsNewDecl)
6269 return nullptr;
6270
6272 EPI.Variadic = FT->isVariadic();
6273 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6274 OverloadParams, EPI);
6275 DeclContext *Parent = FDecl->getParent();
6276 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6277 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6278 FDecl->getIdentifier(), OverloadTy,
6279 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6280 false,
6281 /*hasPrototype=*/true);
6283 FT = cast<FunctionProtoType>(OverloadTy);
6284 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6285 QualType ParamType = FT->getParamType(i);
6286 ParmVarDecl *Parm =
6287 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6288 SourceLocation(), nullptr, ParamType,
6289 /*TInfo=*/nullptr, SC_None, nullptr);
6290 Parm->setScopeInfo(0, i);
6291 Params.push_back(Parm);
6292 }
6293 OverloadDecl->setParams(Params);
6294 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6295 return OverloadDecl;
6296}
6297
6298static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6299 FunctionDecl *Callee,
6300 MultiExprArg ArgExprs) {
6301 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6302 // similar attributes) really don't like it when functions are called with an
6303 // invalid number of args.
6304 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6305 /*PartialOverloading=*/false) &&
6306 !Callee->isVariadic())
6307 return;
6308 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6309 return;
6310
6311 if (const EnableIfAttr *Attr =
6312 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6313 S.Diag(Fn->getBeginLoc(),
6314 isa<CXXMethodDecl>(Callee)
6315 ? diag::err_ovl_no_viable_member_function_in_call
6316 : diag::err_ovl_no_viable_function_in_call)
6317 << Callee << Callee->getSourceRange();
6318 S.Diag(Callee->getLocation(),
6319 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6320 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6321 return;
6322 }
6323}
6324
6326 const UnresolvedMemberExpr *const UME, Sema &S) {
6327
6328 const auto GetFunctionLevelDCIfCXXClass =
6329 [](Sema &S) -> const CXXRecordDecl * {
6330 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6331 if (!DC || !DC->getParent())
6332 return nullptr;
6333
6334 // If the call to some member function was made from within a member
6335 // function body 'M' return return 'M's parent.
6336 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6337 return MD->getParent()->getCanonicalDecl();
6338 // else the call was made from within a default member initializer of a
6339 // class, so return the class.
6340 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6341 return RD->getCanonicalDecl();
6342 return nullptr;
6343 };
6344 // If our DeclContext is neither a member function nor a class (in the
6345 // case of a lambda in a default member initializer), we can't have an
6346 // enclosing 'this'.
6347
6348 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6349 if (!CurParentClass)
6350 return false;
6351
6352 // The naming class for implicit member functions call is the class in which
6353 // name lookup starts.
6354 const CXXRecordDecl *const NamingClass =
6356 assert(NamingClass && "Must have naming class even for implicit access");
6357
6358 // If the unresolved member functions were found in a 'naming class' that is
6359 // related (either the same or derived from) to the class that contains the
6360 // member function that itself contained the implicit member access.
6361
6362 return CurParentClass == NamingClass ||
6363 CurParentClass->isDerivedFrom(NamingClass);
6364}
6365
6366static void
6368 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6369
6370 if (!UME)
6371 return;
6372
6373 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6374 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6375 // already been captured, or if this is an implicit member function call (if
6376 // it isn't, an attempt to capture 'this' should already have been made).
6377 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6378 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6379 return;
6380
6381 // Check if the naming class in which the unresolved members were found is
6382 // related (same as or is a base of) to the enclosing class.
6383
6385 return;
6386
6387
6388 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6389 // If the enclosing function is not dependent, then this lambda is
6390 // capture ready, so if we can capture this, do so.
6391 if (!EnclosingFunctionCtx->isDependentContext()) {
6392 // If the current lambda and all enclosing lambdas can capture 'this' -
6393 // then go ahead and capture 'this' (since our unresolved overload set
6394 // contains at least one non-static member function).
6395 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6396 S.CheckCXXThisCapture(CallLoc);
6397 } else if (S.CurContext->isDependentContext()) {
6398 // ... since this is an implicit member reference, that might potentially
6399 // involve a 'this' capture, mark 'this' for potential capture in
6400 // enclosing lambdas.
6401 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6402 CurLSI->addPotentialThisCapture(CallLoc);
6403 }
6404}
6405
6406// Once a call is fully resolved, warn for unqualified calls to specific
6407// C++ standard functions, like move and forward.
6409 const CallExpr *Call) {
6410 // We are only checking unary move and forward so exit early here.
6411 if (Call->getNumArgs() != 1)
6412 return;
6413
6414 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6415 if (!E || isa<UnresolvedLookupExpr>(E))
6416 return;
6417 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6418 if (!DRE || !DRE->getLocation().isValid())
6419 return;
6420
6421 if (DRE->getQualifier())
6422 return;
6423
6424 const FunctionDecl *FD = Call->getDirectCallee();
6425 if (!FD)
6426 return;
6427
6428 // Only warn for some functions deemed more frequent or problematic.
6429 unsigned BuiltinID = FD->getBuiltinID();
6430 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6431 return;
6432
6433 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6435 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6436}
6437
6439 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6440 Expr *ExecConfig) {
6442 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6443 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6444 if (Call.isInvalid())
6445 return Call;
6446
6447 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6448 // language modes.
6449 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6450 ULE && ULE->hasExplicitTemplateArgs() &&
6451 ULE->decls_begin() == ULE->decls_end()) {
6452 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6453 ? diag::warn_cxx17_compat_adl_only_template_id
6454 : diag::ext_adl_only_template_id)
6455 << ULE->getName();
6456 }
6457
6458 if (LangOpts.OpenMP)
6459 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6460 ExecConfig);
6461 if (LangOpts.CPlusPlus) {
6462 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6464
6465 // If we previously found that the id-expression of this call refers to a
6466 // consteval function but the call is dependent, we should not treat is an
6467 // an invalid immediate call.
6468 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6469 DRE && Call.get()->isValueDependent()) {
6471 }
6472 }
6473 return Call;
6474}
6475
6477 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6478 Expr *ExecConfig, bool IsExecConfig,
6479 bool AllowRecovery) {
6480 // Since this might be a postfix expression, get rid of ParenListExprs.
6482 if (Result.isInvalid()) return ExprError();
6483 Fn = Result.get();
6484
6485 if (CheckArgsForPlaceholders(ArgExprs))
6486 return ExprError();
6487
6488 // The result of __builtin_counted_by_ref cannot be used as a function
6489 // argument. It allows leaking and modification of bounds safety information.
6490 for (const Expr *Arg : ArgExprs)
6491 if (CheckInvalidBuiltinCountedByRef(Arg, FunctionArgKind))
6492 return ExprError();
6493
6494 if (getLangOpts().CPlusPlus) {
6495 // If this is a pseudo-destructor expression, build the call immediately.
6496 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6497 if (!ArgExprs.empty()) {
6498 // Pseudo-destructor calls should not have any arguments.
6499 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6501 SourceRange(ArgExprs.front()->getBeginLoc(),
6502 ArgExprs.back()->getEndLoc()));
6503 }
6504
6505 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6506 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6507 }
6508 if (Fn->getType() == Context.PseudoObjectTy) {
6509 ExprResult result = CheckPlaceholderExpr(Fn);
6510 if (result.isInvalid()) return ExprError();
6511 Fn = result.get();
6512 }
6513
6514 // Determine whether this is a dependent call inside a C++ template,
6515 // in which case we won't do any semantic analysis now.
6516 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6517 if (ExecConfig) {
6519 cast<CallExpr>(ExecConfig), ArgExprs,
6521 RParenLoc, CurFPFeatureOverrides());
6522 } else {
6523
6525 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6526 Fn->getBeginLoc());
6527
6528 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6529 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6530 }
6531 }
6532
6533 // Determine whether this is a call to an object (C++ [over.call.object]).
6534 if (Fn->getType()->isRecordType())
6535 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6536 RParenLoc);
6537
6538 if (Fn->getType() == Context.UnknownAnyTy) {
6539 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6540 if (result.isInvalid()) return ExprError();
6541 Fn = result.get();
6542 }
6543
6544 if (Fn->getType() == Context.BoundMemberTy) {
6545 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6546 RParenLoc, ExecConfig, IsExecConfig,
6547 AllowRecovery);
6548 }
6549 }
6550
6551 // Check for overloaded calls. This can happen even in C due to extensions.
6552 if (Fn->getType() == Context.OverloadTy) {
6554
6555 // We aren't supposed to apply this logic if there's an '&' involved.
6558 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6559 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6560 OverloadExpr *ovl = find.Expression;
6561 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6563 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6564 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6565 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6566 RParenLoc, ExecConfig, IsExecConfig,
6567 AllowRecovery);
6568 }
6569 }
6570
6571 // If we're directly calling a function, get the appropriate declaration.
6572 if (Fn->getType() == Context.UnknownAnyTy) {
6573 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6574 if (result.isInvalid()) return ExprError();
6575 Fn = result.get();
6576 }
6577
6578 Expr *NakedFn = Fn->IgnoreParens();
6579
6580 bool CallingNDeclIndirectly = false;
6581 NamedDecl *NDecl = nullptr;
6582 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6583 if (UnOp->getOpcode() == UO_AddrOf) {
6584 CallingNDeclIndirectly = true;
6585 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6586 }
6587 }
6588
6589 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6590 NDecl = DRE->getDecl();
6591
6592 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6593 if (FDecl && FDecl->getBuiltinID()) {
6594 // Rewrite the function decl for this builtin by replacing parameters
6595 // with no explicit address space with the address space of the arguments
6596 // in ArgExprs.
6597 if ((FDecl =
6598 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6599 NDecl = FDecl;
6601 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6602 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6603 nullptr, DRE->isNonOdrUse());
6604 }
6605 }
6606 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6607 NDecl = ME->getMemberDecl();
6608
6609 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6610 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6611 FD, /*Complain=*/true, Fn->getBeginLoc()))
6612 return ExprError();
6613
6614 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6615
6616 // If this expression is a call to a builtin function in HIP device
6617 // compilation, allow a pointer-type argument to default address space to be
6618 // passed as a pointer-type parameter to a non-default address space.
6619 // If Arg is declared in the default address space and Param is declared
6620 // in a non-default address space, perform an implicit address space cast to
6621 // the parameter type.
6622 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6623 FD->getBuiltinID()) {
6624 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6625 ++Idx) {
6626 ParmVarDecl *Param = FD->getParamDecl(Idx);
6627 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6628 !ArgExprs[Idx]->getType()->isPointerType())
6629 continue;
6630
6631 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6632 auto ArgTy = ArgExprs[Idx]->getType();
6633 auto ArgPtTy = ArgTy->getPointeeType();
6634 auto ArgAS = ArgPtTy.getAddressSpace();
6635
6636 // Add address space cast if target address spaces are different
6637 bool NeedImplicitASC =
6638 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6639 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6640 // or from specific AS which has target AS matching that of Param.
6642 if (!NeedImplicitASC)
6643 continue;
6644
6645 // First, ensure that the Arg is an RValue.
6646 if (ArgExprs[Idx]->isGLValue()) {
6647 ArgExprs[Idx] = ImplicitCastExpr::Create(
6648 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6649 nullptr, VK_PRValue, FPOptionsOverride());
6650 }
6651
6652 // Construct a new arg type with address space of Param
6653 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6654 ArgPtQuals.setAddressSpace(ParamAS);
6655 auto NewArgPtTy =
6656 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6657 auto NewArgTy =
6659 ArgTy.getQualifiers());
6660
6661 // Finally perform an implicit address space cast
6662 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6663 CK_AddressSpaceConversion)
6664 .get();
6665 }
6666 }
6667 }
6668
6670 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6671 assert(!getLangOpts().CPlusPlus);
6672 assert((Fn->containsErrors() ||
6673 llvm::any_of(ArgExprs,
6674 [](clang::Expr *E) { return E->containsErrors(); })) &&
6675 "should only occur in error-recovery path.");
6676 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6677 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6678 }
6679 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6680 ExecConfig, IsExecConfig);
6681}
6682
6684 MultiExprArg CallArgs) {
6685 StringRef Name = Context.BuiltinInfo.getName(Id);
6686 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6688 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6689
6690 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6691 assert(BuiltInDecl && "failed to find builtin declaration");
6692
6693 ExprResult DeclRef =
6694 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6695 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6696
6698 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6699
6700 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6701 return Call.get();
6702}
6703
6705 SourceLocation BuiltinLoc,
6706 SourceLocation RParenLoc) {
6707 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6708 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6709}
6710
6712 SourceLocation BuiltinLoc,
6713 SourceLocation RParenLoc) {
6716 QualType SrcTy = E->getType();
6717 if (!SrcTy->isDependentType() &&
6718 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6719 return ExprError(
6720 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6721 << DestTy << SrcTy << E->getSourceRange());
6722 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6723}
6724
6726 SourceLocation BuiltinLoc,
6727 SourceLocation RParenLoc) {
6728 TypeSourceInfo *TInfo;
6729 GetTypeFromParser(ParsedDestTy, &TInfo);
6730 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6731}
6732
6734 SourceLocation LParenLoc,
6735 ArrayRef<Expr *> Args,
6736 SourceLocation RParenLoc, Expr *Config,
6737 bool IsExecConfig, ADLCallKind UsesADL) {
6738 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6739 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6740
6741 // Functions with 'interrupt' attribute cannot be called directly.
6742 if (FDecl) {
6743 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6744 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6745 return ExprError();
6746 }
6747 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6748 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6749 return ExprError();
6750 }
6751 }
6752
6753 // X86 interrupt handlers may only call routines with attribute
6754 // no_caller_saved_registers since there is no efficient way to
6755 // save and restore the non-GPR state.
6756 if (auto *Caller = getCurFunctionDecl()) {
6757 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6758 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6759 const TargetInfo &TI = Context.getTargetInfo();
6760 bool HasNonGPRRegisters =
6761 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6762 if (HasNonGPRRegisters &&
6763 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6764 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6765 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6766 if (FDecl)
6767 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6768 }
6769 }
6770 }
6771
6772 // Promote the function operand.
6773 // We special-case function promotion here because we only allow promoting
6774 // builtin functions to function pointers in the callee of a call.
6776 QualType ResultTy;
6777 if (BuiltinID &&
6778 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6779 // Extract the return type from the (builtin) function pointer type.
6780 // FIXME Several builtins still have setType in
6781 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6782 // Builtins.td to ensure they are correct before removing setType calls.
6783 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6784 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6785 ResultTy = FDecl->getCallResultType();
6786 } else {
6788 ResultTy = Context.BoolTy;
6789 }
6790 if (Result.isInvalid())
6791 return ExprError();
6792 Fn = Result.get();
6793
6794 // Check for a valid function type, but only if it is not a builtin which
6795 // requires custom type checking. These will be handled by
6796 // CheckBuiltinFunctionCall below just after creation of the call expression.
6797 const FunctionType *FuncT = nullptr;
6798 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6799 retry:
6800 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6801 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6802 // have type pointer to function".
6803 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6804 if (!FuncT)
6805 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6806 << Fn->getType() << Fn->getSourceRange());
6807 } else if (const BlockPointerType *BPT =
6808 Fn->getType()->getAs<BlockPointerType>()) {
6809 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6810 } else {
6811 // Handle calls to expressions of unknown-any type.
6812 if (Fn->getType() == Context.UnknownAnyTy) {
6813 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6814 if (rewrite.isInvalid())
6815 return ExprError();
6816 Fn = rewrite.get();
6817 goto retry;
6818 }
6819
6820 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6821 << Fn->getType() << Fn->getSourceRange());
6822 }
6823 }
6824
6825 // Get the number of parameters in the function prototype, if any.
6826 // We will allocate space for max(Args.size(), NumParams) arguments
6827 // in the call expression.
6828 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6829 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6830
6831 CallExpr *TheCall;
6832 if (Config) {
6833 assert(UsesADL == ADLCallKind::NotADL &&
6834 "CUDAKernelCallExpr should not use ADL");
6835 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6836 Args, ResultTy, VK_PRValue, RParenLoc,
6837 CurFPFeatureOverrides(), NumParams);
6838 } else {
6839 TheCall =
6840 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6841 CurFPFeatureOverrides(), NumParams, UsesADL);
6842 }
6843
6845 // Forget about the nulled arguments since typo correction
6846 // do not handle them well.
6847 TheCall->shrinkNumArgs(Args.size());
6848 // C cannot always handle TypoExpr nodes in builtin calls and direct
6849 // function calls as their argument checking don't necessarily handle
6850 // dependent types properly, so make sure any TypoExprs have been
6851 // dealt with.
6853 if (!Result.isUsable()) return ExprError();
6854 CallExpr *TheOldCall = TheCall;
6855 TheCall = dyn_cast<CallExpr>(Result.get());
6856 bool CorrectedTypos = TheCall != TheOldCall;
6857 if (!TheCall) return Result;
6858 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6859
6860 // A new call expression node was created if some typos were corrected.
6861 // However it may not have been constructed with enough storage. In this
6862 // case, rebuild the node with enough storage. The waste of space is
6863 // immaterial since this only happens when some typos were corrected.
6864 if (CorrectedTypos && Args.size() < NumParams) {
6865 if (Config)
6867 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6868 RParenLoc, CurFPFeatureOverrides(), NumParams);
6869 else
6870 TheCall =
6871 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6872 CurFPFeatureOverrides(), NumParams, UsesADL);
6873 }
6874 // We can now handle the nulled arguments for the default arguments.
6875 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6876 }
6877
6878 // Bail out early if calling a builtin with custom type checking.
6879 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6880 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6881 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6883 return E;
6884 }
6885
6886 if (getLangOpts().CUDA) {
6887 if (Config) {
6888 // CUDA: Kernel calls must be to global functions
6889 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6890 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6891 << FDecl << Fn->getSourceRange());
6892
6893 // CUDA: Kernel function must have 'void' return type
6894 if (!FuncT->getReturnType()->isVoidType() &&
6895 !FuncT->getReturnType()->getAs<AutoType>() &&
6897 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6898 << Fn->getType() << Fn->getSourceRange());
6899 } else {
6900 // CUDA: Calls to global functions must be configured
6901 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6902 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6903 << FDecl << Fn->getSourceRange());
6904 }
6905 }
6906
6907 // Check for a valid return type
6908 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6909 FDecl))
6910 return ExprError();
6911
6912 // We know the result type of the call, set it.
6913 TheCall->setType(FuncT->getCallResultType(Context));
6915
6916 // WebAssembly tables can't be used as arguments.
6917 if (Context.getTargetInfo().getTriple().isWasm()) {
6918 for (const Expr *Arg : Args) {
6919 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6920 return ExprError(Diag(Arg->getExprLoc(),
6921 diag::err_wasm_table_as_function_parameter));
6922 }
6923 }
6924 }
6925
6926 if (Proto) {
6927 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6928 IsExecConfig))
6929 return ExprError();
6930 } else {
6931 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6932
6933 if (FDecl) {
6934 // Check if we have too few/too many template arguments, based
6935 // on our knowledge of the function definition.
6936 const FunctionDecl *Def = nullptr;
6937 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6938 Proto = Def->getType()->getAs<FunctionProtoType>();
6939 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6940 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6941 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6942 }
6943
6944 // If the function we're calling isn't a function prototype, but we have
6945 // a function prototype from a prior declaratiom, use that prototype.
6946 if (!FDecl->hasPrototype())
6947 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6948 }
6949
6950 // If we still haven't found a prototype to use but there are arguments to
6951 // the call, diagnose this as calling a function without a prototype.
6952 // However, if we found a function declaration, check to see if
6953 // -Wdeprecated-non-prototype was disabled where the function was declared.
6954 // If so, we will silence the diagnostic here on the assumption that this
6955 // interface is intentional and the user knows what they're doing. We will
6956 // also silence the diagnostic if there is a function declaration but it
6957 // was implicitly defined (the user already gets diagnostics about the
6958 // creation of the implicit function declaration, so the additional warning
6959 // is not helpful).
6960 if (!Proto && !Args.empty() &&
6961 (!FDecl || (!FDecl->isImplicit() &&
6962 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6963 FDecl->getLocation()))))
6964 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6965 << (FDecl != nullptr) << FDecl;
6966
6967 // Promote the arguments (C99 6.5.2.2p6).
6968 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6969 Expr *Arg = Args[i];
6970
6971 if (Proto && i < Proto->getNumParams()) {
6973 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6974 ExprResult ArgE =
6976 if (ArgE.isInvalid())
6977 return true;
6978
6979 Arg = ArgE.getAs<Expr>();
6980
6981 } else {
6983
6984 if (ArgE.isInvalid())
6985 return true;
6986
6987 Arg = ArgE.getAs<Expr>();
6988 }
6989
6990 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6991 diag::err_call_incomplete_argument, Arg))
6992 return ExprError();
6993
6994 TheCall->setArg(i, Arg);
6995 }
6996 TheCall->computeDependence();
6997 }
6998
6999 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7000 if (Method->isImplicitObjectMemberFunction())
7001 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7002 << Fn->getSourceRange() << 0);
7003
7004 // Check for sentinels
7005 if (NDecl)
7006 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7007
7008 // Warn for unions passing across security boundary (CMSE).
7009 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7010 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7011 if (const auto *RT =
7012 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7013 if (RT->getDecl()->isOrContainsUnion())
7014 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7015 << 0 << i;
7016 }
7017 }
7018 }
7019
7020 // Do special checking on direct calls to functions.
7021 if (FDecl) {
7022 if (CheckFunctionCall(FDecl, TheCall, Proto))
7023 return ExprError();
7024
7025 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7026
7027 if (BuiltinID)
7028 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7029 } else if (NDecl) {
7030 if (CheckPointerCall(NDecl, TheCall, Proto))
7031 return ExprError();
7032 } else {
7033 if (CheckOtherCall(TheCall, Proto))
7034 return ExprError();
7035 }
7036
7037 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7038}
7039
7042 SourceLocation RParenLoc, Expr *InitExpr) {
7043 assert(Ty && "ActOnCompoundLiteral(): missing type");
7044 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7045
7046 TypeSourceInfo *TInfo;
7047 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7048 if (!TInfo)
7049 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7050
7051 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7052}
7053
7056 SourceLocation RParenLoc, Expr *LiteralExpr) {
7057 QualType literalType = TInfo->getType();
7058
7059 if (literalType->isArrayType()) {
7061 LParenLoc, Context.getBaseElementType(literalType),
7062 diag::err_array_incomplete_or_sizeless_type,
7063 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7064 return ExprError();
7065 if (literalType->isVariableArrayType()) {
7066 // C23 6.7.10p4: An entity of variable length array type shall not be
7067 // initialized except by an empty initializer.
7068 //
7069 // The C extension warnings are issued from ParseBraceInitializer() and
7070 // do not need to be issued here. However, we continue to issue an error
7071 // in the case there are initializers or we are compiling C++. We allow
7072 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7073 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7074 // FIXME: should we allow this construct in C++ when it makes sense to do
7075 // so?
7076 //
7077 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7078 // shall specify an object type or an array of unknown size, but not a
7079 // variable length array type. This seems odd, as it allows 'int a[size] =
7080 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7081 // says, this is what's implemented here for C (except for the extension
7082 // that permits constant foldable size arrays)
7083
7084 auto diagID = LangOpts.CPlusPlus
7085 ? diag::err_variable_object_no_init
7086 : diag::err_compound_literal_with_vla_type;
7087 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7088 diagID))
7089 return ExprError();
7090 }
7091 } else if (!literalType->isDependentType() &&
7092 RequireCompleteType(LParenLoc, literalType,
7093 diag::err_typecheck_decl_incomplete_type,
7094 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7095 return ExprError();
7096
7097 InitializedEntity Entity
7101 SourceRange(LParenLoc, RParenLoc),
7102 /*InitList=*/true);
7103 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7104 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7105 &literalType);
7106 if (Result.isInvalid())
7107 return ExprError();
7108 LiteralExpr = Result.get();
7109
7110 bool isFileScope = !CurContext->isFunctionOrMethod();
7111
7112 // In C, compound literals are l-values for some reason.
7113 // For GCC compatibility, in C++, file-scope array compound literals with
7114 // constant initializers are also l-values, and compound literals are
7115 // otherwise prvalues.
7116 //
7117 // (GCC also treats C++ list-initialized file-scope array prvalues with
7118 // constant initializers as l-values, but that's non-conforming, so we don't
7119 // follow it there.)
7120 //
7121 // FIXME: It would be better to handle the lvalue cases as materializing and
7122 // lifetime-extending a temporary object, but our materialized temporaries
7123 // representation only supports lifetime extension from a variable, not "out
7124 // of thin air".
7125 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7126 // is bound to the result of applying array-to-pointer decay to the compound
7127 // literal.
7128 // FIXME: GCC supports compound literals of reference type, which should
7129 // obviously have a value kind derived from the kind of reference involved.
7130 ExprValueKind VK =
7131 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7132 ? VK_PRValue
7133 : VK_LValue;
7134
7135 if (isFileScope)
7136 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7137 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7138 Expr *Init = ILE->getInit(i);
7139 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7140 }
7141
7142 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7143 VK, LiteralExpr, isFileScope);
7144 if (isFileScope) {
7145 if (!LiteralExpr->isTypeDependent() &&
7146 !LiteralExpr->isValueDependent() &&
7147 !literalType->isDependentType()) // C99 6.5.2.5p3
7148 if (CheckForConstantInitializer(LiteralExpr))
7149 return ExprError();
7150 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7151 literalType.getAddressSpace() != LangAS::Default) {
7152 // Embedded-C extensions to C99 6.5.2.5:
7153 // "If the compound literal occurs inside the body of a function, the
7154 // type name shall not be qualified by an address-space qualifier."
7155 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7156 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7157 return ExprError();
7158 }
7159
7160 if (!isFileScope && !getLangOpts().CPlusPlus) {
7161 // Compound literals that have automatic storage duration are destroyed at
7162 // the end of the scope in C; in C++, they're just temporaries.
7163
7164 // Emit diagnostics if it is or contains a C union type that is non-trivial
7165 // to destruct.
7169
7170 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7171 if (literalType.isDestructedType()) {
7173 ExprCleanupObjects.push_back(E);
7175 }
7176 }
7177
7180 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7181 E->getInitializer()->getExprLoc());
7182
7183 return MaybeBindToTemporary(E);
7184}
7185
7188 SourceLocation RBraceLoc) {
7189 // Only produce each kind of designated initialization diagnostic once.
7190 SourceLocation FirstDesignator;
7191 bool DiagnosedArrayDesignator = false;
7192 bool DiagnosedNestedDesignator = false;
7193 bool DiagnosedMixedDesignator = false;
7194
7195 // Check that any designated initializers are syntactically valid in the
7196 // current language mode.
7197 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7198 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7199 if (FirstDesignator.isInvalid())
7200 FirstDesignator = DIE->getBeginLoc();
7201
7202 if (!getLangOpts().CPlusPlus)
7203 break;
7204
7205 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7206 DiagnosedNestedDesignator = true;
7207 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7208 << DIE->getDesignatorsSourceRange();
7209 }
7210
7211 for (auto &Desig : DIE->designators()) {
7212 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7213 DiagnosedArrayDesignator = true;
7214 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7215 << Desig.getSourceRange();
7216 }
7217 }
7218
7219 if (!DiagnosedMixedDesignator &&
7220 !isa<DesignatedInitExpr>(InitArgList[0])) {
7221 DiagnosedMixedDesignator = true;
7222 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7223 << DIE->getSourceRange();
7224 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7225 << InitArgList[0]->getSourceRange();
7226 }
7227 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7228 isa<DesignatedInitExpr>(InitArgList[0])) {
7229 DiagnosedMixedDesignator = true;
7230 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7231 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7232 << DIE->getSourceRange();
7233 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7234 << InitArgList[I]->getSourceRange();
7235 }
7236 }
7237
7238 if (FirstDesignator.isValid()) {
7239 // Only diagnose designated initiaization as a C++20 extension if we didn't
7240 // already diagnose use of (non-C++20) C99 designator syntax.
7241 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7242 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7243 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7244 ? diag::warn_cxx17_compat_designated_init
7245 : diag::ext_cxx_designated_init);
7246 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7247 Diag(FirstDesignator, diag::ext_designated_init);
7248 }
7249 }
7250
7251 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7252}
7253
7256 SourceLocation RBraceLoc) {
7257 // Semantic analysis for initializers is done by ActOnDeclarator() and
7258 // CheckInitializer() - it requires knowledge of the object being initialized.
7259
7260 // Immediately handle non-overload placeholders. Overloads can be
7261 // resolved contextually, but everything else here can't.
7262 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7263 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7264 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7265
7266 // Ignore failures; dropping the entire initializer list because
7267 // of one failure would be terrible for indexing/etc.
7268 if (result.isInvalid()) continue;
7269
7270 InitArgList[I] = result.get();
7271 }
7272 }
7273
7274 InitListExpr *E =
7275 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7276 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7277 return E;
7278}
7279
7281 assert(E.get()->getType()->isBlockPointerType());
7282 assert(E.get()->isPRValue());
7283
7284 // Only do this in an r-value context.
7285 if (!getLangOpts().ObjCAutoRefCount) return;
7286
7288 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7289 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7291}
7292
7294 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7295 // Also, callers should have filtered out the invalid cases with
7296 // pointers. Everything else should be possible.
7297
7298 QualType SrcTy = Src.get()->getType();
7299 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7300 return CK_NoOp;
7301
7302 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7304 llvm_unreachable("member pointer type in C");
7305
7306 case Type::STK_CPointer:
7309 switch (DestTy->getScalarTypeKind()) {
7310 case Type::STK_CPointer: {
7311 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7312 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7313 if (SrcAS != DestAS)
7314 return CK_AddressSpaceConversion;
7315 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7316 return CK_NoOp;
7317 return CK_BitCast;
7318 }
7320 return (SrcKind == Type::STK_BlockPointer
7321 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7323 if (SrcKind == Type::STK_ObjCObjectPointer)
7324 return CK_BitCast;
7325 if (SrcKind == Type::STK_CPointer)
7326 return CK_CPointerToObjCPointerCast;
7328 return CK_BlockPointerToObjCPointerCast;
7329 case Type::STK_Bool:
7330 return CK_PointerToBoolean;
7331 case Type::STK_Integral:
7332 return CK_PointerToIntegral;
7333 case Type::STK_Floating:
7338 llvm_unreachable("illegal cast from pointer");
7339 }
7340 llvm_unreachable("Should have returned before this");
7341
7343 switch (DestTy->getScalarTypeKind()) {
7345 return CK_FixedPointCast;
7346 case Type::STK_Bool:
7347 return CK_FixedPointToBoolean;
7348 case Type::STK_Integral:
7349 return CK_FixedPointToIntegral;
7350 case Type::STK_Floating:
7351 return CK_FixedPointToFloating;
7354 Diag(Src.get()->getExprLoc(),
7355 diag::err_unimplemented_conversion_with_fixed_point_type)
7356 << DestTy;
7357 return CK_IntegralCast;
7358 case Type::STK_CPointer:
7362 llvm_unreachable("illegal cast to pointer type");
7363 }
7364 llvm_unreachable("Should have returned before this");
7365
7366 case Type::STK_Bool: // casting from bool is like casting from an integer
7367 case Type::STK_Integral:
7368 switch (DestTy->getScalarTypeKind()) {
7369 case Type::STK_CPointer:
7374 return CK_NullToPointer;
7375 return CK_IntegralToPointer;
7376 case Type::STK_Bool:
7377 return CK_IntegralToBoolean;
7378 case Type::STK_Integral:
7379 return CK_IntegralCast;
7380 case Type::STK_Floating:
7381 return CK_IntegralToFloating;
7383 Src = ImpCastExprToType(Src.get(),
7384 DestTy->castAs<ComplexType>()->getElementType(),
7385 CK_IntegralCast);
7386 return CK_IntegralRealToComplex;
7388 Src = ImpCastExprToType(Src.get(),
7389 DestTy->castAs<ComplexType>()->getElementType(),
7390 CK_IntegralToFloating);
7391 return CK_FloatingRealToComplex;
7393 llvm_unreachable("member pointer type in C");
7395 return CK_IntegralToFixedPoint;
7396 }
7397 llvm_unreachable("Should have returned before this");
7398
7399 case Type::STK_Floating:
7400 switch (DestTy->getScalarTypeKind()) {
7401 case Type::STK_Floating:
7402 return CK_FloatingCast;
7403 case Type::STK_Bool:
7404 return CK_FloatingToBoolean;
7405 case Type::STK_Integral:
7406 return CK_FloatingToIntegral;
7408 Src = ImpCastExprToType(Src.get(),
7409 DestTy->castAs<ComplexType>()->getElementType(),
7410 CK_FloatingCast);
7411 return CK_FloatingRealToComplex;
7413 Src = ImpCastExprToType(Src.get(),
7414 DestTy->castAs<ComplexType>()->getElementType(),
7415 CK_FloatingToIntegral);
7416 return CK_IntegralRealToComplex;
7417 case Type::STK_CPointer:
7420 llvm_unreachable("valid float->pointer cast?");
7422 llvm_unreachable("member pointer type in C");
7424 return CK_FloatingToFixedPoint;
7425 }
7426 llvm_unreachable("Should have returned before this");
7427
7429 switch (DestTy->getScalarTypeKind()) {
7431 return CK_FloatingComplexCast;
7433 return CK_FloatingComplexToIntegralComplex;
7434 case Type::STK_Floating: {
7435 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7436 if (Context.hasSameType(ET, DestTy))
7437 return CK_FloatingComplexToReal;
7438 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7439 return CK_FloatingCast;
7440 }
7441 case Type::STK_Bool:
7442 return CK_FloatingComplexToBoolean;
7443 case Type::STK_Integral:
7444 Src = ImpCastExprToType(Src.get(),
7445 SrcTy->castAs<ComplexType>()->getElementType(),
7446 CK_FloatingComplexToReal);
7447 return CK_FloatingToIntegral;
7448 case Type::STK_CPointer:
7451 llvm_unreachable("valid complex float->pointer cast?");
7453 llvm_unreachable("member pointer type in C");
7455 Diag(Src.get()->getExprLoc(),
7456 diag::err_unimplemented_conversion_with_fixed_point_type)
7457 << SrcTy;
7458 return CK_IntegralCast;
7459 }
7460 llvm_unreachable("Should have returned before this");
7461
7463 switch (DestTy->getScalarTypeKind()) {
7465 return CK_IntegralComplexToFloatingComplex;
7467 return CK_IntegralComplexCast;
7468 case Type::STK_Integral: {
7469 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7470 if (Context.hasSameType(ET, DestTy))
7471 return CK_IntegralComplexToReal;
7472 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7473 return CK_IntegralCast;
7474 }
7475 case Type::STK_Bool:
7476 return CK_IntegralComplexToBoolean;
7477 case Type::STK_Floating:
7478 Src = ImpCastExprToType(Src.get(),
7479 SrcTy->castAs<ComplexType>()->getElementType(),
7480 CK_IntegralComplexToReal);
7481 return CK_IntegralToFloating;
7482 case Type::STK_CPointer:
7485 llvm_unreachable("valid complex int->pointer cast?");
7487 llvm_unreachable("member pointer type in C");
7489 Diag(Src.get()->getExprLoc(),
7490 diag::err_unimplemented_conversion_with_fixed_point_type)
7491 << SrcTy;
7492 return CK_IntegralCast;
7493 }
7494 llvm_unreachable("Should have returned before this");
7495 }
7496
7497 llvm_unreachable("Unhandled scalar cast");
7498}
7499
7500static bool breakDownVectorType(QualType type, uint64_t &len,
7501 QualType &eltType) {
7502 // Vectors are simple.
7503 if (const VectorType *vecType = type->getAs<VectorType>()) {
7504 len = vecType->getNumElements();
7505 eltType = vecType->getElementType();
7506 assert(eltType->isScalarType());
7507 return true;
7508 }
7509
7510 // We allow lax conversion to and from non-vector types, but only if
7511 // they're real types (i.e. non-complex, non-pointer scalar types).
7512 if (!type->isRealType()) return false;
7513
7514 len = 1;
7515 eltType = type;
7516 return true;
7517}
7518
7520 assert(srcTy->isVectorType() || destTy->isVectorType());
7521
7522 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7523 if (!FirstType->isSVESizelessBuiltinType())
7524 return false;
7525
7526 const auto *VecTy = SecondType->getAs<VectorType>();
7527 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7528 };
7529
7530 return ValidScalableConversion(srcTy, destTy) ||
7531 ValidScalableConversion(destTy, srcTy);
7532}
7533
7535 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7536 return false;
7537
7538 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7539 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7540
7541 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7542 matSrcType->getNumColumns() == matDestType->getNumColumns();
7543}
7544
7546 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7547
7548 uint64_t SrcLen, DestLen;
7549 QualType SrcEltTy, DestEltTy;
7550 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7551 return false;
7552 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7553 return false;
7554
7555 // ASTContext::getTypeSize will return the size rounded up to a
7556 // power of 2, so instead of using that, we need to use the raw
7557 // element size multiplied by the element count.
7558 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7559 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7560
7561 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7562}
7563
7565 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7566 "expected at least one type to be a vector here");
7567
7568 bool IsSrcTyAltivec =
7569 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7571 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7573 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7575
7576 bool IsDestTyAltivec = DestTy->isVectorType() &&
7577 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7579 (DestTy->castAs<VectorType>()->getVectorKind() ==
7581 (DestTy->castAs<VectorType>()->getVectorKind() ==
7583
7584 return (IsSrcTyAltivec || IsDestTyAltivec);
7585}
7586
7588 assert(destTy->isVectorType() || srcTy->isVectorType());
7589
7590 // Disallow lax conversions between scalars and ExtVectors (these
7591 // conversions are allowed for other vector types because common headers
7592 // depend on them). Most scalar OP ExtVector cases are handled by the
7593 // splat path anyway, which does what we want (convert, not bitcast).
7594 // What this rules out for ExtVectors is crazy things like char4*float.
7595 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7596 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7597
7598 return areVectorTypesSameSize(srcTy, destTy);
7599}
7600
7602 assert(destTy->isVectorType() || srcTy->isVectorType());
7603
7604 switch (Context.getLangOpts().getLaxVectorConversions()) {
7606 return false;
7607
7609 if (!srcTy->isIntegralOrEnumerationType()) {
7610 auto *Vec = srcTy->getAs<VectorType>();
7611 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7612 return false;
7613 }
7614 if (!destTy->isIntegralOrEnumerationType()) {
7615 auto *Vec = destTy->getAs<VectorType>();
7616 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7617 return false;
7618 }
7619 // OK, integer (vector) -> integer (vector) bitcast.
7620 break;
7621
7623 break;
7624 }
7625
7626 return areLaxCompatibleVectorTypes(srcTy, destTy);
7627}
7628
7630 CastKind &Kind) {
7631 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7632 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7633 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7634 << DestTy << SrcTy << R;
7635 }
7636 } else if (SrcTy->isMatrixType()) {
7637 return Diag(R.getBegin(),
7638 diag::err_invalid_conversion_between_matrix_and_type)
7639 << SrcTy << DestTy << R;
7640 } else if (DestTy->isMatrixType()) {
7641 return Diag(R.getBegin(),
7642 diag::err_invalid_conversion_between_matrix_and_type)
7643 << DestTy << SrcTy << R;
7644 }
7645
7646 Kind = CK_MatrixCast;
7647 return false;
7648}
7649
7651 CastKind &Kind) {
7652 assert(VectorTy->isVectorType() && "Not a vector type!");
7653
7654 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7655 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7656 return Diag(R.getBegin(),
7657 Ty->isVectorType() ?
7658 diag::err_invalid_conversion_between_vectors :
7659 diag::err_invalid_conversion_between_vector_and_integer)
7660 << VectorTy << Ty << R;
7661 } else
7662 return Diag(R.getBegin(),
7663 diag::err_invalid_conversion_between_vector_and_scalar)
7664 << VectorTy << Ty << R;
7665
7666 Kind = CK_BitCast;
7667 return false;
7668}
7669
7671 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7672
7673 if (DestElemTy == SplattedExpr->getType())
7674 return SplattedExpr;
7675
7676 assert(DestElemTy->isFloatingType() ||
7677 DestElemTy->isIntegralOrEnumerationType());
7678
7679 CastKind CK;
7680 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7681 // OpenCL requires that we convert `true` boolean expressions to -1, but
7682 // only when splatting vectors.
7683 if (DestElemTy->isFloatingType()) {
7684 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7685 // in two steps: boolean to signed integral, then to floating.
7686 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7687 CK_BooleanToSignedIntegral);
7688 SplattedExpr = CastExprRes.get();
7689 CK = CK_IntegralToFloating;
7690 } else {
7691 CK = CK_BooleanToSignedIntegral;
7692 }
7693 } else {
7694 ExprResult CastExprRes = SplattedExpr;
7695 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7696 if (CastExprRes.isInvalid())
7697 return ExprError();
7698 SplattedExpr = CastExprRes.get();
7699 }
7700 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7701}
7702
7704 Expr *CastExpr, CastKind &Kind) {
7705 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7706
7707 QualType SrcTy = CastExpr->getType();
7708
7709 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7710 // an ExtVectorType.
7711 // In OpenCL, casts between vectors of different types are not allowed.
7712 // (See OpenCL 6.2).
7713 if (SrcTy->isVectorType()) {
7714 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7715 (getLangOpts().OpenCL &&
7716 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7717 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7718 << DestTy << SrcTy << R;
7719 return ExprError();
7720 }
7721 Kind = CK_BitCast;
7722 return CastExpr;
7723 }
7724
7725 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7726 // conversion will take place first from scalar to elt type, and then
7727 // splat from elt type to vector.
7728 if (SrcTy->isPointerType())
7729 return Diag(R.getBegin(),
7730 diag::err_invalid_conversion_between_vector_and_scalar)
7731 << DestTy << SrcTy << R;
7732
7733 Kind = CK_VectorSplat;
7734 return prepareVectorSplat(DestTy, CastExpr);
7735}
7736
7739 Declarator &D, ParsedType &Ty,
7740 SourceLocation RParenLoc, Expr *CastExpr) {
7741 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7742 "ActOnCastExpr(): missing type or expr");
7743
7745 if (D.isInvalidType())
7746 return ExprError();
7747
7748 if (getLangOpts().CPlusPlus) {
7749 // Check that there are no default arguments (C++ only).
7751 } else {
7752 // Make sure any TypoExprs have been dealt with.
7754 if (!Res.isUsable())
7755 return ExprError();
7756 CastExpr = Res.get();
7757 }
7758
7760
7761 QualType castType = castTInfo->getType();
7762 Ty = CreateParsedType(castType, castTInfo);
7763
7764 bool isVectorLiteral = false;
7765
7766 // Check for an altivec or OpenCL literal,
7767 // i.e. all the elements are integer constants.
7768 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7769 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7770 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7771 && castType->isVectorType() && (PE || PLE)) {
7772 if (PLE && PLE->getNumExprs() == 0) {
7773 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7774 return ExprError();
7775 }
7776 if (PE || PLE->getNumExprs() == 1) {
7777 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7778 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7779 isVectorLiteral = true;
7780 }
7781 else
7782 isVectorLiteral = true;
7783 }
7784
7785 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7786 // then handle it as such.
7787 if (isVectorLiteral)
7788 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7789
7790 // If the Expr being casted is a ParenListExpr, handle it specially.
7791 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7792 // sequence of BinOp comma operators.
7793 if (isa<ParenListExpr>(CastExpr)) {
7795 if (Result.isInvalid()) return ExprError();
7796 CastExpr = Result.get();
7797 }
7798
7799 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7800 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7801
7803
7805
7807
7808 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7809}
7810
7812 SourceLocation RParenLoc, Expr *E,
7813 TypeSourceInfo *TInfo) {
7814 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7815 "Expected paren or paren list expression");
7816
7817 Expr **exprs;
7818 unsigned numExprs;
7819 Expr *subExpr;
7820 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7821 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7822 LiteralLParenLoc = PE->getLParenLoc();
7823 LiteralRParenLoc = PE->getRParenLoc();
7824 exprs = PE->getExprs();
7825 numExprs = PE->getNumExprs();
7826 } else { // isa<ParenExpr> by assertion at function entrance
7827 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7828 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7829 subExpr = cast<ParenExpr>(E)->getSubExpr();
7830 exprs = &subExpr;
7831 numExprs = 1;
7832 }
7833
7834 QualType Ty = TInfo->getType();
7835 assert(Ty->isVectorType() && "Expected vector type");
7836
7837 SmallVector<Expr *, 8> initExprs;
7838 const VectorType *VTy = Ty->castAs<VectorType>();
7839 unsigned numElems = VTy->getNumElements();
7840
7841 // '(...)' form of vector initialization in AltiVec: the number of
7842 // initializers must be one or must match the size of the vector.
7843 // If a single value is specified in the initializer then it will be
7844 // replicated to all the components of the vector
7846 VTy->getElementType()))
7847 return ExprError();
7849 // The number of initializers must be one or must match the size of the
7850 // vector. If a single value is specified in the initializer then it will
7851 // be replicated to all the components of the vector
7852 if (numExprs == 1) {
7853 QualType ElemTy = VTy->getElementType();
7854 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7855 if (Literal.isInvalid())
7856 return ExprError();
7857 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7858 PrepareScalarCast(Literal, ElemTy));
7859 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7860 }
7861 else if (numExprs < numElems) {
7862 Diag(E->getExprLoc(),
7863 diag::err_incorrect_number_of_vector_initializers);
7864 return ExprError();
7865 }
7866 else
7867 initExprs.append(exprs, exprs + numExprs);
7868 }
7869 else {
7870 // For OpenCL, when the number of initializers is a single value,
7871 // it will be replicated to all components of the vector.
7873 numExprs == 1) {
7874 QualType ElemTy = VTy->getElementType();
7875 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7876 if (Literal.isInvalid())
7877 return ExprError();
7878 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7879 PrepareScalarCast(Literal, ElemTy));
7880 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7881 }
7882
7883 initExprs.append(exprs, exprs + numExprs);
7884 }
7885 // FIXME: This means that pretty-printing the final AST will produce curly
7886 // braces instead of the original commas.
7887 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7888 initExprs, LiteralRParenLoc);
7889 initE->setType(Ty);
7890 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7891}
7892
7895 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7896 if (!E)
7897 return OrigExpr;
7898
7899 ExprResult Result(E->getExpr(0));
7900
7901 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7902 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7903 E->getExpr(i));
7904
7905 if (Result.isInvalid()) return ExprError();
7906
7907 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7908}
7909
7912 MultiExprArg Val) {
7913 return ParenListExpr::Create(Context, L, Val, R);
7914}
7915
7916bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7917 SourceLocation QuestionLoc) {
7918 const Expr *NullExpr = LHSExpr;
7919 const Expr *NonPointerExpr = RHSExpr;
7923
7924 if (NullKind == Expr::NPCK_NotNull) {
7925 NullExpr = RHSExpr;
7926 NonPointerExpr = LHSExpr;
7927 NullKind =
7930 }
7931
7932 if (NullKind == Expr::NPCK_NotNull)
7933 return false;
7934
7935 if (NullKind == Expr::NPCK_ZeroExpression)
7936 return false;
7937
7938 if (NullKind == Expr::NPCK_ZeroLiteral) {
7939 // In this case, check to make sure that we got here from a "NULL"
7940 // string in the source code.
7941 NullExpr = NullExpr->IgnoreParenImpCasts();
7942 SourceLocation loc = NullExpr->getExprLoc();
7943 if (!findMacroSpelling(loc, "NULL"))
7944 return false;
7945 }
7946
7947 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7948 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7949 << NonPointerExpr->getType() << DiagType
7950 << NonPointerExpr->getSourceRange();
7951 return true;
7952}
7953
7954/// Return false if the condition expression is valid, true otherwise.
7955static bool checkCondition(Sema &S, const Expr *Cond,
7956 SourceLocation QuestionLoc) {
7957 QualType CondTy = Cond->getType();
7958
7959 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7960 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7961 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7962 << CondTy << Cond->getSourceRange();
7963 return true;
7964 }
7965
7966 // C99 6.5.15p2
7967 if (CondTy->isScalarType()) return false;
7968
7969 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7970 << CondTy << Cond->getSourceRange();
7971 return true;
7972}
7973
7974/// Return false if the NullExpr can be promoted to PointerTy,
7975/// true otherwise.
7977 QualType PointerTy) {
7978 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7979 !NullExpr.get()->isNullPointerConstant(S.Context,
7981 return true;
7982
7983 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7984 return false;
7985}
7986
7987/// Checks compatibility between two pointers and return the resulting
7988/// type.
7990 ExprResult &RHS,
7992 QualType LHSTy = LHS.get()->getType();
7993 QualType RHSTy = RHS.get()->getType();
7994
7995 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7996 // Two identical pointers types are always compatible.
7997 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7998 }
7999
8000 QualType lhptee, rhptee;
8001
8002 // Get the pointee types.
8003 bool IsBlockPointer = false;
8004 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8005 lhptee = LHSBTy->getPointeeType();
8006 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8007 IsBlockPointer = true;
8008 } else {
8009 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8010 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8011 }
8012
8013 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8014 // differently qualified versions of compatible types, the result type is
8015 // a pointer to an appropriately qualified version of the composite
8016 // type.
8017
8018 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8019 // clause doesn't make sense for our extensions. E.g. address space 2 should
8020 // be incompatible with address space 3: they may live on different devices or
8021 // anything.
8022 Qualifiers lhQual = lhptee.getQualifiers();
8023 Qualifiers rhQual = rhptee.getQualifiers();
8024
8025 LangAS ResultAddrSpace = LangAS::Default;
8026 LangAS LAddrSpace = lhQual.getAddressSpace();
8027 LangAS RAddrSpace = rhQual.getAddressSpace();
8028
8029 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8030 // spaces is disallowed.
8031 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8032 ResultAddrSpace = LAddrSpace;
8033 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8034 ResultAddrSpace = RAddrSpace;
8035 else {
8036 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8037 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8038 << RHS.get()->getSourceRange();
8039 return QualType();
8040 }
8041
8042 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8043 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8044 lhQual.removeCVRQualifiers();
8045 rhQual.removeCVRQualifiers();
8046
8047 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8048 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8049 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8050 // qual types are compatible iff
8051 // * corresponded types are compatible
8052 // * CVR qualifiers are equal
8053 // * address spaces are equal
8054 // Thus for conditional operator we merge CVR and address space unqualified
8055 // pointees and if there is a composite type we return a pointer to it with
8056 // merged qualifiers.
8057 LHSCastKind =
8058 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8059 RHSCastKind =
8060 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8061 lhQual.removeAddressSpace();
8062 rhQual.removeAddressSpace();
8063
8064 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8065 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8066
8067 QualType CompositeTy = S.Context.mergeTypes(
8068 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8069 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8070
8071 if (CompositeTy.isNull()) {
8072 // In this situation, we assume void* type. No especially good
8073 // reason, but this is what gcc does, and we do have to pick
8074 // to get a consistent AST.
8075 QualType incompatTy;
8076 incompatTy = S.Context.getPointerType(
8077 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8078 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8079 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8080
8081 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8082 // for casts between types with incompatible address space qualifiers.
8083 // For the following code the compiler produces casts between global and
8084 // local address spaces of the corresponded innermost pointees:
8085 // local int *global *a;
8086 // global int *global *b;
8087 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8088 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8089 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8090 << RHS.get()->getSourceRange();
8091
8092 return incompatTy;
8093 }
8094
8095 // The pointer types are compatible.
8096 // In case of OpenCL ResultTy should have the address space qualifier
8097 // which is a superset of address spaces of both the 2nd and the 3rd
8098 // operands of the conditional operator.
8099 QualType ResultTy = [&, ResultAddrSpace]() {
8100 if (S.getLangOpts().OpenCL) {
8101 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8102 CompositeQuals.setAddressSpace(ResultAddrSpace);
8103 return S.Context
8104 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8105 .withCVRQualifiers(MergedCVRQual);
8106 }
8107 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8108 }();
8109 if (IsBlockPointer)
8110 ResultTy = S.Context.getBlockPointerType(ResultTy);
8111 else
8112 ResultTy = S.Context.getPointerType(ResultTy);
8113
8114 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8115 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8116 return ResultTy;
8117}
8118
8119/// Return the resulting type when the operands are both block pointers.
8121 ExprResult &LHS,
8122 ExprResult &RHS,
8124 QualType LHSTy = LHS.get()->getType();
8125 QualType RHSTy = RHS.get()->getType();
8126
8127 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8128 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8130 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8131 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8132 return destType;
8133 }
8134 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8135 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8136 << RHS.get()->getSourceRange();
8137 return QualType();
8138 }
8139
8140 // We have 2 block pointer types.
8141 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8142}
8143
8144/// Return the resulting type when the operands are both pointers.
8145static QualType
8147 ExprResult &RHS,
8149 // get the pointer types
8150 QualType LHSTy = LHS.get()->getType();
8151 QualType RHSTy = RHS.get()->getType();
8152
8153 // get the "pointed to" types
8154 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8155 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8156
8157 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8158 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8159 // Figure out necessary qualifiers (C99 6.5.15p6)
8160 QualType destPointee
8161 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8162 QualType destType = S.Context.getPointerType(destPointee);
8163 // Add qualifiers if necessary.
8164 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8165 // Promote to void*.
8166 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8167 return destType;
8168 }
8169 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8170 QualType destPointee
8171 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8172 QualType destType = S.Context.getPointerType(destPointee);
8173 // Add qualifiers if necessary.
8174 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8175 // Promote to void*.
8176 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8177 return destType;
8178 }
8179
8180 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8181}
8182
8183/// Return false if the first expression is not an integer and the second
8184/// expression is not a pointer, true otherwise.
8186 Expr* PointerExpr, SourceLocation Loc,
8187 bool IsIntFirstExpr) {
8188 if (!PointerExpr->getType()->isPointerType() ||
8189 !Int.get()->getType()->isIntegerType())
8190 return false;
8191
8192 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8193 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8194
8195 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8196 << Expr1->getType() << Expr2->getType()
8197 << Expr1->getSourceRange() << Expr2->getSourceRange();
8198 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8199 CK_IntegralToPointer);
8200 return true;
8201}
8202
8203/// Simple conversion between integer and floating point types.
8204///
8205/// Used when handling the OpenCL conditional operator where the
8206/// condition is a vector while the other operands are scalar.
8207///
8208/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8209/// types are either integer or floating type. Between the two
8210/// operands, the type with the higher rank is defined as the "result
8211/// type". The other operand needs to be promoted to the same type. No
8212/// other type promotion is allowed. We cannot use
8213/// UsualArithmeticConversions() for this purpose, since it always
8214/// promotes promotable types.
8216 ExprResult &RHS,
8217 SourceLocation QuestionLoc) {
8219 if (LHS.isInvalid())
8220 return QualType();
8222 if (RHS.isInvalid())
8223 return QualType();
8224
8225 // For conversion purposes, we ignore any qualifiers.
8226 // For example, "const float" and "float" are equivalent.
8227 QualType LHSType =
8229 QualType RHSType =
8231
8232 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8233 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8234 << LHSType << LHS.get()->getSourceRange();
8235 return QualType();
8236 }
8237
8238 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8239 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8240 << RHSType << RHS.get()->getSourceRange();
8241 return QualType();
8242 }
8243
8244 // If both types are identical, no conversion is needed.
8245 if (LHSType == RHSType)
8246 return LHSType;
8247
8248 // Now handle "real" floating types (i.e. float, double, long double).
8249 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8250 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8251 /*IsCompAssign = */ false);
8252
8253 // Finally, we have two differing integer types.
8254 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8255 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8256}
8257
8258/// Convert scalar operands to a vector that matches the
8259/// condition in length.
8260///
8261/// Used when handling the OpenCL conditional operator where the
8262/// condition is a vector while the other operands are scalar.
8263///
8264/// We first compute the "result type" for the scalar operands
8265/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8266/// into a vector of that type where the length matches the condition
8267/// vector type. s6.11.6 requires that the element types of the result
8268/// and the condition must have the same number of bits.
8269static QualType
8271 QualType CondTy, SourceLocation QuestionLoc) {
8272 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8273 if (ResTy.isNull()) return QualType();
8274
8275 const VectorType *CV = CondTy->getAs<VectorType>();
8276 assert(CV);
8277
8278 // Determine the vector result type
8279 unsigned NumElements = CV->getNumElements();
8280 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8281
8282 // Ensure that all types have the same number of bits
8284 != S.Context.getTypeSize(ResTy)) {
8285 // Since VectorTy is created internally, it does not pretty print
8286 // with an OpenCL name. Instead, we just print a description.
8287 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8288 SmallString<64> Str;
8289 llvm::raw_svector_ostream OS(Str);
8290 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8291 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8292 << CondTy << OS.str();
8293 return QualType();
8294 }
8295
8296 // Convert operands to the vector result type
8297 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8298 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8299
8300 return VectorTy;
8301}
8302
8303/// Return false if this is a valid OpenCL condition vector
8305 SourceLocation QuestionLoc) {
8306 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8307 // integral type.
8308 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8309 assert(CondTy);
8310 QualType EleTy = CondTy->getElementType();
8311 if (EleTy->isIntegerType()) return false;
8312
8313 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8314 << Cond->getType() << Cond->getSourceRange();
8315 return true;
8316}
8317
8318/// Return false if the vector condition type and the vector
8319/// result type are compatible.
8320///
8321/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8322/// number of elements, and their element types have the same number
8323/// of bits.
8324static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8325 SourceLocation QuestionLoc) {
8326 const VectorType *CV = CondTy->getAs<VectorType>();
8327 const VectorType *RV = VecResTy->getAs<VectorType>();
8328 assert(CV && RV);
8329
8330 if (CV->getNumElements() != RV->getNumElements()) {
8331 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8332 << CondTy << VecResTy;
8333 return true;
8334 }
8335
8336 QualType CVE = CV->getElementType();
8337 QualType RVE = RV->getElementType();
8338
8339 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8340 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8341 << CondTy << VecResTy;
8342 return true;
8343 }
8344
8345 return false;
8346}
8347
8348/// Return the resulting type for the conditional operator in
8349/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8350/// s6.3.i) when the condition is a vector type.
8351static QualType
8353 ExprResult &LHS, ExprResult &RHS,
8354 SourceLocation QuestionLoc) {
8356 if (Cond.isInvalid())
8357 return QualType();
8358 QualType CondTy = Cond.get()->getType();
8359
8360 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8361 return QualType();
8362
8363 // If either operand is a vector then find the vector type of the
8364 // result as specified in OpenCL v1.1 s6.3.i.
8365 if (LHS.get()->getType()->isVectorType() ||
8366 RHS.get()->getType()->isVectorType()) {
8367 bool IsBoolVecLang =
8368 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8369 QualType VecResTy =
8370 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8371 /*isCompAssign*/ false,
8372 /*AllowBothBool*/ true,
8373 /*AllowBoolConversions*/ false,
8374 /*AllowBooleanOperation*/ IsBoolVecLang,
8375 /*ReportInvalid*/ true);
8376 if (VecResTy.isNull())
8377 return QualType();
8378 // The result type must match the condition type as specified in
8379 // OpenCL v1.1 s6.11.6.
8380 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8381 return QualType();
8382 return VecResTy;
8383 }
8384
8385 // Both operands are scalar.
8386 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8387}
8388
8389/// Return true if the Expr is block type
8390static bool checkBlockType(Sema &S, const Expr *E) {
8391 if (E->getType()->isBlockPointerType()) {
8392 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8393 return true;
8394 }
8395
8396 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8397 QualType Ty = CE->getCallee()->getType();
8398 if (Ty->isBlockPointerType()) {
8399 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8400 return true;
8401 }
8402 }
8403 return false;
8404}
8405
8406/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8407/// In that case, LHS = cond.
8408/// C99 6.5.15
8410 ExprResult &RHS, ExprValueKind &VK,
8411 ExprObjectKind &OK,
8412 SourceLocation QuestionLoc) {
8413
8414 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8415 if (!LHSResult.isUsable()) return QualType();
8416 LHS = LHSResult;
8417
8418 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8419 if (!RHSResult.isUsable()) return QualType();
8420 RHS = RHSResult;
8421
8422 // C++ is sufficiently different to merit its own checker.
8423 if (getLangOpts().CPlusPlus)
8424 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8425
8426 VK = VK_PRValue;
8427 OK = OK_Ordinary;
8428
8430 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8431 RHS.get()->isTypeDependent())) {
8432 assert(!getLangOpts().CPlusPlus);
8433 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8434 RHS.get()->containsErrors()) &&
8435 "should only occur in error-recovery path.");
8436 return Context.DependentTy;
8437 }
8438
8439 // The OpenCL operator with a vector condition is sufficiently
8440 // different to merit its own checker.
8441 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8442 Cond.get()->getType()->isExtVectorType())
8443 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8444
8445 // First, check the condition.
8446 Cond = UsualUnaryConversions(Cond.get());
8447 if (Cond.isInvalid())
8448 return QualType();
8449 if (checkCondition(*this, Cond.get(), QuestionLoc))
8450 return QualType();
8451
8452 // Handle vectors.
8453 if (LHS.get()->getType()->isVectorType() ||
8454 RHS.get()->getType()->isVectorType())
8455 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8456 /*AllowBothBool*/ true,
8457 /*AllowBoolConversions*/ false,
8458 /*AllowBooleanOperation*/ false,
8459 /*ReportInvalid*/ true);
8460
8461 QualType ResTy =
8462 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8463 if (LHS.isInvalid() || RHS.isInvalid())
8464 return QualType();
8465
8466 // WebAssembly tables are not allowed as conditional LHS or RHS.
8467 QualType LHSTy = LHS.get()->getType();
8468 QualType RHSTy = RHS.get()->getType();
8469 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8470 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8471 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8472 return QualType();
8473 }
8474
8475 // Diagnose attempts to convert between __ibm128, __float128 and long double
8476 // where such conversions currently can't be handled.
8477 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8478 Diag(QuestionLoc,
8479 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8480 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8481 return QualType();
8482 }
8483
8484 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8485 // selection operator (?:).
8486 if (getLangOpts().OpenCL &&
8487 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8488 return QualType();
8489 }
8490
8491 // If both operands have arithmetic type, do the usual arithmetic conversions
8492 // to find a common type: C99 6.5.15p3,5.
8493 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8494 // Disallow invalid arithmetic conversions, such as those between bit-
8495 // precise integers types of different sizes, or between a bit-precise
8496 // integer and another type.
8497 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8498 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8499 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8500 << RHS.get()->getSourceRange();
8501 return QualType();
8502 }
8503
8504 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8505 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8506
8507 return ResTy;
8508 }
8509
8510 // If both operands are the same structure or union type, the result is that
8511 // type.
8512 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8513 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8514 if (LHSRT->getDecl() == RHSRT->getDecl())
8515 // "If both the operands have structure or union type, the result has
8516 // that type." This implies that CV qualifiers are dropped.
8518 RHSTy.getUnqualifiedType());
8519 // FIXME: Type of conditional expression must be complete in C mode.
8520 }
8521
8522 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8523 // The following || allows only one side to be void (a GCC-ism).
8524 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8525 QualType ResTy;
8526 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8527 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8528 } else if (RHSTy->isVoidType()) {
8529 ResTy = RHSTy;
8530 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8531 << RHS.get()->getSourceRange();
8532 } else {
8533 ResTy = LHSTy;
8534 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8535 << LHS.get()->getSourceRange();
8536 }
8537 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8538 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8539 return ResTy;
8540 }
8541
8542 // C23 6.5.15p7:
8543 // ... if both the second and third operands have nullptr_t type, the
8544 // result also has that type.
8545 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8546 return ResTy;
8547
8548 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8549 // the type of the other operand."
8550 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8551 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8552
8553 // All objective-c pointer type analysis is done here.
8554 QualType compositeType =
8555 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8556 if (LHS.isInvalid() || RHS.isInvalid())
8557 return QualType();
8558 if (!compositeType.isNull())
8559 return compositeType;
8560
8561
8562 // Handle block pointer types.
8563 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8564 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8565 QuestionLoc);
8566
8567 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8568 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8569 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8570 QuestionLoc);
8571
8572 // GCC compatibility: soften pointer/integer mismatch. Note that
8573 // null pointers have been filtered out by this point.
8574 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8575 /*IsIntFirstExpr=*/true))
8576 return RHSTy;
8577 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8578 /*IsIntFirstExpr=*/false))
8579 return LHSTy;
8580
8581 // Emit a better diagnostic if one of the expressions is a null pointer
8582 // constant and the other is not a pointer type. In this case, the user most
8583 // likely forgot to take the address of the other expression.
8584 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8585 return QualType();
8586
8587 // Finally, if the LHS and RHS types are canonically the same type, we can
8588 // use the common sugared type.
8589 if (Context.hasSameType(LHSTy, RHSTy))
8590 return Context.getCommonSugaredType(LHSTy, RHSTy);
8591
8592 // Otherwise, the operands are not compatible.
8593 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8594 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8595 << RHS.get()->getSourceRange();
8596 return QualType();
8597}
8598
8599/// SuggestParentheses - Emit a note with a fixit hint that wraps
8600/// ParenRange in parentheses.
8602 const PartialDiagnostic &Note,
8603 SourceRange ParenRange) {
8604 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8605 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8606 EndLoc.isValid()) {
8607 Self.Diag(Loc, Note)
8608 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8609 << FixItHint::CreateInsertion(EndLoc, ")");
8610 } else {
8611 // We can't display the parentheses, so just show the bare note.
8612 Self.Diag(Loc, Note) << ParenRange;
8613 }
8614}
8615
8617 return BinaryOperator::isAdditiveOp(Opc) ||
8619 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8620 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8621 // not any of the logical operators. Bitwise-xor is commonly used as a
8622 // logical-xor because there is no logical-xor operator. The logical
8623 // operators, including uses of xor, have a high false positive rate for
8624 // precedence warnings.
8625}
8626
8627/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8628/// expression, either using a built-in or overloaded operator,
8629/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8630/// expression.
8632 const Expr **RHSExprs) {
8633 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8634 E = E->IgnoreImpCasts();
8636 E = E->IgnoreImpCasts();
8637 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8638 E = MTE->getSubExpr();
8639 E = E->IgnoreImpCasts();
8640 }
8641
8642 // Built-in binary operator.
8643 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8644 OP && IsArithmeticOp(OP->getOpcode())) {
8645 *Opcode = OP->getOpcode();
8646 *RHSExprs = OP->getRHS();
8647 return true;
8648 }
8649
8650 // Overloaded operator.
8651 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8652 if (Call->getNumArgs() != 2)
8653 return false;
8654
8655 // Make sure this is really a binary operator that is safe to pass into
8656 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8657 OverloadedOperatorKind OO = Call->getOperator();
8658 if (OO < OO_Plus || OO > OO_Arrow ||
8659 OO == OO_PlusPlus || OO == OO_MinusMinus)
8660 return false;
8661
8663 if (IsArithmeticOp(OpKind)) {
8664 *Opcode = OpKind;
8665 *RHSExprs = Call->getArg(1);
8666 return true;
8667 }
8668 }
8669
8670 return false;
8671}
8672
8673/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8674/// or is a logical expression such as (x==y) which has int type, but is
8675/// commonly interpreted as boolean.
8676static bool ExprLooksBoolean(const Expr *E) {
8677 E = E->IgnoreParenImpCasts();
8678
8679 if (E->getType()->isBooleanType())
8680 return true;
8681 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8682 return OP->isComparisonOp() || OP->isLogicalOp();
8683 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8684 return OP->getOpcode() == UO_LNot;
8685 if (E->getType()->isPointerType())
8686 return true;
8687 // FIXME: What about overloaded operator calls returning "unspecified boolean
8688 // type"s (commonly pointer-to-members)?
8689
8690 return false;
8691}
8692
8693/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8694/// and binary operator are mixed in a way that suggests the programmer assumed
8695/// the conditional operator has higher precedence, for example:
8696/// "int x = a + someBinaryCondition ? 1 : 2".
8698 Expr *Condition, const Expr *LHSExpr,
8699 const Expr *RHSExpr) {
8700 BinaryOperatorKind CondOpcode;
8701 const Expr *CondRHS;
8702
8703 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8704 return;
8705 if (!ExprLooksBoolean(CondRHS))
8706 return;
8707
8708 // The condition is an arithmetic binary expression, with a right-
8709 // hand side that looks boolean, so warn.
8710
8711 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8712 ? diag::warn_precedence_bitwise_conditional
8713 : diag::warn_precedence_conditional;
8714
8715 Self.Diag(OpLoc, DiagID)
8716 << Condition->getSourceRange()
8717 << BinaryOperator::getOpcodeStr(CondOpcode);
8718
8720 Self, OpLoc,
8721 Self.PDiag(diag::note_precedence_silence)
8722 << BinaryOperator::getOpcodeStr(CondOpcode),
8723 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8724
8725 SuggestParentheses(Self, OpLoc,
8726 Self.PDiag(diag::note_precedence_conditional_first),
8727 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8728}
8729
8730/// Compute the nullability of a conditional expression.
8732 QualType LHSTy, QualType RHSTy,
8733 ASTContext &Ctx) {
8734 if (!ResTy->isAnyPointerType())
8735 return ResTy;
8736
8737 auto GetNullability = [](QualType Ty) {
8738 std::optional<NullabilityKind> Kind = Ty->getNullability();
8739 if (Kind) {
8740 // For our purposes, treat _Nullable_result as _Nullable.
8743 return *Kind;
8744 }
8746 };
8747
8748 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8749 NullabilityKind MergedKind;
8750
8751 // Compute nullability of a binary conditional expression.
8752 if (IsBin) {
8753 if (LHSKind == NullabilityKind::NonNull)
8754 MergedKind = NullabilityKind::NonNull;
8755 else
8756 MergedKind = RHSKind;
8757 // Compute nullability of a normal conditional expression.
8758 } else {
8759 if (LHSKind == NullabilityKind::Nullable ||
8760 RHSKind == NullabilityKind::Nullable)
8761 MergedKind = NullabilityKind::Nullable;
8762 else if (LHSKind == NullabilityKind::NonNull)
8763 MergedKind = RHSKind;
8764 else if (RHSKind == NullabilityKind::NonNull)
8765 MergedKind = LHSKind;
8766 else
8767 MergedKind = NullabilityKind::Unspecified;
8768 }
8769
8770 // Return if ResTy already has the correct nullability.
8771 if (GetNullability(ResTy) == MergedKind)
8772 return ResTy;
8773
8774 // Strip all nullability from ResTy.
8775 while (ResTy->getNullability())
8776 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8777
8778 // Create a new AttributedType with the new nullability kind.
8779 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8780}
8781
8783 SourceLocation ColonLoc,
8784 Expr *CondExpr, Expr *LHSExpr,
8785 Expr *RHSExpr) {
8787 // C cannot handle TypoExpr nodes in the condition because it
8788 // doesn't handle dependent types properly, so make sure any TypoExprs have
8789 // been dealt with before checking the operands.
8790 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8791 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8792 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8793
8794 if (!CondResult.isUsable())
8795 return ExprError();
8796
8797 if (LHSExpr) {
8798 if (!LHSResult.isUsable())
8799 return ExprError();
8800 }
8801
8802 if (!RHSResult.isUsable())
8803 return ExprError();
8804
8805 CondExpr = CondResult.get();
8806 LHSExpr = LHSResult.get();
8807 RHSExpr = RHSResult.get();
8808 }
8809
8810 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8811 // was the condition.
8812 OpaqueValueExpr *opaqueValue = nullptr;
8813 Expr *commonExpr = nullptr;
8814 if (!LHSExpr) {
8815 commonExpr = CondExpr;
8816 // Lower out placeholder types first. This is important so that we don't
8817 // try to capture a placeholder. This happens in few cases in C++; such
8818 // as Objective-C++'s dictionary subscripting syntax.
8819 if (commonExpr->hasPlaceholderType()) {
8820 ExprResult result = CheckPlaceholderExpr(commonExpr);
8821 if (!result.isUsable()) return ExprError();
8822 commonExpr = result.get();
8823 }
8824 // We usually want to apply unary conversions *before* saving, except
8825 // in the special case of a C++ l-value conditional.
8826 if (!(getLangOpts().CPlusPlus
8827 && !commonExpr->isTypeDependent()
8828 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8829 && commonExpr->isGLValue()
8830 && commonExpr->isOrdinaryOrBitFieldObject()
8831 && RHSExpr->isOrdinaryOrBitFieldObject()
8832 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8833 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8834 if (commonRes.isInvalid())
8835 return ExprError();
8836 commonExpr = commonRes.get();
8837 }
8838
8839 // If the common expression is a class or array prvalue, materialize it
8840 // so that we can safely refer to it multiple times.
8841 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8842 commonExpr->getType()->isArrayType())) {
8843 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8844 if (MatExpr.isInvalid())
8845 return ExprError();
8846 commonExpr = MatExpr.get();
8847 }
8848
8849 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8850 commonExpr->getType(),
8851 commonExpr->getValueKind(),
8852 commonExpr->getObjectKind(),
8853 commonExpr);
8854 LHSExpr = CondExpr = opaqueValue;
8855 }
8856
8857 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8860 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8861 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8862 VK, OK, QuestionLoc);
8863 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8864 RHS.isInvalid())
8865 return ExprError();
8866
8867 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8868 RHS.get());
8869
8870 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8871
8872 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8873 Context);
8874
8875 if (!commonExpr)
8876 return new (Context)
8877 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8878 RHS.get(), result, VK, OK);
8879
8881 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8882 ColonLoc, result, VK, OK);
8883}
8884
8886 unsigned FromAttributes = 0, ToAttributes = 0;
8887 if (const auto *FromFn =
8888 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8889 FromAttributes =
8890 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8891 if (const auto *ToFn =
8892 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8893 ToAttributes =
8894 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8895
8896 return FromAttributes != ToAttributes;
8897}
8898
8899// Check if we have a conversion between incompatible cmse function pointer
8900// types, that is, a conversion between a function pointer with the
8901// cmse_nonsecure_call attribute and one without.
8903 QualType ToType) {
8904 if (const auto *ToFn =
8905 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8906 if (const auto *FromFn =
8907 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8908 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8909 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8910
8911 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8912 }
8913 }
8914 return false;
8915}
8916
8917// checkPointerTypesForAssignment - This is a very tricky routine (despite
8918// being closely modeled after the C99 spec:-). The odd characteristic of this
8919// routine is it effectively iqnores the qualifiers on the top level pointee.
8920// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8921// FIXME: add a couple examples in this comment.
8925 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8926 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8927
8928 // get the "pointed to" type (ignoring qualifiers at the top level)
8929 const Type *lhptee, *rhptee;
8930 Qualifiers lhq, rhq;
8931 std::tie(lhptee, lhq) =
8932 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8933 std::tie(rhptee, rhq) =
8934 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8935
8937
8938 // C99 6.5.16.1p1: This following citation is common to constraints
8939 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8940 // qualifiers of the type *pointed to* by the right;
8941
8942 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8943 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8945 // Ignore lifetime for further calculation.
8946 lhq.removeObjCLifetime();
8947 rhq.removeObjCLifetime();
8948 }
8949
8950 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
8951 // Treat address-space mismatches as fatal.
8952 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
8954
8955 // It's okay to add or remove GC or lifetime qualifiers when converting to
8956 // and from void*.
8959 S.getASTContext()) &&
8960 (lhptee->isVoidType() || rhptee->isVoidType()))
8961 ; // keep old
8962
8963 // Treat lifetime mismatches as fatal.
8964 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8966
8967 // For GCC/MS compatibility, other qualifier mismatches are treated
8968 // as still compatible in C.
8970 }
8971
8972 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8973 // incomplete type and the other is a pointer to a qualified or unqualified
8974 // version of void...
8975 if (lhptee->isVoidType()) {
8976 if (rhptee->isIncompleteOrObjectType())
8977 return ConvTy;
8978
8979 // As an extension, we allow cast to/from void* to function pointer.
8980 assert(rhptee->isFunctionType());
8982 }
8983
8984 if (rhptee->isVoidType()) {
8985 if (lhptee->isIncompleteOrObjectType())
8986 return ConvTy;
8987
8988 // As an extension, we allow cast to/from void* to function pointer.
8989 assert(lhptee->isFunctionType());
8991 }
8992
8993 if (!S.Diags.isIgnored(
8994 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8995 Loc) &&
8996 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8997 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8999
9000 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9001 // unqualified versions of compatible types, ...
9002 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9003 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9004 // Check if the pointee types are compatible ignoring the sign.
9005 // We explicitly check for char so that we catch "char" vs
9006 // "unsigned char" on systems where "char" is unsigned.
9007 if (lhptee->isCharType())
9008 ltrans = S.Context.UnsignedCharTy;
9009 else if (lhptee->hasSignedIntegerRepresentation())
9010 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9011
9012 if (rhptee->isCharType())
9013 rtrans = S.Context.UnsignedCharTy;
9014 else if (rhptee->hasSignedIntegerRepresentation())
9015 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9016
9017 if (ltrans == rtrans) {
9018 // Types are compatible ignoring the sign. Qualifier incompatibility
9019 // takes priority over sign incompatibility because the sign
9020 // warning can be disabled.
9021 if (ConvTy != Sema::Compatible)
9022 return ConvTy;
9023
9025 }
9026
9027 // If we are a multi-level pointer, it's possible that our issue is simply
9028 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9029 // the eventual target type is the same and the pointers have the same
9030 // level of indirection, this must be the issue.
9031 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9032 do {
9033 std::tie(lhptee, lhq) =
9034 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9035 std::tie(rhptee, rhq) =
9036 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9037
9038 // Inconsistent address spaces at this point is invalid, even if the
9039 // address spaces would be compatible.
9040 // FIXME: This doesn't catch address space mismatches for pointers of
9041 // different nesting levels, like:
9042 // __local int *** a;
9043 // int ** b = a;
9044 // It's not clear how to actually determine when such pointers are
9045 // invalidly incompatible.
9046 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9048
9049 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9050
9051 if (lhptee == rhptee)
9053 }
9054
9055 // General pointer incompatibility takes priority over qualifiers.
9056 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9059 }
9060 if (!S.getLangOpts().CPlusPlus &&
9061 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9063 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9065 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9067 return ConvTy;
9068}
9069
9070/// checkBlockPointerTypesForAssignment - This routine determines whether two
9071/// block pointer types are compatible or whether a block and normal pointer
9072/// are compatible. It is more restrict than comparing two function pointer
9073// types.
9076 QualType RHSType) {
9077 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9078 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9079
9080 QualType lhptee, rhptee;
9081
9082 // get the "pointed to" type (ignoring qualifiers at the top level)
9083 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9084 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9085
9086 // In C++, the types have to match exactly.
9087 if (S.getLangOpts().CPlusPlus)
9089
9091
9092 // For blocks we enforce that qualifiers are identical.
9093 Qualifiers LQuals = lhptee.getLocalQualifiers();
9094 Qualifiers RQuals = rhptee.getLocalQualifiers();
9095 if (S.getLangOpts().OpenCL) {
9096 LQuals.removeAddressSpace();
9097 RQuals.removeAddressSpace();
9098 }
9099 if (LQuals != RQuals)
9101
9102 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9103 // assignment.
9104 // The current behavior is similar to C++ lambdas. A block might be
9105 // assigned to a variable iff its return type and parameters are compatible
9106 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9107 // an assignment. Presumably it should behave in way that a function pointer
9108 // assignment does in C, so for each parameter and return type:
9109 // * CVR and address space of LHS should be a superset of CVR and address
9110 // space of RHS.
9111 // * unqualified types should be compatible.
9112 if (S.getLangOpts().OpenCL) {
9114 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9115 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9117 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9119
9120 return ConvTy;
9121}
9122
9123/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9124/// for assignment compatibility.
9127 QualType RHSType) {
9128 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9129 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9130
9131 if (LHSType->isObjCBuiltinType()) {
9132 // Class is not compatible with ObjC object pointers.
9133 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9134 !RHSType->isObjCQualifiedClassType())
9136 return Sema::Compatible;
9137 }
9138 if (RHSType->isObjCBuiltinType()) {
9139 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9140 !LHSType->isObjCQualifiedClassType())
9142 return Sema::Compatible;
9143 }
9144 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9145 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9146
9147 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9148 // make an exception for id<P>
9149 !LHSType->isObjCQualifiedIdType())
9151
9152 if (S.Context.typesAreCompatible(LHSType, RHSType))
9153 return Sema::Compatible;
9154 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9157}
9158
9161 QualType LHSType, QualType RHSType) {
9162 // Fake up an opaque expression. We don't actually care about what
9163 // cast operations are required, so if CheckAssignmentConstraints
9164 // adds casts to this they'll be wasted, but fortunately that doesn't
9165 // usually happen on valid code.
9166 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9167 ExprResult RHSPtr = &RHSExpr;
9168 CastKind K;
9169
9170 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9171}
9172
9173/// This helper function returns true if QT is a vector type that has element
9174/// type ElementType.
9175static bool isVector(QualType QT, QualType ElementType) {
9176 if (const VectorType *VT = QT->getAs<VectorType>())
9177 return VT->getElementType().getCanonicalType() == ElementType;
9178 return false;
9179}
9180
9181/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9182/// has code to accommodate several GCC extensions when type checking
9183/// pointers. Here are some objectionable examples that GCC considers warnings:
9184///
9185/// int a, *pint;
9186/// short *pshort;
9187/// struct foo *pfoo;
9188///
9189/// pint = pshort; // warning: assignment from incompatible pointer type
9190/// a = pint; // warning: assignment makes integer from pointer without a cast
9191/// pint = a; // warning: assignment makes pointer from integer without a cast
9192/// pint = pfoo; // warning: assignment from incompatible pointer type
9193///
9194/// As a result, the code for dealing with pointers is more complex than the
9195/// C99 spec dictates.
9196///
9197/// Sets 'Kind' for any result kind except Incompatible.
9200 CastKind &Kind, bool ConvertRHS) {
9201 QualType RHSType = RHS.get()->getType();
9202 QualType OrigLHSType = LHSType;
9203
9204 // Get canonical types. We're not formatting these types, just comparing
9205 // them.
9206 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9207 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9208
9209 // Common case: no conversion required.
9210 if (LHSType == RHSType) {
9211 Kind = CK_NoOp;
9212 return Compatible;
9213 }
9214
9215 // If the LHS has an __auto_type, there are no additional type constraints
9216 // to be worried about.
9217 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9218 if (AT->isGNUAutoType()) {
9219 Kind = CK_NoOp;
9220 return Compatible;
9221 }
9222 }
9223
9224 // If we have an atomic type, try a non-atomic assignment, then just add an
9225 // atomic qualification step.
9226 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9228 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9229 if (result != Compatible)
9230 return result;
9231 if (Kind != CK_NoOp && ConvertRHS)
9232 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9233 Kind = CK_NonAtomicToAtomic;
9234 return Compatible;
9235 }
9236
9237 // If the left-hand side is a reference type, then we are in a
9238 // (rare!) case where we've allowed the use of references in C,
9239 // e.g., as a parameter type in a built-in function. In this case,
9240 // just make sure that the type referenced is compatible with the
9241 // right-hand side type. The caller is responsible for adjusting
9242 // LHSType so that the resulting expression does not have reference
9243 // type.
9244 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9245 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9246 Kind = CK_LValueBitCast;
9247 return Compatible;
9248 }
9249 return Incompatible;
9250 }
9251
9252 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9253 // to the same ExtVector type.
9254 if (LHSType->isExtVectorType()) {
9255 if (RHSType->isExtVectorType())
9256 return Incompatible;
9257 if (RHSType->isArithmeticType()) {
9258 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9259 if (ConvertRHS)
9260 RHS = prepareVectorSplat(LHSType, RHS.get());
9261 Kind = CK_VectorSplat;
9262 return Compatible;
9263 }
9264 }
9265
9266 // Conversions to or from vector type.
9267 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9268 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9269 // Allow assignments of an AltiVec vector type to an equivalent GCC
9270 // vector type and vice versa
9271 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9272 Kind = CK_BitCast;
9273 return Compatible;
9274 }
9275
9276 // If we are allowing lax vector conversions, and LHS and RHS are both
9277 // vectors, the total size only needs to be the same. This is a bitcast;
9278 // no bits are changed but the result type is different.
9279 if (isLaxVectorConversion(RHSType, LHSType)) {
9280 // The default for lax vector conversions with Altivec vectors will
9281 // change, so if we are converting between vector types where
9282 // at least one is an Altivec vector, emit a warning.
9283 if (Context.getTargetInfo().getTriple().isPPC() &&
9284 anyAltivecTypes(RHSType, LHSType) &&
9285 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9286 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9287 << RHSType << LHSType;
9288 Kind = CK_BitCast;
9289 return IncompatibleVectors;
9290 }
9291 }
9292
9293 // When the RHS comes from another lax conversion (e.g. binops between
9294 // scalars and vectors) the result is canonicalized as a vector. When the
9295 // LHS is also a vector, the lax is allowed by the condition above. Handle
9296 // the case where LHS is a scalar.
9297 if (LHSType->isScalarType()) {
9298 const VectorType *VecType = RHSType->getAs<VectorType>();
9299 if (VecType && VecType->getNumElements() == 1 &&
9300 isLaxVectorConversion(RHSType, LHSType)) {
9301 if (Context.getTargetInfo().getTriple().isPPC() &&
9303 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9305 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9306 << RHSType << LHSType;
9307 ExprResult *VecExpr = &RHS;
9308 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9309 Kind = CK_BitCast;
9310 return Compatible;
9311 }
9312 }
9313
9314 // Allow assignments between fixed-length and sizeless SVE vectors.
9315 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9316 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9317 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9318 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9319 Kind = CK_BitCast;
9320 return Compatible;
9321 }
9322
9323 // Allow assignments between fixed-length and sizeless RVV vectors.
9324 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9325 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9326 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9327 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9328 Kind = CK_BitCast;
9329 return Compatible;
9330 }
9331 }
9332
9333 return Incompatible;
9334 }
9335
9336 // Diagnose attempts to convert between __ibm128, __float128 and long double
9337 // where such conversions currently can't be handled.
9338 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9339 return Incompatible;
9340
9341 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9342 // discards the imaginary part.
9343 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9344 !LHSType->getAs<ComplexType>())
9345 return Incompatible;
9346
9347 // Arithmetic conversions.
9348 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9349 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9350 if (ConvertRHS)
9351 Kind = PrepareScalarCast(RHS, LHSType);
9352 return Compatible;
9353 }
9354
9355 // Conversions to normal pointers.
9356 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9357 // U* -> T*
9358 if (isa<PointerType>(RHSType)) {
9359 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9360 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9361 if (AddrSpaceL != AddrSpaceR)
9362 Kind = CK_AddressSpaceConversion;
9363 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9364 Kind = CK_NoOp;
9365 else
9366 Kind = CK_BitCast;
9367 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9368 RHS.get()->getBeginLoc());
9369 }
9370
9371 // int -> T*
9372 if (RHSType->isIntegerType()) {
9373 Kind = CK_IntegralToPointer; // FIXME: null?
9374 return IntToPointer;
9375 }
9376
9377 // C pointers are not compatible with ObjC object pointers,
9378 // with two exceptions:
9379 if (isa<ObjCObjectPointerType>(RHSType)) {
9380 // - conversions to void*
9381 if (LHSPointer->getPointeeType()->isVoidType()) {
9382 Kind = CK_BitCast;
9383 return Compatible;
9384 }
9385
9386 // - conversions from 'Class' to the redefinition type
9387 if (RHSType->isObjCClassType() &&
9388 Context.hasSameType(LHSType,
9390 Kind = CK_BitCast;
9391 return Compatible;
9392 }
9393
9394 Kind = CK_BitCast;
9395 return IncompatiblePointer;
9396 }
9397
9398 // U^ -> void*
9399 if (RHSType->getAs<BlockPointerType>()) {
9400 if (LHSPointer->getPointeeType()->isVoidType()) {
9401 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9402 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9403 ->getPointeeType()
9404 .getAddressSpace();
9405 Kind =
9406 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9407 return Compatible;
9408 }
9409 }
9410
9411 return Incompatible;
9412 }
9413
9414 // Conversions to block pointers.
9415 if (isa<BlockPointerType>(LHSType)) {
9416 // U^ -> T^
9417 if (RHSType->isBlockPointerType()) {
9418 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9419 ->getPointeeType()
9420 .getAddressSpace();
9421 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9422 ->getPointeeType()
9423 .getAddressSpace();
9424 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9425 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9426 }
9427
9428 // int or null -> T^
9429 if (RHSType->isIntegerType()) {
9430 Kind = CK_IntegralToPointer; // FIXME: null
9431 return IntToBlockPointer;
9432 }
9433
9434 // id -> T^
9435 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9436 Kind = CK_AnyPointerToBlockPointerCast;
9437 return Compatible;
9438 }
9439
9440 // void* -> T^
9441 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9442 if (RHSPT->getPointeeType()->isVoidType()) {
9443 Kind = CK_AnyPointerToBlockPointerCast;
9444 return Compatible;
9445 }
9446
9447 return Incompatible;
9448 }
9449
9450 // Conversions to Objective-C pointers.
9451 if (isa<ObjCObjectPointerType>(LHSType)) {
9452 // A* -> B*
9453 if (RHSType->isObjCObjectPointerType()) {
9454 Kind = CK_BitCast;
9456 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9457 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9458 result == Compatible &&
9459 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9460 result = IncompatibleObjCWeakRef;
9461 return result;
9462 }
9463
9464 // int or null -> A*
9465 if (RHSType->isIntegerType()) {
9466 Kind = CK_IntegralToPointer; // FIXME: null
9467 return IntToPointer;
9468 }
9469
9470 // In general, C pointers are not compatible with ObjC object pointers,
9471 // with two exceptions:
9472 if (isa<PointerType>(RHSType)) {
9473 Kind = CK_CPointerToObjCPointerCast;
9474
9475 // - conversions from 'void*'
9476 if (RHSType->isVoidPointerType()) {
9477 return Compatible;
9478 }
9479
9480 // - conversions to 'Class' from its redefinition type
9481 if (LHSType->isObjCClassType() &&
9482 Context.hasSameType(RHSType,
9484 return Compatible;
9485 }
9486
9487 return IncompatiblePointer;
9488 }
9489
9490 // Only under strict condition T^ is compatible with an Objective-C pointer.
9491 if (RHSType->isBlockPointerType() &&
9493 if (ConvertRHS)
9495 Kind = CK_BlockPointerToObjCPointerCast;
9496 return Compatible;
9497 }
9498
9499 return Incompatible;
9500 }
9501
9502 // Conversion to nullptr_t (C23 only)
9503 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9506 // null -> nullptr_t
9507 Kind = CK_NullToPointer;
9508 return Compatible;
9509 }
9510
9511 // Conversions from pointers that are not covered by the above.
9512 if (isa<PointerType>(RHSType)) {
9513 // T* -> _Bool
9514 if (LHSType == Context.BoolTy) {
9515 Kind = CK_PointerToBoolean;
9516 return Compatible;
9517 }
9518
9519 // T* -> int
9520 if (LHSType->isIntegerType()) {
9521 Kind = CK_PointerToIntegral;
9522 return PointerToInt;
9523 }
9524
9525 return Incompatible;
9526 }
9527
9528 // Conversions from Objective-C pointers that are not covered by the above.
9529 if (isa<ObjCObjectPointerType>(RHSType)) {
9530 // T* -> _Bool
9531 if (LHSType == Context.BoolTy) {
9532 Kind = CK_PointerToBoolean;
9533 return Compatible;
9534 }
9535
9536 // T* -> int
9537 if (LHSType->isIntegerType()) {
9538 Kind = CK_PointerToIntegral;
9539 return PointerToInt;
9540 }
9541
9542 return Incompatible;
9543 }
9544
9545 // struct A -> struct B
9546 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9547 if (Context.typesAreCompatible(LHSType, RHSType)) {
9548 Kind = CK_NoOp;
9549 return Compatible;
9550 }
9551 }
9552
9553 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9554 Kind = CK_IntToOCLSampler;
9555 return Compatible;
9556 }
9557
9558 return Incompatible;
9559}
9560
9561/// Constructs a transparent union from an expression that is
9562/// used to initialize the transparent union.
9564 ExprResult &EResult, QualType UnionType,
9565 FieldDecl *Field) {
9566 // Build an initializer list that designates the appropriate member
9567 // of the transparent union.
9568 Expr *E = EResult.get();
9570 E, SourceLocation());
9571 Initializer->setType(UnionType);
9572 Initializer->setInitializedFieldInUnion(Field);
9573
9574 // Build a compound literal constructing a value of the transparent
9575 // union type from this initializer list.
9576 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9577 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9578 VK_PRValue, Initializer, false);
9579}
9580
9583 ExprResult &RHS) {
9584 QualType RHSType = RHS.get()->getType();
9585
9586 // If the ArgType is a Union type, we want to handle a potential
9587 // transparent_union GCC extension.
9588 const RecordType *UT = ArgType->getAsUnionType();
9589 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9590 return Incompatible;
9591
9592 // The field to initialize within the transparent union.
9593 RecordDecl *UD = UT->getDecl();
9594 FieldDecl *InitField = nullptr;
9595 // It's compatible if the expression matches any of the fields.
9596 for (auto *it : UD->fields()) {
9597 if (it->getType()->isPointerType()) {
9598 // If the transparent union contains a pointer type, we allow:
9599 // 1) void pointer
9600 // 2) null pointer constant
9601 if (RHSType->isPointerType())
9602 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9603 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9604 InitField = it;
9605 break;
9606 }
9607
9610 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9611 CK_NullToPointer);
9612 InitField = it;
9613 break;
9614 }
9615 }
9616
9617 CastKind Kind;
9618 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9619 == Compatible) {
9620 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9621 InitField = it;
9622 break;
9623 }
9624 }
9625
9626 if (!InitField)
9627 return Incompatible;
9628
9629 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9630 return Compatible;
9631}
9632
9635 bool Diagnose,
9636 bool DiagnoseCFAudited,
9637 bool ConvertRHS) {
9638 // We need to be able to tell the caller whether we diagnosed a problem, if
9639 // they ask us to issue diagnostics.
9640 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9641
9642 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9643 // we can't avoid *all* modifications at the moment, so we need some somewhere
9644 // to put the updated value.
9645 ExprResult LocalRHS = CallerRHS;
9646 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9647
9648 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9649 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9650 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9651 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9652 Diag(RHS.get()->getExprLoc(),
9653 diag::warn_noderef_to_dereferenceable_pointer)
9654 << RHS.get()->getSourceRange();
9655 }
9656 }
9657 }
9658
9659 if (getLangOpts().CPlusPlus) {
9660 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9661 // C++ 5.17p3: If the left operand is not of class type, the
9662 // expression is implicitly converted (C++ 4) to the
9663 // cv-unqualified type of the left operand.
9664 QualType RHSType = RHS.get()->getType();
9665 if (Diagnose) {
9666 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9668 } else {
9671 /*SuppressUserConversions=*/false,
9672 AllowedExplicit::None,
9673 /*InOverloadResolution=*/false,
9674 /*CStyle=*/false,
9675 /*AllowObjCWritebackConversion=*/false);
9676 if (ICS.isFailure())
9677 return Incompatible;
9678 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9680 }
9681 if (RHS.isInvalid())
9682 return Incompatible;
9684 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9685 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9686 result = IncompatibleObjCWeakRef;
9687 return result;
9688 }
9689
9690 // FIXME: Currently, we fall through and treat C++ classes like C
9691 // structures.
9692 // FIXME: We also fall through for atomics; not sure what should
9693 // happen there, though.
9694 } else if (RHS.get()->getType() == Context.OverloadTy) {
9695 // As a set of extensions to C, we support overloading on functions. These
9696 // functions need to be resolved here.
9697 DeclAccessPair DAP;
9699 RHS.get(), LHSType, /*Complain=*/false, DAP))
9700 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9701 else
9702 return Incompatible;
9703 }
9704
9705 // This check seems unnatural, however it is necessary to ensure the proper
9706 // conversion of functions/arrays. If the conversion were done for all
9707 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9708 // expressions that suppress this implicit conversion (&, sizeof). This needs
9709 // to happen before we check for null pointer conversions because C does not
9710 // undergo the same implicit conversions as C++ does above (by the calls to
9711 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9712 // lvalue to rvalue cast before checking for null pointer constraints. This
9713 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9714 //
9715 // Suppress this for references: C++ 8.5.3p5.
9716 if (!LHSType->isReferenceType()) {
9717 // FIXME: We potentially allocate here even if ConvertRHS is false.
9719 if (RHS.isInvalid())
9720 return Incompatible;
9721 }
9722
9723 // The constraints are expressed in terms of the atomic, qualified, or
9724 // unqualified type of the LHS.
9725 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9726
9727 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9728 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9729 if ((LHSTypeAfterConversion->isPointerType() ||
9730 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9731 LHSTypeAfterConversion->isBlockPointerType()) &&
9732 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9735 if (Diagnose || ConvertRHS) {
9736 CastKind Kind;
9738 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9739 /*IgnoreBaseAccess=*/false, Diagnose);
9740 if (ConvertRHS)
9741 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9742 }
9743 return Compatible;
9744 }
9745 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9746 // unqualified bool, and the right operand is a pointer or its type is
9747 // nullptr_t.
9748 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9749 RHS.get()->getType()->isNullPtrType()) {
9750 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9751 // only handles nullptr -> _Bool due to needing an extra conversion
9752 // step.
9753 // We model this by converting from nullptr -> void * and then let the
9754 // conversion from void * -> _Bool happen naturally.
9755 if (Diagnose || ConvertRHS) {
9756 CastKind Kind;
9759 /*IgnoreBaseAccess=*/false, Diagnose);
9760 if (ConvertRHS)
9761 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9762 &Path);
9763 }
9764 }
9765
9766 // OpenCL queue_t type assignment.
9767 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9769 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9770 return Compatible;
9771 }
9772
9773 CastKind Kind;
9775 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9776
9777 // C99 6.5.16.1p2: The value of the right operand is converted to the
9778 // type of the assignment expression.
9779 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9780 // so that we can use references in built-in functions even in C.
9781 // The getNonReferenceType() call makes sure that the resulting expression
9782 // does not have reference type.
9783 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9785 Expr *E = RHS.get();
9786
9787 // Check for various Objective-C errors. If we are not reporting
9788 // diagnostics and just checking for errors, e.g., during overload
9789 // resolution, return Incompatible to indicate the failure.
9790 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9791 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9793 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9794 if (!Diagnose)
9795 return Incompatible;
9796 }
9797 if (getLangOpts().ObjC &&
9798 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9799 E->getType(), E, Diagnose) ||
9800 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9801 if (!Diagnose)
9802 return Incompatible;
9803 // Replace the expression with a corrected version and continue so we
9804 // can find further errors.
9805 RHS = E;
9806 return Compatible;
9807 }
9808
9809 if (ConvertRHS)
9810 RHS = ImpCastExprToType(E, Ty, Kind);
9811 }
9812
9813 return result;
9814}
9815
9816namespace {
9817/// The original operand to an operator, prior to the application of the usual
9818/// arithmetic conversions and converting the arguments of a builtin operator
9819/// candidate.
9820struct OriginalOperand {
9821 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9822 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9823 Op = MTE->getSubExpr();
9824 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9825 Op = BTE->getSubExpr();
9826 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9827 Orig = ICE->getSubExprAsWritten();
9828 Conversion = ICE->getConversionFunction();
9829 }
9830 }
9831
9832 QualType getType() const { return Orig->getType(); }
9833
9834 Expr *Orig;
9835 NamedDecl *Conversion;
9836};
9837}
9838
9840 ExprResult &RHS) {
9841 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9842
9843 Diag(Loc, diag::err_typecheck_invalid_operands)
9844 << OrigLHS.getType() << OrigRHS.getType()
9845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9846
9847 // If a user-defined conversion was applied to either of the operands prior
9848 // to applying the built-in operator rules, tell the user about it.
9849 if (OrigLHS.Conversion) {
9850 Diag(OrigLHS.Conversion->getLocation(),
9851 diag::note_typecheck_invalid_operands_converted)
9852 << 0 << LHS.get()->getType();
9853 }
9854 if (OrigRHS.Conversion) {
9855 Diag(OrigRHS.Conversion->getLocation(),
9856 diag::note_typecheck_invalid_operands_converted)
9857 << 1 << RHS.get()->getType();
9858 }
9859
9860 return QualType();
9861}
9862
9864 ExprResult &RHS) {
9865 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9866 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9867
9868 bool LHSNatVec = LHSType->isVectorType();
9869 bool RHSNatVec = RHSType->isVectorType();
9870
9871 if (!(LHSNatVec && RHSNatVec)) {
9872 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9873 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9874 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9875 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9876 << Vector->getSourceRange();
9877 return QualType();
9878 }
9879
9880 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9881 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9882 << RHS.get()->getSourceRange();
9883
9884 return QualType();
9885}
9886
9887/// Try to convert a value of non-vector type to a vector type by converting
9888/// the type to the element type of the vector and then performing a splat.
9889/// If the language is OpenCL, we only use conversions that promote scalar
9890/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9891/// for float->int.
9892///
9893/// OpenCL V2.0 6.2.6.p2:
9894/// An error shall occur if any scalar operand type has greater rank
9895/// than the type of the vector element.
9896///
9897/// \param scalar - if non-null, actually perform the conversions
9898/// \return true if the operation fails (but without diagnosing the failure)
9900 QualType scalarTy,
9901 QualType vectorEltTy,
9902 QualType vectorTy,
9903 unsigned &DiagID) {
9904 // The conversion to apply to the scalar before splatting it,
9905 // if necessary.
9906 CastKind scalarCast = CK_NoOp;
9907
9908 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
9909 scalarCast = CK_IntegralToBoolean;
9910 } else if (vectorEltTy->isIntegralType(S.Context)) {
9911 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9912 (scalarTy->isIntegerType() &&
9913 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9914 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9915 return true;
9916 }
9917 if (!scalarTy->isIntegralType(S.Context))
9918 return true;
9919 scalarCast = CK_IntegralCast;
9920 } else if (vectorEltTy->isRealFloatingType()) {
9921 if (scalarTy->isRealFloatingType()) {
9922 if (S.getLangOpts().OpenCL &&
9923 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9924 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9925 return true;
9926 }
9927 scalarCast = CK_FloatingCast;
9928 }
9929 else if (scalarTy->isIntegralType(S.Context))
9930 scalarCast = CK_IntegralToFloating;
9931 else
9932 return true;
9933 } else {
9934 return true;
9935 }
9936
9937 // Adjust scalar if desired.
9938 if (scalar) {
9939 if (scalarCast != CK_NoOp)
9940 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9941 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9942 }
9943 return false;
9944}
9945
9946/// Convert vector E to a vector with the same number of elements but different
9947/// element type.
9948static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9949 const auto *VecTy = E->getType()->getAs<VectorType>();
9950 assert(VecTy && "Expression E must be a vector");
9951 QualType NewVecTy =
9952 VecTy->isExtVectorType()
9953 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9954 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9955 VecTy->getVectorKind());
9956
9957 // Look through the implicit cast. Return the subexpression if its type is
9958 // NewVecTy.
9959 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9960 if (ICE->getSubExpr()->getType() == NewVecTy)
9961 return ICE->getSubExpr();
9962
9963 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9964 return S.ImpCastExprToType(E, NewVecTy, Cast);
9965}
9966
9967/// Test if a (constant) integer Int can be casted to another integer type
9968/// IntTy without losing precision.
9970 QualType OtherIntTy) {
9971 if (Int->get()->containsErrors())
9972 return false;
9973
9974 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9975
9976 // Reject cases where the value of the Int is unknown as that would
9977 // possibly cause truncation, but accept cases where the scalar can be
9978 // demoted without loss of precision.
9979 Expr::EvalResult EVResult;
9980 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9981 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9982 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9983 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9984
9985 if (CstInt) {
9986 // If the scalar is constant and is of a higher order and has more active
9987 // bits that the vector element type, reject it.
9988 llvm::APSInt Result = EVResult.Val.getInt();
9989 unsigned NumBits = IntSigned
9990 ? (Result.isNegative() ? Result.getSignificantBits()
9991 : Result.getActiveBits())
9992 : Result.getActiveBits();
9993 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9994 return true;
9995
9996 // If the signedness of the scalar type and the vector element type
9997 // differs and the number of bits is greater than that of the vector
9998 // element reject it.
9999 return (IntSigned != OtherIntSigned &&
10000 NumBits > S.Context.getIntWidth(OtherIntTy));
10001 }
10002
10003 // Reject cases where the value of the scalar is not constant and it's
10004 // order is greater than that of the vector element type.
10005 return (Order < 0);
10006}
10007
10008/// Test if a (constant) integer Int can be casted to floating point type
10009/// FloatTy without losing precision.
10011 QualType FloatTy) {
10012 if (Int->get()->containsErrors())
10013 return false;
10014
10015 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10016
10017 // Determine if the integer constant can be expressed as a floating point
10018 // number of the appropriate type.
10019 Expr::EvalResult EVResult;
10020 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10021
10022 uint64_t Bits = 0;
10023 if (CstInt) {
10024 // Reject constants that would be truncated if they were converted to
10025 // the floating point type. Test by simple to/from conversion.
10026 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10027 // could be avoided if there was a convertFromAPInt method
10028 // which could signal back if implicit truncation occurred.
10029 llvm::APSInt Result = EVResult.Val.getInt();
10030 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10031 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10032 llvm::APFloat::rmTowardZero);
10033 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10035 bool Ignored = false;
10036 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10037 &Ignored);
10038 if (Result != ConvertBack)
10039 return true;
10040 } else {
10041 // Reject types that cannot be fully encoded into the mantissa of
10042 // the float.
10043 Bits = S.Context.getTypeSize(IntTy);
10044 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10045 S.Context.getFloatTypeSemantics(FloatTy));
10046 if (Bits > FloatPrec)
10047 return true;
10048 }
10049
10050 return false;
10051}
10052
10053/// Attempt to convert and splat Scalar into a vector whose types matches
10054/// Vector following GCC conversion rules. The rule is that implicit
10055/// conversion can occur when Scalar can be casted to match Vector's element
10056/// type without causing truncation of Scalar.
10058 ExprResult *Vector) {
10059 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10060 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10061 QualType VectorEltTy;
10062
10063 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10064 assert(!isa<ExtVectorType>(VT) &&
10065 "ExtVectorTypes should not be handled here!");
10066 VectorEltTy = VT->getElementType();
10067 } else if (VectorTy->isSveVLSBuiltinType()) {
10068 VectorEltTy =
10069 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10070 } else {
10071 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10072 }
10073
10074 // Reject cases where the vector element type or the scalar element type are
10075 // not integral or floating point types.
10076 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10077 return true;
10078
10079 // The conversion to apply to the scalar before splatting it,
10080 // if necessary.
10081 CastKind ScalarCast = CK_NoOp;
10082
10083 // Accept cases where the vector elements are integers and the scalar is
10084 // an integer.
10085 // FIXME: Notionally if the scalar was a floating point value with a precise
10086 // integral representation, we could cast it to an appropriate integer
10087 // type and then perform the rest of the checks here. GCC will perform
10088 // this conversion in some cases as determined by the input language.
10089 // We should accept it on a language independent basis.
10090 if (VectorEltTy->isIntegralType(S.Context) &&
10091 ScalarTy->isIntegralType(S.Context) &&
10092 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10093
10094 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10095 return true;
10096
10097 ScalarCast = CK_IntegralCast;
10098 } else if (VectorEltTy->isIntegralType(S.Context) &&
10099 ScalarTy->isRealFloatingType()) {
10100 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10101 ScalarCast = CK_FloatingToIntegral;
10102 else
10103 return true;
10104 } else if (VectorEltTy->isRealFloatingType()) {
10105 if (ScalarTy->isRealFloatingType()) {
10106
10107 // Reject cases where the scalar type is not a constant and has a higher
10108 // Order than the vector element type.
10109 llvm::APFloat Result(0.0);
10110
10111 // Determine whether this is a constant scalar. In the event that the
10112 // value is dependent (and thus cannot be evaluated by the constant
10113 // evaluator), skip the evaluation. This will then diagnose once the
10114 // expression is instantiated.
10115 bool CstScalar = Scalar->get()->isValueDependent() ||
10116 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10117 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10118 if (!CstScalar && Order < 0)
10119 return true;
10120
10121 // If the scalar cannot be safely casted to the vector element type,
10122 // reject it.
10123 if (CstScalar) {
10124 bool Truncated = false;
10125 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10126 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10127 if (Truncated)
10128 return true;
10129 }
10130
10131 ScalarCast = CK_FloatingCast;
10132 } else if (ScalarTy->isIntegralType(S.Context)) {
10133 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10134 return true;
10135
10136 ScalarCast = CK_IntegralToFloating;
10137 } else
10138 return true;
10139 } else if (ScalarTy->isEnumeralType())
10140 return true;
10141
10142 // Adjust scalar if desired.
10143 if (ScalarCast != CK_NoOp)
10144 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10145 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10146 return false;
10147}
10148
10150 SourceLocation Loc, bool IsCompAssign,
10151 bool AllowBothBool,
10152 bool AllowBoolConversions,
10153 bool AllowBoolOperation,
10154 bool ReportInvalid) {
10155 if (!IsCompAssign) {
10157 if (LHS.isInvalid())
10158 return QualType();
10159 }
10161 if (RHS.isInvalid())
10162 return QualType();
10163
10164 // For conversion purposes, we ignore any qualifiers.
10165 // For example, "const float" and "float" are equivalent.
10166 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10167 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10168
10169 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10170 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10171 assert(LHSVecType || RHSVecType);
10172
10173 if (getLangOpts().HLSL)
10174 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10175 IsCompAssign);
10176
10177 // AltiVec-style "vector bool op vector bool" combinations are allowed
10178 // for some operators but not others.
10179 if (!AllowBothBool && LHSVecType &&
10180 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10181 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10182 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10183
10184 // This operation may not be performed on boolean vectors.
10185 if (!AllowBoolOperation &&
10186 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10187 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10188
10189 // If the vector types are identical, return.
10190 if (Context.hasSameType(LHSType, RHSType))
10191 return Context.getCommonSugaredType(LHSType, RHSType);
10192
10193 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10194 if (LHSVecType && RHSVecType &&
10195 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10196 if (isa<ExtVectorType>(LHSVecType)) {
10197 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10198 return LHSType;
10199 }
10200
10201 if (!IsCompAssign)
10202 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10203 return RHSType;
10204 }
10205
10206 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10207 // can be mixed, with the result being the non-bool type. The non-bool
10208 // operand must have integer element type.
10209 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10210 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10211 (Context.getTypeSize(LHSVecType->getElementType()) ==
10212 Context.getTypeSize(RHSVecType->getElementType()))) {
10213 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10214 LHSVecType->getElementType()->isIntegerType() &&
10215 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10216 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10217 return LHSType;
10218 }
10219 if (!IsCompAssign &&
10220 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10221 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10222 RHSVecType->getElementType()->isIntegerType()) {
10223 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10224 return RHSType;
10225 }
10226 }
10227
10228 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10229 // invalid since the ambiguity can affect the ABI.
10230 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10231 unsigned &SVEorRVV) {
10232 const VectorType *VecType = SecondType->getAs<VectorType>();
10233 SVEorRVV = 0;
10234 if (FirstType->isSizelessBuiltinType() && VecType) {
10237 return true;
10243 SVEorRVV = 1;
10244 return true;
10245 }
10246 }
10247
10248 return false;
10249 };
10250
10251 unsigned SVEorRVV;
10252 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10253 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10254 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10255 << SVEorRVV << LHSType << RHSType;
10256 return QualType();
10257 }
10258
10259 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10260 // invalid since the ambiguity can affect the ABI.
10261 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10262 unsigned &SVEorRVV) {
10263 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10264 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10265
10266 SVEorRVV = 0;
10267 if (FirstVecType && SecondVecType) {
10268 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10269 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10270 SecondVecType->getVectorKind() ==
10272 return true;
10273 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10274 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10275 SecondVecType->getVectorKind() ==
10277 SecondVecType->getVectorKind() ==
10279 SecondVecType->getVectorKind() ==
10281 SVEorRVV = 1;
10282 return true;
10283 }
10284 }
10285 return false;
10286 }
10287
10288 if (SecondVecType &&
10289 SecondVecType->getVectorKind() == VectorKind::Generic) {
10290 if (FirstType->isSVESizelessBuiltinType())
10291 return true;
10292 if (FirstType->isRVVSizelessBuiltinType()) {
10293 SVEorRVV = 1;
10294 return true;
10295 }
10296 }
10297
10298 return false;
10299 };
10300
10301 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10302 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10303 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10304 << SVEorRVV << LHSType << RHSType;
10305 return QualType();
10306 }
10307
10308 // If there's a vector type and a scalar, try to convert the scalar to
10309 // the vector element type and splat.
10310 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10311 if (!RHSVecType) {
10312 if (isa<ExtVectorType>(LHSVecType)) {
10313 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10314 LHSVecType->getElementType(), LHSType,
10315 DiagID))
10316 return LHSType;
10317 } else {
10318 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10319 return LHSType;
10320 }
10321 }
10322 if (!LHSVecType) {
10323 if (isa<ExtVectorType>(RHSVecType)) {
10324 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10325 LHSType, RHSVecType->getElementType(),
10326 RHSType, DiagID))
10327 return RHSType;
10328 } else {
10329 if (LHS.get()->isLValue() ||
10330 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10331 return RHSType;
10332 }
10333 }
10334
10335 // FIXME: The code below also handles conversion between vectors and
10336 // non-scalars, we should break this down into fine grained specific checks
10337 // and emit proper diagnostics.
10338 QualType VecType = LHSVecType ? LHSType : RHSType;
10339 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10340 QualType OtherType = LHSVecType ? RHSType : LHSType;
10341 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10342 if (isLaxVectorConversion(OtherType, VecType)) {
10343 if (Context.getTargetInfo().getTriple().isPPC() &&
10344 anyAltivecTypes(RHSType, LHSType) &&
10345 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10346 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10347 // If we're allowing lax vector conversions, only the total (data) size
10348 // needs to be the same. For non compound assignment, if one of the types is
10349 // scalar, the result is always the vector type.
10350 if (!IsCompAssign) {
10351 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10352 return VecType;
10353 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10354 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10355 // type. Note that this is already done by non-compound assignments in
10356 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10357 // <1 x T> -> T. The result is also a vector type.
10358 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10359 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10360 ExprResult *RHSExpr = &RHS;
10361 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10362 return VecType;
10363 }
10364 }
10365
10366 // Okay, the expression is invalid.
10367
10368 // If there's a non-vector, non-real operand, diagnose that.
10369 if ((!RHSVecType && !RHSType->isRealType()) ||
10370 (!LHSVecType && !LHSType->isRealType())) {
10371 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10372 << LHSType << RHSType
10373 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10374 return QualType();
10375 }
10376
10377 // OpenCL V1.1 6.2.6.p1:
10378 // If the operands are of more than one vector type, then an error shall
10379 // occur. Implicit conversions between vector types are not permitted, per
10380 // section 6.2.1.
10381 if (getLangOpts().OpenCL &&
10382 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10383 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10384 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10385 << RHSType;
10386 return QualType();
10387 }
10388
10389
10390 // If there is a vector type that is not a ExtVector and a scalar, we reach
10391 // this point if scalar could not be converted to the vector's element type
10392 // without truncation.
10393 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10394 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10395 QualType Scalar = LHSVecType ? RHSType : LHSType;
10396 QualType Vector = LHSVecType ? LHSType : RHSType;
10397 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10398 Diag(Loc,
10399 diag::err_typecheck_vector_not_convertable_implict_truncation)
10400 << ScalarOrVector << Scalar << Vector;
10401
10402 return QualType();
10403 }
10404
10405 // Otherwise, use the generic diagnostic.
10406 Diag(Loc, DiagID)
10407 << LHSType << RHSType
10408 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10409 return QualType();
10410}
10411
10414 bool IsCompAssign,
10415 ArithConvKind OperationKind) {
10416 if (!IsCompAssign) {
10418 if (LHS.isInvalid())
10419 return QualType();
10420 }
10422 if (RHS.isInvalid())
10423 return QualType();
10424
10425 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10426 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10427
10428 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10429 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10430
10431 unsigned DiagID = diag::err_typecheck_invalid_operands;
10432 if ((OperationKind == ACK_Arithmetic) &&
10433 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10434 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10435 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10436 << RHS.get()->getSourceRange();
10437 return QualType();
10438 }
10439
10440 if (Context.hasSameType(LHSType, RHSType))
10441 return LHSType;
10442
10443 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10444 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10445 return LHSType;
10446 }
10447 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10448 if (LHS.get()->isLValue() ||
10449 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10450 return RHSType;
10451 }
10452
10453 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10454 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10455 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10456 << LHSType << RHSType << LHS.get()->getSourceRange()
10457 << RHS.get()->getSourceRange();
10458 return QualType();
10459 }
10460
10461 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10462 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10463 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10464 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10465 << LHSType << RHSType << LHS.get()->getSourceRange()
10466 << RHS.get()->getSourceRange();
10467 return QualType();
10468 }
10469
10470 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10471 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10472 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10473 bool ScalarOrVector =
10474 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10475
10476 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10477 << ScalarOrVector << Scalar << Vector;
10478
10479 return QualType();
10480 }
10481
10482 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10483 << RHS.get()->getSourceRange();
10484 return QualType();
10485}
10486
10487// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10488// expression. These are mainly cases where the null pointer is used as an
10489// integer instead of a pointer.
10491 SourceLocation Loc, bool IsCompare) {
10492 // The canonical way to check for a GNU null is with isNullPointerConstant,
10493 // but we use a bit of a hack here for speed; this is a relatively
10494 // hot path, and isNullPointerConstant is slow.
10495 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10496 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10497
10498 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10499
10500 // Avoid analyzing cases where the result will either be invalid (and
10501 // diagnosed as such) or entirely valid and not something to warn about.
10502 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10503 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10504 return;
10505
10506 // Comparison operations would not make sense with a null pointer no matter
10507 // what the other expression is.
10508 if (!IsCompare) {
10509 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10510 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10511 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10512 return;
10513 }
10514
10515 // The rest of the operations only make sense with a null pointer
10516 // if the other expression is a pointer.
10517 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10518 NonNullType->canDecayToPointerType())
10519 return;
10520
10521 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10522 << LHSNull /* LHS is NULL */ << NonNullType
10523 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10524}
10525
10528 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10529 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10530 if (!LUE || !RUE)
10531 return;
10532 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10533 RUE->getKind() != UETT_SizeOf)
10534 return;
10535
10536 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10537 QualType LHSTy = LHSArg->getType();
10538 QualType RHSTy;
10539
10540 if (RUE->isArgumentType())
10541 RHSTy = RUE->getArgumentType().getNonReferenceType();
10542 else
10543 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10544
10545 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10546 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10547 return;
10548
10549 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10550 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10551 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10552 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10553 << LHSArgDecl;
10554 }
10555 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10556 QualType ArrayElemTy = ArrayTy->getElementType();
10557 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10558 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10559 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10560 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10561 return;
10562 S.Diag(Loc, diag::warn_division_sizeof_array)
10563 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10564 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10565 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10566 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10567 << LHSArgDecl;
10568 }
10569
10570 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10571 }
10572}
10573
10575 ExprResult &RHS,
10576 SourceLocation Loc, bool IsDiv) {
10577 // Check for division/remainder by zero.
10578 Expr::EvalResult RHSValue;
10579 if (!RHS.get()->isValueDependent() &&
10580 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10581 RHSValue.Val.getInt() == 0)
10582 S.DiagRuntimeBehavior(Loc, RHS.get(),
10583 S.PDiag(diag::warn_remainder_division_by_zero)
10584 << IsDiv << RHS.get()->getSourceRange());
10585}
10586
10589 bool IsCompAssign, bool IsDiv) {
10590 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10591
10592 QualType LHSTy = LHS.get()->getType();
10593 QualType RHSTy = RHS.get()->getType();
10594 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10595 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10596 /*AllowBothBool*/ getLangOpts().AltiVec,
10597 /*AllowBoolConversions*/ false,
10598 /*AllowBooleanOperation*/ false,
10599 /*ReportInvalid*/ true);
10600 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10601 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10603 if (!IsDiv &&
10604 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10605 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10606 // For division, only matrix-by-scalar is supported. Other combinations with
10607 // matrix types are invalid.
10608 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10609 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10610
10612 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10613 if (LHS.isInvalid() || RHS.isInvalid())
10614 return QualType();
10615
10616
10617 if (compType.isNull() || !compType->isArithmeticType())
10618 return InvalidOperands(Loc, LHS, RHS);
10619 if (IsDiv) {
10620 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10621 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10622 }
10623 return compType;
10624}
10625
10627 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10628 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10629
10630 if (LHS.get()->getType()->isVectorType() ||
10631 RHS.get()->getType()->isVectorType()) {
10632 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10634 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10635 /*AllowBothBool*/ getLangOpts().AltiVec,
10636 /*AllowBoolConversions*/ false,
10637 /*AllowBooleanOperation*/ false,
10638 /*ReportInvalid*/ true);
10639 return InvalidOperands(Loc, LHS, RHS);
10640 }
10641
10642 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10643 RHS.get()->getType()->isSveVLSBuiltinType()) {
10644 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10646 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10648
10649 return InvalidOperands(Loc, LHS, RHS);
10650 }
10651
10653 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10654 if (LHS.isInvalid() || RHS.isInvalid())
10655 return QualType();
10656
10657 if (compType.isNull() || !compType->isIntegerType())
10658 return InvalidOperands(Loc, LHS, RHS);
10659 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10660 return compType;
10661}
10662
10663/// Diagnose invalid arithmetic on two void pointers.
10665 Expr *LHSExpr, Expr *RHSExpr) {
10666 S.Diag(Loc, S.getLangOpts().CPlusPlus
10667 ? diag::err_typecheck_pointer_arith_void_type
10668 : diag::ext_gnu_void_ptr)
10669 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10670 << RHSExpr->getSourceRange();
10671}
10672
10673/// Diagnose invalid arithmetic on a void pointer.
10675 Expr *Pointer) {
10676 S.Diag(Loc, S.getLangOpts().CPlusPlus
10677 ? diag::err_typecheck_pointer_arith_void_type
10678 : diag::ext_gnu_void_ptr)
10679 << 0 /* one pointer */ << Pointer->getSourceRange();
10680}
10681
10682/// Diagnose invalid arithmetic on a null pointer.
10683///
10684/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10685/// idiom, which we recognize as a GNU extension.
10686///
10688 Expr *Pointer, bool IsGNUIdiom) {
10689 if (IsGNUIdiom)
10690 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10691 << Pointer->getSourceRange();
10692 else
10693 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10694 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10695}
10696
10697/// Diagnose invalid subraction on a null pointer.
10698///
10700 Expr *Pointer, bool BothNull) {
10701 // Null - null is valid in C++ [expr.add]p7
10702 if (BothNull && S.getLangOpts().CPlusPlus)
10703 return;
10704
10705 // Is this s a macro from a system header?
10707 return;
10708
10710 S.PDiag(diag::warn_pointer_sub_null_ptr)
10711 << S.getLangOpts().CPlusPlus
10712 << Pointer->getSourceRange());
10713}
10714
10715/// Diagnose invalid arithmetic on two function pointers.
10717 Expr *LHS, Expr *RHS) {
10718 assert(LHS->getType()->isAnyPointerType());
10719 assert(RHS->getType()->isAnyPointerType());
10720 S.Diag(Loc, S.getLangOpts().CPlusPlus
10721 ? diag::err_typecheck_pointer_arith_function_type
10722 : diag::ext_gnu_ptr_func_arith)
10723 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10724 // We only show the second type if it differs from the first.
10726 RHS->getType())
10727 << RHS->getType()->getPointeeType()
10728 << LHS->getSourceRange() << RHS->getSourceRange();
10729}
10730
10731/// Diagnose invalid arithmetic on a function pointer.
10733 Expr *Pointer) {
10734 assert(Pointer->getType()->isAnyPointerType());
10735 S.Diag(Loc, S.getLangOpts().CPlusPlus
10736 ? diag::err_typecheck_pointer_arith_function_type
10737 : diag::ext_gnu_ptr_func_arith)
10738 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10739 << 0 /* one pointer, so only one type */
10740 << Pointer->getSourceRange();
10741}
10742
10743/// Emit error if Operand is incomplete pointer type
10744///
10745/// \returns True if pointer has incomplete type
10747 Expr *Operand) {
10748 QualType ResType = Operand->getType();
10749 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10750 ResType = ResAtomicType->getValueType();
10751
10752 assert(ResType->isAnyPointerType());
10753 QualType PointeeTy = ResType->getPointeeType();
10754 return S.RequireCompleteSizedType(
10755 Loc, PointeeTy,
10756 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10757 Operand->getSourceRange());
10758}
10759
10760/// Check the validity of an arithmetic pointer operand.
10761///
10762/// If the operand has pointer type, this code will check for pointer types
10763/// which are invalid in arithmetic operations. These will be diagnosed
10764/// appropriately, including whether or not the use is supported as an
10765/// extension.
10766///
10767/// \returns True when the operand is valid to use (even if as an extension).
10769 Expr *Operand) {
10770 QualType ResType = Operand->getType();
10771 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10772 ResType = ResAtomicType->getValueType();
10773
10774 if (!ResType->isAnyPointerType()) return true;
10775
10776 QualType PointeeTy = ResType->getPointeeType();
10777 if (PointeeTy->isVoidType()) {
10779 return !S.getLangOpts().CPlusPlus;
10780 }
10781 if (PointeeTy->isFunctionType()) {
10783 return !S.getLangOpts().CPlusPlus;
10784 }
10785
10786 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10787
10788 return true;
10789}
10790
10791/// Check the validity of a binary arithmetic operation w.r.t. pointer
10792/// operands.
10793///
10794/// This routine will diagnose any invalid arithmetic on pointer operands much
10795/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10796/// for emitting a single diagnostic even for operations where both LHS and RHS
10797/// are (potentially problematic) pointers.
10798///
10799/// \returns True when the operand is valid to use (even if as an extension).
10801 Expr *LHSExpr, Expr *RHSExpr) {
10802 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10803 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10804 if (!isLHSPointer && !isRHSPointer) return true;
10805
10806 QualType LHSPointeeTy, RHSPointeeTy;
10807 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10808 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10809
10810 // if both are pointers check if operation is valid wrt address spaces
10811 if (isLHSPointer && isRHSPointer) {
10812 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
10813 S.getASTContext())) {
10814 S.Diag(Loc,
10815 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10816 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10817 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10818 return false;
10819 }
10820 }
10821
10822 // Check for arithmetic on pointers to incomplete types.
10823 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10824 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10825 if (isLHSVoidPtr || isRHSVoidPtr) {
10826 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10827 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10828 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10829
10830 return !S.getLangOpts().CPlusPlus;
10831 }
10832
10833 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10834 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10835 if (isLHSFuncPtr || isRHSFuncPtr) {
10836 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10837 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10838 RHSExpr);
10839 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10840
10841 return !S.getLangOpts().CPlusPlus;
10842 }
10843
10844 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10845 return false;
10846 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10847 return false;
10848
10849 return true;
10850}
10851
10852/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10853/// literal.
10855 Expr *LHSExpr, Expr *RHSExpr) {
10856 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10857 Expr* IndexExpr = RHSExpr;
10858 if (!StrExpr) {
10859 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10860 IndexExpr = LHSExpr;
10861 }
10862
10863 bool IsStringPlusInt = StrExpr &&
10865 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10866 return;
10867
10868 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10869 Self.Diag(OpLoc, diag::warn_string_plus_int)
10870 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10871
10872 // Only print a fixit for "str" + int, not for int + "str".
10873 if (IndexExpr == RHSExpr) {
10874 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10875 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10876 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10878 << FixItHint::CreateInsertion(EndLoc, "]");
10879 } else
10880 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10881}
10882
10883/// Emit a warning when adding a char literal to a string.
10885 Expr *LHSExpr, Expr *RHSExpr) {
10886 const Expr *StringRefExpr = LHSExpr;
10887 const CharacterLiteral *CharExpr =
10888 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10889
10890 if (!CharExpr) {
10891 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10892 StringRefExpr = RHSExpr;
10893 }
10894
10895 if (!CharExpr || !StringRefExpr)
10896 return;
10897
10898 const QualType StringType = StringRefExpr->getType();
10899
10900 // Return if not a PointerType.
10901 if (!StringType->isAnyPointerType())
10902 return;
10903
10904 // Return if not a CharacterType.
10905 if (!StringType->getPointeeType()->isAnyCharacterType())
10906 return;
10907
10908 ASTContext &Ctx = Self.getASTContext();
10909 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10910
10911 const QualType CharType = CharExpr->getType();
10912 if (!CharType->isAnyCharacterType() &&
10913 CharType->isIntegerType() &&
10914 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10915 Self.Diag(OpLoc, diag::warn_string_plus_char)
10916 << DiagRange << Ctx.CharTy;
10917 } else {
10918 Self.Diag(OpLoc, diag::warn_string_plus_char)
10919 << DiagRange << CharExpr->getType();
10920 }
10921
10922 // Only print a fixit for str + char, not for char + str.
10923 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10924 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10925 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10926 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10928 << FixItHint::CreateInsertion(EndLoc, "]");
10929 } else {
10930 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10931 }
10932}
10933
10934/// Emit error when two pointers are incompatible.
10936 Expr *LHSExpr, Expr *RHSExpr) {
10937 assert(LHSExpr->getType()->isAnyPointerType());
10938 assert(RHSExpr->getType()->isAnyPointerType());
10939 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10940 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10941 << RHSExpr->getSourceRange();
10942}
10943
10944// C99 6.5.6
10947 QualType* CompLHSTy) {
10948 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10949
10950 if (LHS.get()->getType()->isVectorType() ||
10951 RHS.get()->getType()->isVectorType()) {
10952 QualType compType =
10953 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10954 /*AllowBothBool*/ getLangOpts().AltiVec,
10955 /*AllowBoolConversions*/ getLangOpts().ZVector,
10956 /*AllowBooleanOperation*/ false,
10957 /*ReportInvalid*/ true);
10958 if (CompLHSTy) *CompLHSTy = compType;
10959 return compType;
10960 }
10961
10962 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10963 RHS.get()->getType()->isSveVLSBuiltinType()) {
10964 QualType compType =
10965 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10966 if (CompLHSTy)
10967 *CompLHSTy = compType;
10968 return compType;
10969 }
10970
10971 if (LHS.get()->getType()->isConstantMatrixType() ||
10972 RHS.get()->getType()->isConstantMatrixType()) {
10973 QualType compType =
10974 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10975 if (CompLHSTy)
10976 *CompLHSTy = compType;
10977 return compType;
10978 }
10979
10981 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10982 if (LHS.isInvalid() || RHS.isInvalid())
10983 return QualType();
10984
10985 // Diagnose "string literal" '+' int and string '+' "char literal".
10986 if (Opc == BO_Add) {
10987 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10988 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10989 }
10990
10991 // handle the common case first (both operands are arithmetic).
10992 if (!compType.isNull() && compType->isArithmeticType()) {
10993 if (CompLHSTy) *CompLHSTy = compType;
10994 return compType;
10995 }
10996
10997 // Type-checking. Ultimately the pointer's going to be in PExp;
10998 // note that we bias towards the LHS being the pointer.
10999 Expr *PExp = LHS.get(), *IExp = RHS.get();
11000
11001 bool isObjCPointer;
11002 if (PExp->getType()->isPointerType()) {
11003 isObjCPointer = false;
11004 } else if (PExp->getType()->isObjCObjectPointerType()) {
11005 isObjCPointer = true;
11006 } else {
11007 std::swap(PExp, IExp);
11008 if (PExp->getType()->isPointerType()) {
11009 isObjCPointer = false;
11010 } else if (PExp->getType()->isObjCObjectPointerType()) {
11011 isObjCPointer = true;
11012 } else {
11013 return InvalidOperands(Loc, LHS, RHS);
11014 }
11015 }
11016 assert(PExp->getType()->isAnyPointerType());
11017
11018 if (!IExp->getType()->isIntegerType())
11019 return InvalidOperands(Loc, LHS, RHS);
11020
11021 // Adding to a null pointer results in undefined behavior.
11024 // In C++ adding zero to a null pointer is defined.
11025 Expr::EvalResult KnownVal;
11026 if (!getLangOpts().CPlusPlus ||
11027 (!IExp->isValueDependent() &&
11028 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11029 KnownVal.Val.getInt() != 0))) {
11030 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11032 Context, BO_Add, PExp, IExp);
11033 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11034 }
11035 }
11036
11037 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11038 return QualType();
11039
11040 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11041 return QualType();
11042
11043 // Arithmetic on label addresses is normally allowed, except when we add
11044 // a ptrauth signature to the addresses.
11045 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11046 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11047 << /*addition*/ 1;
11048 return QualType();
11049 }
11050
11051 // Check array bounds for pointer arithemtic
11052 CheckArrayAccess(PExp, IExp);
11053
11054 if (CompLHSTy) {
11056 if (LHSTy.isNull()) {
11057 LHSTy = LHS.get()->getType();
11059 LHSTy = Context.getPromotedIntegerType(LHSTy);
11060 }
11061 *CompLHSTy = LHSTy;
11062 }
11063
11064 return PExp->getType();
11065}
11066
11067// C99 6.5.6
11070 QualType* CompLHSTy) {
11071 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11072
11073 if (LHS.get()->getType()->isVectorType() ||
11074 RHS.get()->getType()->isVectorType()) {
11075 QualType compType =
11076 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11077 /*AllowBothBool*/ getLangOpts().AltiVec,
11078 /*AllowBoolConversions*/ getLangOpts().ZVector,
11079 /*AllowBooleanOperation*/ false,
11080 /*ReportInvalid*/ true);
11081 if (CompLHSTy) *CompLHSTy = compType;
11082 return compType;
11083 }
11084
11085 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11086 RHS.get()->getType()->isSveVLSBuiltinType()) {
11087 QualType compType =
11088 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11089 if (CompLHSTy)
11090 *CompLHSTy = compType;
11091 return compType;
11092 }
11093
11094 if (LHS.get()->getType()->isConstantMatrixType() ||
11095 RHS.get()->getType()->isConstantMatrixType()) {
11096 QualType compType =
11097 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11098 if (CompLHSTy)
11099 *CompLHSTy = compType;
11100 return compType;
11101 }
11102
11104 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11105 if (LHS.isInvalid() || RHS.isInvalid())
11106 return QualType();
11107
11108 // Enforce type constraints: C99 6.5.6p3.
11109
11110 // Handle the common case first (both operands are arithmetic).
11111 if (!compType.isNull() && compType->isArithmeticType()) {
11112 if (CompLHSTy) *CompLHSTy = compType;
11113 return compType;
11114 }
11115
11116 // Either ptr - int or ptr - ptr.
11117 if (LHS.get()->getType()->isAnyPointerType()) {
11118 QualType lpointee = LHS.get()->getType()->getPointeeType();
11119
11120 // Diagnose bad cases where we step over interface counts.
11121 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11122 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11123 return QualType();
11124
11125 // Arithmetic on label addresses is normally allowed, except when we add
11126 // a ptrauth signature to the addresses.
11127 if (isa<AddrLabelExpr>(LHS.get()) &&
11128 getLangOpts().PointerAuthIndirectGotos) {
11129 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11130 << /*subtraction*/ 0;
11131 return QualType();
11132 }
11133
11134 // The result type of a pointer-int computation is the pointer type.
11135 if (RHS.get()->getType()->isIntegerType()) {
11136 // Subtracting from a null pointer should produce a warning.
11137 // The last argument to the diagnose call says this doesn't match the
11138 // GNU int-to-pointer idiom.
11141 // In C++ adding zero to a null pointer is defined.
11142 Expr::EvalResult KnownVal;
11143 if (!getLangOpts().CPlusPlus ||
11144 (!RHS.get()->isValueDependent() &&
11145 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11146 KnownVal.Val.getInt() != 0))) {
11147 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11148 }
11149 }
11150
11151 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11152 return QualType();
11153
11154 // Check array bounds for pointer arithemtic
11155 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11156 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11157
11158 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11159 return LHS.get()->getType();
11160 }
11161
11162 // Handle pointer-pointer subtractions.
11163 if (const PointerType *RHSPTy
11164 = RHS.get()->getType()->getAs<PointerType>()) {
11165 QualType rpointee = RHSPTy->getPointeeType();
11166
11167 if (getLangOpts().CPlusPlus) {
11168 // Pointee types must be the same: C++ [expr.add]
11169 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11170 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11171 }
11172 } else {
11173 // Pointee types must be compatible C99 6.5.6p3
11177 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11178 return QualType();
11179 }
11180 }
11181
11183 LHS.get(), RHS.get()))
11184 return QualType();
11185
11186 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11188 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11190
11191 // Subtracting nullptr or from nullptr is suspect
11192 if (LHSIsNullPtr)
11193 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11194 if (RHSIsNullPtr)
11195 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11196
11197 // The pointee type may have zero size. As an extension, a structure or
11198 // union may have zero size or an array may have zero length. In this
11199 // case subtraction does not make sense.
11200 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11201 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11202 if (ElementSize.isZero()) {
11203 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11204 << rpointee.getUnqualifiedType()
11205 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11206 }
11207 }
11208
11209 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11210 return Context.getPointerDiffType();
11211 }
11212 }
11213
11214 return InvalidOperands(Loc, LHS, RHS);
11215}
11216
11218 if (const EnumType *ET = T->getAs<EnumType>())
11219 return ET->getDecl()->isScoped();
11220 return false;
11221}
11222
11225 QualType LHSType) {
11226 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11227 // so skip remaining warnings as we don't want to modify values within Sema.
11228 if (S.getLangOpts().OpenCL)
11229 return;
11230
11231 // Check right/shifter operand
11232 Expr::EvalResult RHSResult;
11233 if (RHS.get()->isValueDependent() ||
11234 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11235 return;
11236 llvm::APSInt Right = RHSResult.Val.getInt();
11237
11238 if (Right.isNegative()) {
11239 S.DiagRuntimeBehavior(Loc, RHS.get(),
11240 S.PDiag(diag::warn_shift_negative)
11241 << RHS.get()->getSourceRange());
11242 return;
11243 }
11244
11245 QualType LHSExprType = LHS.get()->getType();
11246 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11247 if (LHSExprType->isBitIntType())
11248 LeftSize = S.Context.getIntWidth(LHSExprType);
11249 else if (LHSExprType->isFixedPointType()) {
11250 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11251 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11252 }
11253 if (Right.uge(LeftSize)) {
11254 S.DiagRuntimeBehavior(Loc, RHS.get(),
11255 S.PDiag(diag::warn_shift_gt_typewidth)
11256 << RHS.get()->getSourceRange());
11257 return;
11258 }
11259
11260 // FIXME: We probably need to handle fixed point types specially here.
11261 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11262 return;
11263
11264 // When left shifting an ICE which is signed, we can check for overflow which
11265 // according to C++ standards prior to C++2a has undefined behavior
11266 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11267 // more than the maximum value representable in the result type, so never
11268 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11269 // expression is still probably a bug.)
11270 Expr::EvalResult LHSResult;
11271 if (LHS.get()->isValueDependent() ||
11273 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11274 return;
11275 llvm::APSInt Left = LHSResult.Val.getInt();
11276
11277 // Don't warn if signed overflow is defined, then all the rest of the
11278 // diagnostics will not be triggered because the behavior is defined.
11279 // Also don't warn in C++20 mode (and newer), as signed left shifts
11280 // always wrap and never overflow.
11281 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11282 return;
11283
11284 // If LHS does not have a non-negative value then, the
11285 // behavior is undefined before C++2a. Warn about it.
11286 if (Left.isNegative()) {
11287 S.DiagRuntimeBehavior(Loc, LHS.get(),
11288 S.PDiag(diag::warn_shift_lhs_negative)
11289 << LHS.get()->getSourceRange());
11290 return;
11291 }
11292
11293 llvm::APInt ResultBits =
11294 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11295 if (ResultBits.ule(LeftSize))
11296 return;
11297 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11298 Result = Result.shl(Right);
11299
11300 // Print the bit representation of the signed integer as an unsigned
11301 // hexadecimal number.
11302 SmallString<40> HexResult;
11303 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11304
11305 // If we are only missing a sign bit, this is less likely to result in actual
11306 // bugs -- if the result is cast back to an unsigned type, it will have the
11307 // expected value. Thus we place this behind a different warning that can be
11308 // turned off separately if needed.
11309 if (ResultBits - 1 == LeftSize) {
11310 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11311 << HexResult << LHSType
11312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11313 return;
11314 }
11315
11316 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11317 << HexResult.str() << Result.getSignificantBits() << LHSType
11318 << Left.getBitWidth() << LHS.get()->getSourceRange()
11319 << RHS.get()->getSourceRange();
11320}
11321
11322/// Return the resulting type when a vector is shifted
11323/// by a scalar or vector shift amount.
11325 SourceLocation Loc, bool IsCompAssign) {
11326 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11327 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11328 !LHS.get()->getType()->isVectorType()) {
11329 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11330 << RHS.get()->getType() << LHS.get()->getType()
11331 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11332 return QualType();
11333 }
11334
11335 if (!IsCompAssign) {
11336 LHS = S.UsualUnaryConversions(LHS.get());
11337 if (LHS.isInvalid()) return QualType();
11338 }
11339
11340 RHS = S.UsualUnaryConversions(RHS.get());
11341 if (RHS.isInvalid()) return QualType();
11342
11343 QualType LHSType = LHS.get()->getType();
11344 // Note that LHS might be a scalar because the routine calls not only in
11345 // OpenCL case.
11346 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11347 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11348
11349 // Note that RHS might not be a vector.
11350 QualType RHSType = RHS.get()->getType();
11351 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11352 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11353
11354 // Do not allow shifts for boolean vectors.
11355 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11356 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11357 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11358 << LHS.get()->getType() << RHS.get()->getType()
11359 << LHS.get()->getSourceRange();
11360 return QualType();
11361 }
11362
11363 // The operands need to be integers.
11364 if (!LHSEleType->isIntegerType()) {
11365 S.Diag(Loc, diag::err_typecheck_expect_int)
11366 << LHS.get()->getType() << LHS.get()->getSourceRange();
11367 return QualType();
11368 }
11369
11370 if (!RHSEleType->isIntegerType()) {
11371 S.Diag(Loc, diag::err_typecheck_expect_int)
11372 << RHS.get()->getType() << RHS.get()->getSourceRange();
11373 return QualType();
11374 }
11375
11376 if (!LHSVecTy) {
11377 assert(RHSVecTy);
11378 if (IsCompAssign)
11379 return RHSType;
11380 if (LHSEleType != RHSEleType) {
11381 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11382 LHSEleType = RHSEleType;
11383 }
11384 QualType VecTy =
11385 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11386 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11387 LHSType = VecTy;
11388 } else if (RHSVecTy) {
11389 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11390 // are applied component-wise. So if RHS is a vector, then ensure
11391 // that the number of elements is the same as LHS...
11392 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11393 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11394 << LHS.get()->getType() << RHS.get()->getType()
11395 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11396 return QualType();
11397 }
11398 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11399 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11400 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11401 if (LHSBT != RHSBT &&
11402 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11403 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11404 << LHS.get()->getType() << RHS.get()->getType()
11405 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11406 }
11407 }
11408 } else {
11409 // ...else expand RHS to match the number of elements in LHS.
11410 QualType VecTy =
11411 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11412 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11413 }
11414
11415 return LHSType;
11416}
11417
11420 bool IsCompAssign) {
11421 if (!IsCompAssign) {
11422 LHS = S.UsualUnaryConversions(LHS.get());
11423 if (LHS.isInvalid())
11424 return QualType();
11425 }
11426
11427 RHS = S.UsualUnaryConversions(RHS.get());
11428 if (RHS.isInvalid())
11429 return QualType();
11430
11431 QualType LHSType = LHS.get()->getType();
11432 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11433 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11434 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11435 : LHSType;
11436
11437 // Note that RHS might not be a vector
11438 QualType RHSType = RHS.get()->getType();
11439 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11440 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11441 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11442 : RHSType;
11443
11444 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11445 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11446 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11447 << LHSType << RHSType << LHS.get()->getSourceRange();
11448 return QualType();
11449 }
11450
11451 if (!LHSEleType->isIntegerType()) {
11452 S.Diag(Loc, diag::err_typecheck_expect_int)
11453 << LHS.get()->getType() << LHS.get()->getSourceRange();
11454 return QualType();
11455 }
11456
11457 if (!RHSEleType->isIntegerType()) {
11458 S.Diag(Loc, diag::err_typecheck_expect_int)
11459 << RHS.get()->getType() << RHS.get()->getSourceRange();
11460 return QualType();
11461 }
11462
11463 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11464 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11465 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11466 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11467 << LHSType << RHSType << LHS.get()->getSourceRange()
11468 << RHS.get()->getSourceRange();
11469 return QualType();
11470 }
11471
11472 if (!LHSType->isSveVLSBuiltinType()) {
11473 assert(RHSType->isSveVLSBuiltinType());
11474 if (IsCompAssign)
11475 return RHSType;
11476 if (LHSEleType != RHSEleType) {
11477 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11478 LHSEleType = RHSEleType;
11479 }
11480 const llvm::ElementCount VecSize =
11481 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11482 QualType VecTy =
11483 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11484 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11485 LHSType = VecTy;
11486 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11487 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11488 S.Context.getTypeSize(LHSBuiltinTy)) {
11489 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11490 << LHSType << RHSType << LHS.get()->getSourceRange()
11491 << RHS.get()->getSourceRange();
11492 return QualType();
11493 }
11494 } else {
11495 const llvm::ElementCount VecSize =
11496 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11497 if (LHSEleType != RHSEleType) {
11498 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11499 RHSEleType = LHSEleType;
11500 }
11501 QualType VecTy =
11502 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11503 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11504 }
11505
11506 return LHSType;
11507}
11508
11509// C99 6.5.7
11512 bool IsCompAssign) {
11513 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11514
11515 // Vector shifts promote their scalar inputs to vector type.
11516 if (LHS.get()->getType()->isVectorType() ||
11517 RHS.get()->getType()->isVectorType()) {
11518 if (LangOpts.ZVector) {
11519 // The shift operators for the z vector extensions work basically
11520 // like general shifts, except that neither the LHS nor the RHS is
11521 // allowed to be a "vector bool".
11522 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11523 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11524 return InvalidOperands(Loc, LHS, RHS);
11525 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11526 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11527 return InvalidOperands(Loc, LHS, RHS);
11528 }
11529 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11530 }
11531
11532 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11533 RHS.get()->getType()->isSveVLSBuiltinType())
11534 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11535
11536 // Shifts don't perform usual arithmetic conversions, they just do integer
11537 // promotions on each operand. C99 6.5.7p3
11538
11539 // For the LHS, do usual unary conversions, but then reset them away
11540 // if this is a compound assignment.
11541 ExprResult OldLHS = LHS;
11542 LHS = UsualUnaryConversions(LHS.get());
11543 if (LHS.isInvalid())
11544 return QualType();
11545 QualType LHSType = LHS.get()->getType();
11546 if (IsCompAssign) LHS = OldLHS;
11547
11548 // The RHS is simpler.
11549 RHS = UsualUnaryConversions(RHS.get());
11550 if (RHS.isInvalid())
11551 return QualType();
11552 QualType RHSType = RHS.get()->getType();
11553
11554 // C99 6.5.7p2: Each of the operands shall have integer type.
11555 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11556 if ((!LHSType->isFixedPointOrIntegerType() &&
11557 !LHSType->hasIntegerRepresentation()) ||
11558 !RHSType->hasIntegerRepresentation())
11559 return InvalidOperands(Loc, LHS, RHS);
11560
11561 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11562 // hasIntegerRepresentation() above instead of this.
11563 if (isScopedEnumerationType(LHSType) ||
11564 isScopedEnumerationType(RHSType)) {
11565 return InvalidOperands(Loc, LHS, RHS);
11566 }
11567 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11568
11569 // "The type of the result is that of the promoted left operand."
11570 return LHSType;
11571}
11572
11573/// Diagnose bad pointer comparisons.
11575 ExprResult &LHS, ExprResult &RHS,
11576 bool IsError) {
11577 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11578 : diag::ext_typecheck_comparison_of_distinct_pointers)
11579 << LHS.get()->getType() << RHS.get()->getType()
11580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11581}
11582
11583/// Returns false if the pointers are converted to a composite type,
11584/// true otherwise.
11586 ExprResult &LHS, ExprResult &RHS) {
11587 // C++ [expr.rel]p2:
11588 // [...] Pointer conversions (4.10) and qualification
11589 // conversions (4.4) are performed on pointer operands (or on
11590 // a pointer operand and a null pointer constant) to bring
11591 // them to their composite pointer type. [...]
11592 //
11593 // C++ [expr.eq]p1 uses the same notion for (in)equality
11594 // comparisons of pointers.
11595
11596 QualType LHSType = LHS.get()->getType();
11597 QualType RHSType = RHS.get()->getType();
11598 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11599 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11600
11601 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11602 if (T.isNull()) {
11603 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11604 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11605 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11606 else
11607 S.InvalidOperands(Loc, LHS, RHS);
11608 return true;
11609 }
11610
11611 return false;
11612}
11613
11615 ExprResult &LHS,
11616 ExprResult &RHS,
11617 bool IsError) {
11618 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11619 : diag::ext_typecheck_comparison_of_fptr_to_void)
11620 << LHS.get()->getType() << RHS.get()->getType()
11621 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11622}
11623
11625 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11626 case Stmt::ObjCArrayLiteralClass:
11627 case Stmt::ObjCDictionaryLiteralClass:
11628 case Stmt::ObjCStringLiteralClass:
11629 case Stmt::ObjCBoxedExprClass:
11630 return true;
11631 default:
11632 // Note that ObjCBoolLiteral is NOT an object literal!
11633 return false;
11634 }
11635}
11636
11637static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11640
11641 // If this is not actually an Objective-C object, bail out.
11642 if (!Type)
11643 return false;
11644
11645 // Get the LHS object's interface type.
11646 QualType InterfaceType = Type->getPointeeType();
11647
11648 // If the RHS isn't an Objective-C object, bail out.
11649 if (!RHS->getType()->isObjCObjectPointerType())
11650 return false;
11651
11652 // Try to find the -isEqual: method.
11653 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11654 ObjCMethodDecl *Method =
11655 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11656 /*IsInstance=*/true);
11657 if (!Method) {
11658 if (Type->isObjCIdType()) {
11659 // For 'id', just check the global pool.
11660 Method =
11662 /*receiverId=*/true);
11663 } else {
11664 // Check protocols.
11665 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11666 /*IsInstance=*/true);
11667 }
11668 }
11669
11670 if (!Method)
11671 return false;
11672
11673 QualType T = Method->parameters()[0]->getType();
11674 if (!T->isObjCObjectPointerType())
11675 return false;
11676
11677 QualType R = Method->getReturnType();
11678 if (!R->isScalarType())
11679 return false;
11680
11681 return true;
11682}
11683
11685 ExprResult &LHS, ExprResult &RHS,
11687 Expr *Literal;
11688 Expr *Other;
11689 if (isObjCObjectLiteral(LHS)) {
11690 Literal = LHS.get();
11691 Other = RHS.get();
11692 } else {
11693 Literal = RHS.get();
11694 Other = LHS.get();
11695 }
11696
11697 // Don't warn on comparisons against nil.
11698 Other = Other->IgnoreParenCasts();
11699 if (Other->isNullPointerConstant(S.getASTContext(),
11701 return;
11702
11703 // This should be kept in sync with warn_objc_literal_comparison.
11704 // LK_String should always be after the other literals, since it has its own
11705 // warning flag.
11706 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11707 assert(LiteralKind != SemaObjC::LK_Block);
11708 if (LiteralKind == SemaObjC::LK_None) {
11709 llvm_unreachable("Unknown Objective-C object literal kind");
11710 }
11711
11712 if (LiteralKind == SemaObjC::LK_String)
11713 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11714 << Literal->getSourceRange();
11715 else
11716 S.Diag(Loc, diag::warn_objc_literal_comparison)
11717 << LiteralKind << Literal->getSourceRange();
11718
11720 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11721 SourceLocation Start = LHS.get()->getBeginLoc();
11723 CharSourceRange OpRange =
11725
11726 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11727 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11728 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11729 << FixItHint::CreateInsertion(End, "]");
11730 }
11731}
11732
11733/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11736 BinaryOperatorKind Opc) {
11737 // Check that left hand side is !something.
11738 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11739 if (!UO || UO->getOpcode() != UO_LNot) return;
11740
11741 // Only check if the right hand side is non-bool arithmetic type.
11742 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11743
11744 // Make sure that the something in !something is not bool.
11745 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11746 if (SubExpr->isKnownToHaveBooleanValue()) return;
11747
11748 // Emit warning.
11749 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11750 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11751 << Loc << IsBitwiseOp;
11752
11753 // First note suggest !(x < y)
11754 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11755 SourceLocation FirstClose = RHS.get()->getEndLoc();
11756 FirstClose = S.getLocForEndOfToken(FirstClose);
11757 if (FirstClose.isInvalid())
11758 FirstOpen = SourceLocation();
11759 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11760 << IsBitwiseOp
11761 << FixItHint::CreateInsertion(FirstOpen, "(")
11762 << FixItHint::CreateInsertion(FirstClose, ")");
11763
11764 // Second note suggests (!x) < y
11765 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11766 SourceLocation SecondClose = LHS.get()->getEndLoc();
11767 SecondClose = S.getLocForEndOfToken(SecondClose);
11768 if (SecondClose.isInvalid())
11769 SecondOpen = SourceLocation();
11770 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11771 << FixItHint::CreateInsertion(SecondOpen, "(")
11772 << FixItHint::CreateInsertion(SecondClose, ")");
11773}
11774
11775// Returns true if E refers to a non-weak array.
11776static bool checkForArray(const Expr *E) {
11777 const ValueDecl *D = nullptr;
11778 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11779 D = DR->getDecl();
11780 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11781 if (Mem->isImplicitAccess())
11782 D = Mem->getMemberDecl();
11783 }
11784 if (!D)
11785 return false;
11786 return D->getType()->isArrayType() && !D->isWeak();
11787}
11788
11789/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
11790/// pointer and size is an unsigned integer. Return whether the result is
11791/// always true/false.
11792static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
11793 const Expr *RHS,
11794 BinaryOperatorKind Opc) {
11795 if (!LHS->getType()->isPointerType() ||
11797 return std::nullopt;
11798
11799 // Canonicalize to >= or < predicate.
11800 switch (Opc) {
11801 case BO_GE:
11802 case BO_LT:
11803 break;
11804 case BO_GT:
11805 std::swap(LHS, RHS);
11806 Opc = BO_LT;
11807 break;
11808 case BO_LE:
11809 std::swap(LHS, RHS);
11810 Opc = BO_GE;
11811 break;
11812 default:
11813 return std::nullopt;
11814 }
11815
11816 auto *BO = dyn_cast<BinaryOperator>(LHS);
11817 if (!BO || BO->getOpcode() != BO_Add)
11818 return std::nullopt;
11819
11820 Expr *Other;
11821 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
11822 Other = BO->getRHS();
11823 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
11824 Other = BO->getLHS();
11825 else
11826 return std::nullopt;
11827
11828 if (!Other->getType()->isUnsignedIntegerType())
11829 return std::nullopt;
11830
11831 return Opc == BO_GE;
11832}
11833
11834/// Diagnose some forms of syntactically-obvious tautological comparison.
11836 Expr *LHS, Expr *RHS,
11837 BinaryOperatorKind Opc) {
11838 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11839 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11840
11841 QualType LHSType = LHS->getType();
11842 QualType RHSType = RHS->getType();
11843 if (LHSType->hasFloatingRepresentation() ||
11844 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11846 return;
11847
11848 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11849 // Tautological diagnostics.
11850 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11851 return;
11852
11853 // Comparisons between two array types are ill-formed for operator<=>, so
11854 // we shouldn't emit any additional warnings about it.
11855 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11856 return;
11857
11858 // For non-floating point types, check for self-comparisons of the form
11859 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11860 // often indicate logic errors in the program.
11861 //
11862 // NOTE: Don't warn about comparison expressions resulting from macro
11863 // expansion. Also don't warn about comparisons which are only self
11864 // comparisons within a template instantiation. The warnings should catch
11865 // obvious cases in the definition of the template anyways. The idea is to
11866 // warn when the typed comparison operator will always evaluate to the same
11867 // result.
11868
11869 // Used for indexing into %select in warn_comparison_always
11870 enum {
11871 AlwaysConstant,
11872 AlwaysTrue,
11873 AlwaysFalse,
11874 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11875 };
11876
11877 // C++1a [array.comp]:
11878 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11879 // operands of array type.
11880 // C++2a [depr.array.comp]:
11881 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11882 // operands of array type are deprecated.
11883 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
11884 RHSStripped->getType()->isArrayType()) {
11885 auto IsDeprArrayComparionIgnored =
11886 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
11887 auto DiagID = S.getLangOpts().CPlusPlus26
11888 ? diag::warn_array_comparison_cxx26
11889 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
11890 ? diag::warn_array_comparison
11891 : diag::warn_depr_array_comparison;
11892 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
11893 << LHSStripped->getType() << RHSStripped->getType();
11894 // Carry on to produce the tautological comparison warning, if this
11895 // expression is potentially-evaluated, we can resolve the array to a
11896 // non-weak declaration, and so on.
11897 }
11898
11899 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11900 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11901 unsigned Result;
11902 switch (Opc) {
11903 case BO_EQ:
11904 case BO_LE:
11905 case BO_GE:
11906 Result = AlwaysTrue;
11907 break;
11908 case BO_NE:
11909 case BO_LT:
11910 case BO_GT:
11911 Result = AlwaysFalse;
11912 break;
11913 case BO_Cmp:
11914 Result = AlwaysEqual;
11915 break;
11916 default:
11917 Result = AlwaysConstant;
11918 break;
11919 }
11920 S.DiagRuntimeBehavior(Loc, nullptr,
11921 S.PDiag(diag::warn_comparison_always)
11922 << 0 /*self-comparison*/
11923 << Result);
11924 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11925 // What is it always going to evaluate to?
11926 unsigned Result;
11927 switch (Opc) {
11928 case BO_EQ: // e.g. array1 == array2
11929 Result = AlwaysFalse;
11930 break;
11931 case BO_NE: // e.g. array1 != array2
11932 Result = AlwaysTrue;
11933 break;
11934 default: // e.g. array1 <= array2
11935 // The best we can say is 'a constant'
11936 Result = AlwaysConstant;
11937 break;
11938 }
11939 S.DiagRuntimeBehavior(Loc, nullptr,
11940 S.PDiag(diag::warn_comparison_always)
11941 << 1 /*array comparison*/
11942 << Result);
11943 } else if (std::optional<bool> Res =
11944 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
11945 S.DiagRuntimeBehavior(Loc, nullptr,
11946 S.PDiag(diag::warn_comparison_always)
11947 << 2 /*pointer comparison*/
11948 << (*Res ? AlwaysTrue : AlwaysFalse));
11949 }
11950 }
11951
11952 if (isa<CastExpr>(LHSStripped))
11953 LHSStripped = LHSStripped->IgnoreParenCasts();
11954 if (isa<CastExpr>(RHSStripped))
11955 RHSStripped = RHSStripped->IgnoreParenCasts();
11956
11957 // Warn about comparisons against a string constant (unless the other
11958 // operand is null); the user probably wants string comparison function.
11959 Expr *LiteralString = nullptr;
11960 Expr *LiteralStringStripped = nullptr;
11961 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11962 !RHSStripped->isNullPointerConstant(S.Context,
11964 LiteralString = LHS;
11965 LiteralStringStripped = LHSStripped;
11966 } else if ((isa<StringLiteral>(RHSStripped) ||
11967 isa<ObjCEncodeExpr>(RHSStripped)) &&
11968 !LHSStripped->isNullPointerConstant(S.Context,
11970 LiteralString = RHS;
11971 LiteralStringStripped = RHSStripped;
11972 }
11973
11974 if (LiteralString) {
11975 S.DiagRuntimeBehavior(Loc, nullptr,
11976 S.PDiag(diag::warn_stringcompare)
11977 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11978 << LiteralString->getSourceRange());
11979 }
11980}
11981
11983 switch (CK) {
11984 default: {
11985#ifndef NDEBUG
11986 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11987 << "\n";
11988#endif
11989 llvm_unreachable("unhandled cast kind");
11990 }
11991 case CK_UserDefinedConversion:
11992 return ICK_Identity;
11993 case CK_LValueToRValue:
11994 return ICK_Lvalue_To_Rvalue;
11995 case CK_ArrayToPointerDecay:
11996 return ICK_Array_To_Pointer;
11997 case CK_FunctionToPointerDecay:
11999 case CK_IntegralCast:
12001 case CK_FloatingCast:
12003 case CK_IntegralToFloating:
12004 case CK_FloatingToIntegral:
12005 return ICK_Floating_Integral;
12006 case CK_IntegralComplexCast:
12007 case CK_FloatingComplexCast:
12008 case CK_FloatingComplexToIntegralComplex:
12009 case CK_IntegralComplexToFloatingComplex:
12011 case CK_FloatingComplexToReal:
12012 case CK_FloatingRealToComplex:
12013 case CK_IntegralComplexToReal:
12014 case CK_IntegralRealToComplex:
12015 return ICK_Complex_Real;
12016 case CK_HLSLArrayRValue:
12017 return ICK_HLSL_Array_RValue;
12018 }
12019}
12020
12022 QualType FromType,
12024 // Check for a narrowing implicit conversion.
12027 SCS.setToType(0, FromType);
12028 SCS.setToType(1, ToType);
12029 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12030 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12031
12032 APValue PreNarrowingValue;
12033 QualType PreNarrowingType;
12034 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12035 PreNarrowingType,
12036 /*IgnoreFloatToIntegralConversion*/ true)) {
12038 // Implicit conversion to a narrower type, but the expression is
12039 // value-dependent so we can't tell whether it's actually narrowing.
12040 case NK_Not_Narrowing:
12041 return false;
12042
12044 // Implicit conversion to a narrower type, and the value is not a constant
12045 // expression.
12046 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12047 << /*Constant*/ 1
12048 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12049 return true;
12050
12052 // Implicit conversion to a narrower type, and the value is not a constant
12053 // expression.
12054 case NK_Type_Narrowing:
12055 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12056 << /*Constant*/ 0 << FromType << ToType;
12057 // TODO: It's not a constant expression, but what if the user intended it
12058 // to be? Can we produce notes to help them figure out why it isn't?
12059 return true;
12060 }
12061 llvm_unreachable("unhandled case in switch");
12062}
12063
12065 ExprResult &LHS,
12066 ExprResult &RHS,
12068 QualType LHSType = LHS.get()->getType();
12069 QualType RHSType = RHS.get()->getType();
12070 // Dig out the original argument type and expression before implicit casts
12071 // were applied. These are the types/expressions we need to check the
12072 // [expr.spaceship] requirements against.
12073 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12074 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12075 QualType LHSStrippedType = LHSStripped.get()->getType();
12076 QualType RHSStrippedType = RHSStripped.get()->getType();
12077
12078 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12079 // other is not, the program is ill-formed.
12080 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12081 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12082 return QualType();
12083 }
12084
12085 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12086 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12087 RHSStrippedType->isEnumeralType();
12088 if (NumEnumArgs == 1) {
12089 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12090 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12091 if (OtherTy->hasFloatingRepresentation()) {
12092 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12093 return QualType();
12094 }
12095 }
12096 if (NumEnumArgs == 2) {
12097 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12098 // type E, the operator yields the result of converting the operands
12099 // to the underlying type of E and applying <=> to the converted operands.
12100 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12101 S.InvalidOperands(Loc, LHS, RHS);
12102 return QualType();
12103 }
12104 QualType IntType =
12105 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12106 assert(IntType->isArithmeticType());
12107
12108 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12109 // promote the boolean type, and all other promotable integer types, to
12110 // avoid this.
12111 if (S.Context.isPromotableIntegerType(IntType))
12112 IntType = S.Context.getPromotedIntegerType(IntType);
12113
12114 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12115 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12116 LHSType = RHSType = IntType;
12117 }
12118
12119 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12120 // usual arithmetic conversions are applied to the operands.
12121 QualType Type =
12123 if (LHS.isInvalid() || RHS.isInvalid())
12124 return QualType();
12125 if (Type.isNull())
12126 return S.InvalidOperands(Loc, LHS, RHS);
12127
12128 std::optional<ComparisonCategoryType> CCT =
12130 if (!CCT)
12131 return S.InvalidOperands(Loc, LHS, RHS);
12132
12133 bool HasNarrowing = checkThreeWayNarrowingConversion(
12134 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12135 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12136 RHS.get()->getBeginLoc());
12137 if (HasNarrowing)
12138 return QualType();
12139
12140 assert(!Type.isNull() && "composite type for <=> has not been set");
12141
12144}
12145
12147 ExprResult &RHS,
12149 BinaryOperatorKind Opc) {
12150 if (Opc == BO_Cmp)
12151 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12152
12153 // C99 6.5.8p3 / C99 6.5.9p4
12154 QualType Type =
12156 if (LHS.isInvalid() || RHS.isInvalid())
12157 return QualType();
12158 if (Type.isNull())
12159 return S.InvalidOperands(Loc, LHS, RHS);
12160 assert(Type->isArithmeticType() || Type->isEnumeralType());
12161
12163 return S.InvalidOperands(Loc, LHS, RHS);
12164
12165 // Check for comparisons of floating point operands using != and ==.
12167 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12168
12169 // The result of comparisons is 'bool' in C++, 'int' in C.
12171}
12172
12174 if (!NullE.get()->getType()->isAnyPointerType())
12175 return;
12176 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12177 if (!E.get()->getType()->isAnyPointerType() &&
12181 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12182 if (CL->getValue() == 0)
12183 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12184 << NullValue
12186 NullValue ? "NULL" : "(void *)0");
12187 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12188 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12190 if (T == Context.CharTy)
12191 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12192 << NullValue
12194 NullValue ? "NULL" : "(void *)0");
12195 }
12196 }
12197}
12198
12199// C99 6.5.8, C++ [expr.rel]
12202 BinaryOperatorKind Opc) {
12203 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12204 bool IsThreeWay = Opc == BO_Cmp;
12205 bool IsOrdered = IsRelational || IsThreeWay;
12206 auto IsAnyPointerType = [](ExprResult E) {
12207 QualType Ty = E.get()->getType();
12208 return Ty->isPointerType() || Ty->isMemberPointerType();
12209 };
12210
12211 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12212 // type, array-to-pointer, ..., conversions are performed on both operands to
12213 // bring them to their composite type.
12214 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12215 // any type-related checks.
12216 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12218 if (LHS.isInvalid())
12219 return QualType();
12221 if (RHS.isInvalid())
12222 return QualType();
12223 } else {
12224 LHS = DefaultLvalueConversion(LHS.get());
12225 if (LHS.isInvalid())
12226 return QualType();
12227 RHS = DefaultLvalueConversion(RHS.get());
12228 if (RHS.isInvalid())
12229 return QualType();
12230 }
12231
12232 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12236 }
12237
12238 // Handle vector comparisons separately.
12239 if (LHS.get()->getType()->isVectorType() ||
12240 RHS.get()->getType()->isVectorType())
12241 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12242
12243 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12244 RHS.get()->getType()->isSveVLSBuiltinType())
12245 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12246
12247 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12248 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12249
12250 QualType LHSType = LHS.get()->getType();
12251 QualType RHSType = RHS.get()->getType();
12252 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12253 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12254 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12255
12256 if ((LHSType->isPointerType() &&
12258 (RHSType->isPointerType() &&
12260 return InvalidOperands(Loc, LHS, RHS);
12261
12262 const Expr::NullPointerConstantKind LHSNullKind =
12264 const Expr::NullPointerConstantKind RHSNullKind =
12266 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12267 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12268
12269 auto computeResultTy = [&]() {
12270 if (Opc != BO_Cmp)
12272 assert(getLangOpts().CPlusPlus);
12273 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12274
12275 QualType CompositeTy = LHS.get()->getType();
12276 assert(!CompositeTy->isReferenceType());
12277
12278 std::optional<ComparisonCategoryType> CCT =
12280 if (!CCT)
12281 return InvalidOperands(Loc, LHS, RHS);
12282
12283 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12284 // P0946R0: Comparisons between a null pointer constant and an object
12285 // pointer result in std::strong_equality, which is ill-formed under
12286 // P1959R0.
12287 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12288 << (LHSIsNull ? LHS.get()->getSourceRange()
12289 : RHS.get()->getSourceRange());
12290 return QualType();
12291 }
12292
12295 };
12296
12297 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12298 bool IsEquality = Opc == BO_EQ;
12299 if (RHSIsNull)
12300 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12301 RHS.get()->getSourceRange());
12302 else
12303 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12304 LHS.get()->getSourceRange());
12305 }
12306
12307 if (IsOrdered && LHSType->isFunctionPointerType() &&
12308 RHSType->isFunctionPointerType()) {
12309 // Valid unless a relational comparison of function pointers
12310 bool IsError = Opc == BO_Cmp;
12311 auto DiagID =
12312 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12313 : getLangOpts().CPlusPlus
12314 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12315 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12316 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12317 << RHS.get()->getSourceRange();
12318 if (IsError)
12319 return QualType();
12320 }
12321
12322 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12323 (RHSType->isIntegerType() && !RHSIsNull)) {
12324 // Skip normal pointer conversion checks in this case; we have better
12325 // diagnostics for this below.
12326 } else if (getLangOpts().CPlusPlus) {
12327 // Equality comparison of a function pointer to a void pointer is invalid,
12328 // but we allow it as an extension.
12329 // FIXME: If we really want to allow this, should it be part of composite
12330 // pointer type computation so it works in conditionals too?
12331 if (!IsOrdered &&
12332 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12333 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12334 // This is a gcc extension compatibility comparison.
12335 // In a SFINAE context, we treat this as a hard error to maintain
12336 // conformance with the C++ standard.
12338 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12339
12340 if (isSFINAEContext())
12341 return QualType();
12342
12343 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12344 return computeResultTy();
12345 }
12346
12347 // C++ [expr.eq]p2:
12348 // If at least one operand is a pointer [...] bring them to their
12349 // composite pointer type.
12350 // C++ [expr.spaceship]p6
12351 // If at least one of the operands is of pointer type, [...] bring them
12352 // to their composite pointer type.
12353 // C++ [expr.rel]p2:
12354 // If both operands are pointers, [...] bring them to their composite
12355 // pointer type.
12356 // For <=>, the only valid non-pointer types are arrays and functions, and
12357 // we already decayed those, so this is really the same as the relational
12358 // comparison rule.
12359 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12360 (IsOrdered ? 2 : 1) &&
12361 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12362 RHSType->isObjCObjectPointerType()))) {
12363 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12364 return QualType();
12365 return computeResultTy();
12366 }
12367 } else if (LHSType->isPointerType() &&
12368 RHSType->isPointerType()) { // C99 6.5.8p2
12369 // All of the following pointer-related warnings are GCC extensions, except
12370 // when handling null pointer constants.
12371 QualType LCanPointeeTy =
12373 QualType RCanPointeeTy =
12375
12376 // C99 6.5.9p2 and C99 6.5.8p2
12377 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12378 RCanPointeeTy.getUnqualifiedType())) {
12379 if (IsRelational) {
12380 // Pointers both need to point to complete or incomplete types
12381 if ((LCanPointeeTy->isIncompleteType() !=
12382 RCanPointeeTy->isIncompleteType()) &&
12383 !getLangOpts().C11) {
12384 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12385 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12386 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12387 << RCanPointeeTy->isIncompleteType();
12388 }
12389 }
12390 } else if (!IsRelational &&
12391 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12392 // Valid unless comparison between non-null pointer and function pointer
12393 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12394 && !LHSIsNull && !RHSIsNull)
12396 /*isError*/false);
12397 } else {
12398 // Invalid
12399 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12400 }
12401 if (LCanPointeeTy != RCanPointeeTy) {
12402 // Treat NULL constant as a special case in OpenCL.
12403 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12404 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12405 getASTContext())) {
12406 Diag(Loc,
12407 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12408 << LHSType << RHSType << 0 /* comparison */
12409 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12410 }
12411 }
12412 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12413 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12414 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12415 : CK_BitCast;
12416 if (LHSIsNull && !RHSIsNull)
12417 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12418 else
12419 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12420 }
12421 return computeResultTy();
12422 }
12423
12424
12425 // C++ [expr.eq]p4:
12426 // Two operands of type std::nullptr_t or one operand of type
12427 // std::nullptr_t and the other a null pointer constant compare
12428 // equal.
12429 // C23 6.5.9p5:
12430 // If both operands have type nullptr_t or one operand has type nullptr_t
12431 // and the other is a null pointer constant, they compare equal if the
12432 // former is a null pointer.
12433 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12434 if (LHSType->isNullPtrType()) {
12435 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12436 return computeResultTy();
12437 }
12438 if (RHSType->isNullPtrType()) {
12439 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12440 return computeResultTy();
12441 }
12442 }
12443
12444 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12445 // C23 6.5.9p6:
12446 // Otherwise, at least one operand is a pointer. If one is a pointer and
12447 // the other is a null pointer constant or has type nullptr_t, they
12448 // compare equal
12449 if (LHSIsNull && RHSType->isPointerType()) {
12450 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12451 return computeResultTy();
12452 }
12453 if (RHSIsNull && LHSType->isPointerType()) {
12454 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12455 return computeResultTy();
12456 }
12457 }
12458
12459 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12460 // These aren't covered by the composite pointer type rules.
12461 if (!IsOrdered && RHSType->isNullPtrType() &&
12462 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12463 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12464 return computeResultTy();
12465 }
12466 if (!IsOrdered && LHSType->isNullPtrType() &&
12467 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12468 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12469 return computeResultTy();
12470 }
12471
12472 if (getLangOpts().CPlusPlus) {
12473 if (IsRelational &&
12474 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12475 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12476 // HACK: Relational comparison of nullptr_t against a pointer type is
12477 // invalid per DR583, but we allow it within std::less<> and friends,
12478 // since otherwise common uses of it break.
12479 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12480 // friends to have std::nullptr_t overload candidates.
12481 DeclContext *DC = CurContext;
12482 if (isa<FunctionDecl>(DC))
12483 DC = DC->getParent();
12484 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12485 if (CTSD->isInStdNamespace() &&
12486 llvm::StringSwitch<bool>(CTSD->getName())
12487 .Cases("less", "less_equal", "greater", "greater_equal", true)
12488 .Default(false)) {
12489 if (RHSType->isNullPtrType())
12490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12491 else
12492 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12493 return computeResultTy();
12494 }
12495 }
12496 }
12497
12498 // C++ [expr.eq]p2:
12499 // If at least one operand is a pointer to member, [...] bring them to
12500 // their composite pointer type.
12501 if (!IsOrdered &&
12502 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12503 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12504 return QualType();
12505 else
12506 return computeResultTy();
12507 }
12508 }
12509
12510 // Handle block pointer types.
12511 if (!IsOrdered && LHSType->isBlockPointerType() &&
12512 RHSType->isBlockPointerType()) {
12513 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12514 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12515
12516 if (!LHSIsNull && !RHSIsNull &&
12517 !Context.typesAreCompatible(lpointee, rpointee)) {
12518 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12519 << LHSType << RHSType << LHS.get()->getSourceRange()
12520 << RHS.get()->getSourceRange();
12521 }
12522 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12523 return computeResultTy();
12524 }
12525
12526 // Allow block pointers to be compared with null pointer constants.
12527 if (!IsOrdered
12528 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12529 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12530 if (!LHSIsNull && !RHSIsNull) {
12531 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12533 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12534 ->getPointeeType()->isVoidType())))
12535 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12536 << LHSType << RHSType << LHS.get()->getSourceRange()
12537 << RHS.get()->getSourceRange();
12538 }
12539 if (LHSIsNull && !RHSIsNull)
12540 LHS = ImpCastExprToType(LHS.get(), RHSType,
12541 RHSType->isPointerType() ? CK_BitCast
12542 : CK_AnyPointerToBlockPointerCast);
12543 else
12544 RHS = ImpCastExprToType(RHS.get(), LHSType,
12545 LHSType->isPointerType() ? CK_BitCast
12546 : CK_AnyPointerToBlockPointerCast);
12547 return computeResultTy();
12548 }
12549
12550 if (LHSType->isObjCObjectPointerType() ||
12551 RHSType->isObjCObjectPointerType()) {
12552 const PointerType *LPT = LHSType->getAs<PointerType>();
12553 const PointerType *RPT = RHSType->getAs<PointerType>();
12554 if (LPT || RPT) {
12555 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12556 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12557
12558 if (!LPtrToVoid && !RPtrToVoid &&
12559 !Context.typesAreCompatible(LHSType, RHSType)) {
12560 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12561 /*isError*/false);
12562 }
12563 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12564 // the RHS, but we have test coverage for this behavior.
12565 // FIXME: Consider using convertPointersToCompositeType in C++.
12566 if (LHSIsNull && !RHSIsNull) {
12567 Expr *E = LHS.get();
12568 if (getLangOpts().ObjCAutoRefCount)
12569 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12571 LHS = ImpCastExprToType(E, RHSType,
12572 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12573 }
12574 else {
12575 Expr *E = RHS.get();
12576 if (getLangOpts().ObjCAutoRefCount)
12577 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12579 /*Diagnose=*/true,
12580 /*DiagnoseCFAudited=*/false, Opc);
12581 RHS = ImpCastExprToType(E, LHSType,
12582 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12583 }
12584 return computeResultTy();
12585 }
12586 if (LHSType->isObjCObjectPointerType() &&
12587 RHSType->isObjCObjectPointerType()) {
12588 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12589 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12590 /*isError*/false);
12592 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12593
12594 if (LHSIsNull && !RHSIsNull)
12595 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12596 else
12597 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12598 return computeResultTy();
12599 }
12600
12601 if (!IsOrdered && LHSType->isBlockPointerType() &&
12603 LHS = ImpCastExprToType(LHS.get(), RHSType,
12604 CK_BlockPointerToObjCPointerCast);
12605 return computeResultTy();
12606 } else if (!IsOrdered &&
12608 RHSType->isBlockPointerType()) {
12609 RHS = ImpCastExprToType(RHS.get(), LHSType,
12610 CK_BlockPointerToObjCPointerCast);
12611 return computeResultTy();
12612 }
12613 }
12614 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12615 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12616 unsigned DiagID = 0;
12617 bool isError = false;
12618 if (LangOpts.DebuggerSupport) {
12619 // Under a debugger, allow the comparison of pointers to integers,
12620 // since users tend to want to compare addresses.
12621 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12622 (RHSIsNull && RHSType->isIntegerType())) {
12623 if (IsOrdered) {
12624 isError = getLangOpts().CPlusPlus;
12625 DiagID =
12626 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12627 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12628 }
12629 } else if (getLangOpts().CPlusPlus) {
12630 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12631 isError = true;
12632 } else if (IsOrdered)
12633 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12634 else
12635 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12636
12637 if (DiagID) {
12638 Diag(Loc, DiagID)
12639 << LHSType << RHSType << LHS.get()->getSourceRange()
12640 << RHS.get()->getSourceRange();
12641 if (isError)
12642 return QualType();
12643 }
12644
12645 if (LHSType->isIntegerType())
12646 LHS = ImpCastExprToType(LHS.get(), RHSType,
12647 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12648 else
12649 RHS = ImpCastExprToType(RHS.get(), LHSType,
12650 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12651 return computeResultTy();
12652 }
12653
12654 // Handle block pointers.
12655 if (!IsOrdered && RHSIsNull
12656 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12657 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12658 return computeResultTy();
12659 }
12660 if (!IsOrdered && LHSIsNull
12661 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12662 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12663 return computeResultTy();
12664 }
12665
12666 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12667 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12668 return computeResultTy();
12669 }
12670
12671 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12672 return computeResultTy();
12673 }
12674
12675 if (LHSIsNull && RHSType->isQueueT()) {
12676 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12677 return computeResultTy();
12678 }
12679
12680 if (LHSType->isQueueT() && RHSIsNull) {
12681 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12682 return computeResultTy();
12683 }
12684 }
12685
12686 return InvalidOperands(Loc, LHS, RHS);
12687}
12688
12690 const VectorType *VTy = V->castAs<VectorType>();
12691 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12692
12693 if (isa<ExtVectorType>(VTy)) {
12694 if (VTy->isExtVectorBoolType())
12696 if (TypeSize == Context.getTypeSize(Context.CharTy))
12698 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12700 if (TypeSize == Context.getTypeSize(Context.IntTy))
12702 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12704 if (TypeSize == Context.getTypeSize(Context.LongTy))
12706 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12707 "Unhandled vector element size in vector compare");
12709 }
12710
12711 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12714 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12717 if (TypeSize == Context.getTypeSize(Context.LongTy))
12720 if (TypeSize == Context.getTypeSize(Context.IntTy))
12723 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12726 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12727 "Unhandled vector element size in vector compare");
12730}
12731
12733 const BuiltinType *VTy = V->castAs<BuiltinType>();
12734 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12735
12736 const QualType ETy = V->getSveEltType(Context);
12737 const auto TypeSize = Context.getTypeSize(ETy);
12738
12739 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12740 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12741 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12742}
12743
12746 BinaryOperatorKind Opc) {
12747 if (Opc == BO_Cmp) {
12748 Diag(Loc, diag::err_three_way_vector_comparison);
12749 return QualType();
12750 }
12751
12752 // Check to make sure we're operating on vectors of the same type and width,
12753 // Allowing one side to be a scalar of element type.
12754 QualType vType =
12755 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12756 /*AllowBothBool*/ true,
12757 /*AllowBoolConversions*/ getLangOpts().ZVector,
12758 /*AllowBooleanOperation*/ true,
12759 /*ReportInvalid*/ true);
12760 if (vType.isNull())
12761 return vType;
12762
12763 QualType LHSType = LHS.get()->getType();
12764
12765 // Determine the return type of a vector compare. By default clang will return
12766 // a scalar for all vector compares except vector bool and vector pixel.
12767 // With the gcc compiler we will always return a vector type and with the xl
12768 // compiler we will always return a scalar type. This switch allows choosing
12769 // which behavior is prefered.
12770 if (getLangOpts().AltiVec) {
12771 switch (getLangOpts().getAltivecSrcCompat()) {
12773 // If AltiVec, the comparison results in a numeric type, i.e.
12774 // bool for C++, int for C
12775 if (vType->castAs<VectorType>()->getVectorKind() ==
12778 else
12779 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12780 break;
12782 // For GCC we always return the vector type.
12783 break;
12786 break;
12787 }
12788 }
12789
12790 // For non-floating point types, check for self-comparisons of the form
12791 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12792 // often indicate logic errors in the program.
12793 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12794
12795 // Check for comparisons of floating point operands using != and ==.
12796 if (LHSType->hasFloatingRepresentation()) {
12797 assert(RHS.get()->getType()->hasFloatingRepresentation());
12798 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12799 }
12800
12801 // Return a signed type for the vector.
12802 return GetSignedVectorType(vType);
12803}
12804
12806 ExprResult &RHS,
12808 BinaryOperatorKind Opc) {
12809 if (Opc == BO_Cmp) {
12810 Diag(Loc, diag::err_three_way_vector_comparison);
12811 return QualType();
12812 }
12813
12814 // Check to make sure we're operating on vectors of the same type and width,
12815 // Allowing one side to be a scalar of element type.
12817 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12818
12819 if (vType.isNull())
12820 return vType;
12821
12822 QualType LHSType = LHS.get()->getType();
12823
12824 // For non-floating point types, check for self-comparisons of the form
12825 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12826 // often indicate logic errors in the program.
12827 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12828
12829 // Check for comparisons of floating point operands using != and ==.
12830 if (LHSType->hasFloatingRepresentation()) {
12831 assert(RHS.get()->getType()->hasFloatingRepresentation());
12832 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12833 }
12834
12835 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12836 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12837
12838 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12839 RHSBuiltinTy->isSVEBool())
12840 return LHSType;
12841
12842 // Return a signed type for the vector.
12843 return GetSignedSizelessVectorType(vType);
12844}
12845
12846static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12847 const ExprResult &XorRHS,
12848 const SourceLocation Loc) {
12849 // Do not diagnose macros.
12850 if (Loc.isMacroID())
12851 return;
12852
12853 // Do not diagnose if both LHS and RHS are macros.
12854 if (XorLHS.get()->getExprLoc().isMacroID() &&
12855 XorRHS.get()->getExprLoc().isMacroID())
12856 return;
12857
12858 bool Negative = false;
12859 bool ExplicitPlus = false;
12860 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12861 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12862
12863 if (!LHSInt)
12864 return;
12865 if (!RHSInt) {
12866 // Check negative literals.
12867 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12868 UnaryOperatorKind Opc = UO->getOpcode();
12869 if (Opc != UO_Minus && Opc != UO_Plus)
12870 return;
12871 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12872 if (!RHSInt)
12873 return;
12874 Negative = (Opc == UO_Minus);
12875 ExplicitPlus = !Negative;
12876 } else {
12877 return;
12878 }
12879 }
12880
12881 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12882 llvm::APInt RightSideValue = RHSInt->getValue();
12883 if (LeftSideValue != 2 && LeftSideValue != 10)
12884 return;
12885
12886 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12887 return;
12888
12890 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12891 llvm::StringRef ExprStr =
12893
12894 CharSourceRange XorRange =
12896 llvm::StringRef XorStr =
12898 // Do not diagnose if xor keyword/macro is used.
12899 if (XorStr == "xor")
12900 return;
12901
12902 std::string LHSStr = std::string(Lexer::getSourceText(
12903 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12904 S.getSourceManager(), S.getLangOpts()));
12905 std::string RHSStr = std::string(Lexer::getSourceText(
12906 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12907 S.getSourceManager(), S.getLangOpts()));
12908
12909 if (Negative) {
12910 RightSideValue = -RightSideValue;
12911 RHSStr = "-" + RHSStr;
12912 } else if (ExplicitPlus) {
12913 RHSStr = "+" + RHSStr;
12914 }
12915
12916 StringRef LHSStrRef = LHSStr;
12917 StringRef RHSStrRef = RHSStr;
12918 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12919 // literals.
12920 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12921 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12922 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12923 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12924 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12925 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12926 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12927 return;
12928
12929 bool SuggestXor =
12930 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12931 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12932 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12933 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12934 std::string SuggestedExpr = "1 << " + RHSStr;
12935 bool Overflow = false;
12936 llvm::APInt One = (LeftSideValue - 1);
12937 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12938 if (Overflow) {
12939 if (RightSideIntValue < 64)
12940 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12941 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12942 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12943 else if (RightSideIntValue == 64)
12944 S.Diag(Loc, diag::warn_xor_used_as_pow)
12945 << ExprStr << toString(XorValue, 10, true);
12946 else
12947 return;
12948 } else {
12949 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12950 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12951 << toString(PowValue, 10, true)
12953 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12954 }
12955
12956 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12957 << ("0x2 ^ " + RHSStr) << SuggestXor;
12958 } else if (LeftSideValue == 10) {
12959 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12960 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12961 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12962 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12963 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12964 << ("0xA ^ " + RHSStr) << SuggestXor;
12965 }
12966}
12967
12970 BinaryOperatorKind Opc) {
12971 // Ensure that either both operands are of the same vector type, or
12972 // one operand is of a vector type and the other is of its element type.
12973 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12974 /*AllowBothBool*/ true,
12975 /*AllowBoolConversions*/ false,
12976 /*AllowBooleanOperation*/ false,
12977 /*ReportInvalid*/ false);
12978 if (vType.isNull())
12979 return InvalidOperands(Loc, LHS, RHS);
12980 if (getLangOpts().OpenCL &&
12981 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12983 return InvalidOperands(Loc, LHS, RHS);
12984 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12985 // usage of the logical operators && and || with vectors in C. This
12986 // check could be notionally dropped.
12987 if (!getLangOpts().CPlusPlus &&
12988 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12989 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12990 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
12991 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
12992 // `select` functions.
12993 if (getLangOpts().HLSL &&
12994 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
12995 (void)InvalidOperands(Loc, LHS, RHS);
12996 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
12997 return QualType();
12998 }
12999
13000 return GetSignedVectorType(LHS.get()->getType());
13001}
13002
13005 bool IsCompAssign) {
13006 if (!IsCompAssign) {
13008 if (LHS.isInvalid())
13009 return QualType();
13010 }
13012 if (RHS.isInvalid())
13013 return QualType();
13014
13015 // For conversion purposes, we ignore any qualifiers.
13016 // For example, "const float" and "float" are equivalent.
13017 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13018 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13019
13020 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13021 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13022 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13023
13024 if (Context.hasSameType(LHSType, RHSType))
13025 return Context.getCommonSugaredType(LHSType, RHSType);
13026
13027 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13028 // case we have to return InvalidOperands.
13029 ExprResult OriginalLHS = LHS;
13030 ExprResult OriginalRHS = RHS;
13031 if (LHSMatType && !RHSMatType) {
13032 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13033 if (!RHS.isInvalid())
13034 return LHSType;
13035
13036 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13037 }
13038
13039 if (!LHSMatType && RHSMatType) {
13040 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13041 if (!LHS.isInvalid())
13042 return RHSType;
13043 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13044 }
13045
13046 return InvalidOperands(Loc, LHS, RHS);
13047}
13048
13051 bool IsCompAssign) {
13052 if (!IsCompAssign) {
13054 if (LHS.isInvalid())
13055 return QualType();
13056 }
13058 if (RHS.isInvalid())
13059 return QualType();
13060
13061 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13062 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13063 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13064
13065 if (LHSMatType && RHSMatType) {
13066 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13067 return InvalidOperands(Loc, LHS, RHS);
13068
13069 if (Context.hasSameType(LHSMatType, RHSMatType))
13071 LHS.get()->getType().getUnqualifiedType(),
13072 RHS.get()->getType().getUnqualifiedType());
13073
13074 QualType LHSELTy = LHSMatType->getElementType(),
13075 RHSELTy = RHSMatType->getElementType();
13076 if (!Context.hasSameType(LHSELTy, RHSELTy))
13077 return InvalidOperands(Loc, LHS, RHS);
13078
13080 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13081 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13082 }
13083 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13084}
13085
13087 switch (Opc) {
13088 default:
13089 return false;
13090 case BO_And:
13091 case BO_AndAssign:
13092 case BO_Or:
13093 case BO_OrAssign:
13094 case BO_Xor:
13095 case BO_XorAssign:
13096 return true;
13097 }
13098}
13099
13102 BinaryOperatorKind Opc) {
13103 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13104
13105 bool IsCompAssign =
13106 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13107
13108 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13109
13110 if (LHS.get()->getType()->isVectorType() ||
13111 RHS.get()->getType()->isVectorType()) {
13112 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13114 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13115 /*AllowBothBool*/ true,
13116 /*AllowBoolConversions*/ getLangOpts().ZVector,
13117 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13118 /*ReportInvalid*/ true);
13119 return InvalidOperands(Loc, LHS, RHS);
13120 }
13121
13122 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13123 RHS.get()->getType()->isSveVLSBuiltinType()) {
13124 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13126 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13128 return InvalidOperands(Loc, LHS, RHS);
13129 }
13130
13131 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13132 RHS.get()->getType()->isSveVLSBuiltinType()) {
13133 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13135 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13137 return InvalidOperands(Loc, LHS, RHS);
13138 }
13139
13140 if (Opc == BO_And)
13141 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13142
13143 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13145 return InvalidOperands(Loc, LHS, RHS);
13146
13147 ExprResult LHSResult = LHS, RHSResult = RHS;
13149 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13150 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13151 return QualType();
13152 LHS = LHSResult.get();
13153 RHS = RHSResult.get();
13154
13155 if (Opc == BO_Xor)
13156 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13157
13158 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13159 return compType;
13160 return InvalidOperands(Loc, LHS, RHS);
13161}
13162
13163// C99 6.5.[13,14]
13166 BinaryOperatorKind Opc) {
13167 // Check vector operands differently.
13168 if (LHS.get()->getType()->isVectorType() ||
13169 RHS.get()->getType()->isVectorType())
13170 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13171
13172 bool EnumConstantInBoolContext = false;
13173 for (const ExprResult &HS : {LHS, RHS}) {
13174 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13175 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13176 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13177 EnumConstantInBoolContext = true;
13178 }
13179 }
13180
13181 if (EnumConstantInBoolContext)
13182 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13183
13184 // WebAssembly tables can't be used with logical operators.
13185 QualType LHSTy = LHS.get()->getType();
13186 QualType RHSTy = RHS.get()->getType();
13187 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13188 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13189 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13190 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13191 return InvalidOperands(Loc, LHS, RHS);
13192 }
13193
13194 // Diagnose cases where the user write a logical and/or but probably meant a
13195 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13196 // is a constant.
13197 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13198 !LHS.get()->getType()->isBooleanType() &&
13199 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13200 // Don't warn in macros or template instantiations.
13202 // If the RHS can be constant folded, and if it constant folds to something
13203 // that isn't 0 or 1 (which indicate a potential logical operation that
13204 // happened to fold to true/false) then warn.
13205 // Parens on the RHS are ignored.
13206 Expr::EvalResult EVResult;
13207 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13208 llvm::APSInt Result = EVResult.Val.getInt();
13209 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13210 !RHS.get()->getExprLoc().isMacroID()) ||
13211 (Result != 0 && Result != 1)) {
13212 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13213 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13214 // Suggest replacing the logical operator with the bitwise version
13215 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13216 << (Opc == BO_LAnd ? "&" : "|")
13219 Opc == BO_LAnd ? "&" : "|");
13220 if (Opc == BO_LAnd)
13221 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13222 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13225 RHS.get()->getEndLoc()));
13226 }
13227 }
13228 }
13229
13230 if (!Context.getLangOpts().CPlusPlus) {
13231 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13232 // not operate on the built-in scalar and vector float types.
13233 if (Context.getLangOpts().OpenCL &&
13234 Context.getLangOpts().OpenCLVersion < 120) {
13235 if (LHS.get()->getType()->isFloatingType() ||
13236 RHS.get()->getType()->isFloatingType())
13237 return InvalidOperands(Loc, LHS, RHS);
13238 }
13239
13240 LHS = UsualUnaryConversions(LHS.get());
13241 if (LHS.isInvalid())
13242 return QualType();
13243
13244 RHS = UsualUnaryConversions(RHS.get());
13245 if (RHS.isInvalid())
13246 return QualType();
13247
13248 if (!LHS.get()->getType()->isScalarType() ||
13249 !RHS.get()->getType()->isScalarType())
13250 return InvalidOperands(Loc, LHS, RHS);
13251
13252 return Context.IntTy;
13253 }
13254
13255 // The following is safe because we only use this method for
13256 // non-overloadable operands.
13257
13258 // C++ [expr.log.and]p1
13259 // C++ [expr.log.or]p1
13260 // The operands are both contextually converted to type bool.
13262 if (LHSRes.isInvalid())
13263 return InvalidOperands(Loc, LHS, RHS);
13264 LHS = LHSRes;
13265
13267 if (RHSRes.isInvalid())
13268 return InvalidOperands(Loc, LHS, RHS);
13269 RHS = RHSRes;
13270
13271 // C++ [expr.log.and]p2
13272 // C++ [expr.log.or]p2
13273 // The result is a bool.
13274 return Context.BoolTy;
13275}
13276
13277static bool IsReadonlyMessage(Expr *E, Sema &S) {
13278 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13279 if (!ME) return false;
13280 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13281 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13283 if (!Base) return false;
13284 return Base->getMethodDecl() != nullptr;
13285}
13286
13287/// Is the given expression (which must be 'const') a reference to a
13288/// variable which was originally non-const, but which has become
13289/// 'const' due to being captured within a block?
13292 assert(E->isLValue() && E->getType().isConstQualified());
13293 E = E->IgnoreParens();
13294
13295 // Must be a reference to a declaration from an enclosing scope.
13296 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13297 if (!DRE) return NCCK_None;
13299
13300 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13301
13302 // The declaration must be a value which is not declared 'const'.
13303 if (!Value || Value->getType().isConstQualified())
13304 return NCCK_None;
13305
13306 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13307 if (Binding) {
13308 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13309 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13310 return NCCK_Lambda;
13311 }
13312
13313 VarDecl *Var = dyn_cast<VarDecl>(Value);
13314 if (!Var)
13315 return NCCK_None;
13316
13317 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13318
13319 // Decide whether the first capture was for a block or a lambda.
13320 DeclContext *DC = S.CurContext, *Prev = nullptr;
13321 // Decide whether the first capture was for a block or a lambda.
13322 while (DC) {
13323 // For init-capture, it is possible that the variable belongs to the
13324 // template pattern of the current context.
13325 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13326 if (Var->isInitCapture() &&
13327 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13328 break;
13329 if (DC == Var->getDeclContext())
13330 break;
13331 Prev = DC;
13332 DC = DC->getParent();
13333 }
13334 // Unless we have an init-capture, we've gone one step too far.
13335 if (!Var->isInitCapture())
13336 DC = Prev;
13337 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13338}
13339
13340static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13341 Ty = Ty.getNonReferenceType();
13342 if (IsDereference && Ty->isPointerType())
13343 Ty = Ty->getPointeeType();
13344 return !Ty.isConstQualified();
13345}
13346
13347// Update err_typecheck_assign_const and note_typecheck_assign_const
13348// when this enum is changed.
13349enum {
13355 ConstUnknown, // Keep as last element
13356};
13357
13358/// Emit the "read-only variable not assignable" error and print notes to give
13359/// more information about why the variable is not assignable, such as pointing
13360/// to the declaration of a const variable, showing that a method is const, or
13361/// that the function is returning a const reference.
13362static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13364 SourceRange ExprRange = E->getSourceRange();
13365
13366 // Only emit one error on the first const found. All other consts will emit
13367 // a note to the error.
13368 bool DiagnosticEmitted = false;
13369
13370 // Track if the current expression is the result of a dereference, and if the
13371 // next checked expression is the result of a dereference.
13372 bool IsDereference = false;
13373 bool NextIsDereference = false;
13374
13375 // Loop to process MemberExpr chains.
13376 while (true) {
13377 IsDereference = NextIsDereference;
13378
13380 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13381 NextIsDereference = ME->isArrow();
13382 const ValueDecl *VD = ME->getMemberDecl();
13383 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13384 // Mutable fields can be modified even if the class is const.
13385 if (Field->isMutable()) {
13386 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13387 break;
13388 }
13389
13390 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13391 if (!DiagnosticEmitted) {
13392 S.Diag(Loc, diag::err_typecheck_assign_const)
13393 << ExprRange << ConstMember << false /*static*/ << Field
13394 << Field->getType();
13395 DiagnosticEmitted = true;
13396 }
13397 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13398 << ConstMember << false /*static*/ << Field << Field->getType()
13399 << Field->getSourceRange();
13400 }
13401 E = ME->getBase();
13402 continue;
13403 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13404 if (VDecl->getType().isConstQualified()) {
13405 if (!DiagnosticEmitted) {
13406 S.Diag(Loc, diag::err_typecheck_assign_const)
13407 << ExprRange << ConstMember << true /*static*/ << VDecl
13408 << VDecl->getType();
13409 DiagnosticEmitted = true;
13410 }
13411 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13412 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13413 << VDecl->getSourceRange();
13414 }
13415 // Static fields do not inherit constness from parents.
13416 break;
13417 }
13418 break; // End MemberExpr
13419 } else if (const ArraySubscriptExpr *ASE =
13420 dyn_cast<ArraySubscriptExpr>(E)) {
13421 E = ASE->getBase()->IgnoreParenImpCasts();
13422 continue;
13423 } else if (const ExtVectorElementExpr *EVE =
13424 dyn_cast<ExtVectorElementExpr>(E)) {
13425 E = EVE->getBase()->IgnoreParenImpCasts();
13426 continue;
13427 }
13428 break;
13429 }
13430
13431 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13432 // Function calls
13433 const FunctionDecl *FD = CE->getDirectCallee();
13434 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13435 if (!DiagnosticEmitted) {
13436 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13437 << ConstFunction << FD;
13438 DiagnosticEmitted = true;
13439 }
13441 diag::note_typecheck_assign_const)
13442 << ConstFunction << FD << FD->getReturnType()
13443 << FD->getReturnTypeSourceRange();
13444 }
13445 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13446 // Point to variable declaration.
13447 if (const ValueDecl *VD = DRE->getDecl()) {
13448 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13449 if (!DiagnosticEmitted) {
13450 S.Diag(Loc, diag::err_typecheck_assign_const)
13451 << ExprRange << ConstVariable << VD << VD->getType();
13452 DiagnosticEmitted = true;
13453 }
13454 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13455 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13456 }
13457 }
13458 } else if (isa<CXXThisExpr>(E)) {
13459 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13460 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13461 if (MD->isConst()) {
13462 if (!DiagnosticEmitted) {
13463 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13464 << ConstMethod << MD;
13465 DiagnosticEmitted = true;
13466 }
13467 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13468 << ConstMethod << MD << MD->getSourceRange();
13469 }
13470 }
13471 }
13472 }
13473
13474 if (DiagnosticEmitted)
13475 return;
13476
13477 // Can't determine a more specific message, so display the generic error.
13478 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13479}
13480
13486
13488 const RecordType *Ty,
13490 OriginalExprKind OEK,
13491 bool &DiagnosticEmitted) {
13492 std::vector<const RecordType *> RecordTypeList;
13493 RecordTypeList.push_back(Ty);
13494 unsigned NextToCheckIndex = 0;
13495 // We walk the record hierarchy breadth-first to ensure that we print
13496 // diagnostics in field nesting order.
13497 while (RecordTypeList.size() > NextToCheckIndex) {
13498 bool IsNested = NextToCheckIndex > 0;
13499 for (const FieldDecl *Field :
13500 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13501 // First, check every field for constness.
13502 QualType FieldTy = Field->getType();
13503 if (FieldTy.isConstQualified()) {
13504 if (!DiagnosticEmitted) {
13505 S.Diag(Loc, diag::err_typecheck_assign_const)
13506 << Range << NestedConstMember << OEK << VD
13507 << IsNested << Field;
13508 DiagnosticEmitted = true;
13509 }
13510 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13511 << NestedConstMember << IsNested << Field
13512 << FieldTy << Field->getSourceRange();
13513 }
13514
13515 // Then we append it to the list to check next in order.
13516 FieldTy = FieldTy.getCanonicalType();
13517 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13518 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13519 RecordTypeList.push_back(FieldRecTy);
13520 }
13521 }
13522 ++NextToCheckIndex;
13523 }
13524}
13525
13526/// Emit an error for the case where a record we are trying to assign to has a
13527/// const-qualified field somewhere in its hierarchy.
13530 QualType Ty = E->getType();
13531 assert(Ty->isRecordType() && "lvalue was not record?");
13533 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13534 bool DiagEmitted = false;
13535
13536 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13537 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13538 Range, OEK_Member, DiagEmitted);
13539 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13540 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13541 Range, OEK_Variable, DiagEmitted);
13542 else
13543 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13544 Range, OEK_LValue, DiagEmitted);
13545 if (!DiagEmitted)
13547}
13548
13549/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13550/// emit an error and return true. If so, return false.
13552 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13553
13555
13556 SourceLocation OrigLoc = Loc;
13558 &Loc);
13559 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13561 if (IsLV == Expr::MLV_Valid)
13562 return false;
13563
13564 unsigned DiagID = 0;
13565 bool NeedType = false;
13566 switch (IsLV) { // C99 6.5.16p2
13568 // Use a specialized diagnostic when we're assigning to an object
13569 // from an enclosing function or block.
13571 if (NCCK == NCCK_Block)
13572 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13573 else
13574 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13575 break;
13576 }
13577
13578 // In ARC, use some specialized diagnostics for occasions where we
13579 // infer 'const'. These are always pseudo-strong variables.
13580 if (S.getLangOpts().ObjCAutoRefCount) {
13581 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13582 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13583 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13584
13585 // Use the normal diagnostic if it's pseudo-__strong but the
13586 // user actually wrote 'const'.
13587 if (var->isARCPseudoStrong() &&
13588 (!var->getTypeSourceInfo() ||
13589 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13590 // There are three pseudo-strong cases:
13591 // - self
13592 ObjCMethodDecl *method = S.getCurMethodDecl();
13593 if (method && var == method->getSelfDecl()) {
13594 DiagID = method->isClassMethod()
13595 ? diag::err_typecheck_arc_assign_self_class_method
13596 : diag::err_typecheck_arc_assign_self;
13597
13598 // - Objective-C externally_retained attribute.
13599 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13600 isa<ParmVarDecl>(var)) {
13601 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13602
13603 // - fast enumeration variables
13604 } else {
13605 DiagID = diag::err_typecheck_arr_assign_enumeration;
13606 }
13607
13608 SourceRange Assign;
13609 if (Loc != OrigLoc)
13610 Assign = SourceRange(OrigLoc, OrigLoc);
13611 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13612 // We need to preserve the AST regardless, so migration tool
13613 // can do its job.
13614 return false;
13615 }
13616 }
13617 }
13618
13619 // If none of the special cases above are triggered, then this is a
13620 // simple const assignment.
13621 if (DiagID == 0) {
13623 return true;
13624 }
13625
13626 break;
13629 return true;
13632 return true;
13635 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13636 NeedType = true;
13637 break;
13639 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13640 NeedType = true;
13641 break;
13643 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13644 break;
13645 case Expr::MLV_Valid:
13646 llvm_unreachable("did not take early return for MLV_Valid");
13650 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13651 break;
13654 return S.RequireCompleteType(Loc, E->getType(),
13655 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13657 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13658 break;
13660 llvm_unreachable("readonly properties should be processed differently");
13662 DiagID = diag::err_readonly_message_assignment;
13663 break;
13665 DiagID = diag::err_no_subobject_property_setting;
13666 break;
13667 }
13668
13669 SourceRange Assign;
13670 if (Loc != OrigLoc)
13671 Assign = SourceRange(OrigLoc, OrigLoc);
13672 if (NeedType)
13673 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13674 else
13675 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13676 return true;
13677}
13678
13679static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13681 Sema &Sema) {
13683 return;
13685 return;
13686 if (Loc.isInvalid() || Loc.isMacroID())
13687 return;
13688 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13689 return;
13690
13691 // C / C++ fields
13692 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13693 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13694 if (ML && MR) {
13695 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13696 return;
13697 const ValueDecl *LHSDecl =
13698 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13699 const ValueDecl *RHSDecl =
13700 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13701 if (LHSDecl != RHSDecl)
13702 return;
13703 if (LHSDecl->getType().isVolatileQualified())
13704 return;
13705 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13706 if (RefTy->getPointeeType().isVolatileQualified())
13707 return;
13708
13709 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13710 }
13711
13712 // Objective-C instance variables
13713 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13714 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13715 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13716 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13717 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13718 if (RL && RR && RL->getDecl() == RR->getDecl())
13719 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13720 }
13721}
13722
13723// C99 6.5.16.1
13726 QualType CompoundType,
13727 BinaryOperatorKind Opc) {
13728 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13729
13730 // Verify that LHS is a modifiable lvalue, and emit error if not.
13731 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13732 return QualType();
13733
13734 QualType LHSType = LHSExpr->getType();
13735 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13736 CompoundType;
13737 // OpenCL v1.2 s6.1.1.1 p2:
13738 // The half data type can only be used to declare a pointer to a buffer that
13739 // contains half values
13740 if (getLangOpts().OpenCL &&
13741 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13742 LHSType->isHalfType()) {
13743 Diag(Loc, diag::err_opencl_half_load_store) << 1
13744 << LHSType.getUnqualifiedType();
13745 return QualType();
13746 }
13747
13748 // WebAssembly tables can't be used on RHS of an assignment expression.
13749 if (RHSType->isWebAssemblyTableType()) {
13750 Diag(Loc, diag::err_wasm_table_art) << 0;
13751 return QualType();
13752 }
13753
13754 AssignConvertType ConvTy;
13755 if (CompoundType.isNull()) {
13756 Expr *RHSCheck = RHS.get();
13757
13758 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13759
13760 QualType LHSTy(LHSType);
13761 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13762 if (RHS.isInvalid())
13763 return QualType();
13764 // Special case of NSObject attributes on c-style pointer types.
13765 if (ConvTy == IncompatiblePointer &&
13766 ((Context.isObjCNSObjectType(LHSType) &&
13767 RHSType->isObjCObjectPointerType()) ||
13768 (Context.isObjCNSObjectType(RHSType) &&
13769 LHSType->isObjCObjectPointerType())))
13770 ConvTy = Compatible;
13771
13772 if (ConvTy == Compatible &&
13773 LHSType->isObjCObjectType())
13774 Diag(Loc, diag::err_objc_object_assignment)
13775 << LHSType;
13776
13777 // If the RHS is a unary plus or minus, check to see if they = and + are
13778 // right next to each other. If so, the user may have typo'd "x =+ 4"
13779 // instead of "x += 4".
13780 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13781 RHSCheck = ICE->getSubExpr();
13782 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13783 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13784 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13785 // Only if the two operators are exactly adjacent.
13786 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13787 // And there is a space or other character before the subexpr of the
13788 // unary +/-. We don't want to warn on "x=-1".
13789 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13790 UO->getSubExpr()->getBeginLoc().isFileID()) {
13791 Diag(Loc, diag::warn_not_compound_assign)
13792 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13793 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13794 }
13795 }
13796
13797 if (ConvTy == Compatible) {
13798 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13799 // Warn about retain cycles where a block captures the LHS, but
13800 // not if the LHS is a simple variable into which the block is
13801 // being stored...unless that variable can be captured by reference!
13802 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13803 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13804 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13805 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13806 }
13807
13808 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13810 // It is safe to assign a weak reference into a strong variable.
13811 // Although this code can still have problems:
13812 // id x = self.weakProp;
13813 // id y = self.weakProp;
13814 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13815 // paths through the function. This should be revisited if
13816 // -Wrepeated-use-of-weak is made flow-sensitive.
13817 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13818 // variable, which will be valid for the current autorelease scope.
13819 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13820 RHS.get()->getBeginLoc()))
13822
13823 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13824 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13825 }
13826 }
13827 } else {
13828 // Compound assignment "x += y"
13829 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13830 }
13831
13832 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
13834 return QualType();
13835
13836 CheckForNullPointerDereference(*this, LHSExpr);
13837
13838 AssignedEntity AE{LHSExpr};
13839 checkAssignmentLifetime(*this, AE, RHS.get());
13840
13841 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13842 if (CompoundType.isNull()) {
13843 // C++2a [expr.ass]p5:
13844 // A simple-assignment whose left operand is of a volatile-qualified
13845 // type is deprecated unless the assignment is either a discarded-value
13846 // expression or an unevaluated operand
13847 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13848 }
13849 }
13850
13851 // C11 6.5.16p3: The type of an assignment expression is the type of the
13852 // left operand would have after lvalue conversion.
13853 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13854 // qualified type, the value has the unqualified version of the type of the
13855 // lvalue; additionally, if the lvalue has atomic type, the value has the
13856 // non-atomic version of the type of the lvalue.
13857 // C++ 5.17p1: the type of the assignment expression is that of its left
13858 // operand.
13859 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13860}
13861
13862// Scenarios to ignore if expression E is:
13863// 1. an explicit cast expression into void
13864// 2. a function call expression that returns void
13865static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13866 E = E->IgnoreParens();
13867
13868 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13869 if (CE->getCastKind() == CK_ToVoid) {
13870 return true;
13871 }
13872
13873 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13874 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13875 CE->getSubExpr()->getType()->isDependentType()) {
13876 return true;
13877 }
13878 }
13879
13880 if (const auto *CE = dyn_cast<CallExpr>(E))
13881 return CE->getCallReturnType(Context)->isVoidType();
13882 return false;
13883}
13884
13886 // No warnings in macros
13887 if (Loc.isMacroID())
13888 return;
13889
13890 // Don't warn in template instantiations.
13892 return;
13893
13894 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13895 // instead, skip more than needed, then call back into here with the
13896 // CommaVisitor in SemaStmt.cpp.
13897 // The listed locations are the initialization and increment portions
13898 // of a for loop. The additional checks are on the condition of
13899 // if statements, do/while loops, and for loops.
13900 // Differences in scope flags for C89 mode requires the extra logic.
13901 const unsigned ForIncrementFlags =
13902 getLangOpts().C99 || getLangOpts().CPlusPlus
13905 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13906 const unsigned ScopeFlags = getCurScope()->getFlags();
13907 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13908 (ScopeFlags & ForInitFlags) == ForInitFlags)
13909 return;
13910
13911 // If there are multiple comma operators used together, get the RHS of the
13912 // of the comma operator as the LHS.
13913 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13914 if (BO->getOpcode() != BO_Comma)
13915 break;
13916 LHS = BO->getRHS();
13917 }
13918
13919 // Only allow some expressions on LHS to not warn.
13920 if (IgnoreCommaOperand(LHS, Context))
13921 return;
13922
13923 Diag(Loc, diag::warn_comma_operator);
13924 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13925 << LHS->getSourceRange()
13927 LangOpts.CPlusPlus ? "static_cast<void>("
13928 : "(void)(")
13930 ")");
13931}
13932
13933// C99 6.5.17
13936 LHS = S.CheckPlaceholderExpr(LHS.get());
13937 RHS = S.CheckPlaceholderExpr(RHS.get());
13938 if (LHS.isInvalid() || RHS.isInvalid())
13939 return QualType();
13940
13941 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13942 // operands, but not unary promotions.
13943 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13944
13945 // So we treat the LHS as a ignored value, and in C++ we allow the
13946 // containing site to determine what should be done with the RHS.
13947 LHS = S.IgnoredValueConversions(LHS.get());
13948 if (LHS.isInvalid())
13949 return QualType();
13950
13951 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13952
13953 if (!S.getLangOpts().CPlusPlus) {
13955 if (RHS.isInvalid())
13956 return QualType();
13957 if (!RHS.get()->getType()->isVoidType())
13958 S.RequireCompleteType(Loc, RHS.get()->getType(),
13959 diag::err_incomplete_type);
13960 }
13961
13962 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13963 S.DiagnoseCommaOperator(LHS.get(), Loc);
13964
13965 return RHS.get()->getType();
13966}
13967
13968/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13969/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13971 ExprValueKind &VK,
13972 ExprObjectKind &OK,
13973 SourceLocation OpLoc, bool IsInc,
13974 bool IsPrefix) {
13975 QualType ResType = Op->getType();
13976 // Atomic types can be used for increment / decrement where the non-atomic
13977 // versions can, so ignore the _Atomic() specifier for the purpose of
13978 // checking.
13979 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13980 ResType = ResAtomicType->getValueType();
13981
13982 assert(!ResType.isNull() && "no type for increment/decrement expression");
13983
13984 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13985 // Decrement of bool is not allowed.
13986 if (!IsInc) {
13987 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13988 return QualType();
13989 }
13990 // Increment of bool sets it to true, but is deprecated.
13991 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13992 : diag::warn_increment_bool)
13993 << Op->getSourceRange();
13994 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13995 // Error on enum increments and decrements in C++ mode
13996 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13997 return QualType();
13998 } else if (ResType->isRealType()) {
13999 // OK!
14000 } else if (ResType->isPointerType()) {
14001 // C99 6.5.2.4p2, 6.5.6p2
14002 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14003 return QualType();
14004 } else if (ResType->isObjCObjectPointerType()) {
14005 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14006 // Otherwise, we just need a complete type.
14007 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14008 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14009 return QualType();
14010 } else if (ResType->isAnyComplexType()) {
14011 // C99 does not support ++/-- on complex types, we allow as an extension.
14012 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14013 : diag::ext_c2y_increment_complex)
14014 << IsInc << Op->getSourceRange();
14015 } else if (ResType->isPlaceholderType()) {
14017 if (PR.isInvalid()) return QualType();
14018 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14019 IsInc, IsPrefix);
14020 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14021 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14022 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14023 (ResType->castAs<VectorType>()->getVectorKind() !=
14025 // The z vector extensions allow ++ and -- for non-bool vectors.
14026 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14027 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14028 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14029 } else {
14030 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14031 << ResType << int(IsInc) << Op->getSourceRange();
14032 return QualType();
14033 }
14034 // At this point, we know we have a real, complex or pointer type.
14035 // Now make sure the operand is a modifiable lvalue.
14036 if (CheckForModifiableLvalue(Op, OpLoc, S))
14037 return QualType();
14038 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14039 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14040 // An operand with volatile-qualified type is deprecated
14041 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14042 << IsInc << ResType;
14043 }
14044 // In C++, a prefix increment is the same type as the operand. Otherwise
14045 // (in C or with postfix), the increment is the unqualified type of the
14046 // operand.
14047 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14048 VK = VK_LValue;
14049 OK = Op->getObjectKind();
14050 return ResType;
14051 } else {
14052 VK = VK_PRValue;
14053 return ResType.getUnqualifiedType();
14054 }
14055}
14056
14057/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14058/// This routine allows us to typecheck complex/recursive expressions
14059/// where the declaration is needed for type checking. We only need to
14060/// handle cases when the expression references a function designator
14061/// or is an lvalue. Here are some examples:
14062/// - &(x) => x
14063/// - &*****f => f for f a function designator.
14064/// - &s.xx => s
14065/// - &s.zz[1].yy -> s, if zz is an array
14066/// - *(x + 1) -> x, if x is an array
14067/// - &"123"[2] -> 0
14068/// - & __real__ x -> x
14069///
14070/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14071/// members.
14073 switch (E->getStmtClass()) {
14074 case Stmt::DeclRefExprClass:
14075 return cast<DeclRefExpr>(E)->getDecl();
14076 case Stmt::MemberExprClass:
14077 // If this is an arrow operator, the address is an offset from
14078 // the base's value, so the object the base refers to is
14079 // irrelevant.
14080 if (cast<MemberExpr>(E)->isArrow())
14081 return nullptr;
14082 // Otherwise, the expression refers to a part of the base
14083 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14084 case Stmt::ArraySubscriptExprClass: {
14085 // FIXME: This code shouldn't be necessary! We should catch the implicit
14086 // promotion of register arrays earlier.
14087 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14088 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14089 if (ICE->getSubExpr()->getType()->isArrayType())
14090 return getPrimaryDecl(ICE->getSubExpr());
14091 }
14092 return nullptr;
14093 }
14094 case Stmt::UnaryOperatorClass: {
14095 UnaryOperator *UO = cast<UnaryOperator>(E);
14096
14097 switch(UO->getOpcode()) {
14098 case UO_Real:
14099 case UO_Imag:
14100 case UO_Extension:
14101 return getPrimaryDecl(UO->getSubExpr());
14102 default:
14103 return nullptr;
14104 }
14105 }
14106 case Stmt::ParenExprClass:
14107 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14108 case Stmt::ImplicitCastExprClass:
14109 // If the result of an implicit cast is an l-value, we care about
14110 // the sub-expression; otherwise, the result here doesn't matter.
14111 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14112 case Stmt::CXXUuidofExprClass:
14113 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14114 default:
14115 return nullptr;
14116 }
14117}
14118
14119namespace {
14120enum {
14121 AO_Bit_Field = 0,
14122 AO_Vector_Element = 1,
14123 AO_Property_Expansion = 2,
14124 AO_Register_Variable = 3,
14125 AO_Matrix_Element = 4,
14126 AO_No_Error = 5
14127};
14128}
14129/// Diagnose invalid operand for address of operations.
14130///
14131/// \param Type The type of operand which cannot have its address taken.
14133 Expr *E, unsigned Type) {
14134 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14135}
14136
14138 const Expr *Op,
14139 const CXXMethodDecl *MD) {
14140 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14141
14142 if (Op != DRE)
14143 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14144 << Op->getSourceRange();
14145
14146 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14147 if (isa<CXXDestructorDecl>(MD))
14148 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14149 << DRE->getSourceRange();
14150
14151 if (DRE->getQualifier())
14152 return false;
14153
14154 if (MD->getParent()->getName().empty())
14155 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14156 << DRE->getSourceRange();
14157
14158 SmallString<32> Str;
14159 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14160 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14161 << DRE->getSourceRange()
14162 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14163}
14164
14166 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14167 if (PTy->getKind() == BuiltinType::Overload) {
14168 Expr *E = OrigOp.get()->IgnoreParens();
14169 if (!isa<OverloadExpr>(E)) {
14170 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14171 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14172 << OrigOp.get()->getSourceRange();
14173 return QualType();
14174 }
14175
14176 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14177 if (isa<UnresolvedMemberExpr>(Ovl))
14179 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14180 << OrigOp.get()->getSourceRange();
14181 return QualType();
14182 }
14183
14184 return Context.OverloadTy;
14185 }
14186
14187 if (PTy->getKind() == BuiltinType::UnknownAny)
14188 return Context.UnknownAnyTy;
14189
14190 if (PTy->getKind() == BuiltinType::BoundMember) {
14191 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14192 << OrigOp.get()->getSourceRange();
14193 return QualType();
14194 }
14195
14196 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14197 if (OrigOp.isInvalid()) return QualType();
14198 }
14199
14200 if (OrigOp.get()->isTypeDependent())
14201 return Context.DependentTy;
14202
14203 assert(!OrigOp.get()->hasPlaceholderType());
14204
14205 // Make sure to ignore parentheses in subsequent checks
14206 Expr *op = OrigOp.get()->IgnoreParens();
14207
14208 // In OpenCL captures for blocks called as lambda functions
14209 // are located in the private address space. Blocks used in
14210 // enqueue_kernel can be located in a different address space
14211 // depending on a vendor implementation. Thus preventing
14212 // taking an address of the capture to avoid invalid AS casts.
14213 if (LangOpts.OpenCL) {
14214 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14215 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14216 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14217 return QualType();
14218 }
14219 }
14220
14221 if (getLangOpts().C99) {
14222 // Implement C99-only parts of addressof rules.
14223 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14224 if (uOp->getOpcode() == UO_Deref)
14225 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14226 // (assuming the deref expression is valid).
14227 return uOp->getSubExpr()->getType();
14228 }
14229 // Technically, there should be a check for array subscript
14230 // expressions here, but the result of one is always an lvalue anyway.
14231 }
14232 ValueDecl *dcl = getPrimaryDecl(op);
14233
14234 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14235 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14236 op->getBeginLoc()))
14237 return QualType();
14238
14240 unsigned AddressOfError = AO_No_Error;
14241
14242 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14243 bool sfinae = (bool)isSFINAEContext();
14244 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14245 : diag::ext_typecheck_addrof_temporary)
14246 << op->getType() << op->getSourceRange();
14247 if (sfinae)
14248 return QualType();
14249 // Materialize the temporary as an lvalue so that we can take its address.
14250 OrigOp = op =
14251 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14252 } else if (isa<ObjCSelectorExpr>(op)) {
14253 return Context.getPointerType(op->getType());
14254 } else if (lval == Expr::LV_MemberFunction) {
14255 // If it's an instance method, make a member pointer.
14256 // The expression must have exactly the form &A::foo.
14257
14258 // If the underlying expression isn't a decl ref, give up.
14259 if (!isa<DeclRefExpr>(op)) {
14260 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14261 << OrigOp.get()->getSourceRange();
14262 return QualType();
14263 }
14264 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14265 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14266
14267 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14268
14271
14272 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14273 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14274 // When pointer authentication is enabled, argument and return types of
14275 // vitual member functions must be complete. This is because vitrual
14276 // member function pointers are implemented using virtual dispatch
14277 // thunks and the thunks cannot be emitted if the argument or return
14278 // types are incomplete.
14279 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14280 SourceLocation DeclRefLoc,
14281 SourceLocation RetArgTypeLoc) {
14282 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14283 Diag(DeclRefLoc,
14284 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14285 Diag(RetArgTypeLoc,
14286 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14287 << T;
14288 return true;
14289 }
14290 return false;
14291 };
14292 QualType RetTy = MD->getReturnType();
14293 bool IsIncomplete =
14294 !RetTy->isVoidType() &&
14295 ReturnOrParamTypeIsIncomplete(
14296 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14297 for (auto *PVD : MD->parameters())
14298 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14299 PVD->getBeginLoc());
14300 if (IsIncomplete)
14301 return QualType();
14302 }
14303
14304 // Under the MS ABI, lock down the inheritance model now.
14306 (void)isCompleteType(OpLoc, MPTy);
14307 return MPTy;
14308 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14309 // C99 6.5.3.2p1
14310 // The operand must be either an l-value or a function designator
14311 if (!op->getType()->isFunctionType()) {
14312 // Use a special diagnostic for loads from property references.
14313 if (isa<PseudoObjectExpr>(op)) {
14314 AddressOfError = AO_Property_Expansion;
14315 } else {
14316 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14317 << op->getType() << op->getSourceRange();
14318 return QualType();
14319 }
14320 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14321 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14322 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14323 }
14324
14325 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14326 // The operand cannot be a bit-field
14327 AddressOfError = AO_Bit_Field;
14328 } else if (op->getObjectKind() == OK_VectorComponent) {
14329 // The operand cannot be an element of a vector
14330 AddressOfError = AO_Vector_Element;
14331 } else if (op->getObjectKind() == OK_MatrixComponent) {
14332 // The operand cannot be an element of a matrix.
14333 AddressOfError = AO_Matrix_Element;
14334 } else if (dcl) { // C99 6.5.3.2p1
14335 // We have an lvalue with a decl. Make sure the decl is not declared
14336 // with the register storage-class specifier.
14337 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14338 // in C++ it is not error to take address of a register
14339 // variable (c++03 7.1.1P3)
14340 if (vd->getStorageClass() == SC_Register &&
14342 AddressOfError = AO_Register_Variable;
14343 }
14344 } else if (isa<MSPropertyDecl>(dcl)) {
14345 AddressOfError = AO_Property_Expansion;
14346 } else if (isa<FunctionTemplateDecl>(dcl)) {
14347 return Context.OverloadTy;
14348 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14349 // Okay: we can take the address of a field.
14350 // Could be a pointer to member, though, if there is an explicit
14351 // scope qualifier for the class.
14352
14353 // [C++26] [expr.prim.id.general]
14354 // If an id-expression E denotes a non-static non-type member
14355 // of some class C [...] and if E is a qualified-id, E is
14356 // not the un-parenthesized operand of the unary & operator [...]
14357 // the id-expression is transformed into a class member access expression.
14358 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14359 !isa<ParenExpr>(OrigOp.get())) {
14360 DeclContext *Ctx = dcl->getDeclContext();
14361 if (Ctx && Ctx->isRecord()) {
14362 if (dcl->getType()->isReferenceType()) {
14363 Diag(OpLoc,
14364 diag::err_cannot_form_pointer_to_member_of_reference_type)
14365 << dcl->getDeclName() << dcl->getType();
14366 return QualType();
14367 }
14368
14369 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14370 Ctx = Ctx->getParent();
14371
14373 op->getType(),
14374 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14375 // Under the MS ABI, lock down the inheritance model now.
14377 (void)isCompleteType(OpLoc, MPTy);
14378 return MPTy;
14379 }
14380 }
14383 llvm_unreachable("Unknown/unexpected decl type");
14384 }
14385
14386 if (AddressOfError != AO_No_Error) {
14387 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14388 return QualType();
14389 }
14390
14391 if (lval == Expr::LV_IncompleteVoidType) {
14392 // Taking the address of a void variable is technically illegal, but we
14393 // allow it in cases which are otherwise valid.
14394 // Example: "extern void x; void* y = &x;".
14395 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14396 }
14397
14398 // If the operand has type "type", the result has type "pointer to type".
14399 if (op->getType()->isObjCObjectType())
14401
14402 // Cannot take the address of WebAssembly references or tables.
14403 if (Context.getTargetInfo().getTriple().isWasm()) {
14404 QualType OpTy = op->getType();
14405 if (OpTy.isWebAssemblyReferenceType()) {
14406 Diag(OpLoc, diag::err_wasm_ca_reference)
14407 << 1 << OrigOp.get()->getSourceRange();
14408 return QualType();
14409 }
14410 if (OpTy->isWebAssemblyTableType()) {
14411 Diag(OpLoc, diag::err_wasm_table_pr)
14412 << 1 << OrigOp.get()->getSourceRange();
14413 return QualType();
14414 }
14415 }
14416
14417 CheckAddressOfPackedMember(op);
14418
14419 return Context.getPointerType(op->getType());
14420}
14421
14422static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14423 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14424 if (!DRE)
14425 return;
14426 const Decl *D = DRE->getDecl();
14427 if (!D)
14428 return;
14429 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14430 if (!Param)
14431 return;
14432 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14433 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14434 return;
14435 if (FunctionScopeInfo *FD = S.getCurFunction())
14436 FD->ModifiedNonNullParams.insert(Param);
14437}
14438
14439/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14441 SourceLocation OpLoc,
14442 bool IsAfterAmp = false) {
14443 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14444 if (ConvResult.isInvalid())
14445 return QualType();
14446 Op = ConvResult.get();
14447 QualType OpTy = Op->getType();
14449
14450 if (isa<CXXReinterpretCastExpr>(Op)) {
14451 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14452 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14453 Op->getSourceRange());
14454 }
14455
14456 if (const PointerType *PT = OpTy->getAs<PointerType>())
14457 {
14458 Result = PT->getPointeeType();
14459 }
14460 else if (const ObjCObjectPointerType *OPT =
14462 Result = OPT->getPointeeType();
14463 else {
14465 if (PR.isInvalid()) return QualType();
14466 if (PR.get() != Op)
14467 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14468 }
14469
14470 if (Result.isNull()) {
14471 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14472 << OpTy << Op->getSourceRange();
14473 return QualType();
14474 }
14475
14476 if (Result->isVoidType()) {
14477 // C++ [expr.unary.op]p1:
14478 // [...] the expression to which [the unary * operator] is applied shall
14479 // be a pointer to an object type, or a pointer to a function type
14480 LangOptions LO = S.getLangOpts();
14481 if (LO.CPlusPlus)
14482 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14483 << OpTy << Op->getSourceRange();
14484 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14485 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14486 << OpTy << Op->getSourceRange();
14487 }
14488
14489 // Dereferences are usually l-values...
14490 VK = VK_LValue;
14491
14492 // ...except that certain expressions are never l-values in C.
14493 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14494 VK = VK_PRValue;
14495
14496 return Result;
14497}
14498
14499BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14501 switch (Kind) {
14502 default: llvm_unreachable("Unknown binop!");
14503 case tok::periodstar: Opc = BO_PtrMemD; break;
14504 case tok::arrowstar: Opc = BO_PtrMemI; break;
14505 case tok::star: Opc = BO_Mul; break;
14506 case tok::slash: Opc = BO_Div; break;
14507 case tok::percent: Opc = BO_Rem; break;
14508 case tok::plus: Opc = BO_Add; break;
14509 case tok::minus: Opc = BO_Sub; break;
14510 case tok::lessless: Opc = BO_Shl; break;
14511 case tok::greatergreater: Opc = BO_Shr; break;
14512 case tok::lessequal: Opc = BO_LE; break;
14513 case tok::less: Opc = BO_LT; break;
14514 case tok::greaterequal: Opc = BO_GE; break;
14515 case tok::greater: Opc = BO_GT; break;
14516 case tok::exclaimequal: Opc = BO_NE; break;
14517 case tok::equalequal: Opc = BO_EQ; break;
14518 case tok::spaceship: Opc = BO_Cmp; break;
14519 case tok::amp: Opc = BO_And; break;
14520 case tok::caret: Opc = BO_Xor; break;
14521 case tok::pipe: Opc = BO_Or; break;
14522 case tok::ampamp: Opc = BO_LAnd; break;
14523 case tok::pipepipe: Opc = BO_LOr; break;
14524 case tok::equal: Opc = BO_Assign; break;
14525 case tok::starequal: Opc = BO_MulAssign; break;
14526 case tok::slashequal: Opc = BO_DivAssign; break;
14527 case tok::percentequal: Opc = BO_RemAssign; break;
14528 case tok::plusequal: Opc = BO_AddAssign; break;
14529 case tok::minusequal: Opc = BO_SubAssign; break;
14530 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14531 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14532 case tok::ampequal: Opc = BO_AndAssign; break;
14533 case tok::caretequal: Opc = BO_XorAssign; break;
14534 case tok::pipeequal: Opc = BO_OrAssign; break;
14535 case tok::comma: Opc = BO_Comma; break;
14536 }
14537 return Opc;
14538}
14539
14541 tok::TokenKind Kind) {
14543 switch (Kind) {
14544 default: llvm_unreachable("Unknown unary op!");
14545 case tok::plusplus: Opc = UO_PreInc; break;
14546 case tok::minusminus: Opc = UO_PreDec; break;
14547 case tok::amp: Opc = UO_AddrOf; break;
14548 case tok::star: Opc = UO_Deref; break;
14549 case tok::plus: Opc = UO_Plus; break;
14550 case tok::minus: Opc = UO_Minus; break;
14551 case tok::tilde: Opc = UO_Not; break;
14552 case tok::exclaim: Opc = UO_LNot; break;
14553 case tok::kw___real: Opc = UO_Real; break;
14554 case tok::kw___imag: Opc = UO_Imag; break;
14555 case tok::kw___extension__: Opc = UO_Extension; break;
14556 }
14557 return Opc;
14558}
14559
14560const FieldDecl *
14562 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14563 // common for setters.
14564 // struct A {
14565 // int X;
14566 // -void setX(int X) { X = X; }
14567 // +void setX(int X) { this->X = X; }
14568 // };
14569
14570 // Only consider parameters for self assignment fixes.
14571 if (!isa<ParmVarDecl>(SelfAssigned))
14572 return nullptr;
14573 const auto *Method =
14574 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14575 if (!Method)
14576 return nullptr;
14577
14578 const CXXRecordDecl *Parent = Method->getParent();
14579 // In theory this is fixable if the lambda explicitly captures this, but
14580 // that's added complexity that's rarely going to be used.
14581 if (Parent->isLambda())
14582 return nullptr;
14583
14584 // FIXME: Use an actual Lookup operation instead of just traversing fields
14585 // in order to get base class fields.
14586 auto Field =
14587 llvm::find_if(Parent->fields(),
14588 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14589 return F->getDeclName() == Name;
14590 });
14591 return (Field != Parent->field_end()) ? *Field : nullptr;
14592}
14593
14594/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14595/// This warning suppressed in the event of macro expansions.
14596static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14597 SourceLocation OpLoc, bool IsBuiltin) {
14599 return;
14600 if (S.isUnevaluatedContext())
14601 return;
14602 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14603 return;
14604 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14605 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14606 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14607 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14608 if (!LHSDeclRef || !RHSDeclRef ||
14609 LHSDeclRef->getLocation().isMacroID() ||
14610 RHSDeclRef->getLocation().isMacroID())
14611 return;
14612 const ValueDecl *LHSDecl =
14613 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14614 const ValueDecl *RHSDecl =
14615 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14616 if (LHSDecl != RHSDecl)
14617 return;
14618 if (LHSDecl->getType().isVolatileQualified())
14619 return;
14620 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14621 if (RefTy->getPointeeType().isVolatileQualified())
14622 return;
14623
14624 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14625 : diag::warn_self_assignment_overloaded)
14626 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14627 << RHSExpr->getSourceRange();
14628 if (const FieldDecl *SelfAssignField =
14630 Diag << 1 << SelfAssignField
14631 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14632 else
14633 Diag << 0;
14634}
14635
14636/// Check if a bitwise-& is performed on an Objective-C pointer. This
14637/// is usually indicative of introspection within the Objective-C pointer.
14639 SourceLocation OpLoc) {
14640 if (!S.getLangOpts().ObjC)
14641 return;
14642
14643 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14644 const Expr *LHS = L.get();
14645 const Expr *RHS = R.get();
14646
14648 ObjCPointerExpr = LHS;
14649 OtherExpr = RHS;
14650 }
14651 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14652 ObjCPointerExpr = RHS;
14653 OtherExpr = LHS;
14654 }
14655
14656 // This warning is deliberately made very specific to reduce false
14657 // positives with logic that uses '&' for hashing. This logic mainly
14658 // looks for code trying to introspect into tagged pointers, which
14659 // code should generally never do.
14660 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14661 unsigned Diag = diag::warn_objc_pointer_masking;
14662 // Determine if we are introspecting the result of performSelectorXXX.
14663 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14664 // Special case messages to -performSelector and friends, which
14665 // can return non-pointer values boxed in a pointer value.
14666 // Some clients may wish to silence warnings in this subcase.
14667 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14668 Selector S = ME->getSelector();
14669 StringRef SelArg0 = S.getNameForSlot(0);
14670 if (SelArg0.starts_with("performSelector"))
14671 Diag = diag::warn_objc_pointer_masking_performSelector;
14672 }
14673
14674 S.Diag(OpLoc, Diag)
14675 << ObjCPointerExpr->getSourceRange();
14676 }
14677}
14678
14680 if (!E)
14681 return nullptr;
14682 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14683 return DRE->getDecl();
14684 if (auto *ME = dyn_cast<MemberExpr>(E))
14685 return ME->getMemberDecl();
14686 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14687 return IRE->getDecl();
14688 return nullptr;
14689}
14690
14691// This helper function promotes a binary operator's operands (which are of a
14692// half vector type) to a vector of floats and then truncates the result to
14693// a vector of either half or short.
14695 BinaryOperatorKind Opc, QualType ResultTy,
14697 bool IsCompAssign, SourceLocation OpLoc,
14698 FPOptionsOverride FPFeatures) {
14699 auto &Context = S.getASTContext();
14700 assert((isVector(ResultTy, Context.HalfTy) ||
14701 isVector(ResultTy, Context.ShortTy)) &&
14702 "Result must be a vector of half or short");
14703 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14704 isVector(RHS.get()->getType(), Context.HalfTy) &&
14705 "both operands expected to be a half vector");
14706
14707 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14708 QualType BinOpResTy = RHS.get()->getType();
14709
14710 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14711 // change BinOpResTy to a vector of ints.
14712 if (isVector(ResultTy, Context.ShortTy))
14713 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14714
14715 if (IsCompAssign)
14716 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14717 ResultTy, VK, OK, OpLoc, FPFeatures,
14718 BinOpResTy, BinOpResTy);
14719
14720 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14721 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14722 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14723 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14724}
14725
14726static std::pair<ExprResult, ExprResult>
14728 Expr *RHSExpr) {
14729 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14730 if (!S.Context.isDependenceAllowed()) {
14731 // C cannot handle TypoExpr nodes on either side of a binop because it
14732 // doesn't handle dependent types properly, so make sure any TypoExprs have
14733 // been dealt with before checking the operands.
14734 LHS = S.CorrectDelayedTyposInExpr(LHS);
14736 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14737 [Opc, LHS](Expr *E) {
14738 if (Opc != BO_Assign)
14739 return ExprResult(E);
14740 // Avoid correcting the RHS to the same Expr as the LHS.
14741 Decl *D = getDeclFromExpr(E);
14742 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14743 });
14744 }
14745 return std::make_pair(LHS, RHS);
14746}
14747
14748/// Returns true if conversion between vectors of halfs and vectors of floats
14749/// is needed.
14750static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14751 Expr *E0, Expr *E1 = nullptr) {
14752 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14754 return false;
14755
14756 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14757 QualType Ty = E->IgnoreImplicit()->getType();
14758
14759 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14760 // to vectors of floats. Although the element type of the vectors is __fp16,
14761 // the vectors shouldn't be treated as storage-only types. See the
14762 // discussion here: https://reviews.llvm.org/rG825235c140e7
14763 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14764 if (VT->getVectorKind() == VectorKind::Neon)
14765 return false;
14766 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14767 }
14768 return false;
14769 };
14770
14771 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14772}
14773
14776 Expr *LHSExpr, Expr *RHSExpr) {
14777 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14778 // The syntax only allows initializer lists on the RHS of assignment,
14779 // so we don't need to worry about accepting invalid code for
14780 // non-assignment operators.
14781 // C++11 5.17p9:
14782 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14783 // of x = {} is x = T().
14785 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14786 InitializedEntity Entity =
14788 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14789 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14790 if (Init.isInvalid())
14791 return Init;
14792 RHSExpr = Init.get();
14793 }
14794
14795 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14796 QualType ResultTy; // Result type of the binary operator.
14797 // The following two variables are used for compound assignment operators
14798 QualType CompLHSTy; // Type of LHS after promotions for computation
14799 QualType CompResultTy; // Type of computation result
14802 bool ConvertHalfVec = false;
14803
14804 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14805 if (!LHS.isUsable() || !RHS.isUsable())
14806 return ExprError();
14807
14808 if (getLangOpts().OpenCL) {
14809 QualType LHSTy = LHSExpr->getType();
14810 QualType RHSTy = RHSExpr->getType();
14811 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14812 // the ATOMIC_VAR_INIT macro.
14813 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14814 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14815 if (BO_Assign == Opc)
14816 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14817 else
14818 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14819 return ExprError();
14820 }
14821
14822 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14823 // only with a builtin functions and therefore should be disallowed here.
14824 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14825 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14826 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14827 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14828 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14829 return ExprError();
14830 }
14831 }
14832
14833 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14834 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14835
14836 switch (Opc) {
14837 case BO_Assign:
14838 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14839 if (getLangOpts().CPlusPlus &&
14840 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14841 VK = LHS.get()->getValueKind();
14842 OK = LHS.get()->getObjectKind();
14843 }
14844 if (!ResultTy.isNull()) {
14845 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14846 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14847
14848 // Avoid copying a block to the heap if the block is assigned to a local
14849 // auto variable that is declared in the same scope as the block. This
14850 // optimization is unsafe if the local variable is declared in an outer
14851 // scope. For example:
14852 //
14853 // BlockTy b;
14854 // {
14855 // b = ^{...};
14856 // }
14857 // // It is unsafe to invoke the block here if it wasn't copied to the
14858 // // heap.
14859 // b();
14860
14861 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14862 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14863 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14864 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14865 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14866
14868 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14870 }
14871 RecordModifiableNonNullParam(*this, LHS.get());
14872 break;
14873 case BO_PtrMemD:
14874 case BO_PtrMemI:
14875 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14876 Opc == BO_PtrMemI);
14877 break;
14878 case BO_Mul:
14879 case BO_Div:
14880 ConvertHalfVec = true;
14881 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14882 Opc == BO_Div);
14883 break;
14884 case BO_Rem:
14885 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14886 break;
14887 case BO_Add:
14888 ConvertHalfVec = true;
14889 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14890 break;
14891 case BO_Sub:
14892 ConvertHalfVec = true;
14893 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14894 break;
14895 case BO_Shl:
14896 case BO_Shr:
14897 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14898 break;
14899 case BO_LE:
14900 case BO_LT:
14901 case BO_GE:
14902 case BO_GT:
14903 ConvertHalfVec = true;
14904 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14905
14906 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14907 BI && BI->isComparisonOp())
14908 Diag(OpLoc, diag::warn_consecutive_comparison);
14909
14910 break;
14911 case BO_EQ:
14912 case BO_NE:
14913 ConvertHalfVec = true;
14914 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14915 break;
14916 case BO_Cmp:
14917 ConvertHalfVec = true;
14918 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14919 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14920 break;
14921 case BO_And:
14922 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14923 [[fallthrough]];
14924 case BO_Xor:
14925 case BO_Or:
14926 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14927 break;
14928 case BO_LAnd:
14929 case BO_LOr:
14930 ConvertHalfVec = true;
14931 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14932 break;
14933 case BO_MulAssign:
14934 case BO_DivAssign:
14935 ConvertHalfVec = true;
14936 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14937 Opc == BO_DivAssign);
14938 CompLHSTy = CompResultTy;
14939 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14940 ResultTy =
14941 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14942 break;
14943 case BO_RemAssign:
14944 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14945 CompLHSTy = CompResultTy;
14946 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14947 ResultTy =
14948 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14949 break;
14950 case BO_AddAssign:
14951 ConvertHalfVec = true;
14952 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14953 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14954 ResultTy =
14955 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14956 break;
14957 case BO_SubAssign:
14958 ConvertHalfVec = true;
14959 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14960 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14961 ResultTy =
14962 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14963 break;
14964 case BO_ShlAssign:
14965 case BO_ShrAssign:
14966 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14967 CompLHSTy = CompResultTy;
14968 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14969 ResultTy =
14970 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14971 break;
14972 case BO_AndAssign:
14973 case BO_OrAssign: // fallthrough
14974 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14975 [[fallthrough]];
14976 case BO_XorAssign:
14977 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14978 CompLHSTy = CompResultTy;
14979 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14980 ResultTy =
14981 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14982 break;
14983 case BO_Comma:
14984 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14985 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14986 VK = RHS.get()->getValueKind();
14987 OK = RHS.get()->getObjectKind();
14988 }
14989 break;
14990 }
14991 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14992 return ExprError();
14993
14994 // Some of the binary operations require promoting operands of half vector to
14995 // float vectors and truncating the result back to half vector. For now, we do
14996 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14997 // arm64).
14998 assert(
14999 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15000 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15001 "both sides are half vectors or neither sides are");
15002 ConvertHalfVec =
15003 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15004
15005 // Check for array bounds violations for both sides of the BinaryOperator
15006 CheckArrayAccess(LHS.get());
15007 CheckArrayAccess(RHS.get());
15008
15009 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15010 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15011 &Context.Idents.get("object_setClass"),
15013 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15014 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15015 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15017 "object_setClass(")
15018 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15019 ",")
15020 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15021 }
15022 else
15023 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15024 }
15025 else if (const ObjCIvarRefExpr *OIRE =
15026 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15027 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15028
15029 // Opc is not a compound assignment if CompResultTy is null.
15030 if (CompResultTy.isNull()) {
15031 if (ConvertHalfVec)
15032 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15033 OpLoc, CurFPFeatureOverrides());
15034 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15035 VK, OK, OpLoc, CurFPFeatureOverrides());
15036 }
15037
15038 // Handle compound assignments.
15039 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15041 VK = VK_LValue;
15042 OK = LHS.get()->getObjectKind();
15043 }
15044
15045 // The LHS is not converted to the result type for fixed-point compound
15046 // assignment as the common type is computed on demand. Reset the CompLHSTy
15047 // to the LHS type we would have gotten after unary conversions.
15048 if (CompResultTy->isFixedPointType())
15049 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15050
15051 if (ConvertHalfVec)
15052 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15053 OpLoc, CurFPFeatureOverrides());
15054
15056 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15057 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15058}
15059
15060/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15061/// operators are mixed in a way that suggests that the programmer forgot that
15062/// comparison operators have higher precedence. The most typical example of
15063/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15065 SourceLocation OpLoc, Expr *LHSExpr,
15066 Expr *RHSExpr) {
15067 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15068 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15069
15070 // Check that one of the sides is a comparison operator and the other isn't.
15071 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15072 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15073 if (isLeftComp == isRightComp)
15074 return;
15075
15076 // Bitwise operations are sometimes used as eager logical ops.
15077 // Don't diagnose this.
15078 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15079 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15080 if (isLeftBitwise || isRightBitwise)
15081 return;
15082
15083 SourceRange DiagRange = isLeftComp
15084 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15085 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15086 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15087 SourceRange ParensRange =
15088 isLeftComp
15089 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15090 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15091
15092 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15093 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15094 SuggestParentheses(Self, OpLoc,
15095 Self.PDiag(diag::note_precedence_silence) << OpStr,
15096 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15097 SuggestParentheses(Self, OpLoc,
15098 Self.PDiag(diag::note_precedence_bitwise_first)
15100 ParensRange);
15101}
15102
15103/// It accepts a '&&' expr that is inside a '||' one.
15104/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15105/// in parentheses.
15106static void
15108 BinaryOperator *Bop) {
15109 assert(Bop->getOpcode() == BO_LAnd);
15110 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15111 << Bop->getSourceRange() << OpLoc;
15113 Self.PDiag(diag::note_precedence_silence)
15114 << Bop->getOpcodeStr(),
15115 Bop->getSourceRange());
15116}
15117
15118/// Look for '&&' in the left hand of a '||' expr.
15120 Expr *LHSExpr, Expr *RHSExpr) {
15121 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15122 if (Bop->getOpcode() == BO_LAnd) {
15123 // If it's "string_literal && a || b" don't warn since the precedence
15124 // doesn't matter.
15125 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15126 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15127 } else if (Bop->getOpcode() == BO_LOr) {
15128 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15129 // If it's "a || b && string_literal || c" we didn't warn earlier for
15130 // "a || b && string_literal", but warn now.
15131 if (RBop->getOpcode() == BO_LAnd &&
15132 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15133 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15134 }
15135 }
15136 }
15137}
15138
15139/// Look for '&&' in the right hand of a '||' expr.
15141 Expr *LHSExpr, Expr *RHSExpr) {
15142 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15143 if (Bop->getOpcode() == BO_LAnd) {
15144 // If it's "a || b && string_literal" don't warn since the precedence
15145 // doesn't matter.
15146 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15147 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15148 }
15149 }
15150}
15151
15152/// Look for bitwise op in the left or right hand of a bitwise op with
15153/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15154/// the '&' expression in parentheses.
15156 SourceLocation OpLoc, Expr *SubExpr) {
15157 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15158 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15159 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15160 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15161 << Bop->getSourceRange() << OpLoc;
15162 SuggestParentheses(S, Bop->getOperatorLoc(),
15163 S.PDiag(diag::note_precedence_silence)
15164 << Bop->getOpcodeStr(),
15165 Bop->getSourceRange());
15166 }
15167 }
15168}
15169
15171 Expr *SubExpr, StringRef Shift) {
15172 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15173 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15174 StringRef Op = Bop->getOpcodeStr();
15175 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15176 << Bop->getSourceRange() << OpLoc << Shift << Op;
15177 SuggestParentheses(S, Bop->getOperatorLoc(),
15178 S.PDiag(diag::note_precedence_silence) << Op,
15179 Bop->getSourceRange());
15180 }
15181 }
15182}
15183
15185 Expr *LHSExpr, Expr *RHSExpr) {
15186 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15187 if (!OCE)
15188 return;
15189
15190 FunctionDecl *FD = OCE->getDirectCallee();
15191 if (!FD || !FD->isOverloadedOperator())
15192 return;
15193
15195 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15196 return;
15197
15198 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15199 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15200 << (Kind == OO_LessLess);
15202 S.PDiag(diag::note_precedence_silence)
15203 << (Kind == OO_LessLess ? "<<" : ">>"),
15204 OCE->getSourceRange());
15206 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15207 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15208}
15209
15210/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15211/// precedence.
15213 SourceLocation OpLoc, Expr *LHSExpr,
15214 Expr *RHSExpr){
15215 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15217 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15218
15219 // Diagnose "arg1 & arg2 | arg3"
15220 if ((Opc == BO_Or || Opc == BO_Xor) &&
15221 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15222 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15223 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15224 }
15225
15226 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15227 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15228 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15229 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15230 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15231 }
15232
15233 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15234 || Opc == BO_Shr) {
15235 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15236 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15237 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15238 }
15239
15240 // Warn on overloaded shift operators and comparisons, such as:
15241 // cout << 5 == 4;
15243 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15244}
15245
15247 Expr *Operand) {
15248 if (auto *CT = Operand->getType()->getAs<ComplexType>()) {
15249 QualType ElementType = CT->getElementType();
15250 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
15252 if (ElementType->isFloatingType() && IsComplexRangePromoted) {
15253 ASTContext &Ctx = S.getASTContext();
15254 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
15255 const llvm::fltSemantics &ElementTypeSemantics =
15256 Ctx.getFloatTypeSemantics(ElementType);
15257 const llvm::fltSemantics &HigherElementTypeSemantics =
15258 Ctx.getFloatTypeSemantics(HigherElementType);
15259 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
15260 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
15261 // Retain the location of the first use of higher precision type.
15264 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
15265 if (Type == HigherElementType) {
15266 Num++;
15267 return;
15268 }
15269 }
15270 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
15271 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
15272 }
15273 }
15274 }
15275}
15276
15278 tok::TokenKind Kind,
15279 Expr *LHSExpr, Expr *RHSExpr) {
15280 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15281 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15282 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15283
15284 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15285 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15286
15287 // Emit warnings if the requested higher precision type equal to the current
15288 // type precision.
15289 if (Kind == tok::TokenKind::slash)
15290 DetectPrecisionLossInComplexDivision(*this, TokLoc, LHSExpr);
15291
15292 BuiltinCountedByRefKind K =
15293 BinaryOperator::isAssignmentOp(Opc) ? AssignmentKind : BinaryExprKind;
15294
15295 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15296 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15297
15298 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15299}
15300
15302 UnresolvedSetImpl &Functions) {
15304 if (OverOp != OO_None && OverOp != OO_Equal)
15305 LookupOverloadedOperatorName(OverOp, S, Functions);
15306
15307 // In C++20 onwards, we may have a second operator to look up.
15308 if (getLangOpts().CPlusPlus20) {
15310 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15311 }
15312}
15313
15314/// Build an overloaded binary operator expression in the given scope.
15317 Expr *LHS, Expr *RHS) {
15318 switch (Opc) {
15319 case BO_Assign:
15320 // In the non-overloaded case, we warn about self-assignment (x = x) for
15321 // both simple assignment and certain compound assignments where algebra
15322 // tells us the operation yields a constant result. When the operator is
15323 // overloaded, we can't do the latter because we don't want to assume that
15324 // those algebraic identities still apply; for example, a path-building
15325 // library might use operator/= to append paths. But it's still reasonable
15326 // to assume that simple assignment is just moving/copying values around
15327 // and so self-assignment is likely a bug.
15328 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15329 [[fallthrough]];
15330 case BO_DivAssign:
15331 case BO_RemAssign:
15332 case BO_SubAssign:
15333 case BO_AndAssign:
15334 case BO_OrAssign:
15335 case BO_XorAssign:
15336 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15337 break;
15338 default:
15339 break;
15340 }
15341
15342 // Find all of the overloaded operators visible from this point.
15343 UnresolvedSet<16> Functions;
15344 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15345
15346 // Build the (potentially-overloaded, potentially-dependent)
15347 // binary operation.
15348 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15349}
15350
15353 Expr *LHSExpr, Expr *RHSExpr) {
15354 ExprResult LHS, RHS;
15355 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15356 if (!LHS.isUsable() || !RHS.isUsable())
15357 return ExprError();
15358 LHSExpr = LHS.get();
15359 RHSExpr = RHS.get();
15360
15361 // We want to end up calling one of SemaPseudoObject::checkAssignment
15362 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15363 // both expressions are overloadable or either is type-dependent),
15364 // or CreateBuiltinBinOp (in any other case). We also want to get
15365 // any placeholder types out of the way.
15366
15367 // Handle pseudo-objects in the LHS.
15368 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15369 // Assignments with a pseudo-object l-value need special analysis.
15370 if (pty->getKind() == BuiltinType::PseudoObject &&
15372 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15373
15374 // Don't resolve overloads if the other type is overloadable.
15375 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15376 // We can't actually test that if we still have a placeholder,
15377 // though. Fortunately, none of the exceptions we see in that
15378 // code below are valid when the LHS is an overload set. Note
15379 // that an overload set can be dependently-typed, but it never
15380 // instantiates to having an overloadable type.
15381 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15382 if (resolvedRHS.isInvalid()) return ExprError();
15383 RHSExpr = resolvedRHS.get();
15384
15385 if (RHSExpr->isTypeDependent() ||
15386 RHSExpr->getType()->isOverloadableType())
15387 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15388 }
15389
15390 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15391 // template, diagnose the missing 'template' keyword instead of diagnosing
15392 // an invalid use of a bound member function.
15393 //
15394 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15395 // to C++1z [over.over]/1.4, but we already checked for that case above.
15396 if (Opc == BO_LT && inTemplateInstantiation() &&
15397 (pty->getKind() == BuiltinType::BoundMember ||
15398 pty->getKind() == BuiltinType::Overload)) {
15399 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15400 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15401 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15402 return isa<FunctionTemplateDecl>(ND);
15403 })) {
15404 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15405 : OE->getNameLoc(),
15406 diag::err_template_kw_missing)
15407 << OE->getName().getAsString() << "";
15408 return ExprError();
15409 }
15410 }
15411
15412 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15413 if (LHS.isInvalid()) return ExprError();
15414 LHSExpr = LHS.get();
15415 }
15416
15417 // Handle pseudo-objects in the RHS.
15418 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15419 // An overload in the RHS can potentially be resolved by the type
15420 // being assigned to.
15421 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15422 if (getLangOpts().CPlusPlus &&
15423 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15424 LHSExpr->getType()->isOverloadableType()))
15425 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15426
15427 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15428 }
15429
15430 // Don't resolve overloads if the other type is overloadable.
15431 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15432 LHSExpr->getType()->isOverloadableType())
15433 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15434
15435 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15436 if (!resolvedRHS.isUsable()) return ExprError();
15437 RHSExpr = resolvedRHS.get();
15438 }
15439
15440 if (getLangOpts().CPlusPlus) {
15441 // Otherwise, build an overloaded op if either expression is type-dependent
15442 // or has an overloadable type.
15443 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15444 LHSExpr->getType()->isOverloadableType() ||
15445 RHSExpr->getType()->isOverloadableType())
15446 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15447 }
15448
15449 if (getLangOpts().RecoveryAST &&
15450 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15451 assert(!getLangOpts().CPlusPlus);
15452 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15453 "Should only occur in error-recovery path.");
15455 // C [6.15.16] p3:
15456 // An assignment expression has the value of the left operand after the
15457 // assignment, but is not an lvalue.
15459 Context, LHSExpr, RHSExpr, Opc,
15461 OpLoc, CurFPFeatureOverrides());
15462 QualType ResultType;
15463 switch (Opc) {
15464 case BO_Assign:
15465 ResultType = LHSExpr->getType().getUnqualifiedType();
15466 break;
15467 case BO_LT:
15468 case BO_GT:
15469 case BO_LE:
15470 case BO_GE:
15471 case BO_EQ:
15472 case BO_NE:
15473 case BO_LAnd:
15474 case BO_LOr:
15475 // These operators have a fixed result type regardless of operands.
15476 ResultType = Context.IntTy;
15477 break;
15478 case BO_Comma:
15479 ResultType = RHSExpr->getType();
15480 break;
15481 default:
15482 ResultType = Context.DependentTy;
15483 break;
15484 }
15485 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15486 VK_PRValue, OK_Ordinary, OpLoc,
15488 }
15489
15490 // Build a built-in binary operation.
15491 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15492}
15493
15495 if (T.isNull() || T->isDependentType())
15496 return false;
15497
15498 if (!Ctx.isPromotableIntegerType(T))
15499 return true;
15500
15501 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15502}
15503
15505 UnaryOperatorKind Opc, Expr *InputExpr,
15506 bool IsAfterAmp) {
15507 ExprResult Input = InputExpr;
15510 QualType resultType;
15511 bool CanOverflow = false;
15512
15513 bool ConvertHalfVec = false;
15514 if (getLangOpts().OpenCL) {
15515 QualType Ty = InputExpr->getType();
15516 // The only legal unary operation for atomics is '&'.
15517 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15518 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15519 // only with a builtin functions and therefore should be disallowed here.
15520 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15521 || Ty->isBlockPointerType())) {
15522 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15523 << InputExpr->getType()
15524 << Input.get()->getSourceRange());
15525 }
15526 }
15527
15528 if (getLangOpts().HLSL && OpLoc.isValid()) {
15529 if (Opc == UO_AddrOf)
15530 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15531 if (Opc == UO_Deref)
15532 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15533 }
15534
15535 if (InputExpr->isTypeDependent() &&
15536 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15537 resultType = Context.DependentTy;
15538 } else {
15539 switch (Opc) {
15540 case UO_PreInc:
15541 case UO_PreDec:
15542 case UO_PostInc:
15543 case UO_PostDec:
15544 resultType =
15545 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15546 Opc == UO_PreInc || Opc == UO_PostInc,
15547 Opc == UO_PreInc || Opc == UO_PreDec);
15548 CanOverflow = isOverflowingIntegerType(Context, resultType);
15549 break;
15550 case UO_AddrOf:
15551 resultType = CheckAddressOfOperand(Input, OpLoc);
15552 CheckAddressOfNoDeref(InputExpr);
15553 RecordModifiableNonNullParam(*this, InputExpr);
15554 break;
15555 case UO_Deref: {
15557 if (Input.isInvalid())
15558 return ExprError();
15559 resultType =
15560 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15561 break;
15562 }
15563 case UO_Plus:
15564 case UO_Minus:
15565 CanOverflow = Opc == UO_Minus &&
15567 Input = UsualUnaryConversions(Input.get());
15568 if (Input.isInvalid())
15569 return ExprError();
15570 // Unary plus and minus require promoting an operand of half vector to a
15571 // float vector and truncating the result back to a half vector. For now,
15572 // we do this only when HalfArgsAndReturns is set (that is, when the
15573 // target is arm or arm64).
15574 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15575
15576 // If the operand is a half vector, promote it to a float vector.
15577 if (ConvertHalfVec)
15578 Input = convertVector(Input.get(), Context.FloatTy, *this);
15579 resultType = Input.get()->getType();
15580 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15581 break;
15582 else if (resultType->isVectorType() &&
15583 // The z vector extensions don't allow + or - with bool vectors.
15584 (!Context.getLangOpts().ZVector ||
15585 resultType->castAs<VectorType>()->getVectorKind() !=
15587 break;
15588 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15589 break;
15590 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15591 Opc == UO_Plus && resultType->isPointerType())
15592 break;
15593
15594 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15595 << resultType << Input.get()->getSourceRange());
15596
15597 case UO_Not: // bitwise complement
15598 Input = UsualUnaryConversions(Input.get());
15599 if (Input.isInvalid())
15600 return ExprError();
15601 resultType = Input.get()->getType();
15602 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15603 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15604 // C99 does not support '~' for complex conjugation.
15605 Diag(OpLoc, diag::ext_integer_complement_complex)
15606 << resultType << Input.get()->getSourceRange();
15607 else if (resultType->hasIntegerRepresentation())
15608 break;
15609 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15610 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15611 // on vector float types.
15612 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15613 if (!T->isIntegerType())
15614 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15615 << resultType << Input.get()->getSourceRange());
15616 } else {
15617 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15618 << resultType << Input.get()->getSourceRange());
15619 }
15620 break;
15621
15622 case UO_LNot: // logical negation
15623 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15625 if (Input.isInvalid())
15626 return ExprError();
15627 resultType = Input.get()->getType();
15628
15629 // Though we still have to promote half FP to float...
15630 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15631 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15632 .get();
15633 resultType = Context.FloatTy;
15634 }
15635
15636 // WebAsembly tables can't be used in unary expressions.
15637 if (resultType->isPointerType() &&
15639 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15640 << resultType << Input.get()->getSourceRange());
15641 }
15642
15643 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15644 // C99 6.5.3.3p1: ok, fallthrough;
15645 if (Context.getLangOpts().CPlusPlus) {
15646 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15647 // operand contextually converted to bool.
15648 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15649 ScalarTypeToBooleanCastKind(resultType));
15650 } else if (Context.getLangOpts().OpenCL &&
15651 Context.getLangOpts().OpenCLVersion < 120) {
15652 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15653 // operate on scalar float types.
15654 if (!resultType->isIntegerType() && !resultType->isPointerType())
15655 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15656 << resultType << Input.get()->getSourceRange());
15657 }
15658 } else if (resultType->isExtVectorType()) {
15659 if (Context.getLangOpts().OpenCL &&
15661 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15662 // operate on vector float types.
15663 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15664 if (!T->isIntegerType())
15665 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15666 << resultType << Input.get()->getSourceRange());
15667 }
15668 // Vector logical not returns the signed variant of the operand type.
15669 resultType = GetSignedVectorType(resultType);
15670 break;
15671 } else if (Context.getLangOpts().CPlusPlus &&
15672 resultType->isVectorType()) {
15673 const VectorType *VTy = resultType->castAs<VectorType>();
15674 if (VTy->getVectorKind() != VectorKind::Generic)
15675 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15676 << resultType << Input.get()->getSourceRange());
15677
15678 // Vector logical not returns the signed variant of the operand type.
15679 resultType = GetSignedVectorType(resultType);
15680 break;
15681 } else {
15682 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15683 << resultType << Input.get()->getSourceRange());
15684 }
15685
15686 // LNot always has type int. C99 6.5.3.3p5.
15687 // In C++, it's bool. C++ 5.3.1p8
15688 resultType = Context.getLogicalOperationType();
15689 break;
15690 case UO_Real:
15691 case UO_Imag:
15692 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15693 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15694 // ordinary complex l-values to ordinary l-values and all other values to
15695 // r-values.
15696 if (Input.isInvalid())
15697 return ExprError();
15698 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15699 if (Input.get()->isGLValue() &&
15700 Input.get()->getObjectKind() == OK_Ordinary)
15701 VK = Input.get()->getValueKind();
15702 } else if (!getLangOpts().CPlusPlus) {
15703 // In C, a volatile scalar is read by __imag. In C++, it is not.
15704 Input = DefaultLvalueConversion(Input.get());
15705 }
15706 break;
15707 case UO_Extension:
15708 resultType = Input.get()->getType();
15709 VK = Input.get()->getValueKind();
15710 OK = Input.get()->getObjectKind();
15711 break;
15712 case UO_Coawait:
15713 // It's unnecessary to represent the pass-through operator co_await in the
15714 // AST; just return the input expression instead.
15715 assert(!Input.get()->getType()->isDependentType() &&
15716 "the co_await expression must be non-dependant before "
15717 "building operator co_await");
15718 return Input;
15719 }
15720 }
15721 if (resultType.isNull() || Input.isInvalid())
15722 return ExprError();
15723
15724 // Check for array bounds violations in the operand of the UnaryOperator,
15725 // except for the '*' and '&' operators that have to be handled specially
15726 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15727 // that are explicitly defined as valid by the standard).
15728 if (Opc != UO_AddrOf && Opc != UO_Deref)
15729 CheckArrayAccess(Input.get());
15730
15731 auto *UO =
15732 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15733 OpLoc, CanOverflow, CurFPFeatureOverrides());
15734
15735 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15736 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15738 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15739
15740 // Convert the result back to a half vector.
15741 if (ConvertHalfVec)
15742 return convertVector(UO, Context.HalfTy, *this);
15743 return UO;
15744}
15745
15747 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15748 if (!DRE->getQualifier())
15749 return false;
15750
15751 ValueDecl *VD = DRE->getDecl();
15752 if (!VD->isCXXClassMember())
15753 return false;
15754
15755 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15756 return true;
15757 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15758 return Method->isImplicitObjectMemberFunction();
15759
15760 return false;
15761 }
15762
15763 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15764 if (!ULE->getQualifier())
15765 return false;
15766
15767 for (NamedDecl *D : ULE->decls()) {
15768 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15769 if (Method->isImplicitObjectMemberFunction())
15770 return true;
15771 } else {
15772 // Overload set does not contain methods.
15773 break;
15774 }
15775 }
15776
15777 return false;
15778 }
15779
15780 return false;
15781}
15782
15784 UnaryOperatorKind Opc, Expr *Input,
15785 bool IsAfterAmp) {
15786 // First things first: handle placeholders so that the
15787 // overloaded-operator check considers the right type.
15788 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15789 // Increment and decrement of pseudo-object references.
15790 if (pty->getKind() == BuiltinType::PseudoObject &&
15792 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15793
15794 // extension is always a builtin operator.
15795 if (Opc == UO_Extension)
15796 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15797
15798 // & gets special logic for several kinds of placeholder.
15799 // The builtin code knows what to do.
15800 if (Opc == UO_AddrOf &&
15801 (pty->getKind() == BuiltinType::Overload ||
15802 pty->getKind() == BuiltinType::UnknownAny ||
15803 pty->getKind() == BuiltinType::BoundMember))
15804 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15805
15806 // Anything else needs to be handled now.
15808 if (Result.isInvalid()) return ExprError();
15809 Input = Result.get();
15810 }
15811
15812 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15814 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15815 // Find all of the overloaded operators visible from this point.
15816 UnresolvedSet<16> Functions;
15818 if (S && OverOp != OO_None)
15819 LookupOverloadedOperatorName(OverOp, S, Functions);
15820
15821 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15822 }
15823
15824 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15825}
15826
15828 Expr *Input, bool IsAfterAmp) {
15829 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15830 IsAfterAmp);
15831}
15832
15834 LabelDecl *TheDecl) {
15835 TheDecl->markUsed(Context);
15836 // Create the AST node. The address of a label always has type 'void*'.
15837 auto *Res = new (Context) AddrLabelExpr(
15838 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15839
15840 if (getCurFunction())
15841 getCurFunction()->AddrLabels.push_back(Res);
15842
15843 return Res;
15844}
15845
15848 // Make sure we diagnose jumping into a statement expression.
15850}
15851
15853 // Note that function is also called by TreeTransform when leaving a
15854 // StmtExpr scope without rebuilding anything.
15855
15858}
15859
15861 SourceLocation RPLoc) {
15862 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15863}
15864
15866 SourceLocation RPLoc, unsigned TemplateDepth) {
15867 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15868 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15869
15872 assert(!Cleanup.exprNeedsCleanups() &&
15873 "cleanups within StmtExpr not correctly bound!");
15875
15876 // FIXME: there are a variety of strange constraints to enforce here, for
15877 // example, it is not possible to goto into a stmt expression apparently.
15878 // More semantic analysis is needed.
15879
15880 // If there are sub-stmts in the compound stmt, take the type of the last one
15881 // as the type of the stmtexpr.
15882 QualType Ty = Context.VoidTy;
15883 bool StmtExprMayBindToTemp = false;
15884 if (!Compound->body_empty()) {
15885 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15886 if (const auto *LastStmt =
15887 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15888 if (const Expr *Value = LastStmt->getExprStmt()) {
15889 StmtExprMayBindToTemp = true;
15890 Ty = Value->getType();
15891 }
15892 }
15893 }
15894
15895 // FIXME: Check that expression type is complete/non-abstract; statement
15896 // expressions are not lvalues.
15897 Expr *ResStmtExpr =
15898 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15899 if (StmtExprMayBindToTemp)
15900 return MaybeBindToTemporary(ResStmtExpr);
15901 return ResStmtExpr;
15902}
15903
15905 if (ER.isInvalid())
15906 return ExprError();
15907
15908 // Do function/array conversion on the last expression, but not
15909 // lvalue-to-rvalue. However, initialize an unqualified type.
15911 if (ER.isInvalid())
15912 return ExprError();
15913 Expr *E = ER.get();
15914
15915 if (E->isTypeDependent())
15916 return E;
15917
15918 // In ARC, if the final expression ends in a consume, splice
15919 // the consume out and bind it later. In the alternate case
15920 // (when dealing with a retainable type), the result
15921 // initialization will create a produce. In both cases the
15922 // result will be +1, and we'll need to balance that out with
15923 // a bind.
15924 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15925 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15926 return Cast->getSubExpr();
15927
15928 // FIXME: Provide a better location for the initialization.
15932 SourceLocation(), E);
15933}
15934
15936 TypeSourceInfo *TInfo,
15937 ArrayRef<OffsetOfComponent> Components,
15938 SourceLocation RParenLoc) {
15939 QualType ArgTy = TInfo->getType();
15940 bool Dependent = ArgTy->isDependentType();
15941 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15942
15943 // We must have at least one component that refers to the type, and the first
15944 // one is known to be a field designator. Verify that the ArgTy represents
15945 // a struct/union/class.
15946 if (!Dependent && !ArgTy->isRecordType())
15947 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15948 << ArgTy << TypeRange);
15949
15950 // Type must be complete per C99 7.17p3 because a declaring a variable
15951 // with an incomplete type would be ill-formed.
15952 if (!Dependent
15953 && RequireCompleteType(BuiltinLoc, ArgTy,
15954 diag::err_offsetof_incomplete_type, TypeRange))
15955 return ExprError();
15956
15957 bool DidWarnAboutNonPOD = false;
15958 QualType CurrentType = ArgTy;
15961 for (const OffsetOfComponent &OC : Components) {
15962 if (OC.isBrackets) {
15963 // Offset of an array sub-field. TODO: Should we allow vector elements?
15964 if (!CurrentType->isDependentType()) {
15965 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15966 if(!AT)
15967 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15968 << CurrentType);
15969 CurrentType = AT->getElementType();
15970 } else
15971 CurrentType = Context.DependentTy;
15972
15973 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15974 if (IdxRval.isInvalid())
15975 return ExprError();
15976 Expr *Idx = IdxRval.get();
15977
15978 // The expression must be an integral expression.
15979 // FIXME: An integral constant expression?
15980 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15981 !Idx->getType()->isIntegerType())
15982 return ExprError(
15983 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15984 << Idx->getSourceRange());
15985
15986 // Record this array index.
15987 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15988 Exprs.push_back(Idx);
15989 continue;
15990 }
15991
15992 // Offset of a field.
15993 if (CurrentType->isDependentType()) {
15994 // We have the offset of a field, but we can't look into the dependent
15995 // type. Just record the identifier of the field.
15996 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15997 CurrentType = Context.DependentTy;
15998 continue;
15999 }
16000
16001 // We need to have a complete type to look into.
16002 if (RequireCompleteType(OC.LocStart, CurrentType,
16003 diag::err_offsetof_incomplete_type))
16004 return ExprError();
16005
16006 // Look for the designated field.
16007 const RecordType *RC = CurrentType->getAs<RecordType>();
16008 if (!RC)
16009 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16010 << CurrentType);
16011 RecordDecl *RD = RC->getDecl();
16012
16013 // C++ [lib.support.types]p5:
16014 // The macro offsetof accepts a restricted set of type arguments in this
16015 // International Standard. type shall be a POD structure or a POD union
16016 // (clause 9).
16017 // C++11 [support.types]p4:
16018 // If type is not a standard-layout class (Clause 9), the results are
16019 // undefined.
16020 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16021 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16022 unsigned DiagID =
16023 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16024 : diag::ext_offsetof_non_pod_type;
16025
16026 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16027 Diag(BuiltinLoc, DiagID)
16028 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16029 DidWarnAboutNonPOD = true;
16030 }
16031 }
16032
16033 // Look for the field.
16034 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16035 LookupQualifiedName(R, RD);
16036 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16037 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16038 if (!MemberDecl) {
16039 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16040 MemberDecl = IndirectMemberDecl->getAnonField();
16041 }
16042
16043 if (!MemberDecl) {
16044 // Lookup could be ambiguous when looking up a placeholder variable
16045 // __builtin_offsetof(S, _).
16046 // In that case we would already have emitted a diagnostic
16047 if (!R.isAmbiguous())
16048 Diag(BuiltinLoc, diag::err_no_member)
16049 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16050 return ExprError();
16051 }
16052
16053 // C99 7.17p3:
16054 // (If the specified member is a bit-field, the behavior is undefined.)
16055 //
16056 // We diagnose this as an error.
16057 if (MemberDecl->isBitField()) {
16058 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16059 << MemberDecl->getDeclName()
16060 << SourceRange(BuiltinLoc, RParenLoc);
16061 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16062 return ExprError();
16063 }
16064
16065 RecordDecl *Parent = MemberDecl->getParent();
16066 if (IndirectMemberDecl)
16067 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16068
16069 // If the member was found in a base class, introduce OffsetOfNodes for
16070 // the base class indirections.
16071 CXXBasePaths Paths;
16072 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16073 Paths)) {
16074 if (Paths.getDetectedVirtual()) {
16075 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16076 << MemberDecl->getDeclName()
16077 << SourceRange(BuiltinLoc, RParenLoc);
16078 return ExprError();
16079 }
16080
16081 CXXBasePath &Path = Paths.front();
16082 for (const CXXBasePathElement &B : Path)
16083 Comps.push_back(OffsetOfNode(B.Base));
16084 }
16085
16086 if (IndirectMemberDecl) {
16087 for (auto *FI : IndirectMemberDecl->chain()) {
16088 assert(isa<FieldDecl>(FI));
16089 Comps.push_back(OffsetOfNode(OC.LocStart,
16090 cast<FieldDecl>(FI), OC.LocEnd));
16091 }
16092 } else
16093 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16094
16095 CurrentType = MemberDecl->getType().getNonReferenceType();
16096 }
16097
16098 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16099 Comps, Exprs, RParenLoc);
16100}
16101
16103 SourceLocation BuiltinLoc,
16105 ParsedType ParsedArgTy,
16106 ArrayRef<OffsetOfComponent> Components,
16107 SourceLocation RParenLoc) {
16108
16109 TypeSourceInfo *ArgTInfo;
16110 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16111 if (ArgTy.isNull())
16112 return ExprError();
16113
16114 if (!ArgTInfo)
16115 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16116
16117 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16118}
16119
16120
16122 Expr *CondExpr,
16123 Expr *LHSExpr, Expr *RHSExpr,
16124 SourceLocation RPLoc) {
16125 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16126
16129 QualType resType;
16130 bool CondIsTrue = false;
16131 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16132 resType = Context.DependentTy;
16133 } else {
16134 // The conditional expression is required to be a constant expression.
16135 llvm::APSInt condEval(32);
16137 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16138 if (CondICE.isInvalid())
16139 return ExprError();
16140 CondExpr = CondICE.get();
16141 CondIsTrue = condEval.getZExtValue();
16142
16143 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16144 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16145
16146 resType = ActiveExpr->getType();
16147 VK = ActiveExpr->getValueKind();
16148 OK = ActiveExpr->getObjectKind();
16149 }
16150
16151 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16152 resType, VK, OK, RPLoc, CondIsTrue);
16153}
16154
16155//===----------------------------------------------------------------------===//
16156// Clang Extensions.
16157//===----------------------------------------------------------------------===//
16158
16159void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16161
16162 if (LangOpts.CPlusPlus) {
16164 Decl *ManglingContextDecl;
16165 std::tie(MCtx, ManglingContextDecl) =
16166 getCurrentMangleNumberContext(Block->getDeclContext());
16167 if (MCtx) {
16168 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16169 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16170 }
16171 }
16172
16173 PushBlockScope(CurScope, Block);
16175 if (CurScope)
16176 PushDeclContext(CurScope, Block);
16177 else
16178 CurContext = Block;
16179
16181
16182 // Enter a new evaluation context to insulate the block from any
16183 // cleanups from the enclosing full-expression.
16186}
16187
16189 Scope *CurScope) {
16190 assert(ParamInfo.getIdentifier() == nullptr &&
16191 "block-id should have no identifier!");
16192 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16193 BlockScopeInfo *CurBlock = getCurBlock();
16194
16195 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16196 QualType T = Sig->getType();
16198
16199 // GetTypeForDeclarator always produces a function type for a block
16200 // literal signature. Furthermore, it is always a FunctionProtoType
16201 // unless the function was written with a typedef.
16202 assert(T->isFunctionType() &&
16203 "GetTypeForDeclarator made a non-function block signature");
16204
16205 // Look for an explicit signature in that function type.
16206 FunctionProtoTypeLoc ExplicitSignature;
16207
16208 if ((ExplicitSignature = Sig->getTypeLoc()
16210
16211 // Check whether that explicit signature was synthesized by
16212 // GetTypeForDeclarator. If so, don't save that as part of the
16213 // written signature.
16214 if (ExplicitSignature.getLocalRangeBegin() ==
16215 ExplicitSignature.getLocalRangeEnd()) {
16216 // This would be much cheaper if we stored TypeLocs instead of
16217 // TypeSourceInfos.
16218 TypeLoc Result = ExplicitSignature.getReturnLoc();
16219 unsigned Size = Result.getFullDataSize();
16220 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16221 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16222
16223 ExplicitSignature = FunctionProtoTypeLoc();
16224 }
16225 }
16226
16227 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16228 CurBlock->FunctionType = T;
16229
16230 const auto *Fn = T->castAs<FunctionType>();
16231 QualType RetTy = Fn->getReturnType();
16232 bool isVariadic =
16233 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16234
16235 CurBlock->TheDecl->setIsVariadic(isVariadic);
16236
16237 // Context.DependentTy is used as a placeholder for a missing block
16238 // return type. TODO: what should we do with declarators like:
16239 // ^ * { ... }
16240 // If the answer is "apply template argument deduction"....
16241 if (RetTy != Context.DependentTy) {
16242 CurBlock->ReturnType = RetTy;
16243 CurBlock->TheDecl->setBlockMissingReturnType(false);
16244 CurBlock->HasImplicitReturnType = false;
16245 }
16246
16247 // Push block parameters from the declarator if we had them.
16249 if (ExplicitSignature) {
16250 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16251 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16252 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16253 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16254 // Diagnose this as an extension in C17 and earlier.
16255 if (!getLangOpts().C23)
16256 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16257 }
16258 Params.push_back(Param);
16259 }
16260
16261 // Fake up parameter variables if we have a typedef, like
16262 // ^ fntype { ... }
16263 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16264 for (const auto &I : Fn->param_types()) {
16266 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16267 Params.push_back(Param);
16268 }
16269 }
16270
16271 // Set the parameters on the block decl.
16272 if (!Params.empty()) {
16273 CurBlock->TheDecl->setParams(Params);
16275 /*CheckParameterNames=*/false);
16276 }
16277
16278 // Finally we can process decl attributes.
16279 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16280
16281 // Put the parameter variables in scope.
16282 for (auto *AI : CurBlock->TheDecl->parameters()) {
16283 AI->setOwningFunction(CurBlock->TheDecl);
16284
16285 // If this has an identifier, add it to the scope stack.
16286 if (AI->getIdentifier()) {
16287 CheckShadow(CurBlock->TheScope, AI);
16288
16289 PushOnScopeChains(AI, CurBlock->TheScope);
16290 }
16291
16292 if (AI->isInvalidDecl())
16293 CurBlock->TheDecl->setInvalidDecl();
16294 }
16295}
16296
16297void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16298 // Leave the expression-evaluation context.
16301
16302 // Pop off CurBlock, handle nested blocks.
16305}
16306
16308 Stmt *Body, Scope *CurScope) {
16309 // If blocks are disabled, emit an error.
16310 if (!LangOpts.Blocks)
16311 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16312
16313 // Leave the expression-evaluation context.
16316 assert(!Cleanup.exprNeedsCleanups() &&
16317 "cleanups within block not correctly bound!");
16319
16320 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16321 BlockDecl *BD = BSI->TheDecl;
16322
16324
16325 if (BSI->HasImplicitReturnType)
16327
16328 QualType RetTy = Context.VoidTy;
16329 if (!BSI->ReturnType.isNull())
16330 RetTy = BSI->ReturnType;
16331
16332 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16333 QualType BlockTy;
16334
16335 // If the user wrote a function type in some form, try to use that.
16336 if (!BSI->FunctionType.isNull()) {
16337 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16338
16339 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16340 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16341
16342 // Turn protoless block types into nullary block types.
16343 if (isa<FunctionNoProtoType>(FTy)) {
16345 EPI.ExtInfo = Ext;
16346 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16347
16348 // Otherwise, if we don't need to change anything about the function type,
16349 // preserve its sugar structure.
16350 } else if (FTy->getReturnType() == RetTy &&
16351 (!NoReturn || FTy->getNoReturnAttr())) {
16352 BlockTy = BSI->FunctionType;
16353
16354 // Otherwise, make the minimal modifications to the function type.
16355 } else {
16356 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16358 EPI.TypeQuals = Qualifiers();
16359 EPI.ExtInfo = Ext;
16360 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16361 }
16362
16363 // If we don't have a function type, just build one from nothing.
16364 } else {
16366 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16367 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16368 }
16369
16371 BlockTy = Context.getBlockPointerType(BlockTy);
16372
16373 // If needed, diagnose invalid gotos and switches in the block.
16374 if (getCurFunction()->NeedsScopeChecking() &&
16376 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16377
16378 BD->setBody(cast<CompoundStmt>(Body));
16379
16380 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16382
16383 // Try to apply the named return value optimization. We have to check again
16384 // if we can do this, though, because blocks keep return statements around
16385 // to deduce an implicit return type.
16386 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16387 !BD->isDependentContext())
16388 computeNRVO(Body, BSI);
16389
16394
16396
16397 // Set the captured variables on the block.
16399 for (Capture &Cap : BSI->Captures) {
16400 if (Cap.isInvalid() || Cap.isThisCapture())
16401 continue;
16402 // Cap.getVariable() is always a VarDecl because
16403 // blocks cannot capture structured bindings or other ValueDecl kinds.
16404 auto *Var = cast<VarDecl>(Cap.getVariable());
16405 Expr *CopyExpr = nullptr;
16406 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16407 if (const RecordType *Record =
16408 Cap.getCaptureType()->getAs<RecordType>()) {
16409 // The capture logic needs the destructor, so make sure we mark it.
16410 // Usually this is unnecessary because most local variables have
16411 // their destructors marked at declaration time, but parameters are
16412 // an exception because it's technically only the call site that
16413 // actually requires the destructor.
16414 if (isa<ParmVarDecl>(Var))
16416
16417 // Enter a separate potentially-evaluated context while building block
16418 // initializers to isolate their cleanups from those of the block
16419 // itself.
16420 // FIXME: Is this appropriate even when the block itself occurs in an
16421 // unevaluated operand?
16424
16426
16428 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16429
16430 // According to the blocks spec, the capture of a variable from
16431 // the stack requires a const copy constructor. This is not true
16432 // of the copy/move done to move a __block variable to the heap.
16433 if (!Result.isInvalid() &&
16434 !Result.get()->getType().isConstQualified()) {
16436 Result.get()->getType().withConst(),
16437 CK_NoOp, VK_LValue);
16438 }
16439
16440 if (!Result.isInvalid()) {
16442 InitializedEntity::InitializeBlock(Var->getLocation(),
16443 Cap.getCaptureType()),
16444 Loc, Result.get());
16445 }
16446
16447 // Build a full-expression copy expression if initialization
16448 // succeeded and used a non-trivial constructor. Recover from
16449 // errors by pretending that the copy isn't necessary.
16450 if (!Result.isInvalid() &&
16451 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16452 ->isTrivial()) {
16454 CopyExpr = Result.get();
16455 }
16456 }
16457 }
16458
16459 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16460 CopyExpr);
16461 Captures.push_back(NewCap);
16462 }
16463 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16464
16465 // Pop the block scope now but keep it alive to the end of this function.
16467 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16468
16469 BlockExpr *Result = new (Context)
16470 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16471
16472 // If the block isn't obviously global, i.e. it captures anything at
16473 // all, then we need to do a few things in the surrounding context:
16474 if (Result->getBlockDecl()->hasCaptures()) {
16475 // First, this expression has a new cleanup object.
16476 ExprCleanupObjects.push_back(Result->getBlockDecl());
16478
16479 // It also gets a branch-protected scope if any of the captured
16480 // variables needs destruction.
16481 for (const auto &CI : Result->getBlockDecl()->captures()) {
16482 const VarDecl *var = CI.getVariable();
16483 if (var->getType().isDestructedType() != QualType::DK_none) {
16485 break;
16486 }
16487 }
16488 }
16489
16490 if (getCurFunction())
16491 getCurFunction()->addBlock(BD);
16492
16493 // This can happen if the block's return type is deduced, but
16494 // the return expression is invalid.
16495 if (BD->isInvalidDecl())
16496 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16497 {Result}, Result->getType());
16498 return Result;
16499}
16500
16502 SourceLocation RPLoc) {
16503 TypeSourceInfo *TInfo;
16504 GetTypeFromParser(Ty, &TInfo);
16505 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16506}
16507
16509 Expr *E, TypeSourceInfo *TInfo,
16510 SourceLocation RPLoc) {
16511 Expr *OrigExpr = E;
16512 bool IsMS = false;
16513
16514 // CUDA device code does not support varargs.
16515 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16516 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16520 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16521 }
16522 }
16523
16524 // NVPTX does not support va_arg expression.
16525 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16526 Context.getTargetInfo().getTriple().isNVPTX())
16527 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16528
16529 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16530 // as Microsoft ABI on an actual Microsoft platform, where
16531 // __builtin_ms_va_list and __builtin_va_list are the same.)
16534 QualType MSVaListType = Context.getBuiltinMSVaListType();
16535 if (Context.hasSameType(MSVaListType, E->getType())) {
16536 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16537 return ExprError();
16538 IsMS = true;
16539 }
16540 }
16541
16542 // Get the va_list type
16543 QualType VaListType = Context.getBuiltinVaListType();
16544 if (!IsMS) {
16545 if (VaListType->isArrayType()) {
16546 // Deal with implicit array decay; for example, on x86-64,
16547 // va_list is an array, but it's supposed to decay to
16548 // a pointer for va_arg.
16549 VaListType = Context.getArrayDecayedType(VaListType);
16550 // Make sure the input expression also decays appropriately.
16552 if (Result.isInvalid())
16553 return ExprError();
16554 E = Result.get();
16555 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16556 // If va_list is a record type and we are compiling in C++ mode,
16557 // check the argument using reference binding.
16559 Context, Context.getLValueReferenceType(VaListType), false);
16561 if (Init.isInvalid())
16562 return ExprError();
16563 E = Init.getAs<Expr>();
16564 } else {
16565 // Otherwise, the va_list argument must be an l-value because
16566 // it is modified by va_arg.
16567 if (!E->isTypeDependent() &&
16568 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16569 return ExprError();
16570 }
16571 }
16572
16573 if (!IsMS && !E->isTypeDependent() &&
16574 !Context.hasSameType(VaListType, E->getType()))
16575 return ExprError(
16576 Diag(E->getBeginLoc(),
16577 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16578 << OrigExpr->getType() << E->getSourceRange());
16579
16580 if (!TInfo->getType()->isDependentType()) {
16581 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16582 diag::err_second_parameter_to_va_arg_incomplete,
16583 TInfo->getTypeLoc()))
16584 return ExprError();
16585
16587 TInfo->getType(),
16588 diag::err_second_parameter_to_va_arg_abstract,
16589 TInfo->getTypeLoc()))
16590 return ExprError();
16591
16592 if (!TInfo->getType().isPODType(Context)) {
16593 Diag(TInfo->getTypeLoc().getBeginLoc(),
16594 TInfo->getType()->isObjCLifetimeType()
16595 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16596 : diag::warn_second_parameter_to_va_arg_not_pod)
16597 << TInfo->getType()
16598 << TInfo->getTypeLoc().getSourceRange();
16599 }
16600
16601 if (TInfo->getType()->isArrayType()) {
16603 PDiag(diag::warn_second_parameter_to_va_arg_array)
16604 << TInfo->getType()
16605 << TInfo->getTypeLoc().getSourceRange());
16606 }
16607
16608 // Check for va_arg where arguments of the given type will be promoted
16609 // (i.e. this va_arg is guaranteed to have undefined behavior).
16610 QualType PromoteType;
16611 if (Context.isPromotableIntegerType(TInfo->getType())) {
16612 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16613 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16614 // and C23 7.16.1.1p2 says, in part:
16615 // If type is not compatible with the type of the actual next argument
16616 // (as promoted according to the default argument promotions), the
16617 // behavior is undefined, except for the following cases:
16618 // - both types are pointers to qualified or unqualified versions of
16619 // compatible types;
16620 // - one type is compatible with a signed integer type, the other
16621 // type is compatible with the corresponding unsigned integer type,
16622 // and the value is representable in both types;
16623 // - one type is pointer to qualified or unqualified void and the
16624 // other is a pointer to a qualified or unqualified character type;
16625 // - or, the type of the next argument is nullptr_t and type is a
16626 // pointer type that has the same representation and alignment
16627 // requirements as a pointer to a character type.
16628 // Given that type compatibility is the primary requirement (ignoring
16629 // qualifications), you would think we could call typesAreCompatible()
16630 // directly to test this. However, in C++, that checks for *same type*,
16631 // which causes false positives when passing an enumeration type to
16632 // va_arg. Instead, get the underlying type of the enumeration and pass
16633 // that.
16634 QualType UnderlyingType = TInfo->getType();
16635 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16636 UnderlyingType = ET->getDecl()->getIntegerType();
16637 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16638 /*CompareUnqualified*/ true))
16639 PromoteType = QualType();
16640
16641 // If the types are still not compatible, we need to test whether the
16642 // promoted type and the underlying type are the same except for
16643 // signedness. Ask the AST for the correctly corresponding type and see
16644 // if that's compatible.
16645 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16646 PromoteType->isUnsignedIntegerType() !=
16647 UnderlyingType->isUnsignedIntegerType()) {
16648 UnderlyingType =
16649 UnderlyingType->isUnsignedIntegerType()
16650 ? Context.getCorrespondingSignedType(UnderlyingType)
16651 : Context.getCorrespondingUnsignedType(UnderlyingType);
16652 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16653 /*CompareUnqualified*/ true))
16654 PromoteType = QualType();
16655 }
16656 }
16657 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16658 PromoteType = Context.DoubleTy;
16659 if (!PromoteType.isNull())
16661 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16662 << TInfo->getType()
16663 << PromoteType
16664 << TInfo->getTypeLoc().getSourceRange());
16665 }
16666
16668 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16669}
16670
16672 // The type of __null will be int or long, depending on the size of
16673 // pointers on the target.
16674 QualType Ty;
16676 if (pw == Context.getTargetInfo().getIntWidth())
16677 Ty = Context.IntTy;
16678 else if (pw == Context.getTargetInfo().getLongWidth())
16679 Ty = Context.LongTy;
16680 else if (pw == Context.getTargetInfo().getLongLongWidth())
16681 Ty = Context.LongLongTy;
16682 else {
16683 llvm_unreachable("I don't know size of pointer!");
16684 }
16685
16686 return new (Context) GNUNullExpr(Ty, TokenLoc);
16687}
16688
16690 CXXRecordDecl *ImplDecl = nullptr;
16691
16692 // Fetch the std::source_location::__impl decl.
16693 if (NamespaceDecl *Std = S.getStdNamespace()) {
16694 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16696 if (S.LookupQualifiedName(ResultSL, Std)) {
16697 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16698 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16700 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16701 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16702 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16703 }
16704 }
16705 }
16706 }
16707
16708 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16709 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16710 return nullptr;
16711 }
16712
16713 // Verify that __impl is a trivial struct type, with no base classes, and with
16714 // only the four expected fields.
16715 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16716 ImplDecl->getNumBases() != 0) {
16717 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16718 return nullptr;
16719 }
16720
16721 unsigned Count = 0;
16722 for (FieldDecl *F : ImplDecl->fields()) {
16723 StringRef Name = F->getName();
16724
16725 if (Name == "_M_file_name") {
16726 if (F->getType() !=
16728 break;
16729 Count++;
16730 } else if (Name == "_M_function_name") {
16731 if (F->getType() !=
16733 break;
16734 Count++;
16735 } else if (Name == "_M_line") {
16736 if (!F->getType()->isIntegerType())
16737 break;
16738 Count++;
16739 } else if (Name == "_M_column") {
16740 if (!F->getType()->isIntegerType())
16741 break;
16742 Count++;
16743 } else {
16744 Count = 100; // invalid
16745 break;
16746 }
16747 }
16748 if (Count != 4) {
16749 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16750 return nullptr;
16751 }
16752
16753 return ImplDecl;
16754}
16755
16757 SourceLocation BuiltinLoc,
16758 SourceLocation RPLoc) {
16759 QualType ResultTy;
16760 switch (Kind) {
16766 ResultTy =
16768 break;
16769 }
16772 ResultTy = Context.UnsignedIntTy;
16773 break;
16777 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16779 return ExprError();
16780 }
16781 ResultTy = Context.getPointerType(
16783 break;
16784 }
16785
16786 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16787}
16788
16790 SourceLocation BuiltinLoc,
16791 SourceLocation RPLoc,
16792 DeclContext *ParentContext) {
16793 return new (Context)
16794 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16795}
16796
16798 StringLiteral *BinaryData) {
16800 Data->BinaryData = BinaryData;
16801 return new (Context)
16802 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16803 Data->getDataElementCount());
16804}
16805
16807 const Expr *SrcExpr) {
16808 if (!DstType->isFunctionPointerType() ||
16809 !SrcExpr->getType()->isFunctionType())
16810 return false;
16811
16812 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16813 if (!DRE)
16814 return false;
16815
16816 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16817 if (!FD)
16818 return false;
16819
16821 /*Complain=*/true,
16822 SrcExpr->getBeginLoc());
16823}
16824
16827 QualType DstType, QualType SrcType,
16828 Expr *SrcExpr, AssignmentAction Action,
16829 bool *Complained) {
16830 if (Complained)
16831 *Complained = false;
16832
16833 // Decode the result (notice that AST's are still created for extensions).
16834 bool CheckInferredResultType = false;
16835 bool isInvalid = false;
16836 unsigned DiagKind = 0;
16837 ConversionFixItGenerator ConvHints;
16838 bool MayHaveConvFixit = false;
16839 bool MayHaveFunctionDiff = false;
16840 const ObjCInterfaceDecl *IFace = nullptr;
16841 const ObjCProtocolDecl *PDecl = nullptr;
16842
16843 switch (ConvTy) {
16844 case Compatible:
16845 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16846 return false;
16847
16848 case PointerToInt:
16849 if (getLangOpts().CPlusPlus) {
16850 DiagKind = diag::err_typecheck_convert_pointer_int;
16851 isInvalid = true;
16852 } else {
16853 DiagKind = diag::ext_typecheck_convert_pointer_int;
16854 }
16855 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16856 MayHaveConvFixit = true;
16857 break;
16858 case IntToPointer:
16859 if (getLangOpts().CPlusPlus) {
16860 DiagKind = diag::err_typecheck_convert_int_pointer;
16861 isInvalid = true;
16862 } else {
16863 DiagKind = diag::ext_typecheck_convert_int_pointer;
16864 }
16865 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16866 MayHaveConvFixit = true;
16867 break;
16869 DiagKind =
16870 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16871 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16872 MayHaveConvFixit = true;
16873 break;
16875 if (getLangOpts().CPlusPlus) {
16876 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16877 isInvalid = true;
16878 } else {
16879 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16880 }
16881 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16882 MayHaveConvFixit = true;
16883 break;
16886 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16887 } else if (getLangOpts().CPlusPlus) {
16888 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16889 isInvalid = true;
16890 } else {
16891 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16892 }
16893 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16894 SrcType->isObjCObjectPointerType();
16895 if (CheckInferredResultType) {
16896 SrcType = SrcType.getUnqualifiedType();
16897 DstType = DstType.getUnqualifiedType();
16898 } else {
16899 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16900 }
16901 MayHaveConvFixit = true;
16902 break;
16904 if (getLangOpts().CPlusPlus) {
16905 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16906 isInvalid = true;
16907 } else {
16908 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16909 }
16910 break;
16912 if (getLangOpts().CPlusPlus) {
16913 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16914 isInvalid = true;
16915 } else {
16916 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16917 }
16918 break;
16920 // Perform array-to-pointer decay if necessary.
16921 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16922
16923 isInvalid = true;
16924
16925 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16926 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16927 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16928 DiagKind = diag::err_typecheck_incompatible_address_space;
16929 break;
16930 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16931 DiagKind = diag::err_typecheck_incompatible_ownership;
16932 break;
16933 }
16934
16935 llvm_unreachable("unknown error case for discarding qualifiers!");
16936 // fallthrough
16937 }
16939 // If the qualifiers lost were because we were applying the
16940 // (deprecated) C++ conversion from a string literal to a char*
16941 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16942 // Ideally, this check would be performed in
16943 // checkPointerTypesForAssignment. However, that would require a
16944 // bit of refactoring (so that the second argument is an
16945 // expression, rather than a type), which should be done as part
16946 // of a larger effort to fix checkPointerTypesForAssignment for
16947 // C++ semantics.
16948 if (getLangOpts().CPlusPlus &&
16950 return false;
16951 if (getLangOpts().CPlusPlus) {
16952 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16953 isInvalid = true;
16954 } else {
16955 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16956 }
16957
16958 break;
16960 if (getLangOpts().CPlusPlus) {
16961 isInvalid = true;
16962 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16963 } else {
16964 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16965 }
16966 break;
16968 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16969 isInvalid = true;
16970 break;
16971 case IntToBlockPointer:
16972 DiagKind = diag::err_int_to_block_pointer;
16973 isInvalid = true;
16974 break;
16976 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16977 isInvalid = true;
16978 break;
16980 if (SrcType->isObjCQualifiedIdType()) {
16981 const ObjCObjectPointerType *srcOPT =
16982 SrcType->castAs<ObjCObjectPointerType>();
16983 for (auto *srcProto : srcOPT->quals()) {
16984 PDecl = srcProto;
16985 break;
16986 }
16987 if (const ObjCInterfaceType *IFaceT =
16989 IFace = IFaceT->getDecl();
16990 }
16991 else if (DstType->isObjCQualifiedIdType()) {
16992 const ObjCObjectPointerType *dstOPT =
16993 DstType->castAs<ObjCObjectPointerType>();
16994 for (auto *dstProto : dstOPT->quals()) {
16995 PDecl = dstProto;
16996 break;
16997 }
16998 if (const ObjCInterfaceType *IFaceT =
17000 IFace = IFaceT->getDecl();
17001 }
17002 if (getLangOpts().CPlusPlus) {
17003 DiagKind = diag::err_incompatible_qualified_id;
17004 isInvalid = true;
17005 } else {
17006 DiagKind = diag::warn_incompatible_qualified_id;
17007 }
17008 break;
17009 }
17011 if (getLangOpts().CPlusPlus) {
17012 DiagKind = diag::err_incompatible_vectors;
17013 isInvalid = true;
17014 } else {
17015 DiagKind = diag::warn_incompatible_vectors;
17016 }
17017 break;
17019 DiagKind = diag::err_arc_weak_unavailable_assign;
17020 isInvalid = true;
17021 break;
17022 case Incompatible:
17023 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17024 if (Complained)
17025 *Complained = true;
17026 return true;
17027 }
17028
17029 DiagKind = diag::err_typecheck_convert_incompatible;
17030 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17031 MayHaveConvFixit = true;
17032 isInvalid = true;
17033 MayHaveFunctionDiff = true;
17034 break;
17035 }
17036
17037 QualType FirstType, SecondType;
17038 switch (Action) {
17041 // The destination type comes first.
17042 FirstType = DstType;
17043 SecondType = SrcType;
17044 break;
17045
17052 // The source type comes first.
17053 FirstType = SrcType;
17054 SecondType = DstType;
17055 break;
17056 }
17057
17058 PartialDiagnostic FDiag = PDiag(DiagKind);
17059 AssignmentAction ActionForDiag = Action;
17061 ActionForDiag = AssignmentAction::Passing;
17062
17063 FDiag << FirstType << SecondType << ActionForDiag
17064 << SrcExpr->getSourceRange();
17065
17066 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17067 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17068 auto isPlainChar = [](const clang::Type *Type) {
17069 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17070 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17071 };
17072 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17073 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17074 }
17075
17076 // If we can fix the conversion, suggest the FixIts.
17077 if (!ConvHints.isNull()) {
17078 for (FixItHint &H : ConvHints.Hints)
17079 FDiag << H;
17080 }
17081
17082 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17083
17084 if (MayHaveFunctionDiff)
17085 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17086
17087 Diag(Loc, FDiag);
17088 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17089 DiagKind == diag::err_incompatible_qualified_id) &&
17090 PDecl && IFace && !IFace->hasDefinition())
17091 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17092 << IFace << PDecl;
17093
17094 if (SecondType == Context.OverloadTy)
17096 FirstType, /*TakingAddress=*/true);
17097
17098 if (CheckInferredResultType)
17100
17101 if (Action == AssignmentAction::Returning && ConvTy == IncompatiblePointer)
17103
17104 if (Complained)
17105 *Complained = true;
17106 return isInvalid;
17107}
17108
17110 llvm::APSInt *Result,
17111 AllowFoldKind CanFold) {
17112 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17113 public:
17114 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17115 QualType T) override {
17116 return S.Diag(Loc, diag::err_ice_not_integral)
17117 << T << S.LangOpts.CPlusPlus;
17118 }
17119 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17120 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17121 }
17122 } Diagnoser;
17123
17124 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17125}
17126
17128 llvm::APSInt *Result,
17129 unsigned DiagID,
17130 AllowFoldKind CanFold) {
17131 class IDDiagnoser : public VerifyICEDiagnoser {
17132 unsigned DiagID;
17133
17134 public:
17135 IDDiagnoser(unsigned DiagID)
17136 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17137
17138 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17139 return S.Diag(Loc, DiagID);
17140 }
17141 } Diagnoser(DiagID);
17142
17143 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17144}
17145
17148 QualType T) {
17149 return diagnoseNotICE(S, Loc);
17150}
17151
17154 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17155}
17156
17159 VerifyICEDiagnoser &Diagnoser,
17160 AllowFoldKind CanFold) {
17161 SourceLocation DiagLoc = E->getBeginLoc();
17162
17163 if (getLangOpts().CPlusPlus11) {
17164 // C++11 [expr.const]p5:
17165 // If an expression of literal class type is used in a context where an
17166 // integral constant expression is required, then that class type shall
17167 // have a single non-explicit conversion function to an integral or
17168 // unscoped enumeration type
17169 ExprResult Converted;
17170 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17171 VerifyICEDiagnoser &BaseDiagnoser;
17172 public:
17173 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17174 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17175 BaseDiagnoser.Suppress, true),
17176 BaseDiagnoser(BaseDiagnoser) {}
17177
17178 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17179 QualType T) override {
17180 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17181 }
17182
17183 SemaDiagnosticBuilder diagnoseIncomplete(
17184 Sema &S, SourceLocation Loc, QualType T) override {
17185 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17186 }
17187
17188 SemaDiagnosticBuilder diagnoseExplicitConv(
17189 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17190 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17191 }
17192
17193 SemaDiagnosticBuilder noteExplicitConv(
17194 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17195 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17196 << ConvTy->isEnumeralType() << ConvTy;
17197 }
17198
17199 SemaDiagnosticBuilder diagnoseAmbiguous(
17200 Sema &S, SourceLocation Loc, QualType T) override {
17201 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17202 }
17203
17204 SemaDiagnosticBuilder noteAmbiguous(
17205 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17206 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17207 << ConvTy->isEnumeralType() << ConvTy;
17208 }
17209
17210 SemaDiagnosticBuilder diagnoseConversion(
17211 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17212 llvm_unreachable("conversion functions are permitted");
17213 }
17214 } ConvertDiagnoser(Diagnoser);
17215
17216 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17217 ConvertDiagnoser);
17218 if (Converted.isInvalid())
17219 return Converted;
17220 E = Converted.get();
17221 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17222 // don't try to evaluate it later. We also don't want to return the
17223 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17224 // this function will attempt to use 'Value'.
17225 if (isa<RecoveryExpr>(E))
17226 return ExprError();
17228 return ExprError();
17229 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17230 // An ICE must be of integral or unscoped enumeration type.
17231 if (!Diagnoser.Suppress)
17232 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17233 << E->getSourceRange();
17234 return ExprError();
17235 }
17236
17237 ExprResult RValueExpr = DefaultLvalueConversion(E);
17238 if (RValueExpr.isInvalid())
17239 return ExprError();
17240
17241 E = RValueExpr.get();
17242
17243 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17244 // in the non-ICE case.
17247 if (Result)
17249 if (!isa<ConstantExpr>(E))
17252
17253 if (Notes.empty())
17254 return E;
17255
17256 // If our only note is the usual "invalid subexpression" note, just point
17257 // the caret at its location rather than producing an essentially
17258 // redundant note.
17259 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17260 diag::note_invalid_subexpr_in_const_expr) {
17261 DiagLoc = Notes[0].first;
17262 Notes.clear();
17263 }
17264
17265 if (getLangOpts().CPlusPlus) {
17266 if (!Diagnoser.Suppress) {
17267 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17268 for (const PartialDiagnosticAt &Note : Notes)
17269 Diag(Note.first, Note.second);
17270 }
17271 return ExprError();
17272 }
17273
17274 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17275 for (const PartialDiagnosticAt &Note : Notes)
17276 Diag(Note.first, Note.second);
17277
17278 return E;
17279 }
17280
17281 Expr::EvalResult EvalResult;
17283 EvalResult.Diag = &Notes;
17284
17285 // Try to evaluate the expression, and produce diagnostics explaining why it's
17286 // not a constant expression as a side-effect.
17287 bool Folded =
17288 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17289 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17290 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17291
17292 if (!isa<ConstantExpr>(E))
17293 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17294
17295 // In C++11, we can rely on diagnostics being produced for any expression
17296 // which is not a constant expression. If no diagnostics were produced, then
17297 // this is a constant expression.
17298 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17299 if (Result)
17300 *Result = EvalResult.Val.getInt();
17301 return E;
17302 }
17303
17304 // If our only note is the usual "invalid subexpression" note, just point
17305 // the caret at its location rather than producing an essentially
17306 // redundant note.
17307 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17308 diag::note_invalid_subexpr_in_const_expr) {
17309 DiagLoc = Notes[0].first;
17310 Notes.clear();
17311 }
17312
17313 if (!Folded || !CanFold) {
17314 if (!Diagnoser.Suppress) {
17315 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17316 for (const PartialDiagnosticAt &Note : Notes)
17317 Diag(Note.first, Note.second);
17318 }
17319
17320 return ExprError();
17321 }
17322
17323 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17324 for (const PartialDiagnosticAt &Note : Notes)
17325 Diag(Note.first, Note.second);
17326
17327 if (Result)
17328 *Result = EvalResult.Val.getInt();
17329 return E;
17330}
17331
17332namespace {
17333 // Handle the case where we conclude a expression which we speculatively
17334 // considered to be unevaluated is actually evaluated.
17335 class TransformToPE : public TreeTransform<TransformToPE> {
17336 typedef TreeTransform<TransformToPE> BaseTransform;
17337
17338 public:
17339 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17340
17341 // Make sure we redo semantic analysis
17342 bool AlwaysRebuild() { return true; }
17343 bool ReplacingOriginal() { return true; }
17344
17345 // We need to special-case DeclRefExprs referring to FieldDecls which
17346 // are not part of a member pointer formation; normal TreeTransforming
17347 // doesn't catch this case because of the way we represent them in the AST.
17348 // FIXME: This is a bit ugly; is it really the best way to handle this
17349 // case?
17350 //
17351 // Error on DeclRefExprs referring to FieldDecls.
17352 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17353 if (isa<FieldDecl>(E->getDecl()) &&
17354 !SemaRef.isUnevaluatedContext())
17355 return SemaRef.Diag(E->getLocation(),
17356 diag::err_invalid_non_static_member_use)
17357 << E->getDecl() << E->getSourceRange();
17358
17359 return BaseTransform::TransformDeclRefExpr(E);
17360 }
17361
17362 // Exception: filter out member pointer formation
17363 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17364 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17365 return E;
17366
17367 return BaseTransform::TransformUnaryOperator(E);
17368 }
17369
17370 // The body of a lambda-expression is in a separate expression evaluation
17371 // context so never needs to be transformed.
17372 // FIXME: Ideally we wouldn't transform the closure type either, and would
17373 // just recreate the capture expressions and lambda expression.
17374 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17375 return SkipLambdaBody(E, Body);
17376 }
17377 };
17378}
17379
17381 assert(isUnevaluatedContext() &&
17382 "Should only transform unevaluated expressions");
17383 ExprEvalContexts.back().Context =
17384 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17386 return E;
17387 return TransformToPE(*this).TransformExpr(E);
17388}
17389
17391 assert(isUnevaluatedContext() &&
17392 "Should only transform unevaluated expressions");
17395 return TInfo;
17396 return TransformToPE(*this).TransformType(TInfo);
17397}
17398
17399void
17401 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17403 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17404 LambdaContextDecl, ExprContext);
17405
17406 // Discarded statements and immediate contexts nested in other
17407 // discarded statements or immediate context are themselves
17408 // a discarded statement or an immediate context, respectively.
17409 ExprEvalContexts.back().InDiscardedStatement =
17411
17412 // C++23 [expr.const]/p15
17413 // An expression or conversion is in an immediate function context if [...]
17414 // it is a subexpression of a manifestly constant-evaluated expression or
17415 // conversion.
17416 const auto &Prev = parentEvaluationContext();
17417 ExprEvalContexts.back().InImmediateFunctionContext =
17418 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17419
17420 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17421 Prev.InImmediateEscalatingFunctionContext;
17422
17423 Cleanup.reset();
17424 if (!MaybeODRUseExprs.empty())
17425 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17426}
17427
17428void
17432 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17433 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17434}
17435
17436namespace {
17437
17438const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17439 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17440 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17441 if (E->getOpcode() == UO_Deref)
17442 return CheckPossibleDeref(S, E->getSubExpr());
17443 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17444 return CheckPossibleDeref(S, E->getBase());
17445 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17446 return CheckPossibleDeref(S, E->getBase());
17447 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17448 QualType Inner;
17449 QualType Ty = E->getType();
17450 if (const auto *Ptr = Ty->getAs<PointerType>())
17451 Inner = Ptr->getPointeeType();
17452 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17453 Inner = Arr->getElementType();
17454 else
17455 return nullptr;
17456
17457 if (Inner->hasAttr(attr::NoDeref))
17458 return E;
17459 }
17460 return nullptr;
17461}
17462
17463} // namespace
17464
17466 for (const Expr *E : Rec.PossibleDerefs) {
17467 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17468 if (DeclRef) {
17469 const ValueDecl *Decl = DeclRef->getDecl();
17470 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17471 << Decl->getName() << E->getSourceRange();
17472 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17473 } else {
17474 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17475 << E->getSourceRange();
17476 }
17477 }
17478 Rec.PossibleDerefs.clear();
17479}
17480
17483 return;
17484
17485 // Note: ignoring parens here is not justified by the standard rules, but
17486 // ignoring parentheses seems like a more reasonable approach, and this only
17487 // drives a deprecation warning so doesn't affect conformance.
17488 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17489 if (BO->getOpcode() == BO_Assign) {
17490 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17491 llvm::erase(LHSs, BO->getLHS());
17492 }
17493 }
17494}
17495
17497 assert(getLangOpts().CPlusPlus20 &&
17498 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17499 "Cannot mark an immediate escalating expression outside of an "
17500 "immediate escalating context");
17501 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17502 Call && Call->getCallee()) {
17503 if (auto *DeclRef =
17504 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17505 DeclRef->setIsImmediateEscalating(true);
17506 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17507 Ctr->setIsImmediateEscalating(true);
17508 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17509 DeclRef->setIsImmediateEscalating(true);
17510 } else {
17511 assert(false && "expected an immediately escalating expression");
17512 }
17514 FI->FoundImmediateEscalatingExpression = true;
17515}
17516
17518 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17519 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17522 return E;
17523
17524 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17525 /// It's OK if this fails; we'll also remove this in
17526 /// HandleImmediateInvocations, but catching it here allows us to avoid
17527 /// walking the AST looking for it in simple cases.
17528 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17529 if (auto *DeclRef =
17530 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17531 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17532
17533 // C++23 [expr.const]/p16
17534 // An expression or conversion is immediate-escalating if it is not initially
17535 // in an immediate function context and it is [...] an immediate invocation
17536 // that is not a constant expression and is not a subexpression of an
17537 // immediate invocation.
17538 APValue Cached;
17539 auto CheckConstantExpressionAndKeepResult = [&]() {
17541 Expr::EvalResult Eval;
17542 Eval.Diag = &Notes;
17543 bool Res = E.get()->EvaluateAsConstantExpr(
17544 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17545 if (Res && Notes.empty()) {
17546 Cached = std::move(Eval.Val);
17547 return true;
17548 }
17549 return false;
17550 };
17551
17552 if (!E.get()->isValueDependent() &&
17553 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17554 !CheckConstantExpressionAndKeepResult()) {
17556 return E;
17557 }
17558
17559 if (Cleanup.exprNeedsCleanups()) {
17560 // Since an immediate invocation is a full expression itself - it requires
17561 // an additional ExprWithCleanups node, but it can participate to a bigger
17562 // full expression which actually requires cleanups to be run after so
17563 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17564 // may discard cleanups for outer expression too early.
17565
17566 // Note that ExprWithCleanups created here must always have empty cleanup
17567 // objects:
17568 // - compound literals do not create cleanup objects in C++ and immediate
17569 // invocations are C++-only.
17570 // - blocks are not allowed inside constant expressions and compiler will
17571 // issue an error if they appear there.
17572 //
17573 // Hence, in correct code any cleanup objects created inside current
17574 // evaluation context must be outside the immediate invocation.
17577 }
17578
17580 getASTContext(), E.get(),
17581 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17582 getASTContext()),
17583 /*IsImmediateInvocation*/ true);
17584 if (Cached.hasValue())
17585 Res->MoveIntoResult(Cached, getASTContext());
17586 /// Value-dependent constant expressions should not be immediately
17587 /// evaluated until they are instantiated.
17588 if (!Res->isValueDependent())
17589 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17590 return Res;
17591}
17592
17596 Expr::EvalResult Eval;
17597 Eval.Diag = &Notes;
17598 ConstantExpr *CE = Candidate.getPointer();
17599 bool Result = CE->EvaluateAsConstantExpr(
17600 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17601 if (!Result || !Notes.empty()) {
17603 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17604 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17605 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17606 FunctionDecl *FD = nullptr;
17607 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17608 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17609 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17610 FD = Call->getConstructor();
17611 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17612 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17613
17614 assert(FD && FD->isImmediateFunction() &&
17615 "could not find an immediate function in this expression");
17616 if (FD->isInvalidDecl())
17617 return;
17618 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17619 << FD << FD->isConsteval();
17620 if (auto Context =
17622 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17623 << Context->Decl;
17624 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17625 }
17626 if (!FD->isConsteval())
17628 for (auto &Note : Notes)
17629 SemaRef.Diag(Note.first, Note.second);
17630 return;
17631 }
17633}
17634
17638 struct ComplexRemove : TreeTransform<ComplexRemove> {
17640 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17643 CurrentII;
17644 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17647 4>::reverse_iterator Current)
17648 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17649 void RemoveImmediateInvocation(ConstantExpr* E) {
17650 auto It = std::find_if(CurrentII, IISet.rend(),
17652 return Elem.getPointer() == E;
17653 });
17654 // It is possible that some subexpression of the current immediate
17655 // invocation was handled from another expression evaluation context. Do
17656 // not handle the current immediate invocation if some of its
17657 // subexpressions failed before.
17658 if (It == IISet.rend()) {
17659 if (SemaRef.FailedImmediateInvocations.contains(E))
17660 CurrentII->setInt(1);
17661 } else {
17662 It->setInt(1); // Mark as deleted
17663 }
17664 }
17665 ExprResult TransformConstantExpr(ConstantExpr *E) {
17666 if (!E->isImmediateInvocation())
17667 return Base::TransformConstantExpr(E);
17668 RemoveImmediateInvocation(E);
17669 return Base::TransformExpr(E->getSubExpr());
17670 }
17671 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17672 /// we need to remove its DeclRefExpr from the DRSet.
17673 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17674 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17675 return Base::TransformCXXOperatorCallExpr(E);
17676 }
17677 /// Base::TransformUserDefinedLiteral doesn't preserve the
17678 /// UserDefinedLiteral node.
17679 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17680 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17681 /// here.
17682 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17683 if (!Init)
17684 return Init;
17685
17686 // We cannot use IgnoreImpCasts because we need to preserve
17687 // full expressions.
17688 while (true) {
17689 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
17690 Init = ICE->getSubExpr();
17691 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
17692 Init = ICE->getSubExpr();
17693 else
17694 break;
17695 }
17696 /// ConstantExprs are the first layer of implicit node to be removed so if
17697 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17698 if (auto *CE = dyn_cast<ConstantExpr>(Init);
17699 CE && CE->isImmediateInvocation())
17700 RemoveImmediateInvocation(CE);
17701 return Base::TransformInitializer(Init, NotCopyInit);
17702 }
17703 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17704 DRSet.erase(E);
17705 return E;
17706 }
17707 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17708 // Do not rebuild lambdas to avoid creating a new type.
17709 // Lambdas have already been processed inside their eval contexts.
17710 return E;
17711 }
17712 bool AlwaysRebuild() { return false; }
17713 bool ReplacingOriginal() { return true; }
17714 bool AllowSkippingCXXConstructExpr() {
17715 bool Res = AllowSkippingFirstCXXConstructExpr;
17716 AllowSkippingFirstCXXConstructExpr = true;
17717 return Res;
17718 }
17719 bool AllowSkippingFirstCXXConstructExpr = true;
17720 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17722
17723 /// CXXConstructExpr with a single argument are getting skipped by
17724 /// TreeTransform in some situtation because they could be implicit. This
17725 /// can only occur for the top-level CXXConstructExpr because it is used
17726 /// nowhere in the expression being transformed therefore will not be rebuilt.
17727 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17728 /// skipping the first CXXConstructExpr.
17729 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17730 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17731
17732 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17733 // The result may not be usable in case of previous compilation errors.
17734 // In this case evaluation of the expression may result in crash so just
17735 // don't do anything further with the result.
17736 if (Res.isUsable()) {
17738 It->getPointer()->setSubExpr(Res.get());
17739 }
17740}
17741
17742static void
17745 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17746 Rec.ReferenceToConsteval.size() == 0) ||
17748 return;
17749
17750 /// When we have more than 1 ImmediateInvocationCandidates or previously
17751 /// failed immediate invocations, we need to check for nested
17752 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17753 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17754 /// invocation.
17755 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17757
17758 /// Prevent sema calls during the tree transform from adding pointers that
17759 /// are already in the sets.
17760 llvm::SaveAndRestore DisableIITracking(
17762
17763 /// Prevent diagnostic during tree transfrom as they are duplicates
17765
17766 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17767 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17768 if (!It->getInt())
17770 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17771 Rec.ReferenceToConsteval.size()) {
17772 struct SimpleRemove : DynamicRecursiveASTVisitor {
17773 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17774 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17775 bool VisitDeclRefExpr(DeclRefExpr *E) override {
17776 DRSet.erase(E);
17777 return DRSet.size();
17778 }
17779 } Visitor(Rec.ReferenceToConsteval);
17780 Visitor.TraverseStmt(
17781 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17782 }
17783 for (auto CE : Rec.ImmediateInvocationCandidates)
17784 if (!CE.getInt())
17786 for (auto *DR : Rec.ReferenceToConsteval) {
17787 // If the expression is immediate escalating, it is not an error;
17788 // The outer context itself becomes immediate and further errors,
17789 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17790 if (DR->isImmediateEscalating())
17791 continue;
17792 auto *FD = cast<FunctionDecl>(DR->getDecl());
17793 const NamedDecl *ND = FD;
17794 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17795 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17796 ND = MD->getParent();
17797
17798 // C++23 [expr.const]/p16
17799 // An expression or conversion is immediate-escalating if it is not
17800 // initially in an immediate function context and it is [...] a
17801 // potentially-evaluated id-expression that denotes an immediate function
17802 // that is not a subexpression of an immediate invocation.
17803 bool ImmediateEscalating = false;
17804 bool IsPotentiallyEvaluated =
17805 Rec.Context ==
17807 Rec.Context ==
17809 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17810 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17811
17813 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17814 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17815 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17816 if (!FD->getBuiltinID())
17817 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17818 if (auto Context =
17820 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17821 << Context->Decl;
17822 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17823 }
17824 if (FD->isImmediateEscalating() && !FD->isConsteval())
17826
17827 } else {
17829 }
17830 }
17831}
17832
17835 unsigned NumTypos = Rec.NumTypos;
17836
17837 if (!Rec.Lambdas.empty()) {
17839 if (!getLangOpts().CPlusPlus20 &&
17840 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17841 Rec.isUnevaluated() ||
17843 unsigned D;
17844 if (Rec.isUnevaluated()) {
17845 // C++11 [expr.prim.lambda]p2:
17846 // A lambda-expression shall not appear in an unevaluated operand
17847 // (Clause 5).
17848 D = diag::err_lambda_unevaluated_operand;
17849 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17850 // C++1y [expr.const]p2:
17851 // A conditional-expression e is a core constant expression unless the
17852 // evaluation of e, following the rules of the abstract machine, would
17853 // evaluate [...] a lambda-expression.
17854 D = diag::err_lambda_in_constant_expression;
17855 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17856 // C++17 [expr.prim.lamda]p2:
17857 // A lambda-expression shall not appear [...] in a template-argument.
17858 D = diag::err_lambda_in_invalid_context;
17859 } else
17860 llvm_unreachable("Couldn't infer lambda error message.");
17861
17862 for (const auto *L : Rec.Lambdas)
17863 Diag(L->getBeginLoc(), D);
17864 }
17865 }
17866
17867 // Append the collected materialized temporaries into previous context before
17868 // exit if the previous also is a lifetime extending context.
17870 parentEvaluationContext().InLifetimeExtendingContext &&
17871 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17874 }
17875
17877 HandleImmediateInvocations(*this, Rec);
17878
17879 // Warn on any volatile-qualified simple-assignments that are not discarded-
17880 // value expressions nor unevaluated operands (those cases get removed from
17881 // this list by CheckUnusedVolatileAssignment).
17882 for (auto *BO : Rec.VolatileAssignmentLHSs)
17883 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17884 << BO->getType();
17885
17886 // When are coming out of an unevaluated context, clear out any
17887 // temporaries that we may have created as part of the evaluation of
17888 // the expression in that context: they aren't relevant because they
17889 // will never be constructed.
17890 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17892 ExprCleanupObjects.end());
17893 Cleanup = Rec.ParentCleanup;
17896 // Otherwise, merge the contexts together.
17897 } else {
17899 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17900 Rec.SavedMaybeODRUseExprs.end());
17901 }
17902
17903 // Pop the current expression evaluation context off the stack.
17904 ExprEvalContexts.pop_back();
17905
17906 // The global expression evaluation context record is never popped.
17907 ExprEvalContexts.back().NumTypos += NumTypos;
17908}
17909
17911 ExprCleanupObjects.erase(
17912 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17913 ExprCleanupObjects.end());
17914 Cleanup.reset();
17915 MaybeODRUseExprs.clear();
17916}
17917
17920 if (Result.isInvalid())
17921 return ExprError();
17922 E = Result.get();
17923 if (!E->getType()->isVariablyModifiedType())
17924 return E;
17926}
17927
17928/// Are we in a context that is potentially constant evaluated per C++20
17929/// [expr.const]p12?
17931 /// C++2a [expr.const]p12:
17932 // An expression or conversion is potentially constant evaluated if it is
17933 switch (SemaRef.ExprEvalContexts.back().Context) {
17936
17937 // -- a manifestly constant-evaluated expression,
17941 // -- a potentially-evaluated expression,
17943 // -- an immediate subexpression of a braced-init-list,
17944
17945 // -- [FIXME] an expression of the form & cast-expression that occurs
17946 // within a templated entity
17947 // -- a subexpression of one of the above that is not a subexpression of
17948 // a nested unevaluated operand.
17949 return true;
17950
17953 // Expressions in this context are never evaluated.
17954 return false;
17955 }
17956 llvm_unreachable("Invalid context");
17957}
17958
17959/// Return true if this function has a calling convention that requires mangling
17960/// in the size of the parameter pack.
17962 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17963 // we don't need parameter type sizes.
17964 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17965 if (!TT.isOSWindows() || !TT.isX86())
17966 return false;
17967
17968 // If this is C++ and this isn't an extern "C" function, parameters do not
17969 // need to be complete. In this case, C++ mangling will apply, which doesn't
17970 // use the size of the parameters.
17971 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17972 return false;
17973
17974 // Stdcall, fastcall, and vectorcall need this special treatment.
17975 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17976 switch (CC) {
17977 case CC_X86StdCall:
17978 case CC_X86FastCall:
17979 case CC_X86VectorCall:
17980 return true;
17981 default:
17982 break;
17983 }
17984 return false;
17985}
17986
17987/// Require that all of the parameter types of function be complete. Normally,
17988/// parameter types are only required to be complete when a function is called
17989/// or defined, but to mangle functions with certain calling conventions, the
17990/// mangler needs to know the size of the parameter list. In this situation,
17991/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17992/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17993/// result in a linker error. Clang doesn't implement this behavior, and instead
17994/// attempts to error at compile time.
17997 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17998 FunctionDecl *FD;
17999 ParmVarDecl *Param;
18000
18001 public:
18002 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18003 : FD(FD), Param(Param) {}
18004
18005 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18006 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18007 StringRef CCName;
18008 switch (CC) {
18009 case CC_X86StdCall:
18010 CCName = "stdcall";
18011 break;
18012 case CC_X86FastCall:
18013 CCName = "fastcall";
18014 break;
18015 case CC_X86VectorCall:
18016 CCName = "vectorcall";
18017 break;
18018 default:
18019 llvm_unreachable("CC does not need mangling");
18020 }
18021
18022 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18023 << Param->getDeclName() << FD->getDeclName() << CCName;
18024 }
18025 };
18026
18027 for (ParmVarDecl *Param : FD->parameters()) {
18028 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18029 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18030 }
18031}
18032
18033namespace {
18034enum class OdrUseContext {
18035 /// Declarations in this context are not odr-used.
18036 None,
18037 /// Declarations in this context are formally odr-used, but this is a
18038 /// dependent context.
18039 Dependent,
18040 /// Declarations in this context are odr-used but not actually used (yet).
18041 FormallyOdrUsed,
18042 /// Declarations in this context are used.
18043 Used
18044};
18045}
18046
18047/// Are we within a context in which references to resolved functions or to
18048/// variables result in odr-use?
18049static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18050 OdrUseContext Result;
18051
18052 switch (SemaRef.ExprEvalContexts.back().Context) {
18056 return OdrUseContext::None;
18057
18061 Result = OdrUseContext::Used;
18062 break;
18063
18065 Result = OdrUseContext::FormallyOdrUsed;
18066 break;
18067
18069 // A default argument formally results in odr-use, but doesn't actually
18070 // result in a use in any real sense until it itself is used.
18071 Result = OdrUseContext::FormallyOdrUsed;
18072 break;
18073 }
18074
18076 return OdrUseContext::Dependent;
18077
18078 return Result;
18079}
18080
18082 if (!Func->isConstexpr())
18083 return false;
18084
18085 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18086 return true;
18087 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18088 return CCD && CCD->getInheritedConstructor();
18089}
18090
18092 bool MightBeOdrUse) {
18093 assert(Func && "No function?");
18094
18095 Func->setReferenced();
18096
18097 // Recursive functions aren't really used until they're used from some other
18098 // context.
18099 bool IsRecursiveCall = CurContext == Func;
18100
18101 // C++11 [basic.def.odr]p3:
18102 // A function whose name appears as a potentially-evaluated expression is
18103 // odr-used if it is the unique lookup result or the selected member of a
18104 // set of overloaded functions [...].
18105 //
18106 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18107 // can just check that here.
18108 OdrUseContext OdrUse =
18109 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18110 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18111 OdrUse = OdrUseContext::FormallyOdrUsed;
18112
18113 // Trivial default constructors and destructors are never actually used.
18114 // FIXME: What about other special members?
18115 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18116 OdrUse == OdrUseContext::Used) {
18117 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18118 if (Constructor->isDefaultConstructor())
18119 OdrUse = OdrUseContext::FormallyOdrUsed;
18120 if (isa<CXXDestructorDecl>(Func))
18121 OdrUse = OdrUseContext::FormallyOdrUsed;
18122 }
18123
18124 // C++20 [expr.const]p12:
18125 // A function [...] is needed for constant evaluation if it is [...] a
18126 // constexpr function that is named by an expression that is potentially
18127 // constant evaluated
18128 bool NeededForConstantEvaluation =
18131
18132 // Determine whether we require a function definition to exist, per
18133 // C++11 [temp.inst]p3:
18134 // Unless a function template specialization has been explicitly
18135 // instantiated or explicitly specialized, the function template
18136 // specialization is implicitly instantiated when the specialization is
18137 // referenced in a context that requires a function definition to exist.
18138 // C++20 [temp.inst]p7:
18139 // The existence of a definition of a [...] function is considered to
18140 // affect the semantics of the program if the [...] function is needed for
18141 // constant evaluation by an expression
18142 // C++20 [basic.def.odr]p10:
18143 // Every program shall contain exactly one definition of every non-inline
18144 // function or variable that is odr-used in that program outside of a
18145 // discarded statement
18146 // C++20 [special]p1:
18147 // The implementation will implicitly define [defaulted special members]
18148 // if they are odr-used or needed for constant evaluation.
18149 //
18150 // Note that we skip the implicit instantiation of templates that are only
18151 // used in unused default arguments or by recursive calls to themselves.
18152 // This is formally non-conforming, but seems reasonable in practice.
18153 bool NeedDefinition =
18154 !IsRecursiveCall &&
18155 (OdrUse == OdrUseContext::Used ||
18156 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18157
18158 // C++14 [temp.expl.spec]p6:
18159 // If a template [...] is explicitly specialized then that specialization
18160 // shall be declared before the first use of that specialization that would
18161 // cause an implicit instantiation to take place, in every translation unit
18162 // in which such a use occurs
18163 if (NeedDefinition &&
18164 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18165 Func->getMemberSpecializationInfo()))
18167
18168 if (getLangOpts().CUDA)
18169 CUDA().CheckCall(Loc, Func);
18170
18171 // If we need a definition, try to create one.
18172 if (NeedDefinition && !Func->getBody()) {
18174 if (CXXConstructorDecl *Constructor =
18175 dyn_cast<CXXConstructorDecl>(Func)) {
18176 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18177 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18178 if (Constructor->isDefaultConstructor()) {
18179 if (Constructor->isTrivial() &&
18180 !Constructor->hasAttr<DLLExportAttr>())
18181 return;
18183 } else if (Constructor->isCopyConstructor()) {
18184 DefineImplicitCopyConstructor(Loc, Constructor);
18185 } else if (Constructor->isMoveConstructor()) {
18186 DefineImplicitMoveConstructor(Loc, Constructor);
18187 }
18188 } else if (Constructor->getInheritedConstructor()) {
18189 DefineInheritingConstructor(Loc, Constructor);
18190 }
18191 } else if (CXXDestructorDecl *Destructor =
18192 dyn_cast<CXXDestructorDecl>(Func)) {
18193 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18194 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18195 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18196 return;
18198 }
18199 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18200 MarkVTableUsed(Loc, Destructor->getParent());
18201 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18202 if (MethodDecl->isOverloadedOperator() &&
18203 MethodDecl->getOverloadedOperator() == OO_Equal) {
18204 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18205 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18206 if (MethodDecl->isCopyAssignmentOperator())
18207 DefineImplicitCopyAssignment(Loc, MethodDecl);
18208 else if (MethodDecl->isMoveAssignmentOperator())
18209 DefineImplicitMoveAssignment(Loc, MethodDecl);
18210 }
18211 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18212 MethodDecl->getParent()->isLambda()) {
18213 CXXConversionDecl *Conversion =
18214 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18215 if (Conversion->isLambdaToBlockPointerConversion())
18217 else
18219 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18220 MarkVTableUsed(Loc, MethodDecl->getParent());
18221 }
18222
18223 if (Func->isDefaulted() && !Func->isDeleted()) {
18227 }
18228
18229 // Implicit instantiation of function templates and member functions of
18230 // class templates.
18231 if (Func->isImplicitlyInstantiable()) {
18233 Func->getTemplateSpecializationKindForInstantiation();
18234 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18235 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18236 if (FirstInstantiation) {
18237 PointOfInstantiation = Loc;
18238 if (auto *MSI = Func->getMemberSpecializationInfo())
18239 MSI->setPointOfInstantiation(Loc);
18240 // FIXME: Notify listener.
18241 else
18242 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18243 } else if (TSK != TSK_ImplicitInstantiation) {
18244 // Use the point of use as the point of instantiation, instead of the
18245 // point of explicit instantiation (which we track as the actual point
18246 // of instantiation). This gives better backtraces in diagnostics.
18247 PointOfInstantiation = Loc;
18248 }
18249
18250 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18251 Func->isConstexpr()) {
18252 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18253 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18254 CodeSynthesisContexts.size())
18256 std::make_pair(Func, PointOfInstantiation));
18257 else if (Func->isConstexpr())
18258 // Do not defer instantiations of constexpr functions, to avoid the
18259 // expression evaluator needing to call back into Sema if it sees a
18260 // call to such a function.
18261 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18262 else {
18263 Func->setInstantiationIsPending(true);
18264 PendingInstantiations.push_back(
18265 std::make_pair(Func, PointOfInstantiation));
18266 if (llvm::isTimeTraceVerbose()) {
18267 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18268 std::string Name;
18269 llvm::raw_string_ostream OS(Name);
18270 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18271 /*Qualified=*/true);
18272 return Name;
18273 });
18274 }
18275 // Notify the consumer that a function was implicitly instantiated.
18277 }
18278 }
18279 } else {
18280 // Walk redefinitions, as some of them may be instantiable.
18281 for (auto *i : Func->redecls()) {
18282 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18283 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18284 }
18285 }
18286 });
18287 }
18288
18289 // If a constructor was defined in the context of a default parameter
18290 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18291 // context), its initializers may not be referenced yet.
18292 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18294 *this,
18295 Constructor->isImmediateFunction()
18298 Constructor);
18299 for (CXXCtorInitializer *Init : Constructor->inits()) {
18300 if (Init->isInClassMemberInitializer())
18301 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18302 MarkDeclarationsReferencedInExpr(Init->getInit());
18303 });
18304 }
18305 }
18306
18307 // C++14 [except.spec]p17:
18308 // An exception-specification is considered to be needed when:
18309 // - the function is odr-used or, if it appears in an unevaluated operand,
18310 // would be odr-used if the expression were potentially-evaluated;
18311 //
18312 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18313 // function is a pure virtual function we're calling, and in that case the
18314 // function was selected by overload resolution and we need to resolve its
18315 // exception specification for a different reason.
18316 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18319
18320 // A callee could be called by a host function then by a device function.
18321 // If we only try recording once, we will miss recording the use on device
18322 // side. Therefore keep trying until it is recorded.
18323 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18326
18327 // If this is the first "real" use, act on that.
18328 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18329 // Keep track of used but undefined functions.
18330 if (!Func->isDefined()) {
18331 if (mightHaveNonExternalLinkage(Func))
18332 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18333 else if (Func->getMostRecentDecl()->isInlined() &&
18334 !LangOpts.GNUInline &&
18335 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18336 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18338 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18339 }
18340
18341 // Some x86 Windows calling conventions mangle the size of the parameter
18342 // pack into the name. Computing the size of the parameters requires the
18343 // parameter types to be complete. Check that now.
18346
18347 // In the MS C++ ABI, the compiler emits destructor variants where they are
18348 // used. If the destructor is used here but defined elsewhere, mark the
18349 // virtual base destructors referenced. If those virtual base destructors
18350 // are inline, this will ensure they are defined when emitting the complete
18351 // destructor variant. This checking may be redundant if the destructor is
18352 // provided later in this TU.
18354 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18355 CXXRecordDecl *Parent = Dtor->getParent();
18356 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18358 }
18359 }
18360
18361 Func->markUsed(Context);
18362 }
18363}
18364
18365/// Directly mark a variable odr-used. Given a choice, prefer to use
18366/// MarkVariableReferenced since it does additional checks and then
18367/// calls MarkVarDeclODRUsed.
18368/// If the variable must be captured:
18369/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18370/// - else capture it in the DeclContext that maps to the
18371/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18372static void
18374 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18375 // Keep track of used but undefined variables.
18376 // FIXME: We shouldn't suppress this warning for static data members.
18377 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18378 assert(Var && "expected a capturable variable");
18379
18381 (!Var->isExternallyVisible() || Var->isInline() ||
18383 !(Var->isStaticDataMember() && Var->hasInit())) {
18385 if (old.isInvalid())
18386 old = Loc;
18387 }
18388 QualType CaptureType, DeclRefType;
18389 if (SemaRef.LangOpts.OpenMP)
18392 /*EllipsisLoc*/ SourceLocation(),
18393 /*BuildAndDiagnose*/ true, CaptureType,
18394 DeclRefType, FunctionScopeIndexToStopAt);
18395
18396 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18397 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18398 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18399 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18400 if (VarTarget == SemaCUDA::CVT_Host &&
18401 (UserTarget == CUDAFunctionTarget::Device ||
18402 UserTarget == CUDAFunctionTarget::HostDevice ||
18403 UserTarget == CUDAFunctionTarget::Global)) {
18404 // Diagnose ODR-use of host global variables in device functions.
18405 // Reference of device global variables in host functions is allowed
18406 // through shadow variables therefore it is not diagnosed.
18407 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18408 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18409 << /*host*/ 2 << /*variable*/ 1 << Var
18410 << llvm::to_underlying(UserTarget);
18412 Var->getType().isConstQualified()
18413 ? diag::note_cuda_const_var_unpromoted
18414 : diag::note_cuda_host_var);
18415 }
18416 } else if (VarTarget == SemaCUDA::CVT_Device &&
18417 !Var->hasAttr<CUDASharedAttr>() &&
18418 (UserTarget == CUDAFunctionTarget::Host ||
18419 UserTarget == CUDAFunctionTarget::HostDevice)) {
18420 // Record a CUDA/HIP device side variable if it is ODR-used
18421 // by host code. This is done conservatively, when the variable is
18422 // referenced in any of the following contexts:
18423 // - a non-function context
18424 // - a host function
18425 // - a host device function
18426 // This makes the ODR-use of the device side variable by host code to
18427 // be visible in the device compilation for the compiler to be able to
18428 // emit template variables instantiated by host code only and to
18429 // externalize the static device side variable ODR-used by host code.
18430 if (!Var->hasExternalStorage())
18432 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18433 (!FD || (!FD->getDescribedFunctionTemplate() &&
18437 }
18438 }
18439
18440 V->markUsed(SemaRef.Context);
18441}
18442
18445 unsigned CapturingScopeIndex) {
18446 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18447}
18448
18450 ValueDecl *var) {
18451 DeclContext *VarDC = var->getDeclContext();
18452
18453 // If the parameter still belongs to the translation unit, then
18454 // we're actually just using one parameter in the declaration of
18455 // the next.
18456 if (isa<ParmVarDecl>(var) &&
18457 isa<TranslationUnitDecl>(VarDC))
18458 return;
18459
18460 // For C code, don't diagnose about capture if we're not actually in code
18461 // right now; it's impossible to write a non-constant expression outside of
18462 // function context, so we'll get other (more useful) diagnostics later.
18463 //
18464 // For C++, things get a bit more nasty... it would be nice to suppress this
18465 // diagnostic for certain cases like using a local variable in an array bound
18466 // for a member of a local class, but the correct predicate is not obvious.
18467 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18468 return;
18469
18470 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18471 unsigned ContextKind = 3; // unknown
18472 if (isa<CXXMethodDecl>(VarDC) &&
18473 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18474 ContextKind = 2;
18475 } else if (isa<FunctionDecl>(VarDC)) {
18476 ContextKind = 0;
18477 } else if (isa<BlockDecl>(VarDC)) {
18478 ContextKind = 1;
18479 }
18480
18481 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18482 << var << ValueKind << ContextKind << VarDC;
18483 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18484 << var;
18485
18486 // FIXME: Add additional diagnostic info about class etc. which prevents
18487 // capture.
18488}
18489
18491 ValueDecl *Var,
18492 bool &SubCapturesAreNested,
18493 QualType &CaptureType,
18494 QualType &DeclRefType) {
18495 // Check whether we've already captured it.
18496 if (CSI->CaptureMap.count(Var)) {
18497 // If we found a capture, any subcaptures are nested.
18498 SubCapturesAreNested = true;
18499
18500 // Retrieve the capture type for this variable.
18501 CaptureType = CSI->getCapture(Var).getCaptureType();
18502
18503 // Compute the type of an expression that refers to this variable.
18504 DeclRefType = CaptureType.getNonReferenceType();
18505
18506 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18507 // are mutable in the sense that user can change their value - they are
18508 // private instances of the captured declarations.
18509 const Capture &Cap = CSI->getCapture(Var);
18510 // C++ [expr.prim.lambda]p10:
18511 // The type of such a data member is [...] an lvalue reference to the
18512 // referenced function type if the entity is a reference to a function.
18513 // [...]
18514 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18515 !(isa<LambdaScopeInfo>(CSI) &&
18516 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18517 !(isa<CapturedRegionScopeInfo>(CSI) &&
18518 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18519 DeclRefType.addConst();
18520 return true;
18521 }
18522 return false;
18523}
18524
18525// Only block literals, captured statements, and lambda expressions can
18526// capture; other scopes don't work.
18528 ValueDecl *Var,
18530 const bool Diagnose,
18531 Sema &S) {
18532 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18534
18535 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18536 if (Underlying) {
18537 if (Underlying->hasLocalStorage() && Diagnose)
18539 }
18540 return nullptr;
18541}
18542
18543// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18544// certain types of variables (unnamed, variably modified types etc.)
18545// so check for eligibility.
18547 SourceLocation Loc, const bool Diagnose,
18548 Sema &S) {
18549
18550 assert((isa<VarDecl, BindingDecl>(Var)) &&
18551 "Only variables and structured bindings can be captured");
18552
18553 bool IsBlock = isa<BlockScopeInfo>(CSI);
18554 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18555
18556 // Lambdas are not allowed to capture unnamed variables
18557 // (e.g. anonymous unions).
18558 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18559 // assuming that's the intent.
18560 if (IsLambda && !Var->getDeclName()) {
18561 if (Diagnose) {
18562 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18563 S.Diag(Var->getLocation(), diag::note_declared_at);
18564 }
18565 return false;
18566 }
18567
18568 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18569 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18570 if (Diagnose) {
18571 S.Diag(Loc, diag::err_ref_vm_type);
18572 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18573 }
18574 return false;
18575 }
18576 // Prohibit structs with flexible array members too.
18577 // We cannot capture what is in the tail end of the struct.
18578 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18579 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18580 if (Diagnose) {
18581 if (IsBlock)
18582 S.Diag(Loc, diag::err_ref_flexarray_type);
18583 else
18584 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18585 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18586 }
18587 return false;
18588 }
18589 }
18590 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18591 // Lambdas and captured statements are not allowed to capture __block
18592 // variables; they don't support the expected semantics.
18593 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18594 if (Diagnose) {
18595 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18596 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18597 }
18598 return false;
18599 }
18600 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18601 if (S.getLangOpts().OpenCL && IsBlock &&
18602 Var->getType()->isBlockPointerType()) {
18603 if (Diagnose)
18604 S.Diag(Loc, diag::err_opencl_block_ref_block);
18605 return false;
18606 }
18607
18608 if (isa<BindingDecl>(Var)) {
18609 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18610 if (Diagnose)
18612 return false;
18613 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18614 S.Diag(Loc, S.LangOpts.CPlusPlus20
18615 ? diag::warn_cxx17_compat_capture_binding
18616 : diag::ext_capture_binding)
18617 << Var;
18618 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18619 }
18620 }
18621
18622 return true;
18623}
18624
18625// Returns true if the capture by block was successful.
18627 SourceLocation Loc, const bool BuildAndDiagnose,
18628 QualType &CaptureType, QualType &DeclRefType,
18629 const bool Nested, Sema &S, bool Invalid) {
18630 bool ByRef = false;
18631
18632 // Blocks are not allowed to capture arrays, excepting OpenCL.
18633 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18634 // (decayed to pointers).
18635 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18636 if (BuildAndDiagnose) {
18637 S.Diag(Loc, diag::err_ref_array_type);
18638 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18639 Invalid = true;
18640 } else {
18641 return false;
18642 }
18643 }
18644
18645 // Forbid the block-capture of autoreleasing variables.
18646 if (!Invalid &&
18648 if (BuildAndDiagnose) {
18649 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18650 << /*block*/ 0;
18651 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18652 Invalid = true;
18653 } else {
18654 return false;
18655 }
18656 }
18657
18658 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18659 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18660 QualType PointeeTy = PT->getPointeeType();
18661
18662 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18664 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18665 if (BuildAndDiagnose) {
18666 SourceLocation VarLoc = Var->getLocation();
18667 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18668 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18669 }
18670 }
18671 }
18672
18673 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18674 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18675 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18676 // Block capture by reference does not change the capture or
18677 // declaration reference types.
18678 ByRef = true;
18679 } else {
18680 // Block capture by copy introduces 'const'.
18681 CaptureType = CaptureType.getNonReferenceType().withConst();
18682 DeclRefType = CaptureType;
18683 }
18684
18685 // Actually capture the variable.
18686 if (BuildAndDiagnose)
18687 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18688 CaptureType, Invalid);
18689
18690 return !Invalid;
18691}
18692
18693/// Capture the given variable in the captured region.
18696 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18697 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18698 bool IsTopScope, Sema &S, bool Invalid) {
18699 // By default, capture variables by reference.
18700 bool ByRef = true;
18701 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18702 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18703 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18704 // Using an LValue reference type is consistent with Lambdas (see below).
18705 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18706 bool HasConst = DeclRefType.isConstQualified();
18707 DeclRefType = DeclRefType.getUnqualifiedType();
18708 // Don't lose diagnostics about assignments to const.
18709 if (HasConst)
18710 DeclRefType.addConst();
18711 }
18712 // Do not capture firstprivates in tasks.
18713 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18714 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18715 return true;
18716 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18717 RSI->OpenMPCaptureLevel);
18718 }
18719
18720 if (ByRef)
18721 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18722 else
18723 CaptureType = DeclRefType;
18724
18725 // Actually capture the variable.
18726 if (BuildAndDiagnose)
18727 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18728 Loc, SourceLocation(), CaptureType, Invalid);
18729
18730 return !Invalid;
18731}
18732
18733/// Capture the given variable in the lambda.
18735 SourceLocation Loc, const bool BuildAndDiagnose,
18736 QualType &CaptureType, QualType &DeclRefType,
18737 const bool RefersToCapturedVariable,
18738 const Sema::TryCaptureKind Kind,
18739 SourceLocation EllipsisLoc, const bool IsTopScope,
18740 Sema &S, bool Invalid) {
18741 // Determine whether we are capturing by reference or by value.
18742 bool ByRef = false;
18743 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18744 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18745 } else {
18746 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18747 }
18748
18749 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18751 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18752 Invalid = true;
18753 }
18754
18755 // Compute the type of the field that will capture this variable.
18756 if (ByRef) {
18757 // C++11 [expr.prim.lambda]p15:
18758 // An entity is captured by reference if it is implicitly or
18759 // explicitly captured but not captured by copy. It is
18760 // unspecified whether additional unnamed non-static data
18761 // members are declared in the closure type for entities
18762 // captured by reference.
18763 //
18764 // FIXME: It is not clear whether we want to build an lvalue reference
18765 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18766 // to do the former, while EDG does the latter. Core issue 1249 will
18767 // clarify, but for now we follow GCC because it's a more permissive and
18768 // easily defensible position.
18769 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18770 } else {
18771 // C++11 [expr.prim.lambda]p14:
18772 // For each entity captured by copy, an unnamed non-static
18773 // data member is declared in the closure type. The
18774 // declaration order of these members is unspecified. The type
18775 // of such a data member is the type of the corresponding
18776 // captured entity if the entity is not a reference to an
18777 // object, or the referenced type otherwise. [Note: If the
18778 // captured entity is a reference to a function, the
18779 // corresponding data member is also a reference to a
18780 // function. - end note ]
18781 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18782 if (!RefType->getPointeeType()->isFunctionType())
18783 CaptureType = RefType->getPointeeType();
18784 }
18785
18786 // Forbid the lambda copy-capture of autoreleasing variables.
18787 if (!Invalid &&
18789 if (BuildAndDiagnose) {
18790 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18791 S.Diag(Var->getLocation(), diag::note_previous_decl)
18792 << Var->getDeclName();
18793 Invalid = true;
18794 } else {
18795 return false;
18796 }
18797 }
18798
18799 // Make sure that by-copy captures are of a complete and non-abstract type.
18800 if (!Invalid && BuildAndDiagnose) {
18801 if (!CaptureType->isDependentType() &&
18803 Loc, CaptureType,
18804 diag::err_capture_of_incomplete_or_sizeless_type,
18805 Var->getDeclName()))
18806 Invalid = true;
18807 else if (S.RequireNonAbstractType(Loc, CaptureType,
18808 diag::err_capture_of_abstract_type))
18809 Invalid = true;
18810 }
18811 }
18812
18813 // Compute the type of a reference to this captured variable.
18814 if (ByRef)
18815 DeclRefType = CaptureType.getNonReferenceType();
18816 else {
18817 // C++ [expr.prim.lambda]p5:
18818 // The closure type for a lambda-expression has a public inline
18819 // function call operator [...]. This function call operator is
18820 // declared const (9.3.1) if and only if the lambda-expression's
18821 // parameter-declaration-clause is not followed by mutable.
18822 DeclRefType = CaptureType.getNonReferenceType();
18823 bool Const = LSI->lambdaCaptureShouldBeConst();
18824 // C++ [expr.prim.lambda]p10:
18825 // The type of such a data member is [...] an lvalue reference to the
18826 // referenced function type if the entity is a reference to a function.
18827 // [...]
18828 if (Const && !CaptureType->isReferenceType() &&
18829 !DeclRefType->isFunctionType())
18830 DeclRefType.addConst();
18831 }
18832
18833 // Add the capture.
18834 if (BuildAndDiagnose)
18835 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18836 Loc, EllipsisLoc, CaptureType, Invalid);
18837
18838 return !Invalid;
18839}
18840
18842 const ASTContext &Context) {
18843 // Offer a Copy fix even if the type is dependent.
18844 if (Var->getType()->isDependentType())
18845 return true;
18847 if (T.isTriviallyCopyableType(Context))
18848 return true;
18849 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18850
18851 if (!(RD = RD->getDefinition()))
18852 return false;
18853 if (RD->hasSimpleCopyConstructor())
18854 return true;
18855 if (RD->hasUserDeclaredCopyConstructor())
18856 for (CXXConstructorDecl *Ctor : RD->ctors())
18857 if (Ctor->isCopyConstructor())
18858 return !Ctor->isDeleted();
18859 }
18860 return false;
18861}
18862
18863/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18864/// default capture. Fixes may be omitted if they aren't allowed by the
18865/// standard, for example we can't emit a default copy capture fix-it if we
18866/// already explicitly copy capture capture another variable.
18868 ValueDecl *Var) {
18870 // Don't offer Capture by copy of default capture by copy fixes if Var is
18871 // known not to be copy constructible.
18872 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18873
18874 SmallString<32> FixBuffer;
18875 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18876 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18877 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18878 if (ShouldOfferCopyFix) {
18879 // Offer fixes to insert an explicit capture for the variable.
18880 // [] -> [VarName]
18881 // [OtherCapture] -> [OtherCapture, VarName]
18882 FixBuffer.assign({Separator, Var->getName()});
18883 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18884 << Var << /*value*/ 0
18885 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18886 }
18887 // As above but capture by reference.
18888 FixBuffer.assign({Separator, "&", Var->getName()});
18889 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18890 << Var << /*reference*/ 1
18891 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18892 }
18893
18894 // Only try to offer default capture if there are no captures excluding this
18895 // and init captures.
18896 // [this]: OK.
18897 // [X = Y]: OK.
18898 // [&A, &B]: Don't offer.
18899 // [A, B]: Don't offer.
18900 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18901 return !C.isThisCapture() && !C.isInitCapture();
18902 }))
18903 return;
18904
18905 // The default capture specifiers, '=' or '&', must appear first in the
18906 // capture body.
18907 SourceLocation DefaultInsertLoc =
18909
18910 if (ShouldOfferCopyFix) {
18911 bool CanDefaultCopyCapture = true;
18912 // [=, *this] OK since c++17
18913 // [=, this] OK since c++20
18914 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18915 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18917 : false;
18918 // We can't use default capture by copy if any captures already specified
18919 // capture by copy.
18920 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18921 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18922 })) {
18923 FixBuffer.assign({"=", Separator});
18924 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18925 << /*value*/ 0
18926 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18927 }
18928 }
18929
18930 // We can't use default capture by reference if any captures already specified
18931 // capture by reference.
18932 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18933 return !C.isInitCapture() && C.isReferenceCapture() &&
18934 !C.isThisCapture();
18935 })) {
18936 FixBuffer.assign({"&", Separator});
18937 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18938 << /*reference*/ 1
18939 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18940 }
18941}
18942
18944 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18945 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18946 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18947 // An init-capture is notionally from the context surrounding its
18948 // declaration, but its parent DC is the lambda class.
18949 DeclContext *VarDC = Var->getDeclContext();
18950 DeclContext *DC = CurContext;
18951
18952 // Skip past RequiresExprBodys because they don't constitute function scopes.
18953 while (DC->isRequiresExprBody())
18954 DC = DC->getParent();
18955
18956 // tryCaptureVariable is called every time a DeclRef is formed,
18957 // it can therefore have non-negigible impact on performances.
18958 // For local variables and when there is no capturing scope,
18959 // we can bailout early.
18960 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18961 return true;
18962
18963 // Exception: Function parameters are not tied to the function's DeclContext
18964 // until we enter the function definition. Capturing them anyway would result
18965 // in an out-of-bounds error while traversing DC and its parents.
18966 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18967 return true;
18968
18969 const auto *VD = dyn_cast<VarDecl>(Var);
18970 if (VD) {
18971 if (VD->isInitCapture())
18972 VarDC = VarDC->getParent();
18973 } else {
18975 }
18976 assert(VD && "Cannot capture a null variable");
18977
18978 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18979 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18980 // We need to sync up the Declaration Context with the
18981 // FunctionScopeIndexToStopAt
18982 if (FunctionScopeIndexToStopAt) {
18983 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
18984 unsigned FSIndex = FunctionScopes.size() - 1;
18985 // When we're parsing the lambda parameter list, the current DeclContext is
18986 // NOT the lambda but its parent. So move away the current LSI before
18987 // aligning DC and FunctionScopeIndexToStopAt.
18988 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
18989 FSIndex && LSI && !LSI->AfterParameterList)
18990 --FSIndex;
18991 assert(MaxFunctionScopesIndex <= FSIndex &&
18992 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
18993 "FunctionScopes.");
18994 while (FSIndex != MaxFunctionScopesIndex) {
18996 --FSIndex;
18997 }
18998 }
18999
19000 // Capture global variables if it is required to use private copy of this
19001 // variable.
19002 bool IsGlobal = !VD->hasLocalStorage();
19003 if (IsGlobal && !(LangOpts.OpenMP &&
19004 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19005 MaxFunctionScopesIndex)))
19006 return true;
19007
19008 if (isa<VarDecl>(Var))
19009 Var = cast<VarDecl>(Var->getCanonicalDecl());
19010
19011 // Walk up the stack to determine whether we can capture the variable,
19012 // performing the "simple" checks that don't depend on type. We stop when
19013 // we've either hit the declared scope of the variable or find an existing
19014 // capture of that variable. We start from the innermost capturing-entity
19015 // (the DC) and ensure that all intervening capturing-entities
19016 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19017 // declcontext can either capture the variable or have already captured
19018 // the variable.
19019 CaptureType = Var->getType();
19020 DeclRefType = CaptureType.getNonReferenceType();
19021 bool Nested = false;
19022 bool Explicit = (Kind != TryCapture_Implicit);
19023 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19024 do {
19025
19026 LambdaScopeInfo *LSI = nullptr;
19027 if (!FunctionScopes.empty())
19028 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19029 FunctionScopes[FunctionScopesIndex]);
19030
19031 bool IsInScopeDeclarationContext =
19032 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19033
19034 if (LSI && !LSI->AfterParameterList) {
19035 // This allows capturing parameters from a default value which does not
19036 // seems correct
19037 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19038 return true;
19039 }
19040 // If the variable is declared in the current context, there is no need to
19041 // capture it.
19042 if (IsInScopeDeclarationContext &&
19043 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19044 return true;
19045
19046 // Only block literals, captured statements, and lambda expressions can
19047 // capture; other scopes don't work.
19048 DeclContext *ParentDC =
19049 !IsInScopeDeclarationContext
19050 ? DC->getParent()
19051 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19052 BuildAndDiagnose, *this);
19053 // We need to check for the parent *first* because, if we *have*
19054 // private-captured a global variable, we need to recursively capture it in
19055 // intermediate blocks, lambdas, etc.
19056 if (!ParentDC) {
19057 if (IsGlobal) {
19058 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19059 break;
19060 }
19061 return true;
19062 }
19063
19064 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19065 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19066
19067 // Check whether we've already captured it.
19068 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19069 DeclRefType)) {
19070 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19071 break;
19072 }
19073
19074 // When evaluating some attributes (like enable_if) we might refer to a
19075 // function parameter appertaining to the same declaration as that
19076 // attribute.
19077 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19078 Parm && Parm->getDeclContext() == DC)
19079 return true;
19080
19081 // If we are instantiating a generic lambda call operator body,
19082 // we do not want to capture new variables. What was captured
19083 // during either a lambdas transformation or initial parsing
19084 // should be used.
19086 if (BuildAndDiagnose) {
19087 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19089 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19090 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19091 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19092 buildLambdaCaptureFixit(*this, LSI, Var);
19093 } else
19095 }
19096 return true;
19097 }
19098
19099 // Try to capture variable-length arrays types.
19100 if (Var->getType()->isVariablyModifiedType()) {
19101 // We're going to walk down into the type and look for VLA
19102 // expressions.
19103 QualType QTy = Var->getType();
19104 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19105 QTy = PVD->getOriginalType();
19107 }
19108
19109 if (getLangOpts().OpenMP) {
19110 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19111 // OpenMP private variables should not be captured in outer scope, so
19112 // just break here. Similarly, global variables that are captured in a
19113 // target region should not be captured outside the scope of the region.
19114 if (RSI->CapRegionKind == CR_OpenMP) {
19115 // FIXME: We should support capturing structured bindings in OpenMP.
19116 if (isa<BindingDecl>(Var)) {
19117 if (BuildAndDiagnose) {
19118 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19119 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19120 }
19121 return true;
19122 }
19123 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19124 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19125 // If the variable is private (i.e. not captured) and has variably
19126 // modified type, we still need to capture the type for correct
19127 // codegen in all regions, associated with the construct. Currently,
19128 // it is captured in the innermost captured region only.
19129 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19130 Var->getType()->isVariablyModifiedType()) {
19131 QualType QTy = Var->getType();
19132 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19133 QTy = PVD->getOriginalType();
19134 for (int I = 1,
19135 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19136 I < E; ++I) {
19137 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19138 FunctionScopes[FunctionScopesIndex - I]);
19139 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19140 "Wrong number of captured regions associated with the "
19141 "OpenMP construct.");
19142 captureVariablyModifiedType(Context, QTy, OuterRSI);
19143 }
19144 }
19145 bool IsTargetCap =
19146 IsOpenMPPrivateDecl != OMPC_private &&
19147 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19148 RSI->OpenMPCaptureLevel);
19149 // Do not capture global if it is not privatized in outer regions.
19150 bool IsGlobalCap =
19151 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19152 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19153
19154 // When we detect target captures we are looking from inside the
19155 // target region, therefore we need to propagate the capture from the
19156 // enclosing region. Therefore, the capture is not initially nested.
19157 if (IsTargetCap)
19158 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19159 RSI->OpenMPLevel);
19160
19161 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19162 (IsGlobal && !IsGlobalCap)) {
19163 Nested = !IsTargetCap;
19164 bool HasConst = DeclRefType.isConstQualified();
19165 DeclRefType = DeclRefType.getUnqualifiedType();
19166 // Don't lose diagnostics about assignments to const.
19167 if (HasConst)
19168 DeclRefType.addConst();
19169 CaptureType = Context.getLValueReferenceType(DeclRefType);
19170 break;
19171 }
19172 }
19173 }
19174 }
19176 // No capture-default, and this is not an explicit capture
19177 // so cannot capture this variable.
19178 if (BuildAndDiagnose) {
19179 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19180 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19181 auto *LSI = cast<LambdaScopeInfo>(CSI);
19182 if (LSI->Lambda) {
19183 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19184 buildLambdaCaptureFixit(*this, LSI, Var);
19185 }
19186 // FIXME: If we error out because an outer lambda can not implicitly
19187 // capture a variable that an inner lambda explicitly captures, we
19188 // should have the inner lambda do the explicit capture - because
19189 // it makes for cleaner diagnostics later. This would purely be done
19190 // so that the diagnostic does not misleadingly claim that a variable
19191 // can not be captured by a lambda implicitly even though it is captured
19192 // explicitly. Suggestion:
19193 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19194 // at the function head
19195 // - cache the StartingDeclContext - this must be a lambda
19196 // - captureInLambda in the innermost lambda the variable.
19197 }
19198 return true;
19199 }
19200 Explicit = false;
19201 FunctionScopesIndex--;
19202 if (IsInScopeDeclarationContext)
19203 DC = ParentDC;
19204 } while (!VarDC->Equals(DC));
19205
19206 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19207 // computing the type of the capture at each step, checking type-specific
19208 // requirements, and adding captures if requested.
19209 // If the variable had already been captured previously, we start capturing
19210 // at the lambda nested within that one.
19211 bool Invalid = false;
19212 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19213 ++I) {
19214 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19215
19216 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19217 // certain types of variables (unnamed, variably modified types etc.)
19218 // so check for eligibility.
19219 if (!Invalid)
19220 Invalid =
19221 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19222
19223 // After encountering an error, if we're actually supposed to capture, keep
19224 // capturing in nested contexts to suppress any follow-on diagnostics.
19225 if (Invalid && !BuildAndDiagnose)
19226 return true;
19227
19228 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19229 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19230 DeclRefType, Nested, *this, Invalid);
19231 Nested = true;
19232 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19234 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19235 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19236 Nested = true;
19237 } else {
19238 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19239 Invalid =
19240 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19241 DeclRefType, Nested, Kind, EllipsisLoc,
19242 /*IsTopScope*/ I == N - 1, *this, Invalid);
19243 Nested = true;
19244 }
19245
19246 if (Invalid && !BuildAndDiagnose)
19247 return true;
19248 }
19249 return Invalid;
19250}
19251
19253 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19254 QualType CaptureType;
19255 QualType DeclRefType;
19256 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19257 /*BuildAndDiagnose=*/true, CaptureType,
19258 DeclRefType, nullptr);
19259}
19260
19262 QualType CaptureType;
19263 QualType DeclRefType;
19265 /*BuildAndDiagnose=*/false, CaptureType,
19266 DeclRefType, nullptr);
19267}
19268
19270 assert(Var && "Null value cannot be captured");
19271
19272 QualType CaptureType;
19273 QualType DeclRefType;
19274
19275 // Determine whether we can capture this variable.
19277 /*BuildAndDiagnose=*/false, CaptureType,
19278 DeclRefType, nullptr))
19279 return QualType();
19280
19281 return DeclRefType;
19282}
19283
19284namespace {
19285// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19286// The produced TemplateArgumentListInfo* points to data stored within this
19287// object, so should only be used in contexts where the pointer will not be
19288// used after the CopiedTemplateArgs object is destroyed.
19289class CopiedTemplateArgs {
19290 bool HasArgs;
19291 TemplateArgumentListInfo TemplateArgStorage;
19292public:
19293 template<typename RefExpr>
19294 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19295 if (HasArgs)
19296 E->copyTemplateArgumentsInto(TemplateArgStorage);
19297 }
19298 operator TemplateArgumentListInfo*()
19299#ifdef __has_cpp_attribute
19300#if __has_cpp_attribute(clang::lifetimebound)
19301 [[clang::lifetimebound]]
19302#endif
19303#endif
19304 {
19305 return HasArgs ? &TemplateArgStorage : nullptr;
19306 }
19307};
19308}
19309
19310/// Walk the set of potential results of an expression and mark them all as
19311/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19312///
19313/// \return A new expression if we found any potential results, ExprEmpty() if
19314/// not, and ExprError() if we diagnosed an error.
19316 NonOdrUseReason NOUR) {
19317 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19318 // an object that satisfies the requirements for appearing in a
19319 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19320 // is immediately applied." This function handles the lvalue-to-rvalue
19321 // conversion part.
19322 //
19323 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19324 // transform it into the relevant kind of non-odr-use node and rebuild the
19325 // tree of nodes leading to it.
19326 //
19327 // This is a mini-TreeTransform that only transforms a restricted subset of
19328 // nodes (and only certain operands of them).
19329
19330 // Rebuild a subexpression.
19331 auto Rebuild = [&](Expr *Sub) {
19332 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19333 };
19334
19335 // Check whether a potential result satisfies the requirements of NOUR.
19336 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19337 // Any entity other than a VarDecl is always odr-used whenever it's named
19338 // in a potentially-evaluated expression.
19339 auto *VD = dyn_cast<VarDecl>(D);
19340 if (!VD)
19341 return true;
19342
19343 // C++2a [basic.def.odr]p4:
19344 // A variable x whose name appears as a potentially-evalauted expression
19345 // e is odr-used by e unless
19346 // -- x is a reference that is usable in constant expressions, or
19347 // -- x is a variable of non-reference type that is usable in constant
19348 // expressions and has no mutable subobjects, and e is an element of
19349 // the set of potential results of an expression of
19350 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19351 // conversion is applied, or
19352 // -- x is a variable of non-reference type, and e is an element of the
19353 // set of potential results of a discarded-value expression to which
19354 // the lvalue-to-rvalue conversion is not applied
19355 //
19356 // We check the first bullet and the "potentially-evaluated" condition in
19357 // BuildDeclRefExpr. We check the type requirements in the second bullet
19358 // in CheckLValueToRValueConversionOperand below.
19359 switch (NOUR) {
19360 case NOUR_None:
19361 case NOUR_Unevaluated:
19362 llvm_unreachable("unexpected non-odr-use-reason");
19363
19364 case NOUR_Constant:
19365 // Constant references were handled when they were built.
19366 if (VD->getType()->isReferenceType())
19367 return true;
19368 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19369 if (RD->hasDefinition() && RD->hasMutableFields())
19370 return true;
19371 if (!VD->isUsableInConstantExpressions(S.Context))
19372 return true;
19373 break;
19374
19375 case NOUR_Discarded:
19376 if (VD->getType()->isReferenceType())
19377 return true;
19378 break;
19379 }
19380 return false;
19381 };
19382
19383 // Mark that this expression does not constitute an odr-use.
19384 auto MarkNotOdrUsed = [&] {
19385 S.MaybeODRUseExprs.remove(E);
19386 if (LambdaScopeInfo *LSI = S.getCurLambda())
19387 LSI->markVariableExprAsNonODRUsed(E);
19388 };
19389
19390 // C++2a [basic.def.odr]p2:
19391 // The set of potential results of an expression e is defined as follows:
19392 switch (E->getStmtClass()) {
19393 // -- If e is an id-expression, ...
19394 case Expr::DeclRefExprClass: {
19395 auto *DRE = cast<DeclRefExpr>(E);
19396 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19397 break;
19398
19399 // Rebuild as a non-odr-use DeclRefExpr.
19400 MarkNotOdrUsed();
19401 return DeclRefExpr::Create(
19402 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19403 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19404 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19405 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19406 }
19407
19408 case Expr::FunctionParmPackExprClass: {
19409 auto *FPPE = cast<FunctionParmPackExpr>(E);
19410 // If any of the declarations in the pack is odr-used, then the expression
19411 // as a whole constitutes an odr-use.
19412 for (VarDecl *D : *FPPE)
19413 if (IsPotentialResultOdrUsed(D))
19414 return ExprEmpty();
19415
19416 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19417 // nothing cares about whether we marked this as an odr-use, but it might
19418 // be useful for non-compiler tools.
19419 MarkNotOdrUsed();
19420 break;
19421 }
19422
19423 // -- If e is a subscripting operation with an array operand...
19424 case Expr::ArraySubscriptExprClass: {
19425 auto *ASE = cast<ArraySubscriptExpr>(E);
19426 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19427 if (!OldBase->getType()->isArrayType())
19428 break;
19429 ExprResult Base = Rebuild(OldBase);
19430 if (!Base.isUsable())
19431 return Base;
19432 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19433 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19434 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19435 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19436 ASE->getRBracketLoc());
19437 }
19438
19439 case Expr::MemberExprClass: {
19440 auto *ME = cast<MemberExpr>(E);
19441 // -- If e is a class member access expression [...] naming a non-static
19442 // data member...
19443 if (isa<FieldDecl>(ME->getMemberDecl())) {
19444 ExprResult Base = Rebuild(ME->getBase());
19445 if (!Base.isUsable())
19446 return Base;
19447 return MemberExpr::Create(
19448 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19449 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19450 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19451 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19452 ME->getObjectKind(), ME->isNonOdrUse());
19453 }
19454
19455 if (ME->getMemberDecl()->isCXXInstanceMember())
19456 break;
19457
19458 // -- If e is a class member access expression naming a static data member,
19459 // ...
19460 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19461 break;
19462
19463 // Rebuild as a non-odr-use MemberExpr.
19464 MarkNotOdrUsed();
19465 return MemberExpr::Create(
19466 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19467 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19468 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19469 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19470 }
19471
19472 case Expr::BinaryOperatorClass: {
19473 auto *BO = cast<BinaryOperator>(E);
19474 Expr *LHS = BO->getLHS();
19475 Expr *RHS = BO->getRHS();
19476 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19477 if (BO->getOpcode() == BO_PtrMemD) {
19478 ExprResult Sub = Rebuild(LHS);
19479 if (!Sub.isUsable())
19480 return Sub;
19481 BO->setLHS(Sub.get());
19482 // -- If e is a comma expression, ...
19483 } else if (BO->getOpcode() == BO_Comma) {
19484 ExprResult Sub = Rebuild(RHS);
19485 if (!Sub.isUsable())
19486 return Sub;
19487 BO->setRHS(Sub.get());
19488 } else {
19489 break;
19490 }
19491 return ExprResult(BO);
19492 }
19493
19494 // -- If e has the form (e1)...
19495 case Expr::ParenExprClass: {
19496 auto *PE = cast<ParenExpr>(E);
19497 ExprResult Sub = Rebuild(PE->getSubExpr());
19498 if (!Sub.isUsable())
19499 return Sub;
19500 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19501 }
19502
19503 // -- If e is a glvalue conditional expression, ...
19504 // We don't apply this to a binary conditional operator. FIXME: Should we?
19505 case Expr::ConditionalOperatorClass: {
19506 auto *CO = cast<ConditionalOperator>(E);
19507 ExprResult LHS = Rebuild(CO->getLHS());
19508 if (LHS.isInvalid())
19509 return ExprError();
19510 ExprResult RHS = Rebuild(CO->getRHS());
19511 if (RHS.isInvalid())
19512 return ExprError();
19513 if (!LHS.isUsable() && !RHS.isUsable())
19514 return ExprEmpty();
19515 if (!LHS.isUsable())
19516 LHS = CO->getLHS();
19517 if (!RHS.isUsable())
19518 RHS = CO->getRHS();
19519 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19520 CO->getCond(), LHS.get(), RHS.get());
19521 }
19522
19523 // [Clang extension]
19524 // -- If e has the form __extension__ e1...
19525 case Expr::UnaryOperatorClass: {
19526 auto *UO = cast<UnaryOperator>(E);
19527 if (UO->getOpcode() != UO_Extension)
19528 break;
19529 ExprResult Sub = Rebuild(UO->getSubExpr());
19530 if (!Sub.isUsable())
19531 return Sub;
19532 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19533 Sub.get());
19534 }
19535
19536 // [Clang extension]
19537 // -- If e has the form _Generic(...), the set of potential results is the
19538 // union of the sets of potential results of the associated expressions.
19539 case Expr::GenericSelectionExprClass: {
19540 auto *GSE = cast<GenericSelectionExpr>(E);
19541
19542 SmallVector<Expr *, 4> AssocExprs;
19543 bool AnyChanged = false;
19544 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19545 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19546 if (AssocExpr.isInvalid())
19547 return ExprError();
19548 if (AssocExpr.isUsable()) {
19549 AssocExprs.push_back(AssocExpr.get());
19550 AnyChanged = true;
19551 } else {
19552 AssocExprs.push_back(OrigAssocExpr);
19553 }
19554 }
19555
19556 void *ExOrTy = nullptr;
19557 bool IsExpr = GSE->isExprPredicate();
19558 if (IsExpr)
19559 ExOrTy = GSE->getControllingExpr();
19560 else
19561 ExOrTy = GSE->getControllingType();
19562 return AnyChanged ? S.CreateGenericSelectionExpr(
19563 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19564 GSE->getRParenLoc(), IsExpr, ExOrTy,
19565 GSE->getAssocTypeSourceInfos(), AssocExprs)
19566 : ExprEmpty();
19567 }
19568
19569 // [Clang extension]
19570 // -- If e has the form __builtin_choose_expr(...), the set of potential
19571 // results is the union of the sets of potential results of the
19572 // second and third subexpressions.
19573 case Expr::ChooseExprClass: {
19574 auto *CE = cast<ChooseExpr>(E);
19575
19576 ExprResult LHS = Rebuild(CE->getLHS());
19577 if (LHS.isInvalid())
19578 return ExprError();
19579
19580 ExprResult RHS = Rebuild(CE->getLHS());
19581 if (RHS.isInvalid())
19582 return ExprError();
19583
19584 if (!LHS.get() && !RHS.get())
19585 return ExprEmpty();
19586 if (!LHS.isUsable())
19587 LHS = CE->getLHS();
19588 if (!RHS.isUsable())
19589 RHS = CE->getRHS();
19590
19591 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19592 RHS.get(), CE->getRParenLoc());
19593 }
19594
19595 // Step through non-syntactic nodes.
19596 case Expr::ConstantExprClass: {
19597 auto *CE = cast<ConstantExpr>(E);
19598 ExprResult Sub = Rebuild(CE->getSubExpr());
19599 if (!Sub.isUsable())
19600 return Sub;
19601 return ConstantExpr::Create(S.Context, Sub.get());
19602 }
19603
19604 // We could mostly rely on the recursive rebuilding to rebuild implicit
19605 // casts, but not at the top level, so rebuild them here.
19606 case Expr::ImplicitCastExprClass: {
19607 auto *ICE = cast<ImplicitCastExpr>(E);
19608 // Only step through the narrow set of cast kinds we expect to encounter.
19609 // Anything else suggests we've left the region in which potential results
19610 // can be found.
19611 switch (ICE->getCastKind()) {
19612 case CK_NoOp:
19613 case CK_DerivedToBase:
19614 case CK_UncheckedDerivedToBase: {
19615 ExprResult Sub = Rebuild(ICE->getSubExpr());
19616 if (!Sub.isUsable())
19617 return Sub;
19618 CXXCastPath Path(ICE->path());
19619 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19620 ICE->getValueKind(), &Path);
19621 }
19622
19623 default:
19624 break;
19625 }
19626 break;
19627 }
19628
19629 default:
19630 break;
19631 }
19632
19633 // Can't traverse through this node. Nothing to do.
19634 return ExprEmpty();
19635}
19636
19638 // Check whether the operand is or contains an object of non-trivial C union
19639 // type.
19640 if (E->getType().isVolatileQualified() &&
19646
19647 // C++2a [basic.def.odr]p4:
19648 // [...] an expression of non-volatile-qualified non-class type to which
19649 // the lvalue-to-rvalue conversion is applied [...]
19651 return E;
19652
19655 if (Result.isInvalid())
19656 return ExprError();
19657 return Result.get() ? Result : E;
19658}
19659
19661 Res = CorrectDelayedTyposInExpr(Res);
19662
19663 if (!Res.isUsable())
19664 return Res;
19665
19666 // If a constant-expression is a reference to a variable where we delay
19667 // deciding whether it is an odr-use, just assume we will apply the
19668 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19669 // (a non-type template argument), we have special handling anyway.
19671}
19672
19674 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19675 // call.
19676 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19677 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19678
19679 for (Expr *E : LocalMaybeODRUseExprs) {
19680 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19681 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19682 DRE->getLocation(), *this);
19683 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19684 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19685 *this);
19686 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19687 for (VarDecl *VD : *FP)
19688 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19689 } else {
19690 llvm_unreachable("Unexpected expression");
19691 }
19692 }
19693
19694 assert(MaybeODRUseExprs.empty() &&
19695 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19696}
19697
19699 ValueDecl *Var, Expr *E) {
19701 if (!VD)
19702 return;
19703
19704 const bool RefersToEnclosingScope =
19705 (SemaRef.CurContext != VD->getDeclContext() &&
19707 if (RefersToEnclosingScope) {
19708 LambdaScopeInfo *const LSI =
19709 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19710 if (LSI && (!LSI->CallOperator ||
19711 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19712 // If a variable could potentially be odr-used, defer marking it so
19713 // until we finish analyzing the full expression for any
19714 // lvalue-to-rvalue
19715 // or discarded value conversions that would obviate odr-use.
19716 // Add it to the list of potential captures that will be analyzed
19717 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19718 // unless the variable is a reference that was initialized by a constant
19719 // expression (this will never need to be captured or odr-used).
19720 //
19721 // FIXME: We can simplify this a lot after implementing P0588R1.
19722 assert(E && "Capture variable should be used in an expression.");
19723 if (!Var->getType()->isReferenceType() ||
19726 }
19727 }
19728}
19729
19732 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19733 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19734 isa<FunctionParmPackExpr>(E)) &&
19735 "Invalid Expr argument to DoMarkVarDeclReferenced");
19736 Var->setReferenced();
19737
19738 if (Var->isInvalidDecl())
19739 return;
19740
19741 auto *MSI = Var->getMemberSpecializationInfo();
19744
19745 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19746 bool UsableInConstantExpr =
19748
19749 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19750 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19751 }
19752
19753 // C++20 [expr.const]p12:
19754 // A variable [...] is needed for constant evaluation if it is [...] a
19755 // variable whose name appears as a potentially constant evaluated
19756 // expression that is either a contexpr variable or is of non-volatile
19757 // const-qualified integral type or of reference type
19758 bool NeededForConstantEvaluation =
19759 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19760
19761 bool NeedDefinition =
19762 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19763
19764 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19765 "Can't instantiate a partial template specialization.");
19766
19767 // If this might be a member specialization of a static data member, check
19768 // the specialization is visible. We already did the checks for variable
19769 // template specializations when we created them.
19770 if (NeedDefinition && TSK != TSK_Undeclared &&
19771 !isa<VarTemplateSpecializationDecl>(Var))
19773
19774 // Perform implicit instantiation of static data members, static data member
19775 // templates of class templates, and variable template specializations. Delay
19776 // instantiations of variable templates, except for those that could be used
19777 // in a constant expression.
19778 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19779 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19780 // instantiation declaration if a variable is usable in a constant
19781 // expression (among other cases).
19782 bool TryInstantiating =
19784 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19785
19786 if (TryInstantiating) {
19787 SourceLocation PointOfInstantiation =
19788 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19789 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19790 if (FirstInstantiation) {
19791 PointOfInstantiation = Loc;
19792 if (MSI)
19793 MSI->setPointOfInstantiation(PointOfInstantiation);
19794 // FIXME: Notify listener.
19795 else
19796 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19797 }
19798
19799 if (UsableInConstantExpr) {
19800 // Do not defer instantiations of variables that could be used in a
19801 // constant expression.
19802 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19803 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19804 });
19805
19806 // Re-set the member to trigger a recomputation of the dependence bits
19807 // for the expression.
19808 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19809 DRE->setDecl(DRE->getDecl());
19810 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19811 ME->setMemberDecl(ME->getMemberDecl());
19812 } else if (FirstInstantiation) {
19814 .push_back(std::make_pair(Var, PointOfInstantiation));
19815 } else {
19816 bool Inserted = false;
19817 for (auto &I : SemaRef.SavedPendingInstantiations) {
19818 auto Iter = llvm::find_if(
19819 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19820 return P.first == Var;
19821 });
19822 if (Iter != I.end()) {
19824 I.erase(Iter);
19825 Inserted = true;
19826 break;
19827 }
19828 }
19829
19830 // FIXME: For a specialization of a variable template, we don't
19831 // distinguish between "declaration and type implicitly instantiated"
19832 // and "implicit instantiation of definition requested", so we have
19833 // no direct way to avoid enqueueing the pending instantiation
19834 // multiple times.
19835 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19837 .push_back(std::make_pair(Var, PointOfInstantiation));
19838 }
19839 }
19840 }
19841
19842 // C++2a [basic.def.odr]p4:
19843 // A variable x whose name appears as a potentially-evaluated expression e
19844 // is odr-used by e unless
19845 // -- x is a reference that is usable in constant expressions
19846 // -- x is a variable of non-reference type that is usable in constant
19847 // expressions and has no mutable subobjects [FIXME], and e is an
19848 // element of the set of potential results of an expression of
19849 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19850 // conversion is applied
19851 // -- x is a variable of non-reference type, and e is an element of the set
19852 // of potential results of a discarded-value expression to which the
19853 // lvalue-to-rvalue conversion is not applied [FIXME]
19854 //
19855 // We check the first part of the second bullet here, and
19856 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19857 // FIXME: To get the third bullet right, we need to delay this even for
19858 // variables that are not usable in constant expressions.
19859
19860 // If we already know this isn't an odr-use, there's nothing more to do.
19861 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19862 if (DRE->isNonOdrUse())
19863 return;
19864 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19865 if (ME->isNonOdrUse())
19866 return;
19867
19868 switch (OdrUse) {
19869 case OdrUseContext::None:
19870 // In some cases, a variable may not have been marked unevaluated, if it
19871 // appears in a defaukt initializer.
19872 assert((!E || isa<FunctionParmPackExpr>(E) ||
19874 "missing non-odr-use marking for unevaluated decl ref");
19875 break;
19876
19877 case OdrUseContext::FormallyOdrUsed:
19878 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19879 // behavior.
19880 break;
19881
19882 case OdrUseContext::Used:
19883 // If we might later find that this expression isn't actually an odr-use,
19884 // delay the marking.
19886 SemaRef.MaybeODRUseExprs.insert(E);
19887 else
19889 break;
19890
19891 case OdrUseContext::Dependent:
19892 // If this is a dependent context, we don't need to mark variables as
19893 // odr-used, but we may still need to track them for lambda capture.
19894 // FIXME: Do we also need to do this inside dependent typeid expressions
19895 // (which are modeled as unevaluated at this point)?
19897 break;
19898 }
19899}
19900
19902 BindingDecl *BD, Expr *E) {
19903 BD->setReferenced();
19904
19905 if (BD->isInvalidDecl())
19906 return;
19907
19908 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19909 if (OdrUse == OdrUseContext::Used) {
19910 QualType CaptureType, DeclRefType;
19912 /*EllipsisLoc*/ SourceLocation(),
19913 /*BuildAndDiagnose*/ true, CaptureType,
19914 DeclRefType,
19915 /*FunctionScopeIndexToStopAt*/ nullptr);
19916 } else if (OdrUse == OdrUseContext::Dependent) {
19918 }
19919}
19920
19922 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19923}
19924
19925// C++ [temp.dep.expr]p3:
19926// An id-expression is type-dependent if it contains:
19927// - an identifier associated by name lookup with an entity captured by copy
19928// in a lambda-expression that has an explicit object parameter whose type
19929// is dependent ([dcl.fct]),
19931 Sema &SemaRef, ValueDecl *D, Expr *E) {
19932 auto *ID = dyn_cast<DeclRefExpr>(E);
19933 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19934 return;
19935
19936 // If any enclosing lambda with a dependent explicit object parameter either
19937 // explicitly captures the variable by value, or has a capture default of '='
19938 // and does not capture the variable by reference, then the type of the DRE
19939 // is dependent on the type of that lambda's explicit object parameter.
19940 auto IsDependent = [&]() {
19941 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19942 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19943 if (!LSI)
19944 continue;
19945
19946 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19947 LSI->AfterParameterList)
19948 return false;
19949
19950 const auto *MD = LSI->CallOperator;
19951 if (MD->getType().isNull())
19952 continue;
19953
19954 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19955 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19956 !Ty->getParamType(0)->isDependentType())
19957 continue;
19958
19959 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19960 if (C->isCopyCapture())
19961 return true;
19962 continue;
19963 }
19964
19965 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19966 return true;
19967 }
19968 return false;
19969 }();
19970
19971 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19972 IsDependent, SemaRef.getASTContext());
19973}
19974
19975static void
19977 bool MightBeOdrUse,
19978 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19981
19982 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19984 if (SemaRef.getLangOpts().CPlusPlus)
19986 Var, E);
19987 return;
19988 }
19989
19990 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19992 if (SemaRef.getLangOpts().CPlusPlus)
19994 Decl, E);
19995 return;
19996 }
19997 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19998
19999 // If this is a call to a method via a cast, also mark the method in the
20000 // derived class used in case codegen can devirtualize the call.
20001 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20002 if (!ME)
20003 return;
20004 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20005 if (!MD)
20006 return;
20007 // Only attempt to devirtualize if this is truly a virtual call.
20008 bool IsVirtualCall = MD->isVirtual() &&
20010 if (!IsVirtualCall)
20011 return;
20012
20013 // If it's possible to devirtualize the call, mark the called function
20014 // referenced.
20016 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20017 if (DM)
20018 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20019}
20020
20022 // TODO: update this with DR# once a defect report is filed.
20023 // C++11 defect. The address of a pure member should not be an ODR use, even
20024 // if it's a qualified reference.
20025 bool OdrUse = true;
20026 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20027 if (Method->isVirtual() &&
20028 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20029 OdrUse = false;
20030
20031 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20035 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20036 !FD->isDependentContext())
20037 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20038 }
20039 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20041}
20042
20044 // C++11 [basic.def.odr]p2:
20045 // A non-overloaded function whose name appears as a potentially-evaluated
20046 // expression or a member of a set of candidate functions, if selected by
20047 // overload resolution when referred to from a potentially-evaluated
20048 // expression, is odr-used, unless it is a pure virtual function and its
20049 // name is not explicitly qualified.
20050 bool MightBeOdrUse = true;
20051 if (E->performsVirtualDispatch(getLangOpts())) {
20052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20053 if (Method->isPureVirtual())
20054 MightBeOdrUse = false;
20055 }
20057 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20058 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20060}
20061
20063 for (VarDecl *VD : *E)
20064 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20066}
20067
20068/// Perform marking for a reference to an arbitrary declaration. It
20069/// marks the declaration referenced, and performs odr-use checking for
20070/// functions and variables. This method should not be used when building a
20071/// normal expression which refers to a variable.
20073 bool MightBeOdrUse) {
20074 if (MightBeOdrUse) {
20075 if (auto *VD = dyn_cast<VarDecl>(D)) {
20077 return;
20078 }
20079 }
20080 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20081 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20082 return;
20083 }
20084 D->setReferenced();
20085}
20086
20087namespace {
20088 // Mark all of the declarations used by a type as referenced.
20089 // FIXME: Not fully implemented yet! We need to have a better understanding
20090 // of when we're entering a context we should not recurse into.
20091 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20092 // TreeTransforms rebuilding the type in a new context. Rather than
20093 // duplicating the TreeTransform logic, we should consider reusing it here.
20094 // Currently that causes problems when rebuilding LambdaExprs.
20095class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20096 Sema &S;
20098
20099public:
20100 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20101
20102 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20103};
20104}
20105
20106bool MarkReferencedDecls::TraverseTemplateArgument(
20107 const TemplateArgument &Arg) {
20108 {
20109 // A non-type template argument is a constant-evaluated context.
20113 if (Decl *D = Arg.getAsDecl())
20114 S.MarkAnyDeclReferenced(Loc, D, true);
20115 } else if (Arg.getKind() == TemplateArgument::Expression) {
20117 }
20118 }
20119
20121}
20122
20124 MarkReferencedDecls Marker(*this, Loc);
20125 Marker.TraverseType(T);
20126}
20127
20128namespace {
20129/// Helper class that marks all of the declarations referenced by
20130/// potentially-evaluated subexpressions as "referenced".
20131class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20132public:
20133 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20134 bool SkipLocalVariables;
20136
20137 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20139 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20140
20141 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20142 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20143 }
20144
20145 void Visit(Expr *E) {
20146 if (llvm::is_contained(StopAt, E))
20147 return;
20148 Inherited::Visit(E);
20149 }
20150
20151 void VisitConstantExpr(ConstantExpr *E) {
20152 // Don't mark declarations within a ConstantExpression, as this expression
20153 // will be evaluated and folded to a value.
20154 }
20155
20156 void VisitDeclRefExpr(DeclRefExpr *E) {
20157 // If we were asked not to visit local variables, don't.
20158 if (SkipLocalVariables) {
20159 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20160 if (VD->hasLocalStorage())
20161 return;
20162 }
20163
20164 // FIXME: This can trigger the instantiation of the initializer of a
20165 // variable, which can cause the expression to become value-dependent
20166 // or error-dependent. Do we need to propagate the new dependence bits?
20168 }
20169
20170 void VisitMemberExpr(MemberExpr *E) {
20172 Visit(E->getBase());
20173 }
20174};
20175} // namespace
20176
20178 bool SkipLocalVariables,
20179 ArrayRef<const Expr*> StopAt) {
20180 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20181}
20182
20183/// Emit a diagnostic when statements are reachable.
20184/// FIXME: check for reachability even in expressions for which we don't build a
20185/// CFG (eg, in the initializer of a global or in a constant expression).
20186/// For example,
20187/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20189 const PartialDiagnostic &PD) {
20190 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20191 if (!FunctionScopes.empty())
20192 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20194 return true;
20195 }
20196
20197 // The initializer of a constexpr variable or of the first declaration of a
20198 // static data member is not syntactically a constant evaluated constant,
20199 // but nonetheless is always required to be a constant expression, so we
20200 // can skip diagnosing.
20201 // FIXME: Using the mangling context here is a hack.
20202 if (auto *VD = dyn_cast_or_null<VarDecl>(
20203 ExprEvalContexts.back().ManglingContextDecl)) {
20204 if (VD->isConstexpr() ||
20205 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20206 return false;
20207 // FIXME: For any other kind of variable, we should build a CFG for its
20208 // initializer and check whether the context in question is reachable.
20209 }
20210
20211 Diag(Loc, PD);
20212 return true;
20213}
20214
20215/// Emit a diagnostic that describes an effect on the run-time behavior
20216/// of the program being compiled.
20217///
20218/// This routine emits the given diagnostic when the code currently being
20219/// type-checked is "potentially evaluated", meaning that there is a
20220/// possibility that the code will actually be executable. Code in sizeof()
20221/// expressions, code used only during overload resolution, etc., are not
20222/// potentially evaluated. This routine will suppress such diagnostics or,
20223/// in the absolutely nutty case of potentially potentially evaluated
20224/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20225/// later.
20226///
20227/// This routine should be used for all diagnostics that describe the run-time
20228/// behavior of a program, such as passing a non-POD value through an ellipsis.
20229/// Failure to do so will likely result in spurious diagnostics or failures
20230/// during overload resolution or within sizeof/alignof/typeof/typeid.
20232 const PartialDiagnostic &PD) {
20233
20234 if (ExprEvalContexts.back().isDiscardedStatementContext())
20235 return false;
20236
20237 switch (ExprEvalContexts.back().Context) {
20242 // The argument will never be evaluated, so don't complain.
20243 break;
20244
20247 // Relevant diagnostics should be produced by constant evaluation.
20248 break;
20249
20252 return DiagIfReachable(Loc, Stmts, PD);
20253 }
20254
20255 return false;
20256}
20257
20259 const PartialDiagnostic &PD) {
20260 return DiagRuntimeBehavior(
20261 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20262 PD);
20263}
20264
20266 CallExpr *CE, FunctionDecl *FD) {
20267 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20268 return false;
20269
20270 // If we're inside a decltype's expression, don't check for a valid return
20271 // type or construct temporaries until we know whether this is the last call.
20272 if (ExprEvalContexts.back().ExprContext ==
20274 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20275 return false;
20276 }
20277
20278 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20279 FunctionDecl *FD;
20280 CallExpr *CE;
20281
20282 public:
20283 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20284 : FD(FD), CE(CE) { }
20285
20286 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20287 if (!FD) {
20288 S.Diag(Loc, diag::err_call_incomplete_return)
20289 << T << CE->getSourceRange();
20290 return;
20291 }
20292
20293 S.Diag(Loc, diag::err_call_function_incomplete_return)
20294 << CE->getSourceRange() << FD << T;
20295 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20296 << FD->getDeclName();
20297 }
20298 } Diagnoser(FD, CE);
20299
20300 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20301 return true;
20302
20303 return false;
20304}
20305
20306// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20307// will prevent this condition from triggering, which is what we want.
20310
20311 unsigned diagnostic = diag::warn_condition_is_assignment;
20312 bool IsOrAssign = false;
20313
20314 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20315 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20316 return;
20317
20318 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20319
20320 // Greylist some idioms by putting them into a warning subcategory.
20321 if (ObjCMessageExpr *ME
20322 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20323 Selector Sel = ME->getSelector();
20324
20325 // self = [<foo> init...]
20326 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20327 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20328
20329 // <foo> = [<bar> nextObject]
20330 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20331 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20332 }
20333
20334 Loc = Op->getOperatorLoc();
20335 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20336 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20337 return;
20338
20339 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20340 Loc = Op->getOperatorLoc();
20341 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20342 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20343 else {
20344 // Not an assignment.
20345 return;
20346 }
20347
20348 Diag(Loc, diagnostic) << E->getSourceRange();
20349
20352 Diag(Loc, diag::note_condition_assign_silence)
20354 << FixItHint::CreateInsertion(Close, ")");
20355
20356 if (IsOrAssign)
20357 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20359 else
20360 Diag(Loc, diag::note_condition_assign_to_comparison)
20362}
20363
20365 // Don't warn if the parens came from a macro.
20366 SourceLocation parenLoc = ParenE->getBeginLoc();
20367 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20368 return;
20369 // Don't warn for dependent expressions.
20370 if (ParenE->isTypeDependent())
20371 return;
20372
20373 Expr *E = ParenE->IgnoreParens();
20374 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20375 return;
20376
20377 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20378 if (opE->getOpcode() == BO_EQ &&
20379 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20380 == Expr::MLV_Valid) {
20381 SourceLocation Loc = opE->getOperatorLoc();
20382
20383 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20384 SourceRange ParenERange = ParenE->getSourceRange();
20385 Diag(Loc, diag::note_equality_comparison_silence)
20386 << FixItHint::CreateRemoval(ParenERange.getBegin())
20387 << FixItHint::CreateRemoval(ParenERange.getEnd());
20388 Diag(Loc, diag::note_equality_comparison_to_assign)
20390 }
20391}
20392
20394 bool IsConstexpr) {
20396 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20398
20400 if (result.isInvalid()) return ExprError();
20401 E = result.get();
20402
20403 if (!E->isTypeDependent()) {
20404 if (getLangOpts().CPlusPlus)
20405 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20406
20408 if (ERes.isInvalid())
20409 return ExprError();
20410 E = ERes.get();
20411
20412 QualType T = E->getType();
20413 if (!T->isScalarType()) { // C99 6.8.4.1p1
20414 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20415 << T << E->getSourceRange();
20416 return ExprError();
20417 }
20418 CheckBoolLikeConversion(E, Loc);
20419 }
20420
20421 return E;
20422}
20423
20425 Expr *SubExpr, ConditionKind CK,
20426 bool MissingOK) {
20427 // MissingOK indicates whether having no condition expression is valid
20428 // (for loop) or invalid (e.g. while loop).
20429 if (!SubExpr)
20430 return MissingOK ? ConditionResult() : ConditionError();
20431
20432 ExprResult Cond;
20433 switch (CK) {
20435 Cond = CheckBooleanCondition(Loc, SubExpr);
20436 break;
20437
20439 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20440 break;
20441
20443 Cond = CheckSwitchCondition(Loc, SubExpr);
20444 break;
20445 }
20446 if (Cond.isInvalid()) {
20447 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20448 {SubExpr}, PreferredConditionType(CK));
20449 if (!Cond.get())
20450 return ConditionError();
20451 }
20452 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20454 if (!FullExpr.get())
20455 return ConditionError();
20456
20457 return ConditionResult(*this, nullptr, FullExpr,
20459}
20460
20461namespace {
20462 /// A visitor for rebuilding a call to an __unknown_any expression
20463 /// to have an appropriate type.
20464 struct RebuildUnknownAnyFunction
20465 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20466
20467 Sema &S;
20468
20469 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20470
20471 ExprResult VisitStmt(Stmt *S) {
20472 llvm_unreachable("unexpected statement!");
20473 }
20474
20475 ExprResult VisitExpr(Expr *E) {
20476 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20477 << E->getSourceRange();
20478 return ExprError();
20479 }
20480
20481 /// Rebuild an expression which simply semantically wraps another
20482 /// expression which it shares the type and value kind of.
20483 template <class T> ExprResult rebuildSugarExpr(T *E) {
20484 ExprResult SubResult = Visit(E->getSubExpr());
20485 if (SubResult.isInvalid()) return ExprError();
20486
20487 Expr *SubExpr = SubResult.get();
20488 E->setSubExpr(SubExpr);
20489 E->setType(SubExpr->getType());
20490 E->setValueKind(SubExpr->getValueKind());
20491 assert(E->getObjectKind() == OK_Ordinary);
20492 return E;
20493 }
20494
20495 ExprResult VisitParenExpr(ParenExpr *E) {
20496 return rebuildSugarExpr(E);
20497 }
20498
20499 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20500 return rebuildSugarExpr(E);
20501 }
20502
20503 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20504 ExprResult SubResult = Visit(E->getSubExpr());
20505 if (SubResult.isInvalid()) return ExprError();
20506
20507 Expr *SubExpr = SubResult.get();
20508 E->setSubExpr(SubExpr);
20509 E->setType(S.Context.getPointerType(SubExpr->getType()));
20510 assert(E->isPRValue());
20511 assert(E->getObjectKind() == OK_Ordinary);
20512 return E;
20513 }
20514
20515 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20516 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20517
20518 E->setType(VD->getType());
20519
20520 assert(E->isPRValue());
20521 if (S.getLangOpts().CPlusPlus &&
20522 !(isa<CXXMethodDecl>(VD) &&
20523 cast<CXXMethodDecl>(VD)->isInstance()))
20525
20526 return E;
20527 }
20528
20529 ExprResult VisitMemberExpr(MemberExpr *E) {
20530 return resolveDecl(E, E->getMemberDecl());
20531 }
20532
20533 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20534 return resolveDecl(E, E->getDecl());
20535 }
20536 };
20537}
20538
20539/// Given a function expression of unknown-any type, try to rebuild it
20540/// to have a function type.
20542 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20543 if (Result.isInvalid()) return ExprError();
20544 return S.DefaultFunctionArrayConversion(Result.get());
20545}
20546
20547namespace {
20548 /// A visitor for rebuilding an expression of type __unknown_anytype
20549 /// into one which resolves the type directly on the referring
20550 /// expression. Strict preservation of the original source
20551 /// structure is not a goal.
20552 struct RebuildUnknownAnyExpr
20553 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20554
20555 Sema &S;
20556
20557 /// The current destination type.
20558 QualType DestType;
20559
20560 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20561 : S(S), DestType(CastType) {}
20562
20563 ExprResult VisitStmt(Stmt *S) {
20564 llvm_unreachable("unexpected statement!");
20565 }
20566
20567 ExprResult VisitExpr(Expr *E) {
20568 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20569 << E->getSourceRange();
20570 return ExprError();
20571 }
20572
20573 ExprResult VisitCallExpr(CallExpr *E);
20574 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20575
20576 /// Rebuild an expression which simply semantically wraps another
20577 /// expression which it shares the type and value kind of.
20578 template <class T> ExprResult rebuildSugarExpr(T *E) {
20579 ExprResult SubResult = Visit(E->getSubExpr());
20580 if (SubResult.isInvalid()) return ExprError();
20581 Expr *SubExpr = SubResult.get();
20582 E->setSubExpr(SubExpr);
20583 E->setType(SubExpr->getType());
20584 E->setValueKind(SubExpr->getValueKind());
20585 assert(E->getObjectKind() == OK_Ordinary);
20586 return E;
20587 }
20588
20589 ExprResult VisitParenExpr(ParenExpr *E) {
20590 return rebuildSugarExpr(E);
20591 }
20592
20593 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20594 return rebuildSugarExpr(E);
20595 }
20596
20597 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20598 const PointerType *Ptr = DestType->getAs<PointerType>();
20599 if (!Ptr) {
20600 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20601 << E->getSourceRange();
20602 return ExprError();
20603 }
20604
20605 if (isa<CallExpr>(E->getSubExpr())) {
20606 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20607 << E->getSourceRange();
20608 return ExprError();
20609 }
20610
20611 assert(E->isPRValue());
20612 assert(E->getObjectKind() == OK_Ordinary);
20613 E->setType(DestType);
20614
20615 // Build the sub-expression as if it were an object of the pointee type.
20616 DestType = Ptr->getPointeeType();
20617 ExprResult SubResult = Visit(E->getSubExpr());
20618 if (SubResult.isInvalid()) return ExprError();
20619 E->setSubExpr(SubResult.get());
20620 return E;
20621 }
20622
20623 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20624
20625 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20626
20627 ExprResult VisitMemberExpr(MemberExpr *E) {
20628 return resolveDecl(E, E->getMemberDecl());
20629 }
20630
20631 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20632 return resolveDecl(E, E->getDecl());
20633 }
20634 };
20635}
20636
20637/// Rebuilds a call expression which yielded __unknown_anytype.
20638ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20639 Expr *CalleeExpr = E->getCallee();
20640
20641 enum FnKind {
20642 FK_MemberFunction,
20643 FK_FunctionPointer,
20644 FK_BlockPointer
20645 };
20646
20647 FnKind Kind;
20648 QualType CalleeType = CalleeExpr->getType();
20649 if (CalleeType == S.Context.BoundMemberTy) {
20650 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20651 Kind = FK_MemberFunction;
20652 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20653 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20654 CalleeType = Ptr->getPointeeType();
20655 Kind = FK_FunctionPointer;
20656 } else {
20657 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20658 Kind = FK_BlockPointer;
20659 }
20660 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20661
20662 // Verify that this is a legal result type of a function.
20663 if (DestType->isArrayType() || DestType->isFunctionType()) {
20664 unsigned diagID = diag::err_func_returning_array_function;
20665 if (Kind == FK_BlockPointer)
20666 diagID = diag::err_block_returning_array_function;
20667
20668 S.Diag(E->getExprLoc(), diagID)
20669 << DestType->isFunctionType() << DestType;
20670 return ExprError();
20671 }
20672
20673 // Otherwise, go ahead and set DestType as the call's result.
20674 E->setType(DestType.getNonLValueExprType(S.Context));
20676 assert(E->getObjectKind() == OK_Ordinary);
20677
20678 // Rebuild the function type, replacing the result type with DestType.
20679 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20680 if (Proto) {
20681 // __unknown_anytype(...) is a special case used by the debugger when
20682 // it has no idea what a function's signature is.
20683 //
20684 // We want to build this call essentially under the K&R
20685 // unprototyped rules, but making a FunctionNoProtoType in C++
20686 // would foul up all sorts of assumptions. However, we cannot
20687 // simply pass all arguments as variadic arguments, nor can we
20688 // portably just call the function under a non-variadic type; see
20689 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20690 // However, it turns out that in practice it is generally safe to
20691 // call a function declared as "A foo(B,C,D);" under the prototype
20692 // "A foo(B,C,D,...);". The only known exception is with the
20693 // Windows ABI, where any variadic function is implicitly cdecl
20694 // regardless of its normal CC. Therefore we change the parameter
20695 // types to match the types of the arguments.
20696 //
20697 // This is a hack, but it is far superior to moving the
20698 // corresponding target-specific code from IR-gen to Sema/AST.
20699
20700 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20701 SmallVector<QualType, 8> ArgTypes;
20702 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20703 ArgTypes.reserve(E->getNumArgs());
20704 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20705 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20706 }
20707 ParamTypes = ArgTypes;
20708 }
20709 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20710 Proto->getExtProtoInfo());
20711 } else {
20712 DestType = S.Context.getFunctionNoProtoType(DestType,
20713 FnType->getExtInfo());
20714 }
20715
20716 // Rebuild the appropriate pointer-to-function type.
20717 switch (Kind) {
20718 case FK_MemberFunction:
20719 // Nothing to do.
20720 break;
20721
20722 case FK_FunctionPointer:
20723 DestType = S.Context.getPointerType(DestType);
20724 break;
20725
20726 case FK_BlockPointer:
20727 DestType = S.Context.getBlockPointerType(DestType);
20728 break;
20729 }
20730
20731 // Finally, we can recurse.
20732 ExprResult CalleeResult = Visit(CalleeExpr);
20733 if (!CalleeResult.isUsable()) return ExprError();
20734 E->setCallee(CalleeResult.get());
20735
20736 // Bind a temporary if necessary.
20737 return S.MaybeBindToTemporary(E);
20738}
20739
20740ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20741 // Verify that this is a legal result type of a call.
20742 if (DestType->isArrayType() || DestType->isFunctionType()) {
20743 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20744 << DestType->isFunctionType() << DestType;
20745 return ExprError();
20746 }
20747
20748 // Rewrite the method result type if available.
20749 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20750 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20751 Method->setReturnType(DestType);
20752 }
20753
20754 // Change the type of the message.
20755 E->setType(DestType.getNonReferenceType());
20757
20758 return S.MaybeBindToTemporary(E);
20759}
20760
20761ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20762 // The only case we should ever see here is a function-to-pointer decay.
20763 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20764 assert(E->isPRValue());
20765 assert(E->getObjectKind() == OK_Ordinary);
20766
20767 E->setType(DestType);
20768
20769 // Rebuild the sub-expression as the pointee (function) type.
20770 DestType = DestType->castAs<PointerType>()->getPointeeType();
20771
20772 ExprResult Result = Visit(E->getSubExpr());
20773 if (!Result.isUsable()) return ExprError();
20774
20775 E->setSubExpr(Result.get());
20776 return E;
20777 } else if (E->getCastKind() == CK_LValueToRValue) {
20778 assert(E->isPRValue());
20779 assert(E->getObjectKind() == OK_Ordinary);
20780
20781 assert(isa<BlockPointerType>(E->getType()));
20782
20783 E->setType(DestType);
20784
20785 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20786 DestType = S.Context.getLValueReferenceType(DestType);
20787
20788 ExprResult Result = Visit(E->getSubExpr());
20789 if (!Result.isUsable()) return ExprError();
20790
20791 E->setSubExpr(Result.get());
20792 return E;
20793 } else {
20794 llvm_unreachable("Unhandled cast type!");
20795 }
20796}
20797
20798ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20799 ExprValueKind ValueKind = VK_LValue;
20800 QualType Type = DestType;
20801
20802 // We know how to make this work for certain kinds of decls:
20803
20804 // - functions
20805 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20806 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20807 DestType = Ptr->getPointeeType();
20808 ExprResult Result = resolveDecl(E, VD);
20809 if (Result.isInvalid()) return ExprError();
20810 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20811 VK_PRValue);
20812 }
20813
20814 if (!Type->isFunctionType()) {
20815 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20816 << VD << E->getSourceRange();
20817 return ExprError();
20818 }
20819 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20820 // We must match the FunctionDecl's type to the hack introduced in
20821 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20822 // type. See the lengthy commentary in that routine.
20823 QualType FDT = FD->getType();
20824 const FunctionType *FnType = FDT->castAs<FunctionType>();
20825 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20826 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20827 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20828 SourceLocation Loc = FD->getLocation();
20830 S.Context, FD->getDeclContext(), Loc, Loc,
20831 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20833 false /*isInlineSpecified*/, FD->hasPrototype(),
20834 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20835
20836 if (FD->getQualifier())
20837 NewFD->setQualifierInfo(FD->getQualifierLoc());
20838
20840 for (const auto &AI : FT->param_types()) {
20841 ParmVarDecl *Param =
20843 Param->setScopeInfo(0, Params.size());
20844 Params.push_back(Param);
20845 }
20846 NewFD->setParams(Params);
20847 DRE->setDecl(NewFD);
20848 VD = DRE->getDecl();
20849 }
20850 }
20851
20852 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20853 if (MD->isInstance()) {
20854 ValueKind = VK_PRValue;
20856 }
20857
20858 // Function references aren't l-values in C.
20859 if (!S.getLangOpts().CPlusPlus)
20860 ValueKind = VK_PRValue;
20861
20862 // - variables
20863 } else if (isa<VarDecl>(VD)) {
20864 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20865 Type = RefTy->getPointeeType();
20866 } else if (Type->isFunctionType()) {
20867 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20868 << VD << E->getSourceRange();
20869 return ExprError();
20870 }
20871
20872 // - nothing else
20873 } else {
20874 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20875 << VD << E->getSourceRange();
20876 return ExprError();
20877 }
20878
20879 // Modifying the declaration like this is friendly to IR-gen but
20880 // also really dangerous.
20881 VD->setType(DestType);
20882 E->setType(Type);
20883 E->setValueKind(ValueKind);
20884 return E;
20885}
20886
20890 // The type we're casting to must be either void or complete.
20891 if (!CastType->isVoidType() &&
20893 diag::err_typecheck_cast_to_incomplete))
20894 return ExprError();
20895
20896 // Rewrite the casted expression from scratch.
20897 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20898 if (!result.isUsable()) return ExprError();
20899
20900 CastExpr = result.get();
20901 VK = CastExpr->getValueKind();
20902 CastKind = CK_NoOp;
20903
20904 return CastExpr;
20905}
20906
20908 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20909}
20910
20912 Expr *arg, QualType &paramType) {
20913 // If the syntactic form of the argument is not an explicit cast of
20914 // any sort, just do default argument promotion.
20915 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20916 if (!castArg) {
20918 if (result.isInvalid()) return ExprError();
20919 paramType = result.get()->getType();
20920 return result;
20921 }
20922
20923 // Otherwise, use the type that was written in the explicit cast.
20924 assert(!arg->hasPlaceholderType());
20925 paramType = castArg->getTypeAsWritten();
20926
20927 // Copy-initialize a parameter of that type.
20928 InitializedEntity entity =
20930 /*consumed*/ false);
20931 return PerformCopyInitialization(entity, callLoc, arg);
20932}
20933
20935 Expr *orig = E;
20936 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20937 while (true) {
20938 E = E->IgnoreParenImpCasts();
20939 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20940 E = call->getCallee();
20941 diagID = diag::err_uncasted_call_of_unknown_any;
20942 } else {
20943 break;
20944 }
20945 }
20946
20947 SourceLocation loc;
20948 NamedDecl *d;
20949 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20950 loc = ref->getLocation();
20951 d = ref->getDecl();
20952 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20953 loc = mem->getMemberLoc();
20954 d = mem->getMemberDecl();
20955 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20956 diagID = diag::err_uncasted_call_of_unknown_any;
20957 loc = msg->getSelectorStartLoc();
20958 d = msg->getMethodDecl();
20959 if (!d) {
20960 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20961 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20962 << orig->getSourceRange();
20963 return ExprError();
20964 }
20965 } else {
20966 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20967 << E->getSourceRange();
20968 return ExprError();
20969 }
20970
20971 S.Diag(loc, diagID) << d << orig->getSourceRange();
20972
20973 // Never recoverable.
20974 return ExprError();
20975}
20976
20979 // C cannot handle TypoExpr nodes on either side of a binop because it
20980 // doesn't handle dependent types properly, so make sure any TypoExprs have
20981 // been dealt with before checking the operands.
20983 if (!Result.isUsable()) return ExprError();
20984 E = Result.get();
20985 }
20986
20987 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20988 if (!placeholderType) return E;
20989
20990 switch (placeholderType->getKind()) {
20991 case BuiltinType::UnresolvedTemplate: {
20992 auto *ULE = cast<UnresolvedLookupExpr>(E);
20993 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20994 // There's only one FoundDecl for UnresolvedTemplate type. See
20995 // BuildTemplateIdExpr.
20996 NamedDecl *Temp = *ULE->decls_begin();
20997 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20998
20999 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
21000 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21001 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
21002 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
21003 else
21004 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21005 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
21006 << IsTypeAliasTemplateDecl;
21007 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21008 << IsTypeAliasTemplateDecl;
21009
21010 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
21011 }
21012
21013 // Overloaded expressions.
21014 case BuiltinType::Overload: {
21015 // Try to resolve a single function template specialization.
21016 // This is obligatory.
21019 return Result;
21020
21021 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21022 // leaves Result unchanged on failure.
21023 Result = E;
21025 return Result;
21026
21027 // If that failed, try to recover with a call.
21028 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21029 /*complain*/ true);
21030 return Result;
21031 }
21032
21033 // Bound member functions.
21034 case BuiltinType::BoundMember: {
21035 ExprResult result = E;
21036 const Expr *BME = E->IgnoreParens();
21037 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21038 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21039 if (isa<CXXPseudoDestructorExpr>(BME)) {
21040 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21041 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21042 if (ME->getMemberNameInfo().getName().getNameKind() ==
21044 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21045 }
21046 tryToRecoverWithCall(result, PD,
21047 /*complain*/ true);
21048 return result;
21049 }
21050
21051 // ARC unbridged casts.
21052 case BuiltinType::ARCUnbridgedCast: {
21053 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21054 ObjC().diagnoseARCUnbridgedCast(realCast);
21055 return realCast;
21056 }
21057
21058 // Expressions of unknown type.
21059 case BuiltinType::UnknownAny:
21060 return diagnoseUnknownAnyExpr(*this, E);
21061
21062 // Pseudo-objects.
21063 case BuiltinType::PseudoObject:
21064 return PseudoObject().checkRValue(E);
21065
21066 case BuiltinType::BuiltinFn: {
21067 // Accept __noop without parens by implicitly converting it to a call expr.
21068 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21069 if (DRE) {
21070 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21071 unsigned BuiltinID = FD->getBuiltinID();
21072 if (BuiltinID == Builtin::BI__noop) {
21073 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21074 CK_BuiltinFnToFnPtr)
21075 .get();
21076 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21079 }
21080
21081 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21082 // Any use of these other than a direct call is ill-formed as of C++20,
21083 // because they are not addressable functions. In earlier language
21084 // modes, warn and force an instantiation of the real body.
21085 Diag(E->getBeginLoc(),
21087 ? diag::err_use_of_unaddressable_function
21088 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21089 if (FD->isImplicitlyInstantiable()) {
21090 // Require a definition here because a normal attempt at
21091 // instantiation for a builtin will be ignored, and we won't try
21092 // again later. We assume that the definition of the template
21093 // precedes this use.
21095 /*Recursive=*/false,
21096 /*DefinitionRequired=*/true,
21097 /*AtEndOfTU=*/false);
21098 }
21099 // Produce a properly-typed reference to the function.
21100 CXXScopeSpec SS;
21101 SS.Adopt(DRE->getQualifierLoc());
21102 TemplateArgumentListInfo TemplateArgs;
21103 DRE->copyTemplateArgumentsInto(TemplateArgs);
21104 return BuildDeclRefExpr(
21105 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21106 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21107 DRE->getTemplateKeywordLoc(),
21108 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21109 }
21110 }
21111
21112 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21113 return ExprError();
21114 }
21115
21116 case BuiltinType::IncompleteMatrixIdx:
21117 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21118 ->getRowIdx()
21119 ->getBeginLoc(),
21120 diag::err_matrix_incomplete_index);
21121 return ExprError();
21122
21123 // Expressions of unknown type.
21124 case BuiltinType::ArraySection:
21125 Diag(E->getBeginLoc(), diag::err_array_section_use)
21126 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21127 return ExprError();
21128
21129 // Expressions of unknown type.
21130 case BuiltinType::OMPArrayShaping:
21131 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21132
21133 case BuiltinType::OMPIterator:
21134 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21135
21136 // Everything else should be impossible.
21137#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21138 case BuiltinType::Id:
21139#include "clang/Basic/OpenCLImageTypes.def"
21140#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21141 case BuiltinType::Id:
21142#include "clang/Basic/OpenCLExtensionTypes.def"
21143#define SVE_TYPE(Name, Id, SingletonId) \
21144 case BuiltinType::Id:
21145#include "clang/Basic/AArch64SVEACLETypes.def"
21146#define PPC_VECTOR_TYPE(Name, Id, Size) \
21147 case BuiltinType::Id:
21148#include "clang/Basic/PPCTypes.def"
21149#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21150#include "clang/Basic/RISCVVTypes.def"
21151#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21152#include "clang/Basic/WebAssemblyReferenceTypes.def"
21153#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21154#include "clang/Basic/AMDGPUTypes.def"
21155#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21156#include "clang/Basic/HLSLIntangibleTypes.def"
21157#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21158#define PLACEHOLDER_TYPE(Id, SingletonId)
21159#include "clang/AST/BuiltinTypes.def"
21160 break;
21161 }
21162
21163 llvm_unreachable("invalid placeholder type!");
21164}
21165
21167 if (E->isTypeDependent())
21168 return true;
21171 return false;
21172}
21173
21175 ArrayRef<Expr *> SubExprs, QualType T) {
21176 if (!Context.getLangOpts().RecoveryAST)
21177 return ExprError();
21178
21179 if (isSFINAEContext())
21180 return ExprError();
21181
21182 if (T.isNull() || T->isUndeducedType() ||
21183 !Context.getLangOpts().RecoveryASTType)
21184 // We don't know the concrete type, fallback to dependent type.
21186
21187 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21188}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1134
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:9126
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17743
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:1940
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:15315
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:10010
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:18694
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10768
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:15064
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6133
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10687
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:8697
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:3157
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8146
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:8352
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:11734
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10732
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11684
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5796
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2225
@ ConstMethod
Definition: SemaExpr.cpp:13353
@ ConstUnknown
Definition: SemaExpr.cpp:13355
@ ConstVariable
Definition: SemaExpr.cpp:13351
@ NestedConstMember
Definition: SemaExpr.cpp:13354
@ ConstMember
Definition: SemaExpr.cpp:13352
@ ConstFunction
Definition: SemaExpr.cpp:13350
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14540
static void DetectPrecisionLossInComplexDivision(Sema &S, SourceLocation OpLoc, Expr *Operand)
Definition: SemaExpr.cpp:15246
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18081
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13290
@ NCCK_Block
Definition: SemaExpr.cpp:13290
@ NCCK_None
Definition: SemaExpr.cpp:13290
@ NCCK_Lambda
Definition: SemaExpr.cpp:13290
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:9899
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:9175
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6065
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:2635
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19930
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18546
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16806
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:8601
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1924
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16689
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13865
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4720
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12146
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14440
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4334
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8676
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17930
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:14596
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:10854
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7989
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19730
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3182
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7955
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11776
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6408
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13487
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19976
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:9948
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19698
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14422
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17593
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12021
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:8631
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:14694
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1310
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6298
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:9563
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:8270
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7976
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10699
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14679
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4777
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8902
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17635
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:15155
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:2360
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:13970
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8215
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:8324
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10526
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11835
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:4211
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10574
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3474
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5755
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:11223
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4118
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9075
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:1267
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18373
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:10884
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13551
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14072
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:17961
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:11585
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15212
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14132
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:1360
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4791
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:10057
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:18734
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15119
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:558
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8731
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:18049
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:13362
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3605
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13340
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18490
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10746
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4163
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11418
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12064
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20934
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:1932
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8390
OriginalExprKind
Definition: SemaExpr.cpp:13481
@ OEK_Variable
Definition: SemaExpr.cpp:13482
@ OEK_LValue
Definition: SemaExpr.cpp:13484
@ OEK_Member
Definition: SemaExpr.cpp:13483
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:18626
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:1217
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10674
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:11324
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18449
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
Definition: SemaExpr.cpp:5564
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1292
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10490
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13277
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
Definition: SemaExpr.cpp:11792
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:18867
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6367
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4148
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8923
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4136
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15140
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4810
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:1492
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10935
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6325
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1406
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4193
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10716
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:8185
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11982
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12846
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8304
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8616
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:1111
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14727
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:14638
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:583
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20541
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:1186
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11637
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1139
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:6225
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19901
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1900
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:107
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:1453
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1162
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13934
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18841
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10664
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11574
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:14750
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11624
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13291
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:8120
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15184
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15170
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11614
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15107
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4400
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:9969
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18527
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15494
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13679
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13086
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:19315
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17995
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11217
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:10800
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7500
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
SourceLocation Begin
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:488
bool hasValue() const
Definition: APValue.h:464
bool isInt() const
Definition: APValue.h:466
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:957
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:83
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType AccumTy
Definition: ASTContext.h:1173
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:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
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:1191
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
Definition: ASTContext.h:1169
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:2258
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType 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:2272
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1172
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
CanQualType DoubleTy
Definition: ASTContext.h:1172
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:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
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:1188
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:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:834
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition: ASTContext.h:802
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1241
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:1161
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:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1245
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:1176
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:1188
CanQualType CharTy
Definition: ASTContext.h:1162
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:1169
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1237
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
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:2469
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
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:2489
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
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:2011
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
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:1681
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:1169
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:1176
CanQualType LongAccumTy
Definition: ASTContext.h:1174
CanQualType Char32Ty
Definition: ASTContext.h:1168
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:799
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2508
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:1169
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1927
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:2139
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1166
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1184
bool isDependenceAllowed() const
Definition: ASTContext.h:840
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:2493
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:4421
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
Wrapper for source info for arrays.
Definition: TypeLoc.h:1593
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
QualType getElementType() const
Definition: Type.h:3589
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6475
Attr - This represents one attribute.
Definition: Attr.h:43
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2196
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:4009
bool isComparisonOp() const
Definition: Expr.h:4010
StringRef getOpcodeStr() const
Definition: Expr.h:3975
bool isRelationalOp() const
Definition: Expr.h:4004
SourceLocation getOperatorLoc() const
Definition: Expr.h:3951
bool isCompoundAssignmentOp() const
Definition: Expr.h:4053
bool isMultiplicativeOp() const
Definition: Expr.h:3994
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2149
bool isShiftOp() const
Definition: Expr.h:3998
Expr * getRHS() const
Definition: Expr.h:3961
bool isEqualityOp() const
Definition: Expr.h:4007
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:4902
bool isBitwiseOp() const
Definition: Expr.h:4001
bool isAdditiveOp() const
Definition: Expr.h:3996
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:2221
Opcode getOpcode() const
Definition: Expr.h:3954
bool isAssignmentOp() const
Definition: Expr.h:4048
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2158
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:4000
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
A class which contains all the information about a particular captured value.
Definition: Decl.h:4502
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5267
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4578
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4635
void setIsVariadic(bool value)
Definition: Decl.h:4572
SourceLocation getCaretLocation() const
Definition: Decl.h:4569
void setBody(CompoundStmt *B)
Definition: Decl.h:4576
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4582
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5278
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5454
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
bool isSVEBool() const
Definition: Type.h:3111
Kind getKind() const
Definition: Type.h:3082
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:210
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:285
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:197
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:183
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:189
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:1906
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:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:3057
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2318
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:1018
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
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:1072
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:1533
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isVirtual() const
Definition: DeclCXX.h:2133
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
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:2426
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:1237
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:612
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2036
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
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 isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
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:123
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:149
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:129
Represents the this expression in C++.
Definition: ExprCXX.h:1152
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3081
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:1499
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3087
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3055
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3058
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3109
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3100
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:3547
const char * getCastKindName() const
Definition: Expr.h:3595
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:1615
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4641
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:3145
QualType getElementType() const
Definition: Type.h:3155
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:4924
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
bool body_empty() const
Definition: Stmt.h:1672
Stmt * getStmtExprResult()
Definition: Stmt.h:1750
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:301
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:377
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1127
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
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:4582
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:1294
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:1372
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
bool isRequiresExprBody() const
Definition: DeclBase.h:2189
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1649
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2036
bool isFunctionOrMethod() const
Definition: DeclBase.h:2156
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1296
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1415
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1370
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1414
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:543
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1418
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:550
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1337
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1386
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:487
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1348
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1352
ValueDecl * getDecl()
Definition: Expr.h:1333
SourceLocation getLocation() const
Definition: Expr.h:1341
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:753
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:572
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setReferenced(bool R=true)
Definition: DeclBase.h:626
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1042
DeclContext * getDeclContext()
Definition: DeclBase.h:451
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
Kind getKind() const
Definition: DeclBase.h:445
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:800
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
DeclaratorContext getContext() const
Definition: DeclSpec.h:2075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2333
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:531
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Recursively visit a template argument and dispatch to the appropriate method for the argument type.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2355
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
Represents a reference to #emded data.
Definition: Expr.h:4916
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:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3826
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
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:3124
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:3053
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:3102
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:3097
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3085
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3106
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:3093
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:3317
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:822
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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:3594
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:3077
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:812
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
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:3970
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:265
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h: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:276
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4222
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:6354
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
bool isFPConstrained() const
Definition: LangOptions.h:906
RoundingMode getRoundingMode() const
Definition: LangOptions.h:912
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:1002
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1081
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
const Expr * getSubExpr() const
Definition: Expr.h:1057
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:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3734
bool isImmediateFunction() const
Definition: Decl.cpp:3300
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3894
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3649
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3752
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3509
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:2124
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4000
bool isConsteval() const
Definition: Decl.h:2410
size_t param_size() const
Definition: Decl.h:2665
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3910
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2756
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4654
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
QualType desugar() const
Definition: Type.h:5651
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
bool isParamConsumed(unsigned I) const
Definition: Type.h:5587
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
Declaration of a template function.
Definition: DeclTemplate.h:958
unsigned getNumParams() const
Definition: TypeLoc.h:1532
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1538
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1484
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1541
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1476
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
bool getCmseNSCall() const
Definition: Type.h:4482
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4656
QualType getReturnType() const
Definition: Type.h:4648
bool getCmseNSCallAttr() const
Definition: Type.h:4658
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4672
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4716
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:4522
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:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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:7637
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:980
Represents the declaration of a label.
Definition: Decl.h:503
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
Definition: LangOptions.h:461
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:299
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:308
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:306
@ 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:313
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:304
@ 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:499
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:667
bool isSignedOverflowDefined() const
Definition: LangOptions.h:663
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:1023
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:309
Represents the results of name lookup.
Definition: Lookup.h:46
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
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:4312
MS property subscript expression.
Definition: ExprCXX.h:1004
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:2796
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4196
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3425
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
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:1769
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3454
Expr * getBase() const
Definition: Expr.h:3313
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:641
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
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:350
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7529
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1487
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
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:941
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:7585
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
qual_range quals() const
Definition: Type.h:7704
Represents a class type in Objective C.
Definition: Type.h:7331
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:177
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
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:1672
Helper class for OffsetOfExpr.
Definition: Expr.h:2413
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:1173
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:1015
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1192
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:2983
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2191
const Expr * getSubExpr() const
Definition: Expr.h:2187
bool isProducedByFoldExpansion() const
Definition: Expr.h:2212
Expr * getExpr(unsigned Init)
Definition: Expr.h:5896
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4774
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
QualType getOriginalType() const
Definition: Decl.cpp:2931
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:2922
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:637
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:677
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
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:8083
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
@ DK_nontrivial_c_struct
Definition: Type.h:1524
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2867
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1411
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
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:8077
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
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:2649
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
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:8139
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2885
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:8146
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8057
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1663
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7993
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:2641
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:8119
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7968
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:8071
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:701
void removeAddressSpace()
Definition: Type.h:589
void setAddressSpace(LangAS space)
Definition: Type.h:584
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
Qualifiers withoutObjCLifetime() const
Definition: Type.h:526
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:521
LangAS getAddressSpace() const
Definition: Type.h:564
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:743
Represents a struct/union/class.
Definition: Decl.h:4162
field_range fields() const
Definition: Decl.h:4376
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5227
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
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:263
@ 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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
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:704
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:880
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:120
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
Definition: SemaHLSL.cpp:2461
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Definition: SemaHLSL.cpp:644
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Definition: SemaHLSL.cpp:577
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:854
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:1260
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
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:591
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: SemaOpenMP.h:371
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12125
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7229
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17147
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17153
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
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:14561
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:6395
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7801
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13134
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:732
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15827
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7851
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15504
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7769
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:870
bool isAttrContext() const
Definition: Sema.h:6469
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15168
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:7844
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9029
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:412
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19660
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13164
VariadicCallType
Definition: Sema.h:2315
@ VariadicDoesNotApply
Definition: Sema.h:2320
@ VariadicFunction
Definition: Sema.h:2316
@ VariadicMethod
Definition: Sema.h:2318
@ VariadicConstructor
Definition: Sema.h:2319
@ VariadicBlock
Definition: Sema.h:2317
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7041
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:3638
@ NTCUC_Assignment
Definition: Sema.h:3636
@ NTCUC_FunctionReturn
Definition: Sema.h:3628
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3642
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:7545
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:2338
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15846
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:17465
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15852
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20177
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:1557
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12173
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:16438
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:856
SemaCUDA & CUDA()
Definition: Sema.h:1071
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17400
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:20393
ConditionKind
Definition: Sema.h:7351
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2676
bool needsRebuildOfDefaultArgOrInit() const
Definition: Sema.h:7789
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition: Sema.h:7931
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:849
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:2292
Preprocessor & getPreprocessor() const
Definition: Sema.h:531
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6447
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2161
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12732
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:7920
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3538
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7832
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:18443
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:17158
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6683
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:10149
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:1665
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7519
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15865
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.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16508
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6459
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:1570
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:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1042
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
Definition: SemaExpr.cpp:13885
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4999
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:1999
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7629
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14165
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15155
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1120
ASTContext & Context
Definition: Sema.h:909
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:7756
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2704
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12968
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:9839
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:20188
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11510
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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:7894
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:21166
SemaObjC & ObjC()
Definition: Sema.h:1111
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13003
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:2670
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:7243
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19673
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
bool isImmediateFunctionContext() const
Definition: Sema.h:7781
ASTContext & getASTContext() const
Definition: Sema.h:532
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:762
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:15783
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:18943
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:19921
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15301
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:17833
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9582
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:692
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:867
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3486
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6200
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
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:7055
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15833
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5606
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7910
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:13049
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1575
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
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:16121
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:1671
AssumedTemplateKind
Definition: Sema.h:11111
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1969
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:507
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:672
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:7816
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:420
FPOptions & getCurFPFeatures()
Definition: Sema.h:527
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7914
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20424
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_Block
Block expression.
Definition: Sema.h:13964
const LangOptions & getLangOpts() const
Definition: Sema.h:525
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:12200
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:7293
SemaOpenACC & OpenACC()
Definition: Sema.h:1116
ReuseLambdaContextDecl_t
Definition: Sema.h:6531
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:6612
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17496
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2252
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:20062
Preprocessor & PP
Definition: Sema.h:908
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10945
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5711
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:6476
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14137
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16789
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4712
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1980
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7534
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:907
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15935
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2406
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:6733
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17517
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7600
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6036
SemaHLSL & HLSL()
Definition: Sema.h:1076
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:17481
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15160
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:73
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20072
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
Definition: SemaExpr.cpp:9863
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:6480
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6062
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1582
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:9582
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:13534
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15746
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:784
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:3355
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:940
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:3638
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10412
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:9634
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:1736
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6477
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:2144
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7785
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7280
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:1639
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:16297
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7670
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2361
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7583
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:20887
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12149
@ VAK_Invalid
Definition: Sema.h:7540
@ VAK_Valid
Definition: Sema.h:7536
@ VAK_ValidInCXX11
Definition: Sema.h:7537
@ VAK_MSVCUndefined
Definition: Sema.h:7539
@ VAK_Undefined
Definition: Sema.h:7538
SemaOpenCL & OpenCL()
Definition: Sema.h:1121
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13543
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16671
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:7916
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:20123
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7777
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1550
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7580
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7624
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7590
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7648
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7653
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7640
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7619
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7598
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7657
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7582
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7609
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7661
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7594
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7603
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7615
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7636
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7630
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7586
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7644
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:8467
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7399
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7401
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7409
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7403
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7407
@ ACK_Comparison
A comparison.
Definition: Sema.h:7405
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20021
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2896
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4109
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16756
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6289
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20977
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17380
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:13490
SourceManager & getSourceManager() const
Definition: Sema.h:530
TryCaptureKind
Definition: Sema.h:6593
@ TryCapture_Implicit
Definition: Sema.h:6594
@ TryCapture_ExplicitByRef
Definition: Sema.h:6596
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6711
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4390
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:8782
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:12744
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10587
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19637
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13724
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:3654
@ NTCUK_Copy
Definition: Sema.h:3655
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition: Sema.h:7930
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20258
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5488
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7564
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:7601
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2192
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:6287
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:216
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:8302
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:2048
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14945
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15277
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:7703
@ CTK_ErrorRecovery
Definition: Sema.h:9384
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2346
bool isConstantEvaluatedContext() const
Definition: Sema.h:2151
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:3095
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12558
ASTConsumer & Consumer
Definition: Sema.h:910
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4227
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:6484
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:945
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13526
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5121
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3534
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16797
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12689
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:8409
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6231
@ 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:2050
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
Definition: SemaExpr.cpp:6704
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4617
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
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:20265
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4227
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16501
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5817
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9119
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:872
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20907
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:19269
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7738
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:7767
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17910
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19261
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7917
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7650
SourceManager & SourceMgr
Definition: Sema.h:912
@ TemplateNameIsRequired
Definition: Sema.h:11088
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4704
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7811
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:2393
DiagnosticsEngine & Diags
Definition: Sema.h:911
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:526
FPOptions CurFPFeatures
Definition: Sema.h:905
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:516
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:693
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:7587
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9771
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3598
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5582
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20308
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:1317
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13100
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6066
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15860
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:997
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6075
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12805
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8885
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:13104
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:16307
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:564
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20043
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:16825
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:18091
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15904
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4757
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:5954
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:284
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20364
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
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:21174
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15351
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3672
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2969
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7255
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16159
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4830
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:14774
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9160
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:6438
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:4687
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7497
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:9043
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9049
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9041
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9046
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9057
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9053
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16188
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10626
@ 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:13522
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:2751
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:15814
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:13356
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11068
static ConditionResult ConditionError()
Definition: Sema.h:7338
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6725
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:20911
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:5814
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16102
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1136
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2337
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7294
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2717
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17918
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7187
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7793
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:5333
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:8268
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:5007
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4810
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
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:4466
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:186
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
unsigned getLength() const
Definition: Expr.h:1895
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
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:1194
StringRef getString() const
Definition: Expr.h:1855
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
bool isUnion() const
Definition: Decl.h:3784
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:220
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:682
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:1002
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:286
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
IntType getSizeType() const
Definition: TargetInfo.h:377
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1676
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:1042
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:879
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
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:398
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
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:3384
const Type * getTypeForDecl() const
Definition: Decl.h:3409
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3412
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:2716
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7907
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:7918
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:8576
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isObjCBuiltinType() const
Definition: Type.h:8384
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:1933
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8693
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8271
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:8491
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
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:2055
bool isVoidPointerType() const
Definition: Type.cpp:698
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:731
bool isArrayType() const
Definition: Type.h:8263
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isConstantMatrixType() const
Definition: Type.h:8325
bool isPointerType() const
Definition: Type.h:8191
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
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:8596
bool isEnumeralType() const
Definition: Type.h:8295
bool isScalarType() const
Definition: Type.h:8614
bool isVariableArrayType() const
Definition: Type.h:8275
bool isSizelessBuiltinType() const
Definition: Type.cpp:2475
bool isClkEventT() const
Definition: Type.h:8406
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8354
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
bool isExtVectorType() const
Definition: Type.h:8307
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isExtVectorBoolType() const
Definition: Type.h:8311
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
bool isImageType() const
Definition: Type.h:8418
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8509
bool isPipeType() const
Definition: Type.h:8425
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8429
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8299
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
bool isHalfType() const
Definition: Type.h:8519
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8584
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2330
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8497
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool isQueueT() const
Definition: Type.h:8410
bool isMemberPointerType() const
Definition: Type.h:8245
bool isAtomicType() const
Definition: Type.h:8346
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8656
bool isObjCIdType() const
Definition: Type.h:8366
bool isMatrixType() const
Definition: Type.h:8321
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isComplexIntegerType() const
Definition: Type.cpp:716
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2116
bool isObjCObjectType() const
Definition: Type.h:8337
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4958
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8791
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2292
bool isMemberFunctionPointerType() const
Definition: Type.h:8249
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:8610
bool isVectorType() const
Definition: Type.h:8303
bool isObjCQualifiedClassType() const
Definition: Type.h:8360
bool isObjCClassType() const
Definition: Type.h:8372
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
ScalarTypeKind
Definition: Type.h:2679
@ STK_FloatingComplex
Definition: Type.h:2688
@ STK_Floating
Definition: Type.h:2686
@ STK_BlockPointer
Definition: Type.h:2681
@ STK_Bool
Definition: Type.h:2684
@ STK_ObjCObjectPointer
Definition: Type.h:2682
@ STK_FixedPoint
Definition: Type.h:2689
@ STK_IntegralComplex
Definition: Type.h:2687
@ STK_CPointer
Definition: Type.h:2680
@ STK_Integral
Definition: Type.h:2685
@ STK_MemberPointer
Definition: Type.h:2683
bool isFloatingType() const
Definition: Type.cpp:2283
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:2230
bool isAnyPointerType() const
Definition: Type.h:8199
bool isRealType() const
Definition: Type.cpp:2306
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSubscriptableVectorType() const
Definition: Type.h:8317
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
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:6837
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2281
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1432
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:4959
bool isIncrementDecrementOp() const
Definition: Expr.h:2333
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3943
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1666
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:1628
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4750
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3453
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:882
bool hasInit() const
Definition: Decl.cpp:2387
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
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:2458
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:2883
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
@ TLS_None
Not a TLS variable.
Definition: Decl.h:902
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
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:2500
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:2776
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
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:2755
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:790
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:796
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:800
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:668
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
bool isNested() const
Definition: ScopeInfo.h:659
Retains information about a captured region.
Definition: ScopeInfo.h:816
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:831
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition: ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:758
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:228
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:771
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition: ScopeInfo.h: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:884
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:989
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:995
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ 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:147
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:169
BinaryOperatorKind
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:28
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_None
Definition: Specifiers.h:250
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.
AssignmentAction
Definition: Sema.h:211
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
StringLiteralKind
Definition: Expr.h:1749
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4797
@ None
No keyword precedes the qualified type name.
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1975
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1589
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:180
#define false
Definition: stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5466
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5463
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5448
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5458
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5457
bool VisitSourceLocExpr(SourceLocExpr *E) override
Definition: SemaExpr.cpp:5422
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
Definition: SemaExpr.cpp:5412
bool VisitCallExpr(CallExpr *E) override
Definition: SemaExpr.cpp:5406
const ASTContext & Context
Definition: SemaExpr.cpp:5399
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
Definition: SemaExpr.cpp:5441
bool VisitLambdaExpr(LambdaExpr *E) override
Definition: SemaExpr.cpp:5433
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
Definition: SemaExpr.cpp:5437
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5400
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single #embed directive.
Definition: Expr.h:4886
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 HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:5192
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12677
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6293
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6327
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6373
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6332
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:6340
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6336
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6346
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:6312
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6350
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6298
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6306
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6295
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6302
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:159
Describes an entity that is being assigned.