1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/ParentMapContext.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticSema.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/TypeTraits.h"
39#include "clang/Lex/LiteralSupport.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Sema/AnalysisBasedWarnings.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Designator.h"
45#include "clang/Sema/EnterExpressionEvaluationContext.h"
46#include "clang/Sema/Initialization.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
49#include "clang/Sema/ParsedTemplate.h"
50#include "clang/Sema/Scope.h"
51#include "clang/Sema/ScopeInfo.h"
52#include "clang/Sema/SemaFixItUtils.h"
53#include "clang/Sema/SemaInternal.h"
54#include "clang/Sema/Template.h"
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/ConvertUTF.h"
59#include "llvm/Support/SaveAndRestore.h"
60#include "llvm/Support/TypeSize.h"
61#include <optional>
62
63using namespace clang;
64using namespace sema;
65
66/// Determine whether the use of this declaration is valid, without
67/// emitting diagnostics.
68bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
69 // See if this is an auto-typed variable whose initializer we are parsing.
70 if (ParsingInitForAutoVars.count(D))
71 return false;
72
73 // See if this is a deleted function.
74 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
75 if (FD->isDeleted())
76 return false;
77
78 // If the function has a deduced return type, and we can't deduce it,
79 // then we can't use it either.
80 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
81 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
82 return false;
83
84 // See if this is an aligned allocation/deallocation function that is
85 // unavailable.
86 if (TreatUnavailableAsInvalid &&
87 isUnavailableAlignedAllocationFunction(FD: *FD))
88 return false;
89 }
90
91 // See if this function is unavailable.
92 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
93 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
94 return false;
95
96 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
97 return false;
98
99 return true;
100}
101
102static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
103 // Warn if this is used but marked unused.
104 if (const auto *A = D->getAttr<UnusedAttr>()) {
105 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
106 // should diagnose them.
107 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
108 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
109 const Decl *DC = cast_or_null<Decl>(Val: S.getCurObjCLexicalContext());
110 if (DC && !DC->hasAttr<UnusedAttr>())
111 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
112 }
113 }
114}
115
116/// Emit a note explaining that this function is deleted.
117void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
118 assert(Decl && Decl->isDeleted());
119
120 if (Decl->isDefaulted()) {
121 // If the method was explicitly defaulted, point at that declaration.
122 if (!Decl->isImplicit())
123 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
124
125 // Try to diagnose why this special member function was implicitly
126 // deleted. This might fail, if that reason no longer applies.
127 DiagnoseDeletedDefaultedFunction(FD: Decl);
128 return;
129 }
130
131 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
132 if (Ctor && Ctor->isInheritingConstructor())
133 return NoteDeletedInheritingConstructor(CD: Ctor);
134
135 Diag(Decl->getLocation(), diag::note_availability_specified_here)
136 << Decl << 1;
137}
138
139/// Determine whether a FunctionDecl was ever declared with an
140/// explicit storage class.
141static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
142 for (auto *I : D->redecls()) {
143 if (I->getStorageClass() != SC_None)
144 return true;
145 }
146 return false;
147}
148
149/// Check whether we're in an extern inline function and referring to a
150/// variable or function with internal linkage (C11 6.7.4p3).
151///
152/// This is only a warning because we used to silently accept this code, but
153/// in many cases it will not behave correctly. This is not enabled in C++ mode
154/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
155/// and so while there may still be user mistakes, most of the time we can't
156/// prove that there are errors.
157static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
158 const NamedDecl *D,
159 SourceLocation Loc) {
160 // This is disabled under C++; there are too many ways for this to fire in
161 // contexts where the warning is a false positive, or where it is technically
162 // correct but benign.
163 if (S.getLangOpts().CPlusPlus)
164 return;
165
166 // Check if this is an inlined function or method.
167 FunctionDecl *Current = S.getCurFunctionDecl();
168 if (!Current)
169 return;
170 if (!Current->isInlined())
171 return;
172 if (!Current->isExternallyVisible())
173 return;
174
175 // Check if the decl has internal linkage.
176 if (D->getFormalLinkage() != Linkage::Internal)
177 return;
178
179 // Downgrade from ExtWarn to Extension if
180 // (1) the supposedly external inline function is in the main file,
181 // and probably won't be included anywhere else.
182 // (2) the thing we're referencing is a pure function.
183 // (3) the thing we're referencing is another inline function.
184 // This last can give us false negatives, but it's better than warning on
185 // wrappers for simple C library functions.
186 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
187 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
188 if (!DowngradeWarning && UsedFn)
189 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
190
191 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
192 : diag::ext_internal_in_extern_inline)
193 << /*IsVar=*/!UsedFn << D;
194
195 S.MaybeSuggestAddingStaticToDecl(D: Current);
196
197 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
198 << D;
199}
200
201void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
202 const FunctionDecl *First = Cur->getFirstDecl();
203
204 // Suggest "static" on the function, if possible.
205 if (!hasAnyExplicitStorageClass(D: First)) {
206 SourceLocation DeclBegin = First->getSourceRange().getBegin();
207 Diag(DeclBegin, diag::note_convert_inline_to_static)
208 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
209 }
210}
211
212/// Determine whether the use of this declaration is valid, and
213/// emit any corresponding diagnostics.
214///
215/// This routine diagnoses various problems with referencing
216/// declarations that can occur when using a declaration. For example,
217/// it might warn if a deprecated or unavailable declaration is being
218/// used, or produce an error (and return true) if a C++0x deleted
219/// function is being used.
220///
221/// \returns true if there was an error (this declaration cannot be
222/// referenced), false otherwise.
223///
224bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
225 const ObjCInterfaceDecl *UnknownObjCClass,
226 bool ObjCPropertyAccess,
227 bool AvoidPartialAvailabilityChecks,
228 ObjCInterfaceDecl *ClassReceiver,
229 bool SkipTrailingRequiresClause) {
230 SourceLocation Loc = Locs.front();
231 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
232 // If there were any diagnostics suppressed by template argument deduction,
233 // emit them now.
234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
236 for (const PartialDiagnosticAt &Suppressed : Pos->second)
237 Diag(Suppressed.first, Suppressed.second);
238
239 // Clear out the list of suppressed diagnostics, so that we don't emit
240 // them again for this specialization. However, we don't obsolete this
241 // entry from the table, because we want to avoid ever emitting these
242 // diagnostics again.
243 Pos->second.clear();
244 }
245
246 // C++ [basic.start.main]p3:
247 // The function 'main' shall not be used within a program.
248 if (cast<FunctionDecl>(D)->isMain())
249 Diag(Loc, diag::ext_main_used);
250
251 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
252 }
253
254 // See if this is an auto-typed variable whose initializer we are parsing.
255 if (ParsingInitForAutoVars.count(D)) {
256 if (isa<BindingDecl>(Val: D)) {
257 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
258 << D->getDeclName();
259 } else {
260 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
261 << D->getDeclName() << cast<VarDecl>(D)->getType();
262 }
263 return true;
264 }
265
266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
267 // See if this is a deleted function.
268 if (FD->isDeleted()) {
269 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
270 if (Ctor && Ctor->isInheritingConstructor())
271 Diag(Loc, diag::err_deleted_inherited_ctor_use)
272 << Ctor->getParent()
273 << Ctor->getInheritedConstructor().getConstructor()->getParent();
274 else
275 Diag(Loc, diag::err_deleted_function_use);
276 NoteDeletedFunction(Decl: FD);
277 return true;
278 }
279
280 // [expr.prim.id]p4
281 // A program that refers explicitly or implicitly to a function with a
282 // trailing requires-clause whose constraint-expression is not satisfied,
283 // other than to declare it, is ill-formed. [...]
284 //
285 // See if this is a function with constraints that need to be satisfied.
286 // Check this before deducing the return type, as it might instantiate the
287 // definition.
288 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
289 ConstraintSatisfaction Satisfaction;
290 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
291 /*ForOverloadResolution*/ true))
292 // A diagnostic will have already been generated (non-constant
293 // constraint expression, for example)
294 return true;
295 if (!Satisfaction.IsSatisfied) {
296 Diag(Loc,
297 diag::err_reference_to_function_with_unsatisfied_constraints)
298 << D;
299 DiagnoseUnsatisfiedConstraint(Satisfaction);
300 return true;
301 }
302 }
303
304 // If the function has a deduced return type, and we can't deduce it,
305 // then we can't use it either.
306 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307 DeduceReturnType(FD, Loc))
308 return true;
309
310 if (getLangOpts().CUDA && !CheckCUDACall(Loc, Callee: FD))
311 return true;
312
313 }
314
315 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
316 // Lambdas are only default-constructible or assignable in C++2a onwards.
317 if (MD->getParent()->isLambda() &&
318 ((isa<CXXConstructorDecl>(Val: MD) &&
319 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
320 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322 << !isa<CXXConstructorDecl>(MD);
323 }
324 }
325
326 auto getReferencedObjCProp = [](const NamedDecl *D) ->
327 const ObjCPropertyDecl * {
328 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
329 return MD->findPropertyDecl();
330 return nullptr;
331 };
332 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334 return true;
335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
336 return true;
337 }
338
339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340 // Only the variables omp_in and omp_out are allowed in the combiner.
341 // Only the variables omp_priv and omp_orig are allowed in the
342 // initializer-clause.
343 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
344 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345 isa<VarDecl>(Val: D)) {
346 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 << getCurFunction()->HasOMPDeclareReductionCombiner;
348 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349 return true;
350 }
351
352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353 // List-items in map clauses on this construct may only refer to the declared
354 // variable var and entities that could be referenced by a procedure defined
355 // at the same location.
356 // [OpenMP 5.2] Also allow iterator declared variables.
357 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
358 !isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
359 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 << getOpenMPDeclareMapperVarName();
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
366 Diag(Loc, diag::err_use_of_empty_using_if_exists);
367 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368 return true;
369 }
370
371 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372 AvoidPartialAvailabilityChecks, ClassReceiver);
373
374 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
375
376 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
377
378 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
379 if (getLangOpts().getFPEvalMethod() !=
380 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
381 PP.getLastFPEvalPragmaLocation().isValid() &&
382 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
383 Diag(D->getLocation(),
384 diag::err_type_available_only_in_default_eval_method)
385 << D->getName();
386 }
387
388 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
389 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
390
391 if (LangOpts.SYCLIsDevice ||
392 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (!Context.getTargetInfo().isTLSSupported())
394 if (const auto *VD = dyn_cast<VarDecl>(D))
395 if (VD->getTLSKind() != VarDecl::TLS_None)
396 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
397 }
398
399 if (isa<ParmVarDecl>(Val: D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 !isUnevaluatedContext()) {
401 // C++ [expr.prim.req.nested] p3
402 // A local parameter shall only appear as an unevaluated operand
403 // (Clause 8) within the constraint-expression.
404 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
405 << D;
406 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
407 return true;
408 }
409
410 return false;
411}
412
413/// DiagnoseSentinelCalls - This routine checks whether a call or
414/// message-send is to a declaration with the sentinel attribute, and
415/// if so, it checks that the requirements of the sentinel are
416/// satisfied.
417void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
422
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
425
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
437 QualType Ty = VD->getType();
438 const FunctionType *Fn = nullptr;
439 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441 if (!Fn)
442 return;
443 CalleeKind = CK_Function;
444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446 CalleeKind = CK_Block;
447 } else {
448 return;
449 }
450
451 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
452 NumFormalParams = proto->getNumParams();
453 else
454 NumFormalParams = 0;
455 } else {
456 return;
457 }
458
459 // "NullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned NullPos = Attr->getNullPos();
464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
466
467 // The number of arguments which should follow the sentinel.
468 unsigned NumArgsAfterSentinel = Attr->getSentinel();
469
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
475 return;
476 }
477
478 // Otherwise, find the sentinel expression.
479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480 if (!SentinelExpr)
481 return;
482 if (SentinelExpr->isValueDependent())
483 return;
484 if (Context.isSentinelNullExpr(E: SentinelExpr))
485 return;
486
487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
488 // or 'NULL' if those are actually defined in the context. Only use
489 // 'nil' for ObjC methods, where it's much more likely that the
490 // variadic arguments form a list of object pointers.
491 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
492 std::string NullValue;
493 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
494 NullValue = "nil";
495 else if (getLangOpts().CPlusPlus11)
496 NullValue = "nullptr";
497 else if (PP.isMacroDefined(Id: "NULL"))
498 NullValue = "NULL";
499 else
500 NullValue = "(void*) 0";
501
502 if (MissingNilLoc.isInvalid())
503 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
504 else
505 Diag(MissingNilLoc, diag::warn_missing_sentinel)
506 << int(CalleeKind)
507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508 Diag(D->getLocation(), diag::note_sentinel_here)
509 << int(CalleeKind) << Attr->getRange();
510}
511
512SourceRange Sema::getExprRange(Expr *E) const {
513 return E ? E->getSourceRange() : SourceRange();
514}
515
516//===----------------------------------------------------------------------===//
517// Standard Promotions and Conversions
518//===----------------------------------------------------------------------===//
519
520/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
522 // Handle any placeholder expressions which made it here.
523 if (E->hasPlaceholderType()) {
524 ExprResult result = CheckPlaceholderExpr(E);
525 if (result.isInvalid()) return ExprError();
526 E = result.get();
527 }
528
529 QualType Ty = E->getType();
530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
531
532 if (Ty->isFunctionType()) {
533 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
535 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
536 return ExprError();
537
538 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
539 CK: CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
547 //
548 // C++ 4.2p1:
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
551 //
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
553 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
554 CK: CK_ArrayToPointerDecay);
555 if (Res.isInvalid())
556 return ExprError();
557 E = Res.get();
558 }
559 }
560 return E;
561}
562
563static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564 // Check to see if we are dereferencing a null pointer. If so,
565 // and if not volatile-qualified, this is undefined behavior that the
566 // optimizer will delete, so warn about it. People sometimes try to use this
567 // to get a deterministic trap and are surprised by clang's behavior. This
568 // only handles the pattern "*null", which is a very syntactic check.
569 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
570 if (UO && UO->getOpcode() == UO_Deref &&
571 UO->getSubExpr()->getType()->isPointerType()) {
572 const LangAS AS =
573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574 if ((!isTargetAddressSpace(AS) ||
575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
578 !UO->getType().isVolatileQualified()) {
579 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
580 S.PDiag(diag::warn_indirection_through_null)
581 << UO->getSubExpr()->getSourceRange());
582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583 S.PDiag(diag::note_indirection_through_null));
584 }
585 }
586}
587
588static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589 SourceLocation AssignLoc,
590 const Expr* RHS) {
591 const ObjCIvarDecl *IV = OIRE->getDecl();
592 if (!IV)
593 return;
594
595 DeclarationName MemberName = IV->getDeclName();
596 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597 if (!Member || !Member->isStr(Str: "isa"))
598 return;
599
600 const Expr *Base = OIRE->getBase();
601 QualType BaseType = Base->getType();
602 if (OIRE->isArrow())
603 BaseType = BaseType->getPointeeType();
604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606 ObjCInterfaceDecl *ClassDeclared = nullptr;
607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
608 if (!ClassDeclared->getSuperClass()
609 && (*ClassDeclared->ivar_begin()) == IV) {
610 if (RHS) {
611 NamedDecl *ObjectSetClass =
612 S.LookupSingleName(S: S.TUScope,
613 Name: &S.Context.Idents.get(Name: "object_setClass"),
614 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
615 if (ObjectSetClass) {
616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
619 "object_setClass(")
620 << FixItHint::CreateReplacement(
621 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
622 << FixItHint::CreateInsertion(RHSLocEnd, ")");
623 }
624 else
625 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
626 } else {
627 NamedDecl *ObjectGetClass =
628 S.LookupSingleName(S: S.TUScope,
629 Name: &S.Context.Idents.get(Name: "object_getClass"),
630 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
631 if (ObjectGetClass)
632 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
634 "object_getClass(")
635 << FixItHint::CreateReplacement(
636 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
637 else
638 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
639 }
640 S.Diag(IV->getLocation(), diag::note_ivar_decl);
641 }
642 }
643}
644
645ExprResult Sema::DefaultLvalueConversion(Expr *E) {
646 // Handle any placeholder expressions which made it here.
647 if (E->hasPlaceholderType()) {
648 ExprResult result = CheckPlaceholderExpr(E);
649 if (result.isInvalid()) return ExprError();
650 E = result.get();
651 }
652
653 // C++ [conv.lval]p1:
654 // A glvalue of a non-function, non-array type T can be
655 // converted to a prvalue.
656 if (!E->isGLValue()) return E;
657
658 QualType T = E->getType();
659 assert(!T.isNull() && "r-value conversion on typeless expression?");
660
661 // lvalue-to-rvalue conversion cannot be applied to function or array types.
662 if (T->isFunctionType() || T->isArrayType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus &&
668 (E->getType() == Context.OverloadTy ||
669 T->isDependentType() ||
670 T->isRecordType()))
671 return E;
672
673 // The C standard is actually really unclear on this point, and
674 // DR106 tells us what the result should be but not why. It's
675 // generally best to say that void types just doesn't undergo
676 // lvalue-to-rvalue at all. Note that expressions of unqualified
677 // 'void' type are never l-values, but qualified void can be.
678 if (T->isVoidType())
679 return E;
680
681 // OpenCL usually rejects direct accesses to values of 'half' type.
682 if (getLangOpts().OpenCL &&
683 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
684 T->isHalfType()) {
685 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
686 << 0 << T;
687 return ExprError();
688 }
689
690 CheckForNullPointerDereference(S&: *this, E);
691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
692 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
693 Name: &Context.Idents.get(Name: "object_getClass"),
694 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
695 if (ObjectGetClass)
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
697 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
698 << FixItHint::CreateReplacement(
699 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
700 else
701 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
702 }
703 else if (const ObjCIvarRefExpr *OIRE =
704 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
705 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
706
707 // C++ [conv.lval]p1:
708 // [...] If T is a non-class type, the type of the prvalue is the
709 // cv-unqualified version of T. Otherwise, the type of the
710 // rvalue is T.
711 //
712 // C99 6.3.2.1p2:
713 // If the lvalue has qualified type, the value has the unqualified
714 // version of the type of the lvalue; otherwise, the value has the
715 // type of the lvalue.
716 if (T.hasQualifiers())
717 T = T.getUnqualifiedType();
718
719 // Under the MS ABI, lock down the inheritance model now.
720 if (T->isMemberPointerType() &&
721 Context.getTargetInfo().getCXXABI().isMicrosoft())
722 (void)isCompleteType(Loc: E->getExprLoc(), T);
723
724 ExprResult Res = CheckLValueToRValueConversionOperand(E);
725 if (Res.isInvalid())
726 return Res;
727 E = Res.get();
728
729 // Loading a __weak object implicitly retains the value, so we need a cleanup to
730 // balance that.
731 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
732 Cleanup.setExprNeedsCleanups(true);
733
734 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
735 Cleanup.setExprNeedsCleanups(true);
736
737 // C++ [conv.lval]p3:
738 // If T is cv std::nullptr_t, the result is a null pointer constant.
739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
741 FPO: CurFPFeatureOverrides());
742
743 // C11 6.3.2.1p2:
744 // ... if the lvalue has atomic type, the value has the non-atomic version
745 // of the type of the lvalue ...
746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747 T = Atomic->getValueType().getUnqualifiedType();
748 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
749 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
750 }
751
752 return Res;
753}
754
755ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
756 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(E: Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
763}
764
765/// CallExprUnaryConversions - a special case of an unary conversion
766/// performed on a function designator of a call expression.
767ExprResult Sema::CallExprUnaryConversions(Expr *E) {
768 QualType Ty = E->getType();
769 ExprResult Res = E;
770 // Only do implicit cast for a function type, but not for a pointer
771 // to function type.
772 if (Ty->isFunctionType()) {
773 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
774 CK: CK_FunctionToPointerDecay);
775 if (Res.isInvalid())
776 return ExprError();
777 }
778 Res = DefaultLvalueConversion(E: Res.get());
779 if (Res.isInvalid())
780 return ExprError();
781 return Res.get();
782}
783
784/// UsualUnaryConversions - Performs various conversions that are common to most
785/// operators (C99 6.3). The conversions of array and function types are
786/// sometimes suppressed. For example, the array->pointer conversion doesn't
787/// apply if the array is an argument to the sizeof or address (&) operators.
788/// In these instances, this routine should *not* be called.
789ExprResult Sema::UsualUnaryConversions(Expr *E) {
790 // First, convert to an r-value.
791 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
792 if (Res.isInvalid())
793 return ExprError();
794 E = Res.get();
795
796 QualType Ty = E->getType();
797 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
798
799 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
800 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
801 (getLangOpts().getFPEvalMethod() !=
802 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
803 PP.getLastFPEvalPragmaLocation().isValid())) {
804 switch (EvalMethod) {
805 default:
806 llvm_unreachable("Unrecognized float evaluation method");
807 break;
808 case LangOptions::FEM_UnsetOnCommandLine:
809 llvm_unreachable("Float evaluation method should be set by now");
810 break;
811 case LangOptions::FEM_Double:
812 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
813 // Widen the expression to double.
814 return Ty->isComplexType()
815 ? ImpCastExprToType(E,
816 Type: Context.getComplexType(Context.DoubleTy),
817 CK: CK_FloatingComplexCast)
818 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
819 break;
820 case LangOptions::FEM_Extended:
821 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
822 // Widen the expression to long double.
823 return Ty->isComplexType()
824 ? ImpCastExprToType(
825 E, Type: Context.getComplexType(Context.LongDoubleTy),
826 CK: CK_FloatingComplexCast)
827 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
828 CK: CK_FloatingCast);
829 break;
830 }
831 }
832
833 // Half FP have to be promoted to float unless it is natively supported
834 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
835 return ImpCastExprToType(E: Res.get(), Type: Context.FloatTy, CK: CK_FloatingCast);
836
837 // Try to perform integral promotions if the object has a theoretically
838 // promotable type.
839 if (Ty->isIntegralOrUnscopedEnumerationType()) {
840 // C99 6.3.1.1p2:
841 //
842 // The following may be used in an expression wherever an int or
843 // unsigned int may be used:
844 // - an object or expression with an integer type whose integer
845 // conversion rank is less than or equal to the rank of int
846 // and unsigned int.
847 // - A bit-field of type _Bool, int, signed int, or unsigned int.
848 //
849 // If an int can represent all values of the original type, the
850 // value is converted to an int; otherwise, it is converted to an
851 // unsigned int. These are called the integer promotions. All
852 // other types are unchanged by the integer promotions.
853
854 QualType PTy = Context.isPromotableBitField(E);
855 if (!PTy.isNull()) {
856 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
857 return E;
858 }
859 if (Context.isPromotableIntegerType(T: Ty)) {
860 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
861 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
862 return E;
863 }
864 }
865 return E;
866}
867
868/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
869/// do not have a prototype. Arguments that have type float or __fp16
870/// are promoted to double. All other argument types are converted by
871/// UsualUnaryConversions().
872ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
873 QualType Ty = E->getType();
874 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
875
876 ExprResult Res = UsualUnaryConversions(E);
877 if (Res.isInvalid())
878 return ExprError();
879 E = Res.get();
880
881 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
882 // promote to double.
883 // Note that default argument promotion applies only to float (and
884 // half/fp16); it does not apply to _Float16.
885 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
886 if (BTy && (BTy->getKind() == BuiltinType::Half ||
887 BTy->getKind() == BuiltinType::Float)) {
888 if (getLangOpts().OpenCL &&
889 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
890 if (BTy->getKind() == BuiltinType::Half) {
891 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
892 }
893 } else {
894 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
895 }
896 }
897 if (BTy &&
898 getLangOpts().getExtendIntArgs() ==
899 LangOptions::ExtendArgsKind::ExtendTo64 &&
900 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
901 Context.getTypeSizeInChars(BTy) <
902 Context.getTypeSizeInChars(Context.LongLongTy)) {
903 E = (Ty->isUnsignedIntegerType())
904 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
905 .get()
906 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
907 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
908 "Unexpected typesize for LongLongTy");
909 }
910
911 // C++ performs lvalue-to-rvalue conversion as a default argument
912 // promotion, even on class types, but note:
913 // C++11 [conv.lval]p2:
914 // When an lvalue-to-rvalue conversion occurs in an unevaluated
915 // operand or a subexpression thereof the value contained in the
916 // referenced object is not accessed. Otherwise, if the glvalue
917 // has a class type, the conversion copy-initializes a temporary
918 // of type T from the glvalue and the result of the conversion
919 // is a prvalue for the temporary.
920 // FIXME: add some way to gate this entire thing for correctness in
921 // potentially potentially evaluated contexts.
922 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
923 ExprResult Temp = PerformCopyInitialization(
924 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
925 EqualLoc: E->getExprLoc(), Init: E);
926 if (Temp.isInvalid())
927 return ExprError();
928 E = Temp.get();
929 }
930
931 return E;
932}
933
934/// Determine the degree of POD-ness for an expression.
935/// Incomplete types are considered POD, since this check can be performed
936/// when we're in an unevaluated context.
937Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
938 if (Ty->isIncompleteType()) {
939 // C++11 [expr.call]p7:
940 // After these conversions, if the argument does not have arithmetic,
941 // enumeration, pointer, pointer to member, or class type, the program
942 // is ill-formed.
943 //
944 // Since we've already performed array-to-pointer and function-to-pointer
945 // decay, the only such type in C++ is cv void. This also handles
946 // initializer lists as variadic arguments.
947 if (Ty->isVoidType())
948 return VAK_Invalid;
949
950 if (Ty->isObjCObjectType())
951 return VAK_Invalid;
952 return VAK_Valid;
953 }
954
955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
956 return VAK_Invalid;
957
958 if (Context.getTargetInfo().getTriple().isWasm() &&
959 Ty.isWebAssemblyReferenceType()) {
960 return VAK_Invalid;
961 }
962
963 if (Ty.isCXX98PODType(Context))
964 return VAK_Valid;
965
966 // C++11 [expr.call]p7:
967 // Passing a potentially-evaluated argument of class type (Clause 9)
968 // having a non-trivial copy constructor, a non-trivial move constructor,
969 // or a non-trivial destructor, with no corresponding parameter,
970 // is conditionally-supported with implementation-defined semantics.
971 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
972 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
973 if (!Record->hasNonTrivialCopyConstructor() &&
974 !Record->hasNonTrivialMoveConstructor() &&
975 !Record->hasNonTrivialDestructor())
976 return VAK_ValidInCXX11;
977
978 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
979 return VAK_Valid;
980
981 if (Ty->isObjCObjectType())
982 return VAK_Invalid;
983
984 if (getLangOpts().MSVCCompat)
985 return VAK_MSVCUndefined;
986
987 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
988 // permitted to reject them. We should consider doing so.
989 return VAK_Undefined;
990}
991
992void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
993 // Don't allow one to pass an Objective-C interface to a vararg.
994 const QualType &Ty = E->getType();
995 VarArgKind VAK = isValidVarArgType(Ty);
996
997 // Complain about passing non-POD types through varargs.
998 switch (VAK) {
999 case VAK_ValidInCXX11:
1000 DiagRuntimeBehavior(
1001 E->getBeginLoc(), nullptr,
1002 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1003 [[fallthrough]];
1004 case VAK_Valid:
1005 if (Ty->isRecordType()) {
1006 // This is unlikely to be what the user intended. If the class has a
1007 // 'c_str' member function, the user probably meant to call that.
1008 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_pass_class_arg_to_vararg)
1010 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1011 }
1012 break;
1013
1014 case VAK_Undefined:
1015 case VAK_MSVCUndefined:
1016 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1017 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1018 << getLangOpts().CPlusPlus11 << Ty << CT);
1019 break;
1020
1021 case VAK_Invalid:
1022 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1023 Diag(E->getBeginLoc(),
1024 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1025 << Ty << CT;
1026 else if (Ty->isObjCObjectType())
1027 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1028 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1029 << Ty << CT);
1030 else
1031 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1032 << isa<InitListExpr>(E) << Ty << CT;
1033 break;
1034 }
1035}
1036
1037/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1038/// will create a trap if the resulting type is not a POD type.
1039ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1040 FunctionDecl *FDecl) {
1041 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1042 // Strip the unbridged-cast placeholder expression off, if applicable.
1043 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1044 (CT == VariadicMethod ||
1045 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1046 E = stripARCUnbridgedCast(e: E);
1047
1048 // Otherwise, do normal placeholder checking.
1049 } else {
1050 ExprResult ExprRes = CheckPlaceholderExpr(E);
1051 if (ExprRes.isInvalid())
1052 return ExprError();
1053 E = ExprRes.get();
1054 }
1055 }
1056
1057 ExprResult ExprRes = DefaultArgumentPromotion(E);
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1060
1061 // Copy blocks to the heap.
1062 if (ExprRes.get()->getType()->isBlockPointerType())
1063 maybeExtendBlockObject(E&: ExprRes);
1064
1065 E = ExprRes.get();
1066
1067 // Diagnostics regarding non-POD argument types are
1068 // emitted along with format string checking in Sema::CheckFunctionCall().
1069 if (isValidVarArgType(Ty: E->getType()) == VAK_Undefined) {
1070 // Turn this into a trap.
1071 CXXScopeSpec SS;
1072 SourceLocation TemplateKWLoc;
1073 UnqualifiedId Name;
1074 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1075 IdLoc: E->getBeginLoc());
1076 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1077 /*HasTrailingLParen=*/true,
1078 /*IsAddressOfOperand=*/false);
1079 if (TrapFn.isInvalid())
1080 return ExprError();
1081
1082 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(),
1083 ArgExprs: std::nullopt, RParenLoc: E->getEndLoc());
1084 if (Call.isInvalid())
1085 return ExprError();
1086
1087 ExprResult Comma =
1088 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1089 if (Comma.isInvalid())
1090 return ExprError();
1091 return Comma.get();
1092 }
1093
1094 if (!getLangOpts().CPlusPlus &&
1095 RequireCompleteType(E->getExprLoc(), E->getType(),
1096 diag::err_call_incomplete_argument))
1097 return ExprError();
1098
1099 return E;
1100}
1101
1102/// Converts an integer to complex float type. Helper function of
1103/// UsualArithmeticConversions()
1104///
1105/// \return false if the integer expression is an integer type and is
1106/// successfully converted to the complex type.
1107static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1108 ExprResult &ComplexExpr,
1109 QualType IntTy,
1110 QualType ComplexTy,
1111 bool SkipCast) {
1112 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1113 if (SkipCast) return false;
1114 if (IntTy->isIntegerType()) {
1115 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1116 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1117 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1118 CK: CK_FloatingRealToComplex);
1119 } else {
1120 assert(IntTy->isComplexIntegerType());
1121 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1122 CK: CK_IntegralComplexToFloatingComplex);
1123 }
1124 return false;
1125}
1126
1127// This handles complex/complex, complex/float, or float/complex.
1128// When both operands are complex, the shorter operand is converted to the
1129// type of the longer, and that is the type of the result. This corresponds
1130// to what is done when combining two real floating-point operands.
1131// The fun begins when size promotion occur across type domains.
1132// From H&S 6.3.4: When one operand is complex and the other is a real
1133// floating-point type, the less precise type is converted, within it's
1134// real or complex domain, to the precision of the other type. For example,
1135// when combining a "long double" with a "double _Complex", the
1136// "double _Complex" is promoted to "long double _Complex".
1137static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1138 QualType ShorterType,
1139 QualType LongerType,
1140 bool PromotePrecision) {
1141 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1142 QualType Result =
1143 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1144
1145 if (PromotePrecision) {
1146 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1147 Shorter =
1148 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1149 } else {
1150 if (LongerIsComplex)
1151 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1152 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1153 }
1154 }
1155 return Result;
1156}
1157
1158/// Handle arithmetic conversion with complex types. Helper function of
1159/// UsualArithmeticConversions()
1160static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1161 ExprResult &RHS, QualType LHSType,
1162 QualType RHSType, bool IsCompAssign) {
1163 // if we have an integer operand, the result is the complex type.
1164 if (!handleIntegerToComplexFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1165 /*SkipCast=*/false))
1166 return LHSType;
1167 if (!handleIntegerToComplexFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1168 /*SkipCast=*/IsCompAssign))
1169 return RHSType;
1170
1171 // Compute the rank of the two types, regardless of whether they are complex.
1172 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1173 if (Order < 0)
1174 // Promote the precision of the LHS if not an assignment.
1175 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1176 /*PromotePrecision=*/!IsCompAssign);
1177 // Promote the precision of the RHS unless it is already the same as the LHS.
1178 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1179 /*PromotePrecision=*/Order > 0);
1180}
1181
1182/// Handle arithmetic conversion from integer to float. Helper function
1183/// of UsualArithmeticConversions()
1184static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1185 ExprResult &IntExpr,
1186 QualType FloatTy, QualType IntTy,
1187 bool ConvertFloat, bool ConvertInt) {
1188 if (IntTy->isIntegerType()) {
1189 if (ConvertInt)
1190 // Convert intExpr to the lhs floating point type.
1191 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1192 CK: CK_IntegralToFloating);
1193 return FloatTy;
1194 }
1195
1196 // Convert both sides to the appropriate complex float.
1197 assert(IntTy->isComplexIntegerType());
1198 QualType result = S.Context.getComplexType(T: FloatTy);
1199
1200 // _Complex int -> _Complex float
1201 if (ConvertInt)
1202 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1203 CK: CK_IntegralComplexToFloatingComplex);
1204
1205 // float -> _Complex float
1206 if (ConvertFloat)
1207 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1208 CK: CK_FloatingRealToComplex);
1209
1210 return result;
1211}
1212
1213/// Handle arithmethic conversion with floating point types. Helper
1214/// function of UsualArithmeticConversions()
1215static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1216 ExprResult &RHS, QualType LHSType,
1217 QualType RHSType, bool IsCompAssign) {
1218 bool LHSFloat = LHSType->isRealFloatingType();
1219 bool RHSFloat = RHSType->isRealFloatingType();
1220
1221 // N1169 4.1.4: If one of the operands has a floating type and the other
1222 // operand has a fixed-point type, the fixed-point operand
1223 // is converted to the floating type [...]
1224 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1225 if (LHSFloat)
1226 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1227 else if (!IsCompAssign)
1228 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1229 return LHSFloat ? LHSType : RHSType;
1230 }
1231
1232 // If we have two real floating types, convert the smaller operand
1233 // to the bigger result.
1234 if (LHSFloat && RHSFloat) {
1235 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1236 if (order > 0) {
1237 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1238 return LHSType;
1239 }
1240
1241 assert(order < 0 && "illegal float comparison");
1242 if (!IsCompAssign)
1243 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1244 return RHSType;
1245 }
1246
1247 if (LHSFloat) {
1248 // Half FP has to be promoted to float unless it is natively supported
1249 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1250 LHSType = S.Context.FloatTy;
1251
1252 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1253 /*ConvertFloat=*/!IsCompAssign,
1254 /*ConvertInt=*/ true);
1255 }
1256 assert(RHSFloat);
1257 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1258 /*ConvertFloat=*/ true,
1259 /*ConvertInt=*/!IsCompAssign);
1260}
1261
1262/// Diagnose attempts to convert between __float128, __ibm128 and
1263/// long double if there is no support for such conversion.
1264/// Helper function of UsualArithmeticConversions().
1265static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1266 QualType RHSType) {
1267 // No issue if either is not a floating point type.
1268 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1269 return false;
1270
1271 // No issue if both have the same 128-bit float semantics.
1272 auto *LHSComplex = LHSType->getAs<ComplexType>();
1273 auto *RHSComplex = RHSType->getAs<ComplexType>();
1274
1275 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1276 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1277
1278 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1279 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1280
1281 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1282 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1283 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1284 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1285 return false;
1286
1287 return true;
1288}
1289
1290typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1291
1292namespace {
1293/// These helper callbacks are placed in an anonymous namespace to
1294/// permit their use as function template parameters.
1295ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1296 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1297}
1298
1299ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1300 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1301 CK: CK_IntegralComplexCast);
1302}
1303}
1304
1305/// Handle integer arithmetic conversions. Helper function of
1306/// UsualArithmeticConversions()
1307template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1308static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1309 ExprResult &RHS, QualType LHSType,
1310 QualType RHSType, bool IsCompAssign) {
1311 // The rules for this case are in C99 6.3.1.8
1312 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1313 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1314 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1315 if (LHSSigned == RHSSigned) {
1316 // Same signedness; use the higher-ranked type
1317 if (order >= 0) {
1318 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1319 return LHSType;
1320 } else if (!IsCompAssign)
1321 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1322 return RHSType;
1323 } else if (order != (LHSSigned ? 1 : -1)) {
1324 // The unsigned type has greater than or equal rank to the
1325 // signed type, so use the unsigned type
1326 if (RHSSigned) {
1327 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1328 return LHSType;
1329 } else if (!IsCompAssign)
1330 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1331 return RHSType;
1332 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1333 // The two types are different widths; if we are here, that
1334 // means the signed type is larger than the unsigned type, so
1335 // use the signed type.
1336 if (LHSSigned) {
1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338 return LHSType;
1339 } else if (!IsCompAssign)
1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341 return RHSType;
1342 } else {
1343 // The signed type is higher-ranked than the unsigned type,
1344 // but isn't actually any bigger (like unsigned int and long
1345 // on most 32-bit systems). Use the unsigned type corresponding
1346 // to the signed type.
1347 QualType result =
1348 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1349 RHS = (*doRHSCast)(S, RHS.get(), result);
1350 if (!IsCompAssign)
1351 LHS = (*doLHSCast)(S, LHS.get(), result);
1352 return result;
1353 }
1354}
1355
1356/// Handle conversions with GCC complex int extension. Helper function
1357/// of UsualArithmeticConversions()
1358static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1359 ExprResult &RHS, QualType LHSType,
1360 QualType RHSType,
1361 bool IsCompAssign) {
1362 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1363 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1364
1365 if (LHSComplexInt && RHSComplexInt) {
1366 QualType LHSEltType = LHSComplexInt->getElementType();
1367 QualType RHSEltType = RHSComplexInt->getElementType();
1368 QualType ScalarType =
1369 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1370 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1371
1372 return S.Context.getComplexType(T: ScalarType);
1373 }
1374
1375 if (LHSComplexInt) {
1376 QualType LHSEltType = LHSComplexInt->getElementType();
1377 QualType ScalarType =
1378 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1379 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1380 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1381 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1382 CK: CK_IntegralRealToComplex);
1383
1384 return ComplexType;
1385 }
1386
1387 assert(RHSComplexInt);
1388
1389 QualType RHSEltType = RHSComplexInt->getElementType();
1390 QualType ScalarType =
1391 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1392 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1393 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1394
1395 if (!IsCompAssign)
1396 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1397 CK: CK_IntegralRealToComplex);
1398 return ComplexType;
1399}
1400
1401/// Return the rank of a given fixed point or integer type. The value itself
1402/// doesn't matter, but the values must be increasing with proper increasing
1403/// rank as described in N1169 4.1.1.
1404static unsigned GetFixedPointRank(QualType Ty) {
1405 const auto *BTy = Ty->getAs<BuiltinType>();
1406 assert(BTy && "Expected a builtin type.");
1407
1408 switch (BTy->getKind()) {
1409 case BuiltinType::ShortFract:
1410 case BuiltinType::UShortFract:
1411 case BuiltinType::SatShortFract:
1412 case BuiltinType::SatUShortFract:
1413 return 1;
1414 case BuiltinType::Fract:
1415 case BuiltinType::UFract:
1416 case BuiltinType::SatFract:
1417 case BuiltinType::SatUFract:
1418 return 2;
1419 case BuiltinType::LongFract:
1420 case BuiltinType::ULongFract:
1421 case BuiltinType::SatLongFract:
1422 case BuiltinType::SatULongFract:
1423 return 3;
1424 case BuiltinType::ShortAccum:
1425 case BuiltinType::UShortAccum:
1426 case BuiltinType::SatShortAccum:
1427 case BuiltinType::SatUShortAccum:
1428 return 4;
1429 case BuiltinType::Accum:
1430 case BuiltinType::UAccum:
1431 case BuiltinType::SatAccum:
1432 case BuiltinType::SatUAccum:
1433 return 5;
1434 case BuiltinType::LongAccum:
1435 case BuiltinType::ULongAccum:
1436 case BuiltinType::SatLongAccum:
1437 case BuiltinType::SatULongAccum:
1438 return 6;
1439 default:
1440 if (BTy->isInteger())
1441 return 0;
1442 llvm_unreachable("Unexpected fixed point or integer type");
1443 }
1444}
1445
1446/// handleFixedPointConversion - Fixed point operations between fixed
1447/// point types and integers or other fixed point types do not fall under
1448/// usual arithmetic conversion since these conversions could result in loss
1449/// of precsision (N1169 4.1.4). These operations should be calculated with
1450/// the full precision of their result type (N1169 4.1.6.2.1).
1451static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1452 QualType RHSTy) {
1453 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1454 "Expected at least one of the operands to be a fixed point type");
1455 assert((LHSTy->isFixedPointOrIntegerType() ||
1456 RHSTy->isFixedPointOrIntegerType()) &&
1457 "Special fixed point arithmetic operation conversions are only "
1458 "applied to ints or other fixed point types");
1459
1460 // If one operand has signed fixed-point type and the other operand has
1461 // unsigned fixed-point type, then the unsigned fixed-point operand is
1462 // converted to its corresponding signed fixed-point type and the resulting
1463 // type is the type of the converted operand.
1464 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1465 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1466 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1467 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1468
1469 // The result type is the type with the highest rank, whereby a fixed-point
1470 // conversion rank is always greater than an integer conversion rank; if the
1471 // type of either of the operands is a saturating fixedpoint type, the result
1472 // type shall be the saturating fixed-point type corresponding to the type
1473 // with the highest rank; the resulting value is converted (taking into
1474 // account rounding and overflow) to the precision of the resulting type.
1475 // Same ranks between signed and unsigned types are resolved earlier, so both
1476 // types are either signed or both unsigned at this point.
1477 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1478 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1479
1480 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1481
1482 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1483 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1484
1485 return ResultTy;
1486}
1487
1488/// Check that the usual arithmetic conversions can be performed on this pair of
1489/// expressions that might be of enumeration type.
1490static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1491 SourceLocation Loc,
1492 Sema::ArithConvKind ACK) {
1493 // C++2a [expr.arith.conv]p1:
1494 // If one operand is of enumeration type and the other operand is of a
1495 // different enumeration type or a floating-point type, this behavior is
1496 // deprecated ([depr.arith.conv.enum]).
1497 //
1498 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1499 // Eventually we will presumably reject these cases (in C++23 onwards?).
1500 QualType L = LHS->getType(), R = RHS->getType();
1501 bool LEnum = L->isUnscopedEnumerationType(),
1502 REnum = R->isUnscopedEnumerationType();
1503 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1504 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1505 (REnum && L->isFloatingType())) {
1506 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1507 ? diag::err_arith_conv_enum_float_cxx26
1508 : S.getLangOpts().CPlusPlus20
1509 ? diag::warn_arith_conv_enum_float_cxx20
1510 : diag::warn_arith_conv_enum_float)
1511 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1512 << L << R;
1513 } else if (!IsCompAssign && LEnum && REnum &&
1514 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1515 unsigned DiagID;
1516 // In C++ 26, usual arithmetic conversions between 2 different enum types
1517 // are ill-formed.
1518 if (S.getLangOpts().CPlusPlus26)
1519 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1520 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1521 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1522 // If either enumeration type is unnamed, it's less likely that the
1523 // user cares about this, but this situation is still deprecated in
1524 // C++2a. Use a different warning group.
1525 DiagID = S.getLangOpts().CPlusPlus20
1526 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1527 : diag::warn_arith_conv_mixed_anon_enum_types;
1528 } else if (ACK == Sema::ACK_Conditional) {
1529 // Conditional expressions are separated out because they have
1530 // historically had a different warning flag.
1531 DiagID = S.getLangOpts().CPlusPlus20
1532 ? diag::warn_conditional_mixed_enum_types_cxx20
1533 : diag::warn_conditional_mixed_enum_types;
1534 } else if (ACK == Sema::ACK_Comparison) {
1535 // Comparison expressions are separated out because they have
1536 // historically had a different warning flag.
1537 DiagID = S.getLangOpts().CPlusPlus20
1538 ? diag::warn_comparison_mixed_enum_types_cxx20
1539 : diag::warn_comparison_mixed_enum_types;
1540 } else {
1541 DiagID = S.getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_enum_types;
1544 }
1545 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1546 << (int)ACK << L << R;
1547 }
1548}
1549
1550/// UsualArithmeticConversions - Performs various conversions that are common to
1551/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1552/// routine returns the first non-arithmetic type found. The client is
1553/// responsible for emitting appropriate error diagnostics.
1554QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1555 SourceLocation Loc,
1556 ArithConvKind ACK) {
1557 checkEnumArithmeticConversions(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1558
1559 if (ACK != ACK_CompAssign) {
1560 LHS = UsualUnaryConversions(E: LHS.get());
1561 if (LHS.isInvalid())
1562 return QualType();
1563 }
1564
1565 RHS = UsualUnaryConversions(E: RHS.get());
1566 if (RHS.isInvalid())
1567 return QualType();
1568
1569 // For conversion purposes, we ignore any qualifiers.
1570 // For example, "const float" and "float" are equivalent.
1571 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1572 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1573
1574 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1575 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1576 LHSType = AtomicLHS->getValueType();
1577
1578 // If both types are identical, no conversion is needed.
1579 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1580 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1581
1582 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1583 // The caller can deal with this (e.g. pointer + int).
1584 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1585 return QualType();
1586
1587 // Apply unary and bitfield promotions to the LHS's type.
1588 QualType LHSUnpromotedType = LHSType;
1589 if (Context.isPromotableIntegerType(T: LHSType))
1590 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1591 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1592 if (!LHSBitfieldPromoteTy.isNull())
1593 LHSType = LHSBitfieldPromoteTy;
1594 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1595 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1596
1597 // If both types are identical, no conversion is needed.
1598 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1599 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1600
1601 // At this point, we have two different arithmetic types.
1602
1603 // Diagnose attempts to convert between __ibm128, __float128 and long double
1604 // where such conversions currently can't be handled.
1605 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1606 return QualType();
1607
1608 // Handle complex types first (C99 6.3.1.8p1).
1609 if (LHSType->isComplexType() || RHSType->isComplexType())
1610 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1611 IsCompAssign: ACK == ACK_CompAssign);
1612
1613 // Now handle "real" floating types (i.e. float, double, long double).
1614 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1615 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1616 IsCompAssign: ACK == ACK_CompAssign);
1617
1618 // Handle GCC complex int extension.
1619 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1620 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1621 IsCompAssign: ACK == ACK_CompAssign);
1622
1623 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1624 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1625
1626 // Finally, we have two differing integer types.
1627 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1628 (S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ACK_CompAssign);
1629}
1630
1631//===----------------------------------------------------------------------===//
1632// Semantic Analysis for various Expression Types
1633//===----------------------------------------------------------------------===//
1634
1635
1636ExprResult Sema::ActOnGenericSelectionExpr(
1637 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1638 bool PredicateIsExpr, void *ControllingExprOrType,
1639 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1640 unsigned NumAssocs = ArgTypes.size();
1641 assert(NumAssocs == ArgExprs.size());
1642
1643 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1644 for (unsigned i = 0; i < NumAssocs; ++i) {
1645 if (ArgTypes[i])
1646 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1647 else
1648 Types[i] = nullptr;
1649 }
1650
1651 // If we have a controlling type, we need to convert it from a parsed type
1652 // into a semantic type and then pass that along.
1653 if (!PredicateIsExpr) {
1654 TypeSourceInfo *ControllingType;
1655 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1656 TInfo: &ControllingType);
1657 assert(ControllingType && "couldn't get the type out of the parser");
1658 ControllingExprOrType = ControllingType;
1659 }
1660
1661 ExprResult ER = CreateGenericSelectionExpr(
1662 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1663 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1664 delete [] Types;
1665 return ER;
1666}
1667
1668ExprResult Sema::CreateGenericSelectionExpr(
1669 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1670 bool PredicateIsExpr, void *ControllingExprOrType,
1671 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1672 unsigned NumAssocs = Types.size();
1673 assert(NumAssocs == Exprs.size());
1674 assert(ControllingExprOrType &&
1675 "Must have either a controlling expression or a controlling type");
1676
1677 Expr *ControllingExpr = nullptr;
1678 TypeSourceInfo *ControllingType = nullptr;
1679 if (PredicateIsExpr) {
1680 // Decay and strip qualifiers for the controlling expression type, and
1681 // handle placeholder type replacement. See committee discussion from WG14
1682 // DR423.
1683 EnterExpressionEvaluationContext Unevaluated(
1684 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1685 ExprResult R = DefaultFunctionArrayLvalueConversion(
1686 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1687 if (R.isInvalid())
1688 return ExprError();
1689 ControllingExpr = R.get();
1690 } else {
1691 // The extension form uses the type directly rather than converting it.
1692 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1693 if (!ControllingType)
1694 return ExprError();
1695 }
1696
1697 bool TypeErrorFound = false,
1698 IsResultDependent = ControllingExpr
1699 ? ControllingExpr->isTypeDependent()
1700 : ControllingType->getType()->isDependentType(),
1701 ContainsUnexpandedParameterPack =
1702 ControllingExpr
1703 ? ControllingExpr->containsUnexpandedParameterPack()
1704 : ControllingType->getType()->containsUnexpandedParameterPack();
1705
1706 // The controlling expression is an unevaluated operand, so side effects are
1707 // likely unintended.
1708 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1709 ControllingExpr->HasSideEffects(Context, false))
1710 Diag(ControllingExpr->getExprLoc(),
1711 diag::warn_side_effects_unevaluated_context);
1712
1713 for (unsigned i = 0; i < NumAssocs; ++i) {
1714 if (Exprs[i]->containsUnexpandedParameterPack())
1715 ContainsUnexpandedParameterPack = true;
1716
1717 if (Types[i]) {
1718 if (Types[i]->getType()->containsUnexpandedParameterPack())
1719 ContainsUnexpandedParameterPack = true;
1720
1721 if (Types[i]->getType()->isDependentType()) {
1722 IsResultDependent = true;
1723 } else {
1724 // We relax the restriction on use of incomplete types and non-object
1725 // types with the type-based extension of _Generic. Allowing incomplete
1726 // objects means those can be used as "tags" for a type-safe way to map
1727 // to a value. Similarly, matching on function types rather than
1728 // function pointer types can be useful. However, the restriction on VM
1729 // types makes sense to retain as there are open questions about how
1730 // the selection can be made at compile time.
1731 //
1732 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1733 // complete object type other than a variably modified type."
1734 unsigned D = 0;
1735 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1736 D = diag::err_assoc_type_incomplete;
1737 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1738 D = diag::err_assoc_type_nonobject;
1739 else if (Types[i]->getType()->isVariablyModifiedType())
1740 D = diag::err_assoc_type_variably_modified;
1741 else if (ControllingExpr) {
1742 // Because the controlling expression undergoes lvalue conversion,
1743 // array conversion, and function conversion, an association which is
1744 // of array type, function type, or is qualified can never be
1745 // reached. We will warn about this so users are less surprised by
1746 // the unreachable association. However, we don't have to handle
1747 // function types; that's not an object type, so it's handled above.
1748 //
1749 // The logic is somewhat different for C++ because C++ has different
1750 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1751 // If T is a non-class type, the type of the prvalue is the cv-
1752 // unqualified version of T. Otherwise, the type of the prvalue is T.
1753 // The result of these rules is that all qualified types in an
1754 // association in C are unreachable, and in C++, only qualified non-
1755 // class types are unreachable.
1756 //
1757 // NB: this does not apply when the first operand is a type rather
1758 // than an expression, because the type form does not undergo
1759 // conversion.
1760 unsigned Reason = 0;
1761 QualType QT = Types[i]->getType();
1762 if (QT->isArrayType())
1763 Reason = 1;
1764 else if (QT.hasQualifiers() &&
1765 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1766 Reason = 2;
1767
1768 if (Reason)
1769 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1770 diag::warn_unreachable_association)
1771 << QT << (Reason - 1);
1772 }
1773
1774 if (D != 0) {
1775 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1776 << Types[i]->getTypeLoc().getSourceRange()
1777 << Types[i]->getType();
1778 TypeErrorFound = true;
1779 }
1780
1781 // C11 6.5.1.1p2 "No two generic associations in the same generic
1782 // selection shall specify compatible types."
1783 for (unsigned j = i+1; j < NumAssocs; ++j)
1784 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1785 Context.typesAreCompatible(T1: Types[i]->getType(),
1786 T2: Types[j]->getType())) {
1787 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1788 diag::err_assoc_compatible_types)
1789 << Types[j]->getTypeLoc().getSourceRange()
1790 << Types[j]->getType()
1791 << Types[i]->getType();
1792 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1793 diag::note_compat_assoc)
1794 << Types[i]->getTypeLoc().getSourceRange()
1795 << Types[i]->getType();
1796 TypeErrorFound = true;
1797 }
1798 }
1799 }
1800 }
1801 if (TypeErrorFound)
1802 return ExprError();
1803
1804 // If we determined that the generic selection is result-dependent, don't
1805 // try to compute the result expression.
1806 if (IsResultDependent) {
1807 if (ControllingExpr)
1808 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
1809 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1810 ContainsUnexpandedParameterPack);
1811 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1812 AssocExprs: Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 }
1815
1816 SmallVector<unsigned, 1> CompatIndices;
1817 unsigned DefaultIndex = -1U;
1818 // Look at the canonical type of the controlling expression in case it was a
1819 // deduced type like __auto_type. However, when issuing diagnostics, use the
1820 // type the user wrote in source rather than the canonical one.
1821 for (unsigned i = 0; i < NumAssocs; ++i) {
1822 if (!Types[i])
1823 DefaultIndex = i;
1824 else if (ControllingExpr &&
1825 Context.typesAreCompatible(
1826 T1: ControllingExpr->getType().getCanonicalType(),
1827 T2: Types[i]->getType()))
1828 CompatIndices.push_back(Elt: i);
1829 else if (ControllingType &&
1830 Context.typesAreCompatible(
1831 T1: ControllingType->getType().getCanonicalType(),
1832 T2: Types[i]->getType()))
1833 CompatIndices.push_back(Elt: i);
1834 }
1835
1836 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1837 TypeSourceInfo *ControllingType) {
1838 // We strip parens here because the controlling expression is typically
1839 // parenthesized in macro definitions.
1840 if (ControllingExpr)
1841 ControllingExpr = ControllingExpr->IgnoreParens();
1842
1843 SourceRange SR = ControllingExpr
1844 ? ControllingExpr->getSourceRange()
1845 : ControllingType->getTypeLoc().getSourceRange();
1846 QualType QT = ControllingExpr ? ControllingExpr->getType()
1847 : ControllingType->getType();
1848
1849 return std::make_pair(SR, QT);
1850 };
1851
1852 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1853 // type compatible with at most one of the types named in its generic
1854 // association list."
1855 if (CompatIndices.size() > 1) {
1856 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1857 SourceRange SR = P.first;
1858 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1859 << SR << P.second << (unsigned)CompatIndices.size();
1860 for (unsigned I : CompatIndices) {
1861 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1862 diag::note_compat_assoc)
1863 << Types[I]->getTypeLoc().getSourceRange()
1864 << Types[I]->getType();
1865 }
1866 return ExprError();
1867 }
1868
1869 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1870 // its controlling expression shall have type compatible with exactly one of
1871 // the types named in its generic association list."
1872 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1873 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1874 SourceRange SR = P.first;
1875 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1876 return ExprError();
1877 }
1878
1879 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1880 // type name that is compatible with the type of the controlling expression,
1881 // then the result expression of the generic selection is the expression
1882 // in that generic association. Otherwise, the result expression of the
1883 // generic selection is the expression in the default generic association."
1884 unsigned ResultIndex =
1885 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1886
1887 if (ControllingExpr) {
1888 return GenericSelectionExpr::Create(
1889 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1890 ContainsUnexpandedParameterPack, ResultIndex);
1891 }
1892 return GenericSelectionExpr::Create(
1893 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1894 ContainsUnexpandedParameterPack, ResultIndex);
1895}
1896
1897static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
1898 switch (Kind) {
1899 default:
1900 llvm_unreachable("unexpected TokenKind");
1901 case tok::kw___func__:
1902 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1903 case tok::kw___FUNCTION__:
1904 return PredefinedIdentKind::Function;
1905 case tok::kw___FUNCDNAME__:
1906 return PredefinedIdentKind::FuncDName; // [MS]
1907 case tok::kw___FUNCSIG__:
1908 return PredefinedIdentKind::FuncSig; // [MS]
1909 case tok::kw_L__FUNCTION__:
1910 return PredefinedIdentKind::LFunction; // [MS]
1911 case tok::kw_L__FUNCSIG__:
1912 return PredefinedIdentKind::LFuncSig; // [MS]
1913 case tok::kw___PRETTY_FUNCTION__:
1914 return PredefinedIdentKind::PrettyFunction; // [GNU]
1915 }
1916}
1917
1918/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1919/// to determine the value of a PredefinedExpr. This can be either a
1920/// block, lambda, captured statement, function, otherwise a nullptr.
1921static Decl *getPredefinedExprDecl(DeclContext *DC) {
1922 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
1923 DC = DC->getParent();
1924 return cast_or_null<Decl>(Val: DC);
1925}
1926
1927/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1928/// location of the token and the offset of the ud-suffix within it.
1929static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1930 unsigned Offset) {
1931 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
1932 LangOpts: S.getLangOpts());
1933}
1934
1935/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1936/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1937static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1938 IdentifierInfo *UDSuffix,
1939 SourceLocation UDSuffixLoc,
1940 ArrayRef<Expr*> Args,
1941 SourceLocation LitEndLoc) {
1942 assert(Args.size() <= 2 && "too many arguments for literal operator");
1943
1944 QualType ArgTy[2];
1945 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1946 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1947 if (ArgTy[ArgIdx]->isArrayType())
1948 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
1949 }
1950
1951 DeclarationName OpName =
1952 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
1953 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1954 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1955
1956 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1957 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
1958 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1959 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
1960 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1961 return ExprError();
1962
1963 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
1964}
1965
1966ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
1967 // StringToks needs backing storage as it doesn't hold array elements itself
1968 std::vector<Token> ExpandedToks;
1969 if (getLangOpts().MicrosoftExt)
1970 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
1971
1972 StringLiteralParser Literal(StringToks, PP,
1973 StringLiteralEvalMethod::Unevaluated);
1974 if (Literal.hadError)
1975 return ExprError();
1976
1977 SmallVector<SourceLocation, 4> StringTokLocs;
1978 for (const Token &Tok : StringToks)
1979 StringTokLocs.push_back(Elt: Tok.getLocation());
1980
1981 StringLiteral *Lit = StringLiteral::Create(
1982 Ctx: Context, Str: Literal.GetString(), Kind: StringLiteralKind::Unevaluated, Pascal: false, Ty: {},
1983 Loc: &StringTokLocs[0], NumConcatenated: StringTokLocs.size());
1984
1985 if (!Literal.getUDSuffix().empty()) {
1986 SourceLocation UDSuffixLoc =
1987 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
1988 Offset: Literal.getUDSuffixOffset());
1989 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1990 }
1991
1992 return Lit;
1993}
1994
1995std::vector<Token>
1996Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
1997 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1998 // local macros that expand to string literals that may be concatenated.
1999 // These macros are expanded here (in Sema), because StringLiteralParser
2000 // (in Lex) doesn't know the enclosing function (because it hasn't been
2001 // parsed yet).
2002 assert(getLangOpts().MicrosoftExt);
2003
2004 // Note: Although function local macros are defined only inside functions,
2005 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2006 // expansion of macros into empty string literals without additional checks.
2007 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2008 if (!CurrentDecl)
2009 CurrentDecl = Context.getTranslationUnitDecl();
2010
2011 std::vector<Token> ExpandedToks;
2012 ExpandedToks.reserve(n: Toks.size());
2013 for (const Token &Tok : Toks) {
2014 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2015 assert(tok::isStringLiteral(Tok.getKind()));
2016 ExpandedToks.emplace_back(args: Tok);
2017 continue;
2018 }
2019 if (isa<TranslationUnitDecl>(CurrentDecl))
2020 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2021 // Stringify predefined expression
2022 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2023 << Tok.getKind();
2024 SmallString<64> Str;
2025 llvm::raw_svector_ostream OS(Str);
2026 Token &Exp = ExpandedToks.emplace_back();
2027 Exp.startToken();
2028 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2029 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2030 OS << 'L';
2031 Exp.setKind(tok::wide_string_literal);
2032 } else {
2033 Exp.setKind(tok::string_literal);
2034 }
2035 OS << '"'
2036 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2037 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2038 << '"';
2039 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2040 }
2041 return ExpandedToks;
2042}
2043
2044/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2045/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2046/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2047/// multiple tokens. However, the common case is that StringToks points to one
2048/// string.
2049///
2050ExprResult
2051Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2052 assert(!StringToks.empty() && "Must have at least one string!");
2053
2054 // StringToks needs backing storage as it doesn't hold array elements itself
2055 std::vector<Token> ExpandedToks;
2056 if (getLangOpts().MicrosoftExt)
2057 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2058
2059 StringLiteralParser Literal(StringToks, PP);
2060 if (Literal.hadError)
2061 return ExprError();
2062
2063 SmallVector<SourceLocation, 4> StringTokLocs;
2064 for (const Token &Tok : StringToks)
2065 StringTokLocs.push_back(Elt: Tok.getLocation());
2066
2067 QualType CharTy = Context.CharTy;
2068 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2069 if (Literal.isWide()) {
2070 CharTy = Context.getWideCharType();
2071 Kind = StringLiteralKind::Wide;
2072 } else if (Literal.isUTF8()) {
2073 if (getLangOpts().Char8)
2074 CharTy = Context.Char8Ty;
2075 Kind = StringLiteralKind::UTF8;
2076 } else if (Literal.isUTF16()) {
2077 CharTy = Context.Char16Ty;
2078 Kind = StringLiteralKind::UTF16;
2079 } else if (Literal.isUTF32()) {
2080 CharTy = Context.Char32Ty;
2081 Kind = StringLiteralKind::UTF32;
2082 } else if (Literal.isPascal()) {
2083 CharTy = Context.UnsignedCharTy;
2084 }
2085
2086 // Warn on initializing an array of char from a u8 string literal; this
2087 // becomes ill-formed in C++2a.
2088 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
2089 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2090 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2091
2092 // Create removals for all 'u8' prefixes in the string literal(s). This
2093 // ensures C++2a compatibility (but may change the program behavior when
2094 // built by non-Clang compilers for which the execution character set is
2095 // not always UTF-8).
2096 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2097 SourceLocation RemovalDiagLoc;
2098 for (const Token &Tok : StringToks) {
2099 if (Tok.getKind() == tok::utf8_string_literal) {
2100 if (RemovalDiagLoc.isInvalid())
2101 RemovalDiagLoc = Tok.getLocation();
2102 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2103 B: Tok.getLocation(),
2104 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2105 SM: getSourceManager(), LangOpts: getLangOpts())));
2106 }
2107 }
2108 Diag(RemovalDiagLoc, RemovalDiag);
2109 }
2110
2111 QualType StrTy =
2112 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2113
2114 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2115 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2116 Kind, Pascal: Literal.Pascal, Ty: StrTy,
2117 Loc: &StringTokLocs[0],
2118 NumConcatenated: StringTokLocs.size());
2119 if (Literal.getUDSuffix().empty())
2120 return Lit;
2121
2122 // We're building a user-defined literal.
2123 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2124 SourceLocation UDSuffixLoc =
2125 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2126 Offset: Literal.getUDSuffixOffset());
2127
2128 // Make sure we're allowed user-defined literals here.
2129 if (!UDLScope)
2130 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2131
2132 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2133 // operator "" X (str, len)
2134 QualType SizeType = Context.getSizeType();
2135
2136 DeclarationName OpName =
2137 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2138 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2139 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2140
2141 QualType ArgTy[] = {
2142 Context.getArrayDecayedType(T: StrTy), SizeType
2143 };
2144
2145 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2146 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2147 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2148 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2149 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2150
2151 case LOLR_Cooked: {
2152 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2153 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2154 l: StringTokLocs[0]);
2155 Expr *Args[] = { Lit, LenArg };
2156
2157 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2158 }
2159
2160 case LOLR_Template: {
2161 TemplateArgumentListInfo ExplicitArgs;
2162 TemplateArgument Arg(Lit);
2163 TemplateArgumentLocInfo ArgInfo(Lit);
2164 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2165 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt,
2166 LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs);
2167 }
2168
2169 case LOLR_StringTemplatePack: {
2170 TemplateArgumentListInfo ExplicitArgs;
2171
2172 unsigned CharBits = Context.getIntWidth(T: CharTy);
2173 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2174 llvm::APSInt Value(CharBits, CharIsUnsigned);
2175
2176 TemplateArgument TypeArg(CharTy);
2177 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2178 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2179
2180 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2181 Value = Lit->getCodeUnit(i: I);
2182 TemplateArgument Arg(Context, Value, CharTy);
2183 TemplateArgumentLocInfo ArgInfo;
2184 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2185 }
2186 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt,
2187 LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs);
2188 }
2189 case LOLR_Raw:
2190 case LOLR_ErrorNoDiagnostic:
2191 llvm_unreachable("unexpected literal operator lookup result");
2192 case LOLR_Error:
2193 return ExprError();
2194 }
2195 llvm_unreachable("unexpected literal operator lookup result");
2196}
2197
2198DeclRefExpr *
2199Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2200 SourceLocation Loc,
2201 const CXXScopeSpec *SS) {
2202 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2203 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2204}
2205
2206DeclRefExpr *
2207Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2208 const DeclarationNameInfo &NameInfo,
2209 const CXXScopeSpec *SS, NamedDecl *FoundD,
2210 SourceLocation TemplateKWLoc,
2211 const TemplateArgumentListInfo *TemplateArgs) {
2212 NestedNameSpecifierLoc NNS =
2213 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2214 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2215 TemplateArgs);
2216}
2217
2218// CUDA/HIP: Check whether a captured reference variable is referencing a
2219// host variable in a device or host device lambda.
2220static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2221 VarDecl *VD) {
2222 if (!S.getLangOpts().CUDA || !VD->hasInit())
2223 return false;
2224 assert(VD->getType()->isReferenceType());
2225
2226 // Check whether the reference variable is referencing a host variable.
2227 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2228 if (!DRE)
2229 return false;
2230 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2231 if (!Referee || !Referee->hasGlobalStorage() ||
2232 Referee->hasAttr<CUDADeviceAttr>())
2233 return false;
2234
2235 // Check whether the current function is a device or host device lambda.
2236 // Check whether the reference variable is a capture by getDeclContext()
2237 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2238 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2239 if (MD && MD->getParent()->isLambda() &&
2240 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2241 VD->getDeclContext() != MD)
2242 return true;
2243
2244 return false;
2245}
2246
2247NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2248 // A declaration named in an unevaluated operand never constitutes an odr-use.
2249 if (isUnevaluatedContext())
2250 return NOUR_Unevaluated;
2251
2252 // C++2a [basic.def.odr]p4:
2253 // A variable x whose name appears as a potentially-evaluated expression e
2254 // is odr-used by e unless [...] x is a reference that is usable in
2255 // constant expressions.
2256 // CUDA/HIP:
2257 // If a reference variable referencing a host variable is captured in a
2258 // device or host device lambda, the value of the referee must be copied
2259 // to the capture and the reference variable must be treated as odr-use
2260 // since the value of the referee is not known at compile time and must
2261 // be loaded from the captured.
2262 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2263 if (VD->getType()->isReferenceType() &&
2264 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2265 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2266 VD->isUsableInConstantExpressions(C: Context))
2267 return NOUR_Constant;
2268 }
2269
2270 // All remaining non-variable cases constitute an odr-use. For variables, we
2271 // need to wait and see how the expression is used.
2272 return NOUR_None;
2273}
2274
2275/// BuildDeclRefExpr - Build an expression that references a
2276/// declaration that does not require a closure capture.
2277DeclRefExpr *
2278Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2279 const DeclarationNameInfo &NameInfo,
2280 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2281 SourceLocation TemplateKWLoc,
2282 const TemplateArgumentListInfo *TemplateArgs) {
2283 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2284 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2285
2286 DeclRefExpr *E = DeclRefExpr::Create(
2287 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2288 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2289 MarkDeclRefReferenced(E);
2290
2291 // C++ [except.spec]p17:
2292 // An exception-specification is considered to be needed when:
2293 // - in an expression, the function is the unique lookup result or
2294 // the selected member of a set of overloaded functions.
2295 //
2296 // We delay doing this until after we've built the function reference and
2297 // marked it as used so that:
2298 // a) if the function is defaulted, we get errors from defining it before /
2299 // instead of errors from computing its exception specification, and
2300 // b) if the function is a defaulted comparison, we can use the body we
2301 // build when defining it as input to the exception specification
2302 // computation rather than computing a new body.
2303 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2304 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2305 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2306 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2307 }
2308 }
2309
2310 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2311 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2312 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2313 getCurFunction()->recordUseOfWeak(E);
2314
2315 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2316 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2317 FD = IFD->getAnonField();
2318 if (FD) {
2319 UnusedPrivateFields.remove(FD);
2320 // Just in case we're building an illegal pointer-to-member.
2321 if (FD->isBitField())
2322 E->setObjectKind(OK_BitField);
2323 }
2324
2325 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2326 // designates a bit-field.
2327 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2328 if (const auto *BE = BD->getBinding())
2329 E->setObjectKind(BE->getObjectKind());
2330
2331 return E;
2332}
2333
2334/// Decomposes the given name into a DeclarationNameInfo, its location, and
2335/// possibly a list of template arguments.
2336///
2337/// If this produces template arguments, it is permitted to call
2338/// DecomposeTemplateName.
2339///
2340/// This actually loses a lot of source location information for
2341/// non-standard name kinds; we should consider preserving that in
2342/// some way.
2343void
2344Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2345 TemplateArgumentListInfo &Buffer,
2346 DeclarationNameInfo &NameInfo,
2347 const TemplateArgumentListInfo *&TemplateArgs) {
2348 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2349 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2350 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2351
2352 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2353 Id.TemplateId->NumArgs);
2354 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2355
2356 TemplateName TName = Id.TemplateId->Template.get();
2357 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2358 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2359 TemplateArgs = &Buffer;
2360 } else {
2361 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2362 TemplateArgs = nullptr;
2363 }
2364}
2365
2366static void emitEmptyLookupTypoDiagnostic(
2367 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2368 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2369 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2370 DeclContext *Ctx =
2371 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, EnteringContext: false);
2372 if (!TC) {
2373 // Emit a special diagnostic for failed member lookups.
2374 // FIXME: computing the declaration context might fail here (?)
2375 if (Ctx)
2376 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2377 << SS.getRange();
2378 else
2379 SemaRef.Diag(Loc: TypoLoc, DiagID: DiagnosticID) << Typo;
2380 return;
2381 }
2382
2383 std::string CorrectedStr = TC.getAsString(LO: SemaRef.getLangOpts());
2384 bool DroppedSpecifier =
2385 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2386 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2387 ? diag::note_implicit_param_decl
2388 : diag::note_previous_decl;
2389 if (!Ctx)
2390 SemaRef.diagnoseTypo(Correction: TC, TypoDiag: SemaRef.PDiag(DiagID: DiagnosticSuggestID) << Typo,
2391 PrevNote: SemaRef.PDiag(DiagID: NoteID));
2392 else
2393 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2394 << Typo << Ctx << DroppedSpecifier
2395 << SS.getRange(),
2396 SemaRef.PDiag(NoteID));
2397}
2398
2399/// Diagnose a lookup that found results in an enclosing class during error
2400/// recovery. This usually indicates that the results were found in a dependent
2401/// base class that could not be searched as part of a template definition.
2402/// Always issues a diagnostic (though this may be only a warning in MS
2403/// compatibility mode).
2404///
2405/// Return \c true if the error is unrecoverable, or \c false if the caller
2406/// should attempt to recover using these lookup results.
2407bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2408 // During a default argument instantiation the CurContext points
2409 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2410 // function parameter list, hence add an explicit check.
2411 bool isDefaultArgument =
2412 !CodeSynthesisContexts.empty() &&
2413 CodeSynthesisContexts.back().Kind ==
2414 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2415 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2416 bool isInstance = CurMethod && CurMethod->isInstance() &&
2417 R.getNamingClass() == CurMethod->getParent() &&
2418 !isDefaultArgument;
2419
2420 // There are two ways we can find a class-scope declaration during template
2421 // instantiation that we did not find in the template definition: if it is a
2422 // member of a dependent base class, or if it is declared after the point of
2423 // use in the same class. Distinguish these by comparing the class in which
2424 // the member was found to the naming class of the lookup.
2425 unsigned DiagID = diag::err_found_in_dependent_base;
2426 unsigned NoteID = diag::note_member_declared_at;
2427 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2428 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2429 : diag::err_found_later_in_class;
2430 } else if (getLangOpts().MSVCCompat) {
2431 DiagID = diag::ext_found_in_dependent_base;
2432 NoteID = diag::note_dependent_member_use;
2433 }
2434
2435 if (isInstance) {
2436 // Give a code modification hint to insert 'this->'.
2437 Diag(Loc: R.getNameLoc(), DiagID)
2438 << R.getLookupName()
2439 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2440 CheckCXXThisCapture(Loc: R.getNameLoc());
2441 } else {
2442 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2443 // they're not shadowed).
2444 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2445 }
2446
2447 for (const NamedDecl *D : R)
2448 Diag(D->getLocation(), NoteID);
2449
2450 // Return true if we are inside a default argument instantiation
2451 // and the found name refers to an instance member function, otherwise
2452 // the caller will try to create an implicit member call and this is wrong
2453 // for default arguments.
2454 //
2455 // FIXME: Is this special case necessary? We could allow the caller to
2456 // diagnose this.
2457 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2458 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2459 return true;
2460 }
2461
2462 // Tell the callee to try to recover.
2463 return false;
2464}
2465
2466/// Diagnose an empty lookup.
2467///
2468/// \return false if new lookup candidates were found
2469bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2470 CorrectionCandidateCallback &CCC,
2471 TemplateArgumentListInfo *ExplicitTemplateArgs,
2472 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2473 TypoExpr **Out) {
2474 DeclarationName Name = R.getLookupName();
2475
2476 unsigned diagnostic = diag::err_undeclared_var_use;
2477 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2478 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2479 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2480 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2481 diagnostic = diag::err_undeclared_use;
2482 diagnostic_suggest = diag::err_undeclared_use_suggest;
2483 }
2484
2485 // If the original lookup was an unqualified lookup, fake an
2486 // unqualified lookup. This is useful when (for example) the
2487 // original lookup would not have found something because it was a
2488 // dependent name.
2489 DeclContext *DC =
2490 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2491 while (DC) {
2492 if (isa<CXXRecordDecl>(Val: DC)) {
2493 LookupQualifiedName(R, LookupCtx: DC);
2494
2495 if (!R.empty()) {
2496 // Don't give errors about ambiguities in this lookup.
2497 R.suppressDiagnostics();
2498
2499 // If there's a best viable function among the results, only mention
2500 // that one in the notes.
2501 OverloadCandidateSet Candidates(R.getNameLoc(),
2502 OverloadCandidateSet::CSK_Normal);
2503 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2504 OverloadCandidateSet::iterator Best;
2505 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2506 OR_Success) {
2507 R.clear();
2508 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2509 R.resolveKind();
2510 }
2511
2512 return DiagnoseDependentMemberLookup(R);
2513 }
2514
2515 R.clear();
2516 }
2517
2518 DC = DC->getLookupParent();
2519 }
2520
2521 // We didn't find anything, so try to correct for a typo.
2522 TypoCorrection Corrected;
2523 if (S && Out) {
2524 SourceLocation TypoLoc = R.getNameLoc();
2525 assert(!ExplicitTemplateArgs &&
2526 "Diagnosing an empty lookup with explicit template args!");
2527 *Out = CorrectTypoDelayed(
2528 Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
2529 TDG: [=](const TypoCorrection &TC) {
2530 emitEmptyLookupTypoDiagnostic(TC, SemaRef&: *this, SS, Typo: Name, TypoLoc, Args,
2531 DiagnosticID: diagnostic, DiagnosticSuggestID: diagnostic_suggest);
2532 },
2533 TRC: nullptr, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx);
2534 if (*Out)
2535 return true;
2536 } else if (S && (Corrected =
2537 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S,
2538 SS: &SS, CCC, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx))) {
2539 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2540 bool DroppedSpecifier =
2541 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2542 R.setLookupName(Corrected.getCorrection());
2543
2544 bool AcceptableWithRecovery = false;
2545 bool AcceptableWithoutRecovery = false;
2546 NamedDecl *ND = Corrected.getFoundDecl();
2547 if (ND) {
2548 if (Corrected.isOverloaded()) {
2549 OverloadCandidateSet OCS(R.getNameLoc(),
2550 OverloadCandidateSet::CSK_Normal);
2551 OverloadCandidateSet::iterator Best;
2552 for (NamedDecl *CD : Corrected) {
2553 if (FunctionTemplateDecl *FTD =
2554 dyn_cast<FunctionTemplateDecl>(Val: CD))
2555 AddTemplateOverloadCandidate(
2556 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2557 Args, CandidateSet&: OCS);
2558 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2559 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2560 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(FD, AS_none),
2561 Args, CandidateSet&: OCS);
2562 }
2563 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2564 case OR_Success:
2565 ND = Best->FoundDecl;
2566 Corrected.setCorrectionDecl(ND);
2567 break;
2568 default:
2569 // FIXME: Arbitrarily pick the first declaration for the note.
2570 Corrected.setCorrectionDecl(ND);
2571 break;
2572 }
2573 }
2574 R.addDecl(D: ND);
2575 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2576 CXXRecordDecl *Record = nullptr;
2577 if (Corrected.getCorrectionSpecifier()) {
2578 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2579 Record = Ty->getAsCXXRecordDecl();
2580 }
2581 if (!Record)
2582 Record = cast<CXXRecordDecl>(
2583 ND->getDeclContext()->getRedeclContext());
2584 R.setNamingClass(Record);
2585 }
2586
2587 auto *UnderlyingND = ND->getUnderlyingDecl();
2588 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2589 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2590 // FIXME: If we ended up with a typo for a type name or
2591 // Objective-C class name, we're in trouble because the parser
2592 // is in the wrong place to recover. Suggest the typo
2593 // correction, but don't make it a fix-it since we're not going
2594 // to recover well anyway.
2595 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2596 getAsTypeTemplateDecl(UnderlyingND) ||
2597 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2598 } else {
2599 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2600 // because we aren't able to recover.
2601 AcceptableWithoutRecovery = true;
2602 }
2603
2604 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2605 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2606 ? diag::note_implicit_param_decl
2607 : diag::note_previous_decl;
2608 if (SS.isEmpty())
2609 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name,
2610 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2611 else
2612 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2613 << Name << computeDeclContext(SS, false)
2614 << DroppedSpecifier << SS.getRange(),
2615 PDiag(NoteID), AcceptableWithRecovery);
2616
2617 // Tell the callee whether to try to recover.
2618 return !AcceptableWithRecovery;
2619 }
2620 }
2621 R.clear();
2622
2623 // Emit a special diagnostic for failed member lookups.
2624 // FIXME: computing the declaration context might fail here (?)
2625 if (!SS.isEmpty()) {
2626 Diag(R.getNameLoc(), diag::err_no_member)
2627 << Name << computeDeclContext(SS, false)
2628 << SS.getRange();
2629 return true;
2630 }
2631
2632 // Give up, we can't recover.
2633 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name;
2634 return true;
2635}
2636
2637/// In Microsoft mode, if we are inside a template class whose parent class has
2638/// dependent base classes, and we can't resolve an unqualified identifier, then
2639/// assume the identifier is a member of a dependent base class. We can only
2640/// recover successfully in static methods, instance methods, and other contexts
2641/// where 'this' is available. This doesn't precisely match MSVC's
2642/// instantiation model, but it's close enough.
2643static Expr *
2644recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2645 DeclarationNameInfo &NameInfo,
2646 SourceLocation TemplateKWLoc,
2647 const TemplateArgumentListInfo *TemplateArgs) {
2648 // Only try to recover from lookup into dependent bases in static methods or
2649 // contexts where 'this' is available.
2650 QualType ThisType = S.getCurrentThisType();
2651 const CXXRecordDecl *RD = nullptr;
2652 if (!ThisType.isNull())
2653 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2654 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2655 RD = MD->getParent();
2656 if (!RD || !RD->hasAnyDependentBases())
2657 return nullptr;
2658
2659 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2660 // is available, suggest inserting 'this->' as a fixit.
2661 SourceLocation Loc = NameInfo.getLoc();
2662 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2663 DB << NameInfo.getName() << RD;
2664
2665 if (!ThisType.isNull()) {
2666 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2667 return CXXDependentScopeMemberExpr::Create(
2668 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2669 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2670 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2671 }
2672
2673 // Synthesize a fake NNS that points to the derived class. This will
2674 // perform name lookup during template instantiation.
2675 CXXScopeSpec SS;
2676 auto *NNS =
2677 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2678 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2679 return DependentScopeDeclRefExpr::Create(
2680 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2681 TemplateArgs);
2682}
2683
2684ExprResult
2685Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2686 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2687 bool HasTrailingLParen, bool IsAddressOfOperand,
2688 CorrectionCandidateCallback *CCC,
2689 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2690 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2691 "cannot be direct & operand and have a trailing lparen");
2692 if (SS.isInvalid())
2693 return ExprError();
2694
2695 TemplateArgumentListInfo TemplateArgsBuffer;
2696
2697 // Decompose the UnqualifiedId into the following data.
2698 DeclarationNameInfo NameInfo;
2699 const TemplateArgumentListInfo *TemplateArgs;
2700 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2701
2702 DeclarationName Name = NameInfo.getName();
2703 IdentifierInfo *II = Name.getAsIdentifierInfo();
2704 SourceLocation NameLoc = NameInfo.getLoc();
2705
2706 if (II && II->isEditorPlaceholder()) {
2707 // FIXME: When typed placeholders are supported we can create a typed
2708 // placeholder expression node.
2709 return ExprError();
2710 }
2711
2712 // C++ [temp.dep.expr]p3:
2713 // An id-expression is type-dependent if it contains:
2714 // -- an identifier that was declared with a dependent type,
2715 // (note: handled after lookup)
2716 // -- a template-id that is dependent,
2717 // (note: handled in BuildTemplateIdExpr)
2718 // -- a conversion-function-id that specifies a dependent type,
2719 // -- a nested-name-specifier that contains a class-name that
2720 // names a dependent type.
2721 // Determine whether this is a member of an unknown specialization;
2722 // we need to handle these differently.
2723 bool DependentID = false;
2724 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2725 Name.getCXXNameType()->isDependentType()) {
2726 DependentID = true;
2727 } else if (SS.isSet()) {
2728 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
2729 if (RequireCompleteDeclContext(SS, DC))
2730 return ExprError();
2731 } else {
2732 DependentID = true;
2733 }
2734 }
2735
2736 if (DependentID)
2737 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2738 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2739
2740 // Perform the required lookup.
2741 LookupResult R(*this, NameInfo,
2742 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2743 ? LookupObjCImplicitSelfParam
2744 : LookupOrdinaryName);
2745 if (TemplateKWLoc.isValid() || TemplateArgs) {
2746 // Lookup the template name again to correctly establish the context in
2747 // which it was found. This is really unfortunate as we already did the
2748 // lookup to determine that it was a template name in the first place. If
2749 // this becomes a performance hit, we can work harder to preserve those
2750 // results until we get here but it's likely not worth it.
2751 bool MemberOfUnknownSpecialization;
2752 AssumedTemplateKind AssumedTemplate;
2753 if (LookupTemplateName(R, S, SS, ObjectType: QualType(), /*EnteringContext=*/false,
2754 MemberOfUnknownSpecialization, RequiredTemplate: TemplateKWLoc,
2755 ATK: &AssumedTemplate))
2756 return ExprError();
2757
2758 if (MemberOfUnknownSpecialization ||
2759 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2760 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2761 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2762 } else {
2763 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2764 LookupParsedName(R, S, SS: &SS, AllowBuiltinCreation: !IvarLookupFollowUp);
2765
2766 // If the result might be in a dependent base class, this is a dependent
2767 // id-expression.
2768 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2769 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2770 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2771
2772 // If this reference is in an Objective-C method, then we need to do
2773 // some special Objective-C lookup, too.
2774 if (IvarLookupFollowUp) {
2775 ExprResult E(LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2776 if (E.isInvalid())
2777 return ExprError();
2778
2779 if (Expr *Ex = E.getAs<Expr>())
2780 return Ex;
2781 }
2782 }
2783
2784 if (R.isAmbiguous())
2785 return ExprError();
2786
2787 // This could be an implicitly declared function reference if the language
2788 // mode allows it as a feature.
2789 if (R.empty() && HasTrailingLParen && II &&
2790 getLangOpts().implicitFunctionsAllowed()) {
2791 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2792 if (D) R.addDecl(D);
2793 }
2794
2795 // Determine whether this name might be a candidate for
2796 // argument-dependent lookup.
2797 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2798
2799 if (R.empty() && !ADL) {
2800 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2801 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2802 TemplateKWLoc, TemplateArgs))
2803 return E;
2804 }
2805
2806 // Don't diagnose an empty lookup for inline assembly.
2807 if (IsInlineAsmIdentifier)
2808 return ExprError();
2809
2810 // If this name wasn't predeclared and if this is not a function
2811 // call, diagnose the problem.
2812 TypoExpr *TE = nullptr;
2813 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2814 : nullptr);
2815 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2816 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2817 "Typo correction callback misconfigured");
2818 if (CCC) {
2819 // Make sure the callback knows what the typo being diagnosed is.
2820 CCC->setTypoName(II);
2821 if (SS.isValid())
2822 CCC->setTypoNNS(SS.getScopeRep());
2823 }
2824 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2825 // a template name, but we happen to have always already looked up the name
2826 // before we get here if it must be a template name.
2827 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2828 Args: std::nullopt, LookupCtx: nullptr, Out: &TE)) {
2829 if (TE && KeywordReplacement) {
2830 auto &State = getTypoExprState(TE);
2831 auto BestTC = State.Consumer->getNextCorrection();
2832 if (BestTC.isKeyword()) {
2833 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2834 if (State.DiagHandler)
2835 State.DiagHandler(BestTC);
2836 KeywordReplacement->startToken();
2837 KeywordReplacement->setKind(II->getTokenID());
2838 KeywordReplacement->setIdentifierInfo(II);
2839 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2840 // Clean up the state associated with the TypoExpr, since it has
2841 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2842 clearDelayedTypo(TE);
2843 // Signal that a correction to a keyword was performed by returning a
2844 // valid-but-null ExprResult.
2845 return (Expr*)nullptr;
2846 }
2847 State.Consumer->resetCorrectionStream();
2848 }
2849 return TE ? TE : ExprError();
2850 }
2851
2852 assert(!R.empty() &&
2853 "DiagnoseEmptyLookup returned false but added no results");
2854
2855 // If we found an Objective-C instance variable, let
2856 // LookupInObjCMethod build the appropriate expression to
2857 // reference the ivar.
2858 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2859 R.clear();
2860 ExprResult E(LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2861 // In a hopelessly buggy code, Objective-C instance variable
2862 // lookup fails and no expression will be built to reference it.
2863 if (!E.isInvalid() && !E.get())
2864 return ExprError();
2865 return E;
2866 }
2867 }
2868
2869 // This is guaranteed from this point on.
2870 assert(!R.empty() || ADL);
2871
2872 // Check whether this might be a C++ implicit instance member access.
2873 // C++ [class.mfct.non-static]p3:
2874 // When an id-expression that is not part of a class member access
2875 // syntax and not used to form a pointer to member is used in the
2876 // body of a non-static member function of class X, if name lookup
2877 // resolves the name in the id-expression to a non-static non-type
2878 // member of some class C, the id-expression is transformed into a
2879 // class member access expression using (*this) as the
2880 // postfix-expression to the left of the . operator.
2881 //
2882 // But we don't actually need to do this for '&' operands if R
2883 // resolved to a function or overloaded function set, because the
2884 // expression is ill-formed if it actually works out to be a
2885 // non-static member function:
2886 //
2887 // C++ [expr.ref]p4:
2888 // Otherwise, if E1.E2 refers to a non-static member function. . .
2889 // [t]he expression can be used only as the left-hand operand of a
2890 // member function call.
2891 //
2892 // There are other safeguards against such uses, but it's important
2893 // to get this right here so that we don't end up making a
2894 // spuriously dependent expression if we're inside a dependent
2895 // instance method.
2896 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2897 bool MightBeImplicitMember;
2898 if (!IsAddressOfOperand)
2899 MightBeImplicitMember = true;
2900 else if (!SS.isEmpty())
2901 MightBeImplicitMember = false;
2902 else if (R.isOverloadedResult())
2903 MightBeImplicitMember = false;
2904 else if (R.isUnresolvableResult())
2905 MightBeImplicitMember = true;
2906 else
2907 MightBeImplicitMember = isa<FieldDecl>(Val: R.getFoundDecl()) ||
2908 isa<IndirectFieldDecl>(Val: R.getFoundDecl()) ||
2909 isa<MSPropertyDecl>(Val: R.getFoundDecl());
2910
2911 if (MightBeImplicitMember)
2912 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2913 R, TemplateArgs, S);
2914 }
2915
2916 if (TemplateArgs || TemplateKWLoc.isValid()) {
2917
2918 // In C++1y, if this is a variable template id, then check it
2919 // in BuildTemplateIdExpr().
2920 // The single lookup result must be a variable template declaration.
2921 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2922 Id.TemplateId->Kind == TNK_Var_template) {
2923 assert(R.getAsSingle<VarTemplateDecl>() &&
2924 "There should only be one declaration found.");
2925 }
2926
2927 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
2928 }
2929
2930 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
2931}
2932
2933/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2934/// declaration name, generally during template instantiation.
2935/// There's a large number of things which don't need to be done along
2936/// this path.
2937ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2938 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2939 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2940 if (NameInfo.getName().isDependentName())
2941 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2942 NameInfo, /*TemplateArgs=*/nullptr);
2943
2944 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
2945 if (!DC)
2946 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2947 NameInfo, /*TemplateArgs=*/nullptr);
2948
2949 if (RequireCompleteDeclContext(SS, DC))
2950 return ExprError();
2951
2952 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2953 LookupQualifiedName(R, LookupCtx: DC);
2954
2955 if (R.isAmbiguous())
2956 return ExprError();
2957
2958 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2959 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2960 NameInfo, /*TemplateArgs=*/nullptr);
2961
2962 if (R.empty()) {
2963 // Don't diagnose problems with invalid record decl, the secondary no_member
2964 // diagnostic during template instantiation is likely bogus, e.g. if a class
2965 // is invalid because it's derived from an invalid base class, then missing
2966 // members were likely supposed to be inherited.
2967 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
2968 if (CD->isInvalidDecl())
2969 return ExprError();
2970 Diag(NameInfo.getLoc(), diag::err_no_member)
2971 << NameInfo.getName() << DC << SS.getRange();
2972 return ExprError();
2973 }
2974
2975 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2976 // Diagnose a missing typename if this resolved unambiguously to a type in
2977 // a dependent context. If we can recover with a type, downgrade this to
2978 // a warning in Microsoft compatibility mode.
2979 unsigned DiagID = diag::err_typename_missing;
2980 if (RecoveryTSI && getLangOpts().MSVCCompat)
2981 DiagID = diag::ext_typename_missing;
2982 SourceLocation Loc = SS.getBeginLoc();
2983 auto D = Diag(Loc, DiagID);
2984 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2985 << SourceRange(Loc, NameInfo.getEndLoc());
2986
2987 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2988 // context.
2989 if (!RecoveryTSI)
2990 return ExprError();
2991
2992 // Only issue the fixit if we're prepared to recover.
2993 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
2994
2995 // Recover by pretending this was an elaborated type.
2996 QualType Ty = Context.getTypeDeclType(Decl: TD);
2997 TypeLocBuilder TLB;
2998 TLB.pushTypeSpec(T: Ty).setNameLoc(NameInfo.getLoc());
2999
3000 QualType ET = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, T: Ty);
3001 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(T: ET);
3002 QTL.setElaboratedKeywordLoc(SourceLocation());
3003 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
3004
3005 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3006
3007 return ExprEmpty();
3008 }
3009
3010 // Defend against this resolving to an implicit member access. We usually
3011 // won't get here if this might be a legitimate a class member (we end up in
3012 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3013 // a pointer-to-member or in an unevaluated context in C++11.
3014 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3015 return BuildPossibleImplicitMemberExpr(SS,
3016 /*TemplateKWLoc=*/SourceLocation(),
3017 R, /*TemplateArgs=*/nullptr, S);
3018
3019 return BuildDeclarationNameExpr(SS, R, /* ADL */ NeedsADL: false);
3020}
3021
3022/// The parser has read a name in, and Sema has detected that we're currently
3023/// inside an ObjC method. Perform some additional checks and determine if we
3024/// should form a reference to an ivar.
3025///
3026/// Ideally, most of this would be done by lookup, but there's
3027/// actually quite a lot of extra work involved.
3028DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
3029 IdentifierInfo *II) {
3030 SourceLocation Loc = Lookup.getNameLoc();
3031 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3032
3033 // Check for error condition which is already reported.
3034 if (!CurMethod)
3035 return DeclResult(true);
3036
3037 // There are two cases to handle here. 1) scoped lookup could have failed,
3038 // in which case we should look for an ivar. 2) scoped lookup could have
3039 // found a decl, but that decl is outside the current instance method (i.e.
3040 // a global variable). In these two cases, we do a lookup for an ivar with
3041 // this name, if the lookup sucedes, we replace it our current decl.
3042
3043 // If we're in a class method, we don't normally want to look for
3044 // ivars. But if we don't find anything else, and there's an
3045 // ivar, that's an error.
3046 bool IsClassMethod = CurMethod->isClassMethod();
3047
3048 bool LookForIvars;
3049 if (Lookup.empty())
3050 LookForIvars = true;
3051 else if (IsClassMethod)
3052 LookForIvars = false;
3053 else
3054 LookForIvars = (Lookup.isSingleResult() &&
3055 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3056 ObjCInterfaceDecl *IFace = nullptr;
3057 if (LookForIvars) {
3058 IFace = CurMethod->getClassInterface();
3059 ObjCInterfaceDecl *ClassDeclared;
3060 ObjCIvarDecl *IV = nullptr;
3061 if (IFace && (IV = IFace->lookupInstanceVariable(IVarName: II, ClassDeclared))) {
3062 // Diagnose using an ivar in a class method.
3063 if (IsClassMethod) {
3064 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3065 return DeclResult(true);
3066 }
3067
3068 // Diagnose the use of an ivar outside of the declaring class.
3069 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
3070 !declaresSameEntity(ClassDeclared, IFace) &&
3071 !getLangOpts().DebuggerSupport)
3072 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3073
3074 // Success.
3075 return IV;
3076 }
3077 } else if (CurMethod->isInstanceMethod()) {
3078 // We should warn if a local variable hides an ivar.
3079 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3080 ObjCInterfaceDecl *ClassDeclared;
3081 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(IVarName: II, ClassDeclared)) {
3082 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3083 declaresSameEntity(IFace, ClassDeclared))
3084 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3085 }
3086 }
3087 } else if (Lookup.isSingleResult() &&
3088 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3089 // If accessing a stand-alone ivar in a class method, this is an error.
3090 if (const ObjCIvarDecl *IV =
3091 dyn_cast<ObjCIvarDecl>(Val: Lookup.getFoundDecl())) {
3092 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3093 return DeclResult(true);
3094 }
3095 }
3096
3097 // Didn't encounter an error, didn't find an ivar.
3098 return DeclResult(false);
3099}
3100
3101ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
3102 ObjCIvarDecl *IV) {
3103 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3104 assert(CurMethod && CurMethod->isInstanceMethod() &&
3105 "should not reference ivar from this context");
3106
3107 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3108 assert(IFace && "should not reference ivar from this context");
3109
3110 // If we're referencing an invalid decl, just return this as a silent
3111 // error node. The error diagnostic was already emitted on the decl.
3112 if (IV->isInvalidDecl())
3113 return ExprError();
3114
3115 // Check if referencing a field with __attribute__((deprecated)).
3116 if (DiagnoseUseOfDecl(IV, Loc))
3117 return ExprError();
3118
3119 // FIXME: This should use a new expr for a direct reference, don't
3120 // turn this into Self->ivar, just return a BareIVarExpr or something.
3121 IdentifierInfo &II = Context.Idents.get(Name: "self");
3122 UnqualifiedId SelfName;
3123 SelfName.setImplicitSelfParam(&II);
3124 CXXScopeSpec SelfScopeSpec;
3125 SourceLocation TemplateKWLoc;
3126 ExprResult SelfExpr =
3127 ActOnIdExpression(S, SS&: SelfScopeSpec, TemplateKWLoc, Id&: SelfName,
3128 /*HasTrailingLParen=*/false,
3129 /*IsAddressOfOperand=*/false);
3130 if (SelfExpr.isInvalid())
3131 return ExprError();
3132
3133 SelfExpr = DefaultLvalueConversion(E: SelfExpr.get());
3134 if (SelfExpr.isInvalid())
3135 return ExprError();
3136
3137 MarkAnyDeclReferenced(Loc, IV, true);
3138
3139 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3140 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3141 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3142 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3143
3144 ObjCIvarRefExpr *Result = new (Context)
3145 ObjCIvarRefExpr(IV, IV->getUsageType(objectType: SelfExpr.get()->getType()), Loc,
3146 IV->getLocation(), SelfExpr.get(), true, true);
3147
3148 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3149 if (!isUnevaluatedContext() &&
3150 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3151 getCurFunction()->recordUseOfWeak(E: Result);
3152 }
3153 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3154 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3155 ImplicitlyRetainedSelfLocs.push_back(Elt: {Loc, BD});
3156
3157 return Result;
3158}
3159
3160/// The parser has read a name in, and Sema has detected that we're currently
3161/// inside an ObjC method. Perform some additional checks and determine if we
3162/// should form a reference to an ivar. If so, build an expression referencing
3163/// that ivar.
3164ExprResult
3165Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
3166 IdentifierInfo *II, bool AllowBuiltinCreation) {
3167 // FIXME: Integrate this lookup step into LookupParsedName.
3168 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3169 if (Ivar.isInvalid())
3170 return ExprError();
3171 if (Ivar.isUsable())
3172 return BuildIvarRefExpr(S, Loc: Lookup.getNameLoc(),
3173 IV: cast<ObjCIvarDecl>(Val: Ivar.get()));
3174
3175 if (Lookup.empty() && II && AllowBuiltinCreation)
3176 LookupBuiltin(R&: Lookup);
3177
3178 // Sentinel value saying that we didn't do anything special.
3179 return ExprResult(false);
3180}
3181
3182/// Cast a base object to a member's actual type.
3183///
3184/// There are two relevant checks:
3185///
3186/// C++ [class.access.base]p7:
3187///
3188/// If a class member access operator [...] is used to access a non-static
3189/// data member or non-static member function, the reference is ill-formed if
3190/// the left operand [...] cannot be implicitly converted to a pointer to the
3191/// naming class of the right operand.
3192///
3193/// C++ [expr.ref]p7:
3194///
3195/// If E2 is a non-static data member or a non-static member function, the
3196/// program is ill-formed if the class of which E2 is directly a member is an
3197/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3198///
3199/// Note that the latter check does not consider access; the access of the
3200/// "real" base class is checked as appropriate when checking the access of the
3201/// member name.
3202ExprResult
3203Sema::PerformObjectMemberConversion(Expr *From,
3204 NestedNameSpecifier *Qualifier,
3205 NamedDecl *FoundDecl,
3206 NamedDecl *Member) {
3207 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3208 if (!RD)
3209 return From;
3210
3211 QualType DestRecordType;
3212 QualType DestType;
3213 QualType FromRecordType;
3214 QualType FromType = From->getType();
3215 bool PointerConversions = false;
3216 if (isa<FieldDecl>(Val: Member)) {
3217 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(Decl: RD));
3218 auto FromPtrType = FromType->getAs<PointerType>();
3219 DestRecordType = Context.getAddrSpaceQualType(
3220 T: DestRecordType, AddressSpace: FromPtrType
3221 ? FromType->getPointeeType().getAddressSpace()
3222 : FromType.getAddressSpace());
3223
3224 if (FromPtrType) {
3225 DestType = Context.getPointerType(T: DestRecordType);
3226 FromRecordType = FromPtrType->getPointeeType();
3227 PointerConversions = true;
3228 } else {
3229 DestType = DestRecordType;
3230 FromRecordType = FromType;
3231 }
3232 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3233 if (!Method->isImplicitObjectMemberFunction())
3234 return From;
3235
3236 DestType = Method->getThisType().getNonReferenceType();
3237 DestRecordType = Method->getFunctionObjectParameterType();
3238
3239 if (FromType->getAs<PointerType>()) {
3240 FromRecordType = FromType->getPointeeType();
3241 PointerConversions = true;
3242 } else {
3243 FromRecordType = FromType;
3244 DestType = DestRecordType;
3245 }
3246
3247 LangAS FromAS = FromRecordType.getAddressSpace();
3248 LangAS DestAS = DestRecordType.getAddressSpace();
3249 if (FromAS != DestAS) {
3250 QualType FromRecordTypeWithoutAS =
3251 Context.removeAddrSpaceQualType(T: FromRecordType);
3252 QualType FromTypeWithDestAS =
3253 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3254 if (PointerConversions)
3255 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3256 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3257 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3258 .get();
3259 }
3260 } else {
3261 // No conversion necessary.
3262 return From;
3263 }
3264
3265 if (DestType->isDependentType() || FromType->isDependentType())
3266 return From;
3267
3268 // If the unqualified types are the same, no conversion is necessary.
3269 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3270 return From;
3271
3272 SourceRange FromRange = From->getSourceRange();
3273 SourceLocation FromLoc = FromRange.getBegin();
3274
3275 ExprValueKind VK = From->getValueKind();
3276
3277 // C++ [class.member.lookup]p8:
3278 // [...] Ambiguities can often be resolved by qualifying a name with its
3279 // class name.
3280 //
3281 // If the member was a qualified name and the qualified referred to a
3282 // specific base subobject type, we'll cast to that intermediate type
3283 // first and then to the object in which the member is declared. That allows
3284 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3285 //
3286 // class Base { public: int x; };
3287 // class Derived1 : public Base { };
3288 // class Derived2 : public Base { };
3289 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3290 //
3291 // void VeryDerived::f() {
3292 // x = 17; // error: ambiguous base subobjects
3293 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3294 // }
3295 if (Qualifier && Qualifier->getAsType()) {
3296 QualType QType = QualType(Qualifier->getAsType(), 0);
3297 assert(QType->isRecordType() && "lookup done with non-record type");
3298
3299 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3300
3301 // In C++98, the qualifier type doesn't actually have to be a base
3302 // type of the object type, in which case we just ignore it.
3303 // Otherwise build the appropriate casts.
3304 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3305 CXXCastPath BasePath;
3306 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3307 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3308 return ExprError();
3309
3310 if (PointerConversions)
3311 QType = Context.getPointerType(T: QType);
3312 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3313 VK, BasePath: &BasePath).get();
3314
3315 FromType = QType;
3316 FromRecordType = QRecordType;
3317
3318 // If the qualifier type was the same as the destination type,
3319 // we're done.
3320 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3321 return From;
3322 }
3323 }
3324
3325 CXXCastPath BasePath;
3326 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3327 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3328 /*IgnoreAccess=*/true))
3329 return ExprError();
3330
3331 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase,
3332 VK, BasePath: &BasePath);
3333}
3334
3335bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3336 const LookupResult &R,
3337 bool HasTrailingLParen) {
3338 // Only when used directly as the postfix-expression of a call.
3339 if (!HasTrailingLParen)
3340 return false;
3341
3342 // Never if a scope specifier was provided.
3343 if (SS.isSet())
3344 return false;
3345
3346 // Only in C++ or ObjC++.
3347 if (!getLangOpts().CPlusPlus)
3348 return false;
3349
3350 // Turn off ADL when we find certain kinds of declarations during
3351 // normal lookup:
3352 for (const NamedDecl *D : R) {
3353 // C++0x [basic.lookup.argdep]p3:
3354 // -- a declaration of a class member
3355 // Since using decls preserve this property, we check this on the
3356 // original decl.
3357 if (D->isCXXClassMember())
3358 return false;
3359
3360 // C++0x [basic.lookup.argdep]p3:
3361 // -- a block-scope function declaration that is not a
3362 // using-declaration
3363 // NOTE: we also trigger this for function templates (in fact, we
3364 // don't check the decl type at all, since all other decl types
3365 // turn off ADL anyway).
3366 if (isa<UsingShadowDecl>(Val: D))
3367 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3368 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3369 return false;
3370
3371 // C++0x [basic.lookup.argdep]p3:
3372 // -- a declaration that is neither a function or a function
3373 // template
3374 // And also for builtin functions.
3375 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3376 // But also builtin functions.
3377 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3378 return false;
3379 } else if (!isa<FunctionTemplateDecl>(Val: D))
3380 return false;
3381 }
3382
3383 return true;
3384}
3385
3386
3387/// Diagnoses obvious problems with the use of the given declaration
3388/// as an expression. This is only actually called for lookups that
3389/// were not overloaded, and it doesn't promise that the declaration
3390/// will in fact be used.
3391static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3392 bool AcceptInvalid) {
3393 if (D->isInvalidDecl() && !AcceptInvalid)
3394 return true;
3395
3396 if (isa<TypedefNameDecl>(Val: D)) {
3397 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3398 return true;
3399 }
3400
3401 if (isa<ObjCInterfaceDecl>(Val: D)) {
3402 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3403 return true;
3404 }
3405
3406 if (isa<NamespaceDecl>(Val: D)) {
3407 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3408 return true;
3409 }
3410
3411 return false;
3412}
3413
3414// Certain multiversion types should be treated as overloaded even when there is
3415// only one result.
3416static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3417 assert(R.isSingleResult() && "Expected only a single result");
3418 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3419 return FD &&
3420 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3421}
3422
3423ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3424 LookupResult &R, bool NeedsADL,
3425 bool AcceptInvalidDecl) {
3426 // If this is a single, fully-resolved result and we don't need ADL,
3427 // just build an ordinary singleton decl ref.
3428 if (!NeedsADL && R.isSingleResult() &&
3429 !R.getAsSingle<FunctionTemplateDecl>() &&
3430 !ShouldLookupResultBeMultiVersionOverload(R))
3431 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3432 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3433 AcceptInvalidDecl);
3434
3435 // We only need to check the declaration if there's exactly one
3436 // result, because in the overloaded case the results can only be
3437 // functions and function templates.
3438 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3439 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3440 AcceptInvalid: AcceptInvalidDecl))
3441 return ExprError();
3442
3443 // Otherwise, just build an unresolved lookup expression. Suppress
3444 // any lookup-related diagnostics; we'll hash these out later, when
3445 // we've picked a target.
3446 R.suppressDiagnostics();
3447
3448 UnresolvedLookupExpr *ULE
3449 = UnresolvedLookupExpr::Create(Context, NamingClass: R.getNamingClass(),
3450 QualifierLoc: SS.getWithLocInContext(Context),
3451 NameInfo: R.getLookupNameInfo(),
3452 RequiresADL: NeedsADL, Overloaded: R.isOverloadedResult(),
3453 Begin: R.begin(), End: R.end());
3454
3455 return ULE;
3456}
3457
3458static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3459 SourceLocation loc,
3460 ValueDecl *var);
3461
3462/// Complete semantic analysis for a reference to the given declaration.
3463ExprResult Sema::BuildDeclarationNameExpr(
3464 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3465 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3466 bool AcceptInvalidDecl) {
3467 assert(D && "Cannot refer to a NULL declaration");
3468 assert(!isa<FunctionTemplateDecl>(D) &&
3469 "Cannot refer unambiguously to a function template");
3470
3471 SourceLocation Loc = NameInfo.getLoc();
3472 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3473 // Recovery from invalid cases (e.g. D is an invalid Decl).
3474 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3475 // diagnostics, as invalid decls use int as a fallback type.
3476 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3477 }
3478
3479 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: D)) {
3480 // Specifically diagnose references to class templates that are missing
3481 // a template argument list.
3482 diagnoseMissingTemplateArguments(Name: TemplateName(Template), Loc);
3483 return ExprError();
3484 }
3485
3486 // Make sure that we're referring to a value.
3487 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3488 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3489 Diag(D->getLocation(), diag::note_declared_at);
3490 return ExprError();
3491 }
3492
3493 // Check whether this declaration can be used. Note that we suppress
3494 // this check when we're going to perform argument-dependent lookup
3495 // on this function name, because this might not be the function
3496 // that overload resolution actually selects.
3497 if (DiagnoseUseOfDecl(D, Locs: Loc))
3498 return ExprError();
3499
3500 auto *VD = cast<ValueDecl>(Val: D);
3501
3502 // Only create DeclRefExpr's for valid Decl's.
3503 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3504 return ExprError();
3505
3506 // Handle members of anonymous structs and unions. If we got here,
3507 // and the reference is to a class member indirect field, then this
3508 // must be the subject of a pointer-to-member expression.
3509 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3510 IndirectField && !IndirectField->isCXXClassMember())
3511 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3512 indirectField: IndirectField);
3513
3514 QualType type = VD->getType();
3515 if (type.isNull())
3516 return ExprError();
3517 ExprValueKind valueKind = VK_PRValue;
3518
3519 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3520 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3521 // is expanded by some outer '...' in the context of the use.
3522 type = type.getNonPackExpansionType();
3523
3524 switch (D->getKind()) {
3525 // Ignore all the non-ValueDecl kinds.
3526#define ABSTRACT_DECL(kind)
3527#define VALUE(type, base)
3528#define DECL(type, base) case Decl::type:
3529#include "clang/AST/DeclNodes.inc"
3530 llvm_unreachable("invalid value decl kind");
3531
3532 // These shouldn't make it here.
3533 case Decl::ObjCAtDefsField:
3534 llvm_unreachable("forming non-member reference to ivar?");
3535
3536 // Enum constants are always r-values and never references.
3537 // Unresolved using declarations are dependent.
3538 case Decl::EnumConstant:
3539 case Decl::UnresolvedUsingValue:
3540 case Decl::OMPDeclareReduction:
3541 case Decl::OMPDeclareMapper:
3542 valueKind = VK_PRValue;
3543 break;
3544
3545 // Fields and indirect fields that got here must be for
3546 // pointer-to-member expressions; we just call them l-values for
3547 // internal consistency, because this subexpression doesn't really
3548 // exist in the high-level semantics.
3549 case Decl::Field:
3550 case Decl::IndirectField:
3551 case Decl::ObjCIvar:
3552 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3553
3554 // These can't have reference type in well-formed programs, but
3555 // for internal consistency we do this anyway.
3556 type = type.getNonReferenceType();
3557 valueKind = VK_LValue;
3558 break;
3559
3560 // Non-type template parameters are either l-values or r-values
3561 // depending on the type.
3562 case Decl::NonTypeTemplateParm: {
3563 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3564 type = reftype->getPointeeType();
3565 valueKind = VK_LValue; // even if the parameter is an r-value reference
3566 break;
3567 }
3568
3569 // [expr.prim.id.unqual]p2:
3570 // If the entity is a template parameter object for a template
3571 // parameter of type T, the type of the expression is const T.
3572 // [...] The expression is an lvalue if the entity is a [...] template
3573 // parameter object.
3574 if (type->isRecordType()) {
3575 type = type.getUnqualifiedType().withConst();
3576 valueKind = VK_LValue;
3577 break;
3578 }
3579
3580 // For non-references, we need to strip qualifiers just in case
3581 // the template parameter was declared as 'const int' or whatever.
3582 valueKind = VK_PRValue;
3583 type = type.getUnqualifiedType();
3584 break;
3585 }
3586
3587 case Decl::Var:
3588 case Decl::VarTemplateSpecialization:
3589 case Decl::VarTemplatePartialSpecialization:
3590 case Decl::Decomposition:
3591 case Decl::OMPCapturedExpr:
3592 // In C, "extern void blah;" is valid and is an r-value.
3593 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3594 type->isVoidType()) {
3595 valueKind = VK_PRValue;
3596 break;
3597 }
3598 [[fallthrough]];
3599
3600 case Decl::ImplicitParam:
3601 case Decl::ParmVar: {
3602 // These are always l-values.
3603 valueKind = VK_LValue;
3604 type = type.getNonReferenceType();
3605
3606 // FIXME: Does the addition of const really only apply in
3607 // potentially-evaluated contexts? Since the variable isn't actually
3608 // captured in an unevaluated context, it seems that the answer is no.
3609 if (!isUnevaluatedContext()) {
3610 QualType CapturedType = getCapturedDeclRefType(Var: cast<VarDecl>(VD), Loc);
3611 if (!CapturedType.isNull())
3612 type = CapturedType;
3613 }
3614
3615 break;
3616 }
3617
3618 case Decl::Binding:
3619 // These are always lvalues.
3620 valueKind = VK_LValue;
3621 type = type.getNonReferenceType();
3622 break;
3623
3624 case Decl::Function: {
3625 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3626 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3627 type = Context.BuiltinFnTy;
3628 valueKind = VK_PRValue;
3629 break;
3630 }
3631 }
3632
3633 const FunctionType *fty = type->castAs<FunctionType>();
3634
3635 // If we're referring to a function with an __unknown_anytype
3636 // result type, make the entire expression __unknown_anytype.
3637 if (fty->getReturnType() == Context.UnknownAnyTy) {
3638 type = Context.UnknownAnyTy;
3639 valueKind = VK_PRValue;
3640 break;
3641 }
3642
3643 // Functions are l-values in C++.
3644 if (getLangOpts().CPlusPlus) {
3645 valueKind = VK_LValue;
3646 break;
3647 }
3648
3649 // C99 DR 316 says that, if a function type comes from a
3650 // function definition (without a prototype), that type is only
3651 // used for checking compatibility. Therefore, when referencing
3652 // the function, we pretend that we don't have the full function
3653 // type.
3654 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3655 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3656 Info: fty->getExtInfo());
3657
3658 // Functions are r-values in C.
3659 valueKind = VK_PRValue;
3660 break;
3661 }
3662
3663 case Decl::CXXDeductionGuide:
3664 llvm_unreachable("building reference to deduction guide");
3665
3666 case Decl::MSProperty:
3667 case Decl::MSGuid:
3668 case Decl::TemplateParamObject:
3669 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3670 // capture in OpenMP, or duplicated between host and device?
3671 valueKind = VK_LValue;
3672 break;
3673
3674 case Decl::UnnamedGlobalConstant:
3675 valueKind = VK_LValue;
3676 break;
3677
3678 case Decl::CXXMethod:
3679 // If we're referring to a method with an __unknown_anytype
3680 // result type, make the entire expression __unknown_anytype.
3681 // This should only be possible with a type written directly.
3682 if (const FunctionProtoType *proto =
3683 dyn_cast<FunctionProtoType>(VD->getType()))
3684 if (proto->getReturnType() == Context.UnknownAnyTy) {
3685 type = Context.UnknownAnyTy;
3686 valueKind = VK_PRValue;
3687 break;
3688 }
3689
3690 // C++ methods are l-values if static, r-values if non-static.
3691 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3692 valueKind = VK_LValue;
3693 break;
3694 }
3695 [[fallthrough]];
3696
3697 case Decl::CXXConversion:
3698 case Decl::CXXDestructor:
3699 case Decl::CXXConstructor:
3700 valueKind = VK_PRValue;
3701 break;
3702 }
3703
3704 auto *E =
3705 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3706 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3707 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3708 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3709 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3710 // diagnostics).
3711 if (VD->isInvalidDecl() && E)
3712 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3713 return E;
3714}
3715
3716static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3717 SmallString<32> &Target) {
3718 Target.resize(N: CharByteWidth * (Source.size() + 1));
3719 char *ResultPtr = &Target[0];
3720 const llvm::UTF8 *ErrorPtr;
3721 bool success =
3722 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3723 (void)success;
3724 assert(success);
3725 Target.resize(N: ResultPtr - &Target[0]);
3726}
3727
3728ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3729 PredefinedIdentKind IK) {
3730 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3731 if (!currentDecl) {
3732 Diag(Loc, diag::ext_predef_outside_function);
3733 currentDecl = Context.getTranslationUnitDecl();
3734 }
3735
3736 QualType ResTy;
3737 StringLiteral *SL = nullptr;
3738 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3739 ResTy = Context.DependentTy;
3740 else {
3741 // Pre-defined identifiers are of type char[x], where x is the length of
3742 // the string.
3743 auto Str = PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl);
3744 unsigned Length = Str.length();
3745
3746 llvm::APInt LengthI(32, Length + 1);
3747 if (IK == PredefinedIdentKind::LFunction ||
3748 IK == PredefinedIdentKind::LFuncSig) {
3749 ResTy =
3750 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3751 SmallString<32> RawChars;
3752 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3753 Source: Str, Target&: RawChars);
3754 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3755 ASM: ArraySizeModifier::Normal,
3756 /*IndexTypeQuals*/ 0);
3757 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3758 /*Pascal*/ false, Ty: ResTy, Loc);
3759 } else {
3760 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3761 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3762 ASM: ArraySizeModifier::Normal,
3763 /*IndexTypeQuals*/ 0);
3764 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3765 /*Pascal*/ false, Ty: ResTy, Loc);
3766 }
3767 }
3768
3769 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3770 SL);
3771}
3772
3773ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3774 SourceLocation LParen,
3775 SourceLocation RParen,
3776 TypeSourceInfo *TSI) {
3777 return SYCLUniqueStableNameExpr::Create(Ctx: Context, OpLoc, LParen, RParen, TSI);
3778}
3779
3780ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3781 SourceLocation LParen,
3782 SourceLocation RParen,
3783 ParsedType ParsedTy) {
3784 TypeSourceInfo *TSI = nullptr;
3785 QualType Ty = GetTypeFromParser(Ty: ParsedTy, TInfo: &TSI);
3786
3787 if (Ty.isNull())
3788 return ExprError();
3789 if (!TSI)
3790 TSI = Context.getTrivialTypeSourceInfo(T: Ty, Loc: LParen);
3791
3792 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3793}
3794
3795ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3796 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3797}
3798
3799ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3800 SmallString<16> CharBuffer;
3801 bool Invalid = false;
3802 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3803 if (Invalid)
3804 return ExprError();
3805
3806 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3807 PP, Tok.getKind());
3808 if (Literal.hadError())
3809 return ExprError();
3810
3811 QualType Ty;
3812 if (Literal.isWide())
3813 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3814 else if (Literal.isUTF8() && getLangOpts().C23)
3815 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3816 else if (Literal.isUTF8() && getLangOpts().Char8)
3817 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3818 else if (Literal.isUTF16())
3819 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3820 else if (Literal.isUTF32())
3821 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3822 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3823 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3824 else
3825 Ty = Context.CharTy; // 'x' -> char in C++;
3826 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3827
3828 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3829 if (Literal.isWide())
3830 Kind = CharacterLiteralKind::Wide;
3831 else if (Literal.isUTF16())
3832 Kind = CharacterLiteralKind::UTF16;
3833 else if (Literal.isUTF32())
3834 Kind = CharacterLiteralKind::UTF32;
3835 else if (Literal.isUTF8())
3836 Kind = CharacterLiteralKind::UTF8;
3837
3838 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3839 Tok.getLocation());
3840
3841 if (Literal.getUDSuffix().empty())
3842 return Lit;
3843
3844 // We're building a user-defined literal.
3845 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3846 SourceLocation UDSuffixLoc =
3847 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3848
3849 // Make sure we're allowed user-defined literals here.
3850 if (!UDLScope)
3851 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3852
3853 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3854 // operator "" X (ch)
3855 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3856 Args: Lit, LitEndLoc: Tok.getLocation());
3857}
3858
3859ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3860 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3861 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3862 Context.IntTy, Loc);
3863}
3864
3865static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3866 QualType Ty, SourceLocation Loc) {
3867 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3868
3869 using llvm::APFloat;
3870 APFloat Val(Format);
3871
3872 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val);
3873
3874 // Overflow is always an error, but underflow is only an error if
3875 // we underflowed to zero (APFloat reports denormals as underflow).
3876 if ((result & APFloat::opOverflow) ||
3877 ((result & APFloat::opUnderflow) && Val.isZero())) {
3878 unsigned diagnostic;
3879 SmallString<20> buffer;
3880 if (result & APFloat::opOverflow) {
3881 diagnostic = diag::warn_float_overflow;
3882 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3883 } else {
3884 diagnostic = diag::warn_float_underflow;
3885 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3886 }
3887
3888 S.Diag(Loc, DiagID: diagnostic)
3889 << Ty
3890 << StringRef(buffer.data(), buffer.size());
3891 }
3892
3893 bool isExact = (result == APFloat::opOK);
3894 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3895}
3896
3897bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3898 assert(E && "Invalid expression");
3899
3900 if (E->isValueDependent())
3901 return false;
3902
3903 QualType QT = E->getType();
3904 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3905 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3906 return true;
3907 }
3908
3909 llvm::APSInt ValueAPS;
3910 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3911
3912 if (R.isInvalid())
3913 return true;
3914
3915 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3916 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3917 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3918 << toString(ValueAPS, 10) << ValueIsPositive;
3919 return true;
3920 }
3921
3922 return false;
3923}
3924
3925ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3926 // Fast path for a single digit (which is quite common). A single digit
3927 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3928 if (Tok.getLength() == 1) {
3929 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3930 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val: Val-'0');
3931 }
3932
3933 SmallString<128> SpellingBuffer;
3934 // NumericLiteralParser wants to overread by one character. Add padding to
3935 // the buffer in case the token is copied to the buffer. If getSpelling()
3936 // returns a StringRef to the memory buffer, it should have a null char at
3937 // the EOF, so it is also safe.
3938 SpellingBuffer.resize(N: Tok.getLength() + 1);
3939
3940 // Get the spelling of the token, which eliminates trigraphs, etc.
3941 bool Invalid = false;
3942 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3943 if (Invalid)
3944 return ExprError();
3945
3946 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3947 PP.getSourceManager(), PP.getLangOpts(),
3948 PP.getTargetInfo(), PP.getDiagnostics());
3949 if (Literal.hadError)
3950 return ExprError();
3951
3952 if (Literal.hasUDSuffix()) {
3953 // We're building a user-defined literal.
3954 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3955 SourceLocation UDSuffixLoc =
3956 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3957
3958 // Make sure we're allowed user-defined literals here.
3959 if (!UDLScope)
3960 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3961
3962 QualType CookedTy;
3963 if (Literal.isFloatingLiteral()) {
3964 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3965 // long double, the literal is treated as a call of the form
3966 // operator "" X (f L)
3967 CookedTy = Context.LongDoubleTy;
3968 } else {
3969 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3970 // unsigned long long, the literal is treated as a call of the form
3971 // operator "" X (n ULL)
3972 CookedTy = Context.UnsignedLongLongTy;
3973 }
3974
3975 DeclarationName OpName =
3976 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3977 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3978 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3979
3980 SourceLocation TokLoc = Tok.getLocation();
3981
3982 // Perform literal operator lookup to determine if we're building a raw
3983 // literal or a cooked one.
3984 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3985 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3986 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3987 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3988 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3989 case LOLR_ErrorNoDiagnostic:
3990 // Lookup failure for imaginary constants isn't fatal, there's still the
3991 // GNU extension producing _Complex types.
3992 break;
3993 case LOLR_Error:
3994 return ExprError();
3995 case LOLR_Cooked: {
3996 Expr *Lit;
3997 if (Literal.isFloatingLiteral()) {
3998 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3999 } else {
4000 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
4001 if (Literal.GetIntegerValue(ResultVal))
4002 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4003 << /* Unsigned */ 1;
4004 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
4005 l: Tok.getLocation());
4006 }
4007 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
4008 }
4009
4010 case LOLR_Raw: {
4011 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4012 // literal is treated as a call of the form
4013 // operator "" X ("n")
4014 unsigned Length = Literal.getUDSuffixOffset();
4015 QualType StrTy = Context.getConstantArrayType(
4016 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
4017 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
4018 Expr *Lit =
4019 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
4020 Kind: StringLiteralKind::Ordinary,
4021 /*Pascal*/ false, Ty: StrTy, Loc: &TokLoc, NumConcatenated: 1);
4022 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
4023 }
4024
4025 case LOLR_Template: {
4026 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4027 // template), L is treated as a call fo the form
4028 // operator "" X <'c1', 'c2', ... 'ck'>()
4029 // where n is the source character sequence c1 c2 ... ck.
4030 TemplateArgumentListInfo ExplicitArgs;
4031 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
4032 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4033 llvm::APSInt Value(CharBits, CharIsUnsigned);
4034 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4035 Value = TokSpelling[I];
4036 TemplateArgument Arg(Context, Value, Context.CharTy);
4037 TemplateArgumentLocInfo ArgInfo;
4038 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4039 }
4040 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt, LitEndLoc: TokLoc,
4041 ExplicitTemplateArgs: &ExplicitArgs);
4042 }
4043 case LOLR_StringTemplatePack:
4044 llvm_unreachable("unexpected literal operator lookup result");
4045 }
4046 }
4047
4048 Expr *Res;
4049
4050 if (Literal.isFixedPointLiteral()) {
4051 QualType Ty;
4052
4053 if (Literal.isAccum) {
4054 if (Literal.isHalf) {
4055 Ty = Context.ShortAccumTy;
4056 } else if (Literal.isLong) {
4057 Ty = Context.LongAccumTy;
4058 } else {
4059 Ty = Context.AccumTy;
4060 }
4061 } else if (Literal.isFract) {
4062 if (Literal.isHalf) {
4063 Ty = Context.ShortFractTy;
4064 } else if (Literal.isLong) {
4065 Ty = Context.LongFractTy;
4066 } else {
4067 Ty = Context.FractTy;
4068 }
4069 }
4070
4071 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4072
4073 bool isSigned = !Literal.isUnsigned;
4074 unsigned scale = Context.getFixedPointScale(Ty);
4075 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4076
4077 llvm::APInt Val(bit_width, 0, isSigned);
4078 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4079 bool ValIsZero = Val.isZero() && !Overflowed;
4080
4081 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4082 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4083 // Clause 6.4.4 - The value of a constant shall be in the range of
4084 // representable values for its type, with exception for constants of a
4085 // fract type with a value of exactly 1; such a constant shall denote
4086 // the maximal value for the type.
4087 --Val;
4088 else if (Val.ugt(MaxVal) || Overflowed)
4089 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4090
4091 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4092 l: Tok.getLocation(), Scale: scale);
4093 } else if (Literal.isFloatingLiteral()) {
4094 QualType Ty;
4095 if (Literal.isHalf){
4096 if (getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4097 Ty = Context.HalfTy;
4098 else {
4099 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4100 return ExprError();
4101 }
4102 } else if (Literal.isFloat)
4103 Ty = Context.FloatTy;
4104 else if (Literal.isLong)
4105 Ty = Context.LongDoubleTy;
4106 else if (Literal.isFloat16)
4107 Ty = Context.Float16Ty;
4108 else if (Literal.isFloat128)
4109 Ty = Context.Float128Ty;
4110 else
4111 Ty = Context.DoubleTy;
4112
4113 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4114
4115 if (Ty == Context.DoubleTy) {
4116 if (getLangOpts().SinglePrecisionConstants) {
4117 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4118 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4119 }
4120 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4121 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4122 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4123 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4124 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4125 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4126 }
4127 }
4128 } else if (!Literal.isIntegerLiteral()) {
4129 return ExprError();
4130 } else {
4131 QualType Ty;
4132
4133 // 'z/uz' literals are a C++23 feature.
4134 if (Literal.isSizeT)
4135 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4136 ? getLangOpts().CPlusPlus23
4137 ? diag::warn_cxx20_compat_size_t_suffix
4138 : diag::ext_cxx23_size_t_suffix
4139 : diag::err_cxx23_size_t_suffix);
4140
4141 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4142 // but we do not currently support the suffix in C++ mode because it's not
4143 // entirely clear whether WG21 will prefer this suffix to return a library
4144 // type such as std::bit_int instead of returning a _BitInt.
4145 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4146 PP.Diag(Tok.getLocation(), getLangOpts().C23
4147 ? diag::warn_c23_compat_bitint_suffix
4148 : diag::ext_c23_bitint_suffix);
4149
4150 // Get the value in the widest-possible width. What is "widest" depends on
4151 // whether the literal is a bit-precise integer or not. For a bit-precise
4152 // integer type, try to scan the source to determine how many bits are
4153 // needed to represent the value. This may seem a bit expensive, but trying
4154 // to get the integer value from an overly-wide APInt is *extremely*
4155 // expensive, so the naive approach of assuming
4156 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4157 unsigned BitsNeeded =
4158 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4159 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix())
4160 : Context.getTargetInfo().getIntMaxTWidth();
4161 llvm::APInt ResultVal(BitsNeeded, 0);
4162
4163 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4164 // If this value didn't fit into uintmax_t, error and force to ull.
4165 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4166 << /* Unsigned */ 1;
4167 Ty = Context.UnsignedLongLongTy;
4168 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4169 "long long is not intmax_t?");
4170 } else {
4171 // If this value fits into a ULL, try to figure out what else it fits into
4172 // according to the rules of C99 6.4.4.1p5.
4173
4174 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4175 // be an unsigned int.
4176 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4177
4178 // Check from smallest to largest, picking the smallest type we can.
4179 unsigned Width = 0;
4180
4181 // Microsoft specific integer suffixes are explicitly sized.
4182 if (Literal.MicrosoftInteger) {
4183 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4184 Width = 8;
4185 Ty = Context.CharTy;
4186 } else {
4187 Width = Literal.MicrosoftInteger;
4188 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4189 /*Signed=*/!Literal.isUnsigned);
4190 }
4191 }
4192
4193 // Bit-precise integer literals are automagically-sized based on the
4194 // width required by the literal.
4195 if (Literal.isBitInt) {
4196 // The signed version has one more bit for the sign value. There are no
4197 // zero-width bit-precise integers, even if the literal value is 0.
4198 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4199 (Literal.isUnsigned ? 0u : 1u);
4200
4201 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4202 // and reset the type to the largest supported width.
4203 unsigned int MaxBitIntWidth =
4204 Context.getTargetInfo().getMaxBitIntWidth();
4205 if (Width > MaxBitIntWidth) {
4206 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4207 << Literal.isUnsigned;
4208 Width = MaxBitIntWidth;
4209 }
4210
4211 // Reset the result value to the smaller APInt and select the correct
4212 // type to be used. Note, we zext even for signed values because the
4213 // literal itself is always an unsigned value (a preceeding - is a
4214 // unary operator, not part of the literal).
4215 ResultVal = ResultVal.zextOrTrunc(width: Width);
4216 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4217 }
4218
4219 // Check C++23 size_t literals.
4220 if (Literal.isSizeT) {
4221 assert(!Literal.MicrosoftInteger &&
4222 "size_t literals can't be Microsoft literals");
4223 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4224 T: Context.getTargetInfo().getSizeType());
4225
4226 // Does it fit in size_t?
4227 if (ResultVal.isIntN(N: SizeTSize)) {
4228 // Does it fit in ssize_t?
4229 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4230 Ty = Context.getSignedSizeType();
4231 else if (AllowUnsigned)
4232 Ty = Context.getSizeType();
4233 Width = SizeTSize;
4234 }
4235 }
4236
4237 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4238 !Literal.isSizeT) {
4239 // Are int/unsigned possibilities?
4240 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4241
4242 // Does it fit in a unsigned int?
4243 if (ResultVal.isIntN(N: IntSize)) {
4244 // Does it fit in a signed int?
4245 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4246 Ty = Context.IntTy;
4247 else if (AllowUnsigned)
4248 Ty = Context.UnsignedIntTy;
4249 Width = IntSize;
4250 }
4251 }
4252
4253 // Are long/unsigned long possibilities?
4254 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4255 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4256
4257 // Does it fit in a unsigned long?
4258 if (ResultVal.isIntN(N: LongSize)) {
4259 // Does it fit in a signed long?
4260 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4261 Ty = Context.LongTy;
4262 else if (AllowUnsigned)
4263 Ty = Context.UnsignedLongTy;
4264 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4265 // is compatible.
4266 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4267 const unsigned LongLongSize =
4268 Context.getTargetInfo().getLongLongWidth();
4269 Diag(Tok.getLocation(),
4270 getLangOpts().CPlusPlus
4271 ? Literal.isLong
4272 ? diag::warn_old_implicitly_unsigned_long_cxx
4273 : /*C++98 UB*/ diag::
4274 ext_old_implicitly_unsigned_long_cxx
4275 : diag::warn_old_implicitly_unsigned_long)
4276 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4277 : /*will be ill-formed*/ 1);
4278 Ty = Context.UnsignedLongTy;
4279 }
4280 Width = LongSize;
4281 }
4282 }
4283
4284 // Check long long if needed.
4285 if (Ty.isNull() && !Literal.isSizeT) {
4286 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4287
4288 // Does it fit in a unsigned long long?
4289 if (ResultVal.isIntN(N: LongLongSize)) {
4290 // Does it fit in a signed long long?
4291 // To be compatible with MSVC, hex integer literals ending with the
4292 // LL or i64 suffix are always signed in Microsoft mode.
4293 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4294 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4295 Ty = Context.LongLongTy;
4296 else if (AllowUnsigned)
4297 Ty = Context.UnsignedLongLongTy;
4298 Width = LongLongSize;
4299
4300 // 'long long' is a C99 or C++11 feature, whether the literal
4301 // explicitly specified 'long long' or we needed the extra width.
4302 if (getLangOpts().CPlusPlus)
4303 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4304 ? diag::warn_cxx98_compat_longlong
4305 : diag::ext_cxx11_longlong);
4306 else if (!getLangOpts().C99)
4307 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4308 }
4309 }
4310
4311 // If we still couldn't decide a type, we either have 'size_t' literal
4312 // that is out of range, or a decimal literal that does not fit in a
4313 // signed long long and has no U suffix.
4314 if (Ty.isNull()) {
4315 if (Literal.isSizeT)
4316 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4317 << Literal.isUnsigned;
4318 else
4319 Diag(Tok.getLocation(),
4320 diag::ext_integer_literal_too_large_for_signed);
4321 Ty = Context.UnsignedLongLongTy;
4322 Width = Context.getTargetInfo().getLongLongWidth();
4323 }
4324
4325 if (ResultVal.getBitWidth() != Width)
4326 ResultVal = ResultVal.trunc(width: Width);
4327 }
4328 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4329 }
4330
4331 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4332 if (Literal.isImaginary) {
4333 Res = new (Context) ImaginaryLiteral(Res,
4334 Context.getComplexType(T: Res->getType()));
4335
4336 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4337 }
4338 return Res;
4339}
4340
4341ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4342 assert(E && "ActOnParenExpr() missing expr");
4343 QualType ExprTy = E->getType();
4344 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4345 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4346 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4347 return new (Context) ParenExpr(L, R, E);
4348}
4349
4350static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4351 SourceLocation Loc,
4352 SourceRange ArgRange) {
4353 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4354 // scalar or vector data type argument..."
4355 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4356 // type (C99 6.2.5p18) or void.
4357 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4358 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4359 << T << ArgRange;
4360 return true;
4361 }
4362
4363 assert((T->isVoidType() || !T->isIncompleteType()) &&
4364 "Scalar types should always be complete");
4365 return false;
4366}
4367
4368static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4369 SourceLocation Loc,
4370 SourceRange ArgRange) {
4371 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4372 if (!T->isVectorType() && !T->isSizelessVectorType())
4373 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4374 << ""
4375 << "__builtin_vectorelements" << T << ArgRange;
4376
4377 return false;
4378}
4379
4380static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4381 SourceLocation Loc,
4382 SourceRange ArgRange,
4383 UnaryExprOrTypeTrait TraitKind) {
4384 // Invalid types must be hard errors for SFINAE in C++.
4385 if (S.LangOpts.CPlusPlus)
4386 return true;
4387
4388 // C99 6.5.3.4p1:
4389 if (T->isFunctionType() &&
4390 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4391 TraitKind == UETT_PreferredAlignOf)) {
4392 // sizeof(function)/alignof(function) is allowed as an extension.
4393 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4394 << getTraitSpelling(TraitKind) << ArgRange;
4395 return false;
4396 }
4397
4398 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4399 // this is an error (OpenCL v1.1 s6.3.k)
4400 if (T->isVoidType()) {
4401 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4402 : diag::ext_sizeof_alignof_void_type;
4403 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4404 return false;
4405 }
4406
4407 return true;
4408}
4409
4410static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4411 SourceLocation Loc,
4412 SourceRange ArgRange,
4413 UnaryExprOrTypeTrait TraitKind) {
4414 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4415 // runtime doesn't allow it.
4416 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4417 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4418 << T << (TraitKind == UETT_SizeOf)
4419 << ArgRange;
4420 return true;
4421 }
4422
4423 return false;
4424}
4425
4426/// Check whether E is a pointer from a decayed array type (the decayed
4427/// pointer type is equal to T) and emit a warning if it is.
4428static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4429 const Expr *E) {
4430 // Don't warn if the operation changed the type.
4431 if (T != E->getType())
4432 return;
4433
4434 // Now look for array decays.
4435 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4436 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4437 return;
4438
4439 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4440 << ICE->getType()
4441 << ICE->getSubExpr()->getType();
4442}
4443
4444/// Check the constraints on expression operands to unary type expression
4445/// and type traits.
4446///
4447/// Completes any types necessary and validates the constraints on the operand
4448/// expression. The logic mostly mirrors the type-based overload, but may modify
4449/// the expression as it completes the type for that expression through template
4450/// instantiation, etc.
4451bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4452 UnaryExprOrTypeTrait ExprKind) {
4453 QualType ExprTy = E->getType();
4454 assert(!ExprTy->isReferenceType());
4455
4456 bool IsUnevaluatedOperand =
4457 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4458 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4459 ExprKind == UETT_VecStep);
4460 if (IsUnevaluatedOperand) {
4461 ExprResult Result = CheckUnevaluatedOperand(E);
4462 if (Result.isInvalid())
4463 return true;
4464 E = Result.get();
4465 }
4466
4467 // The operand for sizeof and alignof is in an unevaluated expression context,
4468 // so side effects could result in unintended consequences.
4469 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4470 // used to build SFINAE gadgets.
4471 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4472 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4473 !E->isInstantiationDependent() &&
4474 !E->getType()->isVariableArrayType() &&
4475 E->HasSideEffects(Context, false))
4476 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4477
4478 if (ExprKind == UETT_VecStep)
4479 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4480 E->getSourceRange());
4481
4482 if (ExprKind == UETT_VectorElements)
4483 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4484 E->getSourceRange());
4485
4486 // Explicitly list some types as extensions.
4487 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4488 E->getSourceRange(), ExprKind))
4489 return false;
4490
4491 // WebAssembly tables are always illegal operands to unary expressions and
4492 // type traits.
4493 if (Context.getTargetInfo().getTriple().isWasm() &&
4494 E->getType()->isWebAssemblyTableType()) {
4495 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4496 << getTraitSpelling(ExprKind);
4497 return true;
4498 }
4499
4500 // 'alignof' applied to an expression only requires the base element type of
4501 // the expression to be complete. 'sizeof' requires the expression's type to
4502 // be complete (and will attempt to complete it if it's an array of unknown
4503 // bound).
4504 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4505 if (RequireCompleteSizedType(
4506 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4507 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4508 getTraitSpelling(ExprKind), E->getSourceRange()))
4509 return true;
4510 } else {
4511 if (RequireCompleteSizedExprType(
4512 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4513 getTraitSpelling(ExprKind), E->getSourceRange()))
4514 return true;
4515 }
4516
4517 // Completing the expression's type may have changed it.
4518 ExprTy = E->getType();
4519 assert(!ExprTy->isReferenceType());
4520
4521 if (ExprTy->isFunctionType()) {
4522 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4523 << getTraitSpelling(ExprKind) << E->getSourceRange();
4524 return true;
4525 }
4526
4527 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4528 E->getSourceRange(), ExprKind))
4529 return true;
4530
4531 if (ExprKind == UETT_SizeOf) {
4532 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4533 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4534 QualType OType = PVD->getOriginalType();
4535 QualType Type = PVD->getType();
4536 if (Type->isPointerType() && OType->isArrayType()) {
4537 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4538 << Type << OType;
4539 Diag(PVD->getLocation(), diag::note_declared_at);
4540 }
4541 }
4542 }
4543
4544 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4545 // decays into a pointer and returns an unintended result. This is most
4546 // likely a typo for "sizeof(array) op x".
4547 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549 BO->getLHS());
4550 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4551 BO->getRHS());
4552 }
4553 }
4554
4555 return false;
4556}
4557
4558static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4559 // Cannot know anything else if the expression is dependent.
4560 if (E->isTypeDependent())
4561 return false;
4562
4563 if (E->getObjectKind() == OK_BitField) {
4564 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4565 << 1 << E->getSourceRange();
4566 return true;
4567 }
4568
4569 ValueDecl *D = nullptr;
4570 Expr *Inner = E->IgnoreParens();
4571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4572 D = DRE->getDecl();
4573 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4574 D = ME->getMemberDecl();
4575 }
4576
4577 // If it's a field, require the containing struct to have a
4578 // complete definition so that we can compute the layout.
4579 //
4580 // This can happen in C++11 onwards, either by naming the member
4581 // in a way that is not transformed into a member access expression
4582 // (in an unevaluated operand, for instance), or by naming the member
4583 // in a trailing-return-type.
4584 //
4585 // For the record, since __alignof__ on expressions is a GCC
4586 // extension, GCC seems to permit this but always gives the
4587 // nonsensical answer 0.
4588 //
4589 // We don't really need the layout here --- we could instead just
4590 // directly check for all the appropriate alignment-lowing
4591 // attributes --- but that would require duplicating a lot of
4592 // logic that just isn't worth duplicating for such a marginal
4593 // use-case.
4594 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4595 // Fast path this check, since we at least know the record has a
4596 // definition if we can find a member of it.
4597 if (!FD->getParent()->isCompleteDefinition()) {
4598 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4599 << E->getSourceRange();
4600 return true;
4601 }
4602
4603 // Otherwise, if it's a field, and the field doesn't have
4604 // reference type, then it must have a complete type (or be a
4605 // flexible array member, which we explicitly want to
4606 // white-list anyway), which makes the following checks trivial.
4607 if (!FD->getType()->isReferenceType())
4608 return false;
4609 }
4610
4611 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4612}
4613
4614bool Sema::CheckVecStepExpr(Expr *E) {
4615 E = E->IgnoreParens();
4616
4617 // Cannot know anything else if the expression is dependent.
4618 if (E->isTypeDependent())
4619 return false;
4620
4621 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4622}
4623
4624static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4625 CapturingScopeInfo *CSI) {
4626 assert(T->isVariablyModifiedType());
4627 assert(CSI != nullptr);
4628
4629 // We're going to walk down into the type and look for VLA expressions.
4630 do {
4631 const Type *Ty = T.getTypePtr();
4632 switch (Ty->getTypeClass()) {
4633#define TYPE(Class, Base)
4634#define ABSTRACT_TYPE(Class, Base)
4635#define NON_CANONICAL_TYPE(Class, Base)
4636#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4637#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4638#include "clang/AST/TypeNodes.inc"
4639 T = QualType();
4640 break;
4641 // These types are never variably-modified.
4642 case Type::Builtin:
4643 case Type::Complex:
4644 case Type::Vector:
4645 case Type::ExtVector:
4646 case Type::ConstantMatrix:
4647 case Type::Record:
4648 case Type::Enum:
4649 case Type::TemplateSpecialization:
4650 case Type::ObjCObject:
4651 case Type::ObjCInterface:
4652 case Type::ObjCObjectPointer:
4653 case Type::ObjCTypeParam:
4654 case Type::Pipe:
4655 case Type::BitInt:
4656 llvm_unreachable("type class is never variably-modified!");
4657 case Type::Elaborated:
4658 T = cast<ElaboratedType>(Ty)->getNamedType();
4659 break;
4660 case Type::Adjusted:
4661 T = cast<AdjustedType>(Ty)->getOriginalType();
4662 break;
4663 case Type::Decayed:
4664 T = cast<DecayedType>(Ty)->getPointeeType();
4665 break;
4666 case Type::Pointer:
4667 T = cast<PointerType>(Ty)->getPointeeType();
4668 break;
4669 case Type::BlockPointer:
4670 T = cast<BlockPointerType>(Ty)->getPointeeType();
4671 break;
4672 case Type::LValueReference:
4673 case Type::RValueReference:
4674 T = cast<ReferenceType>(Ty)->getPointeeType();
4675 break;
4676 case Type::MemberPointer:
4677 T = cast<MemberPointerType>(Ty)->getPointeeType();
4678 break;
4679 case Type::ConstantArray:
4680 case Type::IncompleteArray:
4681 // Losing element qualification here is fine.
4682 T = cast<ArrayType>(Ty)->getElementType();
4683 break;
4684 case Type::VariableArray: {
4685 // Losing element qualification here is fine.
4686 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4687
4688 // Unknown size indication requires no size computation.
4689 // Otherwise, evaluate and record it.
4690 auto Size = VAT->getSizeExpr();
4691 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4692 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4693 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4694
4695 T = VAT->getElementType();
4696 break;
4697 }
4698 case Type::FunctionProto:
4699 case Type::FunctionNoProto:
4700 T = cast<FunctionType>(Ty)->getReturnType();
4701 break;
4702 case Type::Paren:
4703 case Type::TypeOf:
4704 case Type::UnaryTransform:
4705 case Type::Attributed:
4706 case Type::BTFTagAttributed:
4707 case Type::SubstTemplateTypeParm:
4708 case Type::MacroQualified:
4709 // Keep walking after single level desugaring.
4710 T = T.getSingleStepDesugaredType(Context);
4711 break;
4712 case Type::Typedef:
4713 T = cast<TypedefType>(Ty)->desugar();
4714 break;
4715 case Type::Decltype:
4716 T = cast<DecltypeType>(Ty)->desugar();
4717 break;
4718 case Type::PackIndexing:
4719 T = cast<PackIndexingType>(Ty)->desugar();
4720 break;
4721 case Type::Using:
4722 T = cast<UsingType>(Ty)->desugar();
4723 break;
4724 case Type::Auto:
4725 case Type::DeducedTemplateSpecialization:
4726 T = cast<DeducedType>(Ty)->getDeducedType();
4727 break;
4728 case Type::TypeOfExpr:
4729 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4730 break;
4731 case Type::Atomic:
4732 T = cast<AtomicType>(Ty)->getValueType();
4733 break;
4734 }
4735 } while (!T.isNull() && T->isVariablyModifiedType());
4736}
4737
4738/// Check the constraints on operands to unary expression and type
4739/// traits.
4740///
4741/// This will complete any types necessary, and validate the various constraints
4742/// on those operands.
4743///
4744/// The UsualUnaryConversions() function is *not* called by this routine.
4745/// C99 6.3.2.1p[2-4] all state:
4746/// Except when it is the operand of the sizeof operator ...
4747///
4748/// C++ [expr.sizeof]p4
4749/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4750/// standard conversions are not applied to the operand of sizeof.
4751///
4752/// This policy is followed for all of the unary trait expressions.
4753bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4754 SourceLocation OpLoc,
4755 SourceRange ExprRange,
4756 UnaryExprOrTypeTrait ExprKind,
4757 StringRef KWName) {
4758 if (ExprType->isDependentType())
4759 return false;
4760
4761 // C++ [expr.sizeof]p2:
4762 // When applied to a reference or a reference type, the result
4763 // is the size of the referenced type.
4764 // C++11 [expr.alignof]p3:
4765 // When alignof is applied to a reference type, the result
4766 // shall be the alignment of the referenced type.
4767 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4768 ExprType = Ref->getPointeeType();
4769
4770 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4771 // When alignof or _Alignof is applied to an array type, the result
4772 // is the alignment of the element type.
4773 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4774 ExprKind == UETT_OpenMPRequiredSimdAlign)
4775 ExprType = Context.getBaseElementType(QT: ExprType);
4776
4777 if (ExprKind == UETT_VecStep)
4778 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4779
4780 if (ExprKind == UETT_VectorElements)
4781 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4782 ArgRange: ExprRange);
4783
4784 // Explicitly list some types as extensions.
4785 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4786 TraitKind: ExprKind))
4787 return false;
4788
4789 if (RequireCompleteSizedType(
4790 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4791 KWName, ExprRange))
4792 return true;
4793
4794 if (ExprType->isFunctionType()) {
4795 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4796 return true;
4797 }
4798
4799 // WebAssembly tables are always illegal operands to unary expressions and
4800 // type traits.
4801 if (Context.getTargetInfo().getTriple().isWasm() &&
4802 ExprType->isWebAssemblyTableType()) {
4803 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4804 << getTraitSpelling(ExprKind);
4805 return true;
4806 }
4807
4808 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4809 TraitKind: ExprKind))
4810 return true;
4811
4812 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4813 if (auto *TT = ExprType->getAs<TypedefType>()) {
4814 for (auto I = FunctionScopes.rbegin(),
4815 E = std::prev(x: FunctionScopes.rend());
4816 I != E; ++I) {
4817 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4818 if (CSI == nullptr)
4819 break;
4820 DeclContext *DC = nullptr;
4821 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4822 DC = LSI->CallOperator;
4823 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4824 DC = CRSI->TheCapturedDecl;
4825 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4826 DC = BSI->TheDecl;
4827 if (DC) {
4828 if (DC->containsDecl(TT->getDecl()))
4829 break;
4830 captureVariablyModifiedType(Context, T: ExprType, CSI);
4831 }
4832 }
4833 }
4834 }
4835
4836 return false;
4837}
4838
4839/// Build a sizeof or alignof expression given a type operand.
4840ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4841 SourceLocation OpLoc,
4842 UnaryExprOrTypeTrait ExprKind,
4843 SourceRange R) {
4844 if (!TInfo)
4845 return ExprError();
4846
4847 QualType T = TInfo->getType();
4848
4849 if (!T->isDependentType() &&
4850 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4851 KWName: getTraitSpelling(T: ExprKind)))
4852 return ExprError();
4853
4854 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4855 // properly deal with VLAs in nested calls of sizeof and typeof.
4856 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4857 TInfo->getType()->isVariablyModifiedType())
4858 TInfo = TransformToPotentiallyEvaluated(TInfo);
4859
4860 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4861 return new (Context) UnaryExprOrTypeTraitExpr(
4862 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4863}
4864
4865/// Build a sizeof or alignof expression given an expression
4866/// operand.
4867ExprResult
4868Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4869 UnaryExprOrTypeTrait ExprKind) {
4870 ExprResult PE = CheckPlaceholderExpr(E);
4871 if (PE.isInvalid())
4872 return ExprError();
4873
4874 E = PE.get();
4875
4876 // Verify that the operand is valid.
4877 bool isInvalid = false;
4878 if (E->isTypeDependent()) {
4879 // Delay type-checking for type-dependent expressions.
4880 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4881 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4882 } else if (ExprKind == UETT_VecStep) {
4883 isInvalid = CheckVecStepExpr(E);
4884 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4885 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4886 isInvalid = true;
4887 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4888 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4889 isInvalid = true;
4890 } else if (ExprKind == UETT_VectorElements) {
4891 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VectorElements);
4892 } else {
4893 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_SizeOf);
4894 }
4895
4896 if (isInvalid)
4897 return ExprError();
4898
4899 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4900 PE = TransformToPotentiallyEvaluated(E);
4901 if (PE.isInvalid()) return ExprError();
4902 E = PE.get();
4903 }
4904
4905 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4906 return new (Context) UnaryExprOrTypeTraitExpr(
4907 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4908}
4909
4910/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4911/// expr and the same for @c alignof and @c __alignof
4912/// Note that the ArgRange is invalid if isType is false.
4913ExprResult
4914Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4915 UnaryExprOrTypeTrait ExprKind, bool IsType,
4916 void *TyOrEx, SourceRange ArgRange) {
4917 // If error parsing type, ignore.
4918 if (!TyOrEx) return ExprError();
4919
4920 if (IsType) {
4921 TypeSourceInfo *TInfo;
4922 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4923 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4924 }
4925
4926 Expr *ArgEx = (Expr *)TyOrEx;
4927 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4928 return Result;
4929}
4930
4931bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4932 SourceLocation OpLoc, SourceRange R) {
4933 if (!TInfo)
4934 return true;
4935 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4936 ExprKind: UETT_AlignOf, KWName);
4937}
4938
4939/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4940/// _Alignas(type-name) .
4941/// [dcl.align] An alignment-specifier of the form
4942/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4943///
4944/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4945/// _Alignas(_Alignof(type-name)).
4946bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4947 SourceLocation OpLoc, SourceRange R) {
4948 TypeSourceInfo *TInfo;
4949 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4950 TInfo: &TInfo);
4951 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4952}
4953
4954static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4955 bool IsReal) {
4956 if (V.get()->isTypeDependent())
4957 return S.Context.DependentTy;
4958
4959 // _Real and _Imag are only l-values for normal l-values.
4960 if (V.get()->getObjectKind() != OK_Ordinary) {
4961 V = S.DefaultLvalueConversion(E: V.get());
4962 if (V.isInvalid())
4963 return QualType();
4964 }
4965
4966 // These operators return the element type of a complex type.
4967 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4968 return CT->getElementType();
4969
4970 // Otherwise they pass through real integer and floating point types here.
4971 if (V.get()->getType()->isArithmeticType())
4972 return V.get()->getType();
4973
4974 // Test for placeholders.
4975 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4976 if (PR.isInvalid()) return QualType();
4977 if (PR.get() != V.get()) {
4978 V = PR;
4979 return CheckRealImagOperand(S, V, Loc, IsReal);
4980 }
4981
4982 // Reject anything else.
4983 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4984 << (IsReal ? "__real" : "__imag");
4985 return QualType();
4986}
4987
4988
4989
4990ExprResult
4991Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4992 tok::TokenKind Kind, Expr *Input) {
4993 UnaryOperatorKind Opc;
4994 switch (Kind) {
4995 default: llvm_unreachable("Unknown unary op!");
4996 case tok::plusplus: Opc = UO_PostInc; break;
4997 case tok::minusminus: Opc = UO_PostDec; break;
4998 }
4999
5000 // Since this might is a postfix expression, get rid of ParenListExprs.
5001 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
5002 if (Result.isInvalid()) return ExprError();
5003 Input = Result.get();
5004
5005 return BuildUnaryOp(S, OpLoc, Opc, Input);
5006}
5007
5008/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5009///
5010/// \return true on error
5011static bool checkArithmeticOnObjCPointer(Sema &S,
5012 SourceLocation opLoc,
5013 Expr *op) {
5014 assert(op->getType()->isObjCObjectPointerType());
5015 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5016 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5017 return false;
5018
5019 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5020 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5021 << op->getSourceRange();
5022 return true;
5023}
5024
5025static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5026 auto *BaseNoParens = Base->IgnoreParens();
5027 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5028 return MSProp->getPropertyDecl()->getType()->isArrayType();
5029 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5030}
5031
5032// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5033// Typically this is DependentTy, but can sometimes be more precise.
5034//
5035// There are cases when we could determine a non-dependent type:
5036// - LHS and RHS may have non-dependent types despite being type-dependent
5037// (e.g. unbounded array static members of the current instantiation)
5038// - one may be a dependent-sized array with known element type
5039// - one may be a dependent-typed valid index (enum in current instantiation)
5040//
5041// We *always* return a dependent type, in such cases it is DependentTy.
5042// This avoids creating type-dependent expressions with non-dependent types.
5043// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5044static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5045 const ASTContext &Ctx) {
5046 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5047 QualType LTy = LHS->getType(), RTy = RHS->getType();
5048 QualType Result = Ctx.DependentTy;
5049 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5050 if (const PointerType *PT = LTy->getAs<PointerType>())
5051 Result = PT->getPointeeType();
5052 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5053 Result = AT->getElementType();
5054 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5055 if (const PointerType *PT = RTy->getAs<PointerType>())
5056 Result = PT->getPointeeType();
5057 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5058 Result = AT->getElementType();
5059 }
5060 // Ensure we return a dependent type.
5061 return Result->isDependentType() ? Result : Ctx.DependentTy;
5062}
5063
5064ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5065 SourceLocation lbLoc,
5066 MultiExprArg ArgExprs,
5067 SourceLocation rbLoc) {
5068
5069 if (base && !base->getType().isNull() &&
5070 base->hasPlaceholderType(K: BuiltinType::OMPArraySection))
5071 return ActOnOMPArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(),
5072 ColonLocSecond: SourceLocation(), /*Length*/ nullptr,
5073 /*Stride=*/nullptr, RBLoc: rbLoc);
5074
5075 // Since this might be a postfix expression, get rid of ParenListExprs.
5076 if (isa<ParenListExpr>(Val: base)) {
5077 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5078 if (result.isInvalid())
5079 return ExprError();
5080 base = result.get();
5081 }
5082
5083 // Check if base and idx form a MatrixSubscriptExpr.
5084 //
5085 // Helper to check for comma expressions, which are not allowed as indices for
5086 // matrix subscript expressions.
5087 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5088 if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) {
5089 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5090 << SourceRange(base->getBeginLoc(), rbLoc);
5091 return true;
5092 }
5093 return false;
5094 };
5095 // The matrix subscript operator ([][])is considered a single operator.
5096 // Separating the index expressions by parenthesis is not allowed.
5097 if (base && !base->getType().isNull() &&
5098 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5099 !isa<MatrixSubscriptExpr>(Val: base)) {
5100 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5101 << SourceRange(base->getBeginLoc(), rbLoc);
5102 return ExprError();
5103 }
5104 // If the base is a MatrixSubscriptExpr, try to create a new
5105 // MatrixSubscriptExpr.
5106 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5107 if (matSubscriptE) {
5108 assert(ArgExprs.size() == 1);
5109 if (CheckAndReportCommaError(ArgExprs.front()))
5110 return ExprError();
5111
5112 assert(matSubscriptE->isIncomplete() &&
5113 "base has to be an incomplete matrix subscript");
5114 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5115 RowIdx: matSubscriptE->getRowIdx(),
5116 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5117 }
5118 if (base->getType()->isWebAssemblyTableType()) {
5119 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5120 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5121 return ExprError();
5122 }
5123
5124 // Handle any non-overload placeholder types in the base and index
5125 // expressions. We can't handle overloads here because the other
5126 // operand might be an overloadable type, in which case the overload
5127 // resolution for the operator overload should get the first crack
5128 // at the overload.
5129 bool IsMSPropertySubscript = false;
5130 if (base->getType()->isNonOverloadPlaceholderType()) {
5131 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5132 if (!IsMSPropertySubscript) {
5133 ExprResult result = CheckPlaceholderExpr(E: base);
5134 if (result.isInvalid())
5135 return ExprError();
5136 base = result.get();
5137 }
5138 }
5139
5140 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5141 if (base->getType()->isMatrixType()) {
5142 assert(ArgExprs.size() == 1);
5143 if (CheckAndReportCommaError(ArgExprs.front()))
5144 return ExprError();
5145
5146 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5147 RBLoc: rbLoc);
5148 }
5149
5150 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5151 Expr *idx = ArgExprs[0];
5152 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5153 (isa<CXXOperatorCallExpr>(Val: idx) &&
5154 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5155 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5156 << SourceRange(base->getBeginLoc(), rbLoc);
5157 }
5158 }
5159
5160 if (ArgExprs.size() == 1 &&
5161 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5162 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5163 if (result.isInvalid())
5164 return ExprError();
5165 ArgExprs[0] = result.get();
5166 } else {
5167 if (CheckArgsForPlaceholders(args: ArgExprs))
5168 return ExprError();
5169 }
5170
5171 // Build an unanalyzed expression if either operand is type-dependent.
5172 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5173 (base->isTypeDependent() ||
5174 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5175 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5176 return new (Context) ArraySubscriptExpr(
5177 base, ArgExprs.front(),
5178 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5179 VK_LValue, OK_Ordinary, rbLoc);
5180 }
5181
5182 // MSDN, property (C++)
5183 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5184 // This attribute can also be used in the declaration of an empty array in a
5185 // class or structure definition. For example:
5186 // __declspec(property(get=GetX, put=PutX)) int x[];
5187 // The above statement indicates that x[] can be used with one or more array
5188 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5189 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5190 if (IsMSPropertySubscript) {
5191 assert(ArgExprs.size() == 1);
5192 // Build MS property subscript expression if base is MS property reference
5193 // or MS property subscript.
5194 return new (Context)
5195 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5196 VK_LValue, OK_Ordinary, rbLoc);
5197 }
5198
5199 // Use C++ overloaded-operator rules if either operand has record
5200 // type. The spec says to do this if either type is *overloadable*,
5201 // but enum types can't declare subscript operators or conversion
5202 // operators, so there's nothing interesting for overload resolution
5203 // to do if there aren't any record types involved.
5204 //
5205 // ObjC pointers have their own subscripting logic that is not tied
5206 // to overload resolution and so should not take this path.
5207 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5208 ((base->getType()->isRecordType() ||
5209 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5210 ArgExprs[0]->getType()->isRecordType())))) {
5211 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5212 }
5213
5214 ExprResult Res =
5215 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5216
5217 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5218 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5219
5220 return Res;
5221}
5222
5223ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5224 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5225 InitializationKind Kind =
5226 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5227 InitializationSequence InitSeq(*this, Entity, Kind, E);
5228 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5229}
5230
5231ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5232 Expr *ColumnIdx,
5233 SourceLocation RBLoc) {
5234 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5235 if (BaseR.isInvalid())
5236 return BaseR;
5237 Base = BaseR.get();
5238
5239 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5240 if (RowR.isInvalid())
5241 return RowR;
5242 RowIdx = RowR.get();
5243
5244 if (!ColumnIdx)
5245 return new (Context) MatrixSubscriptExpr(
5246 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5247
5248 // Build an unanalyzed expression if any of the operands is type-dependent.
5249 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5250 ColumnIdx->isTypeDependent())
5251 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5252 Context.DependentTy, RBLoc);
5253
5254 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5255 if (ColumnR.isInvalid())
5256 return ColumnR;
5257 ColumnIdx = ColumnR.get();
5258
5259 // Check that IndexExpr is an integer expression. If it is a constant
5260 // expression, check that it is less than Dim (= the number of elements in the
5261 // corresponding dimension).
5262 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5263 bool IsColumnIdx) -> Expr * {
5264 if (!IndexExpr->getType()->isIntegerType() &&
5265 !IndexExpr->isTypeDependent()) {
5266 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5267 << IsColumnIdx;
5268 return nullptr;
5269 }
5270
5271 if (std::optional<llvm::APSInt> Idx =
5272 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5273 if ((*Idx < 0 || *Idx >= Dim)) {
5274 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5275 << IsColumnIdx << Dim;
5276 return nullptr;
5277 }
5278 }
5279
5280 ExprResult ConvExpr =
5281 tryConvertExprToType(E: IndexExpr, Ty: Context.getSizeType());
5282 assert(!ConvExpr.isInvalid() &&
5283 "should be able to convert any integer type to size type");
5284 return ConvExpr.get();
5285 };
5286
5287 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5288 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5289 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5290 if (!RowIdx || !ColumnIdx)
5291 return ExprError();
5292
5293 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5294 MTy->getElementType(), RBLoc);
5295}
5296
5297void Sema::CheckAddressOfNoDeref(const Expr *E) {
5298 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5299 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5300
5301 // For expressions like `&(*s).b`, the base is recorded and what should be
5302 // checked.
5303 const MemberExpr *Member = nullptr;
5304 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5305 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5306
5307 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5308}
5309
5310void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5311 if (isUnevaluatedContext())
5312 return;
5313
5314 QualType ResultTy = E->getType();
5315 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5316
5317 // Bail if the element is an array since it is not memory access.
5318 if (isa<ArrayType>(Val: ResultTy))
5319 return;
5320
5321 if (ResultTy->hasAttr(attr::NoDeref)) {
5322 LastRecord.PossibleDerefs.insert(E);
5323 return;
5324 }
5325
5326 // Check if the base type is a pointer to a member access of a struct
5327 // marked with noderef.
5328 const Expr *Base = E->getBase();
5329 QualType BaseTy = Base->getType();
5330 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5331 // Not a pointer access
5332 return;
5333
5334 const MemberExpr *Member = nullptr;
5335 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5336 Member->isArrow())
5337 Base = Member->getBase();
5338
5339 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5340 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5341 LastRecord.PossibleDerefs.insert(E);
5342 }
5343}
5344
5345ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5346 Expr *LowerBound,
5347 SourceLocation ColonLocFirst,
5348 SourceLocation ColonLocSecond,
5349 Expr *Length, Expr *Stride,
5350 SourceLocation RBLoc) {
5351 if (Base->hasPlaceholderType() &&
5352 !Base->hasPlaceholderType(K: BuiltinType::OMPArraySection)) {
5353 ExprResult Result = CheckPlaceholderExpr(E: Base);
5354 if (Result.isInvalid())
5355 return ExprError();
5356 Base = Result.get();
5357 }
5358 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5359 ExprResult Result = CheckPlaceholderExpr(E: LowerBound);
5360 if (Result.isInvalid())
5361 return ExprError();
5362 Result = DefaultLvalueConversion(E: Result.get());
5363 if (Result.isInvalid())
5364 return ExprError();
5365 LowerBound = Result.get();
5366 }
5367 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5368 ExprResult Result = CheckPlaceholderExpr(E: Length);
5369 if (Result.isInvalid())
5370 return ExprError();
5371 Result = DefaultLvalueConversion(E: Result.get());
5372 if (Result.isInvalid())
5373 return ExprError();
5374 Length = Result.get();
5375 }
5376 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5377 ExprResult Result = CheckPlaceholderExpr(E: Stride);
5378 if (Result.isInvalid())
5379 return ExprError();
5380 Result = DefaultLvalueConversion(E: Result.get());
5381 if (Result.isInvalid())
5382 return ExprError();
5383 Stride = Result.get();
5384 }
5385
5386 // Build an unanalyzed expression if either operand is type-dependent.
5387 if (Base->isTypeDependent() ||
5388 (LowerBound &&
5389 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5390 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5391 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5392 return new (Context) OMPArraySectionExpr(
5393 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5394 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5395 }
5396
5397 // Perform default conversions.
5398 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5399 QualType ResultTy;
5400 if (OriginalTy->isAnyPointerType()) {
5401 ResultTy = OriginalTy->getPointeeType();
5402 } else if (OriginalTy->isArrayType()) {
5403 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5404 } else {
5405 return ExprError(
5406 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5407 << Base->getSourceRange());
5408 }
5409 // C99 6.5.2.1p1
5410 if (LowerBound) {
5411 auto Res = PerformOpenMPImplicitIntegerConversion(OpLoc: LowerBound->getExprLoc(),
5412 Op: LowerBound);
5413 if (Res.isInvalid())
5414 return ExprError(Diag(LowerBound->getExprLoc(),
5415 diag::err_omp_typecheck_section_not_integer)
5416 << 0 << LowerBound->getSourceRange());
5417 LowerBound = Res.get();
5418
5419 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5420 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5421 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5422 << 0 << LowerBound->getSourceRange();
5423 }
5424 if (Length) {
5425 auto Res =
5426 PerformOpenMPImplicitIntegerConversion(OpLoc: Length->getExprLoc(), Op: Length);
5427 if (Res.isInvalid())
5428 return ExprError(Diag(Length->getExprLoc(),
5429 diag::err_omp_typecheck_section_not_integer)
5430 << 1 << Length->getSourceRange());
5431 Length = Res.get();
5432
5433 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5434 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5435 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5436 << 1 << Length->getSourceRange();
5437 }
5438 if (Stride) {
5439 ExprResult Res =
5440 PerformOpenMPImplicitIntegerConversion(OpLoc: Stride->getExprLoc(), Op: Stride);
5441 if (Res.isInvalid())
5442 return ExprError(Diag(Stride->getExprLoc(),
5443 diag::err_omp_typecheck_section_not_integer)
5444 << 1 << Stride->getSourceRange());
5445 Stride = Res.get();
5446
5447 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5448 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5449 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5450 << 1 << Stride->getSourceRange();
5451 }
5452
5453 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5454 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5455 // type. Note that functions are not objects, and that (in C99 parlance)
5456 // incomplete types are not object types.
5457 if (ResultTy->isFunctionType()) {
5458 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5459 << ResultTy << Base->getSourceRange();
5460 return ExprError();
5461 }
5462
5463 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5464 diag::err_omp_section_incomplete_type, Base))
5465 return ExprError();
5466
5467 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5468 Expr::EvalResult Result;
5469 if (LowerBound->EvaluateAsInt(Result, Ctx: Context)) {
5470 // OpenMP 5.0, [2.1.5 Array Sections]
5471 // The array section must be a subset of the original array.
5472 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5473 if (LowerBoundValue.isNegative()) {
5474 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5475 << LowerBound->getSourceRange();
5476 return ExprError();
5477 }
5478 }
5479 }
5480
5481 if (Length) {
5482 Expr::EvalResult Result;
5483 if (Length->EvaluateAsInt(Result, Ctx: Context)) {
5484 // OpenMP 5.0, [2.1.5 Array Sections]
5485 // The length must evaluate to non-negative integers.
5486 llvm::APSInt LengthValue = Result.Val.getInt();
5487 if (LengthValue.isNegative()) {
5488 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5489 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5490 << Length->getSourceRange();
5491 return ExprError();
5492 }
5493 }
5494 } else if (ColonLocFirst.isValid() &&
5495 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5496 !OriginalTy->isVariableArrayType()))) {
5497 // OpenMP 5.0, [2.1.5 Array Sections]
5498 // When the size of the array dimension is not known, the length must be
5499 // specified explicitly.
5500 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5501 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5502 return ExprError();
5503 }
5504
5505 if (Stride) {
5506 Expr::EvalResult Result;
5507 if (Stride->EvaluateAsInt(Result, Ctx: Context)) {
5508 // OpenMP 5.0, [2.1.5 Array Sections]
5509 // The stride must evaluate to a positive integer.
5510 llvm::APSInt StrideValue = Result.Val.getInt();
5511 if (!StrideValue.isStrictlyPositive()) {
5512 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5513 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5514 << Stride->getSourceRange();
5515 return ExprError();
5516 }
5517 }
5518 }
5519
5520 if (!Base->hasPlaceholderType(K: BuiltinType::OMPArraySection)) {
5521 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: Base);
5522 if (Result.isInvalid())
5523 return ExprError();
5524 Base = Result.get();
5525 }
5526 return new (Context) OMPArraySectionExpr(
5527 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5528 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5529}
5530
5531ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5532 SourceLocation RParenLoc,
5533 ArrayRef<Expr *> Dims,
5534 ArrayRef<SourceRange> Brackets) {
5535 if (Base->hasPlaceholderType()) {
5536 ExprResult Result = CheckPlaceholderExpr(E: Base);
5537 if (Result.isInvalid())
5538 return ExprError();
5539 Result = DefaultLvalueConversion(E: Result.get());
5540 if (Result.isInvalid())
5541 return ExprError();
5542 Base = Result.get();
5543 }
5544 QualType BaseTy = Base->getType();
5545 // Delay analysis of the types/expressions if instantiation/specialization is
5546 // required.
5547 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5548 return OMPArrayShapingExpr::Create(Context, T: Context.DependentTy, Op: Base,
5549 L: LParenLoc, R: RParenLoc, Dims, BracketRanges: Brackets);
5550 if (!BaseTy->isPointerType() ||
5551 (!Base->isTypeDependent() &&
5552 BaseTy->getPointeeType()->isIncompleteType()))
5553 return ExprError(Diag(Base->getExprLoc(),
5554 diag::err_omp_non_pointer_type_array_shaping_base)
5555 << Base->getSourceRange());
5556
5557 SmallVector<Expr *, 4> NewDims;
5558 bool ErrorFound = false;
5559 for (Expr *Dim : Dims) {
5560 if (Dim->hasPlaceholderType()) {
5561 ExprResult Result = CheckPlaceholderExpr(E: Dim);
5562 if (Result.isInvalid()) {
5563 ErrorFound = true;
5564 continue;
5565 }
5566 Result = DefaultLvalueConversion(E: Result.get());
5567 if (Result.isInvalid()) {
5568 ErrorFound = true;
5569 continue;
5570 }
5571 Dim = Result.get();
5572 }
5573 if (!Dim->isTypeDependent()) {
5574 ExprResult Result =
5575 PerformOpenMPImplicitIntegerConversion(OpLoc: Dim->getExprLoc(), Op: Dim);
5576 if (Result.isInvalid()) {
5577 ErrorFound = true;
5578 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5579 << Dim->getSourceRange();
5580 continue;
5581 }
5582 Dim = Result.get();
5583 Expr::EvalResult EvResult;
5584 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(Result&: EvResult, Ctx: Context)) {
5585 // OpenMP 5.0, [2.1.4 Array Shaping]
5586 // Each si is an integral type expression that must evaluate to a
5587 // positive integer.
5588 llvm::APSInt Value = EvResult.Val.getInt();
5589 if (!Value.isStrictlyPositive()) {
5590 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5591 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5592 << Dim->getSourceRange();
5593 ErrorFound = true;
5594 continue;
5595 }
5596 }
5597 }
5598 NewDims.push_back(Elt: Dim);
5599 }
5600 if (ErrorFound)
5601 return ExprError();
5602 return OMPArrayShapingExpr::Create(Context, T: Context.OMPArrayShapingTy, Op: Base,
5603 L: LParenLoc, R: RParenLoc, Dims: NewDims, BracketRanges: Brackets);
5604}
5605
5606ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5607 SourceLocation LLoc, SourceLocation RLoc,
5608 ArrayRef<OMPIteratorData> Data) {
5609 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5610 bool IsCorrect = true;
5611 for (const OMPIteratorData &D : Data) {
5612 TypeSourceInfo *TInfo = nullptr;
5613 SourceLocation StartLoc;
5614 QualType DeclTy;
5615 if (!D.Type.getAsOpaquePtr()) {
5616 // OpenMP 5.0, 2.1.6 Iterators
5617 // In an iterator-specifier, if the iterator-type is not specified then
5618 // the type of that iterator is of int type.
5619 DeclTy = Context.IntTy;
5620 StartLoc = D.DeclIdentLoc;
5621 } else {
5622 DeclTy = GetTypeFromParser(Ty: D.Type, TInfo: &TInfo);
5623 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5624 }
5625
5626 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5627 DeclTy->containsUnexpandedParameterPack() ||
5628 DeclTy->isInstantiationDependentType();
5629 if (!IsDeclTyDependent) {
5630 if (!DeclTy->isIntegralType(Ctx: Context) && !DeclTy->isAnyPointerType()) {
5631 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5632 // The iterator-type must be an integral or pointer type.
5633 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5634 << DeclTy;
5635 IsCorrect = false;
5636 continue;
5637 }
5638 if (DeclTy.isConstant(Ctx: Context)) {
5639 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5640 // The iterator-type must not be const qualified.
5641 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5642 << DeclTy;
5643 IsCorrect = false;
5644 continue;
5645 }
5646 }
5647
5648 // Iterator declaration.
5649 assert(D.DeclIdent && "Identifier expected.");
5650 // Always try to create iterator declarator to avoid extra error messages
5651 // about unknown declarations use.
5652 auto *VD = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: D.DeclIdentLoc,
5653 Id: D.DeclIdent, T: DeclTy, TInfo, S: SC_None);
5654 VD->setImplicit();
5655 if (S) {
5656 // Check for conflicting previous declaration.
5657 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5658 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5659 ForVisibleRedeclaration);
5660 Previous.suppressDiagnostics();
5661 LookupName(R&: Previous, S);
5662
5663 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
5664 /*AllowInlineNamespace=*/false);
5665 if (!Previous.empty()) {
5666 NamedDecl *Old = Previous.getRepresentativeDecl();
5667 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5668 Diag(Old->getLocation(), diag::note_previous_definition);
5669 } else {
5670 PushOnScopeChains(VD, S);
5671 }
5672 } else {
5673 CurContext->addDecl(VD);
5674 }
5675
5676 /// Act on the iterator variable declaration.
5677 ActOnOpenMPIteratorVarDecl(VD);
5678
5679 Expr *Begin = D.Range.Begin;
5680 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5681 ExprResult BeginRes =
5682 PerformImplicitConversion(From: Begin, ToType: DeclTy, Action: AA_Converting);
5683 Begin = BeginRes.get();
5684 }
5685 Expr *End = D.Range.End;
5686 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5687 ExprResult EndRes = PerformImplicitConversion(From: End, ToType: DeclTy, Action: AA_Converting);
5688 End = EndRes.get();
5689 }
5690 Expr *Step = D.Range.Step;
5691 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5692 if (!Step->getType()->isIntegralType(Ctx: Context)) {
5693 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5694 << Step << Step->getSourceRange();
5695 IsCorrect = false;
5696 continue;
5697 }
5698 std::optional<llvm::APSInt> Result =
5699 Step->getIntegerConstantExpr(Ctx: Context);
5700 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5701 // If the step expression of a range-specification equals zero, the
5702 // behavior is unspecified.
5703 if (Result && Result->isZero()) {
5704 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5705 << Step << Step->getSourceRange();
5706 IsCorrect = false;
5707 continue;
5708 }
5709 }
5710 if (!Begin || !End || !IsCorrect) {
5711 IsCorrect = false;
5712 continue;
5713 }
5714 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5715 IDElem.IteratorDecl = VD;
5716 IDElem.AssignmentLoc = D.AssignLoc;
5717 IDElem.Range.Begin = Begin;
5718 IDElem.Range.End = End;
5719 IDElem.Range.Step = Step;
5720 IDElem.ColonLoc = D.ColonLoc;
5721 IDElem.SecondColonLoc = D.SecColonLoc;
5722 }
5723 if (!IsCorrect) {
5724 // Invalidate all created iterator declarations if error is found.
5725 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5726 if (Decl *ID = D.IteratorDecl)
5727 ID->setInvalidDecl();
5728 }
5729 return ExprError();
5730 }
5731 SmallVector<OMPIteratorHelperData, 4> Helpers;
5732 if (!CurContext->isDependentContext()) {
5733 // Build number of ityeration for each iteration range.
5734 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5735 // ((Begini-Stepi-1-Endi) / -Stepi);
5736 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5737 // (Endi - Begini)
5738 ExprResult Res = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Sub, LHSExpr: D.Range.End,
5739 RHSExpr: D.Range.Begin);
5740 if(!Res.isUsable()) {
5741 IsCorrect = false;
5742 continue;
5743 }
5744 ExprResult St, St1;
5745 if (D.Range.Step) {
5746 St = D.Range.Step;
5747 // (Endi - Begini) + Stepi
5748 Res = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Add, LHSExpr: Res.get(), RHSExpr: St.get());
5749 if (!Res.isUsable()) {
5750 IsCorrect = false;
5751 continue;
5752 }
5753 // (Endi - Begini) + Stepi - 1
5754 Res =
5755 CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Sub, LHSExpr: Res.get(),
5756 RHSExpr: ActOnIntegerConstant(Loc: D.AssignmentLoc, Val: 1).get());
5757 if (!Res.isUsable()) {
5758 IsCorrect = false;
5759 continue;
5760 }
5761 // ((Endi - Begini) + Stepi - 1) / Stepi
5762 Res = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Div, LHSExpr: Res.get(), RHSExpr: St.get());
5763 if (!Res.isUsable()) {
5764 IsCorrect = false;
5765 continue;
5766 }
5767 St1 = CreateBuiltinUnaryOp(OpLoc: D.AssignmentLoc, Opc: UO_Minus, InputExpr: D.Range.Step);
5768 // (Begini - Endi)
5769 ExprResult Res1 = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Sub,
5770 LHSExpr: D.Range.Begin, RHSExpr: D.Range.End);
5771 if (!Res1.isUsable()) {
5772 IsCorrect = false;
5773 continue;
5774 }
5775 // (Begini - Endi) - Stepi
5776 Res1 =
5777 CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Add, LHSExpr: Res1.get(), RHSExpr: St1.get());
5778 if (!Res1.isUsable()) {
5779 IsCorrect = false;
5780 continue;
5781 }
5782 // (Begini - Endi) - Stepi - 1
5783 Res1 =
5784 CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Sub, LHSExpr: Res1.get(),
5785 RHSExpr: ActOnIntegerConstant(Loc: D.AssignmentLoc, Val: 1).get());
5786 if (!Res1.isUsable()) {
5787 IsCorrect = false;
5788 continue;
5789 }
5790 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5791 Res1 =
5792 CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Div, LHSExpr: Res1.get(), RHSExpr: St1.get());
5793 if (!Res1.isUsable()) {
5794 IsCorrect = false;
5795 continue;
5796 }
5797 // Stepi > 0.
5798 ExprResult CmpRes =
5799 CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_GT, LHSExpr: D.Range.Step,
5800 RHSExpr: ActOnIntegerConstant(Loc: D.AssignmentLoc, Val: 0).get());
5801 if (!CmpRes.isUsable()) {
5802 IsCorrect = false;
5803 continue;
5804 }
5805 Res = ActOnConditionalOp(QuestionLoc: D.AssignmentLoc, ColonLoc: D.AssignmentLoc, CondExpr: CmpRes.get(),
5806 LHSExpr: Res.get(), RHSExpr: Res1.get());
5807 if (!Res.isUsable()) {
5808 IsCorrect = false;
5809 continue;
5810 }
5811 }
5812 Res = ActOnFinishFullExpr(Expr: Res.get(), /*DiscardedValue=*/false);
5813 if (!Res.isUsable()) {
5814 IsCorrect = false;
5815 continue;
5816 }
5817
5818 // Build counter update.
5819 // Build counter.
5820 auto *CounterVD =
5821 VarDecl::Create(C&: Context, DC: CurContext, StartLoc: D.IteratorDecl->getBeginLoc(),
5822 IdLoc: D.IteratorDecl->getBeginLoc(), Id: nullptr,
5823 T: Res.get()->getType(), TInfo: nullptr, S: SC_None);
5824 CounterVD->setImplicit();
5825 ExprResult RefRes =
5826 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5827 D.IteratorDecl->getBeginLoc());
5828 // Build counter update.
5829 // I = Begini + counter * Stepi;
5830 ExprResult UpdateRes;
5831 if (D.Range.Step) {
5832 UpdateRes = CreateBuiltinBinOp(
5833 OpLoc: D.AssignmentLoc, Opc: BO_Mul,
5834 LHSExpr: DefaultLvalueConversion(E: RefRes.get()).get(), RHSExpr: St.get());
5835 } else {
5836 UpdateRes = DefaultLvalueConversion(E: RefRes.get());
5837 }
5838 if (!UpdateRes.isUsable()) {
5839 IsCorrect = false;
5840 continue;
5841 }
5842 UpdateRes = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Add, LHSExpr: D.Range.Begin,
5843 RHSExpr: UpdateRes.get());
5844 if (!UpdateRes.isUsable()) {
5845 IsCorrect = false;
5846 continue;
5847 }
5848 ExprResult VDRes =
5849 BuildDeclRefExpr(cast<VarDecl>(Val: D.IteratorDecl),
5850 cast<VarDecl>(Val: D.IteratorDecl)->getType(), VK_LValue,
5851 D.IteratorDecl->getBeginLoc());
5852 UpdateRes = CreateBuiltinBinOp(OpLoc: D.AssignmentLoc, Opc: BO_Assign, LHSExpr: VDRes.get(),
5853 RHSExpr: UpdateRes.get());
5854 if (!UpdateRes.isUsable()) {
5855 IsCorrect = false;
5856 continue;
5857 }
5858 UpdateRes =
5859 ActOnFinishFullExpr(Expr: UpdateRes.get(), /*DiscardedValue=*/true);
5860 if (!UpdateRes.isUsable()) {
5861 IsCorrect = false;
5862 continue;
5863 }
5864 ExprResult CounterUpdateRes =
5865 CreateBuiltinUnaryOp(OpLoc: D.AssignmentLoc, Opc: UO_PreInc, InputExpr: RefRes.get());
5866 if (!CounterUpdateRes.isUsable()) {
5867 IsCorrect = false;
5868 continue;
5869 }
5870 CounterUpdateRes =
5871 ActOnFinishFullExpr(Expr: CounterUpdateRes.get(), /*DiscardedValue=*/true);
5872 if (!CounterUpdateRes.isUsable()) {
5873 IsCorrect = false;
5874 continue;
5875 }
5876 OMPIteratorHelperData &HD = Helpers.emplace_back();
5877 HD.CounterVD = CounterVD;
5878 HD.Upper = Res.get();
5879 HD.Update = UpdateRes.get();
5880 HD.CounterUpdate = CounterUpdateRes.get();
5881 }
5882 } else {
5883 Helpers.assign(NumElts: ID.size(), Elt: {});
5884 }
5885 if (!IsCorrect) {
5886 // Invalidate all created iterator declarations if error is found.
5887 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5888 if (Decl *ID = D.IteratorDecl)
5889 ID->setInvalidDecl();
5890 }
5891 return ExprError();
5892 }
5893 return OMPIteratorExpr::Create(Context, T: Context.OMPIteratorTy, IteratorKwLoc,
5894 L: LLoc, R: RLoc, Data: ID, Helpers);
5895}
5896
5897ExprResult
5898Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5899 Expr *Idx, SourceLocation RLoc) {
5900 Expr *LHSExp = Base;
5901 Expr *RHSExp = Idx;
5902
5903 ExprValueKind VK = VK_LValue;
5904 ExprObjectKind OK = OK_Ordinary;
5905
5906 // Per C++ core issue 1213, the result is an xvalue if either operand is
5907 // a non-lvalue array, and an lvalue otherwise.
5908 if (getLangOpts().CPlusPlus11) {
5909 for (auto *Op : {LHSExp, RHSExp}) {
5910 Op = Op->IgnoreImplicit();
5911 if (Op->getType()->isArrayType() && !Op->isLValue())
5912 VK = VK_XValue;
5913 }
5914 }
5915
5916 // Perform default conversions.
5917 if (!LHSExp->getType()->getAs<VectorType>()) {
5918 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5919 if (Result.isInvalid())
5920 return ExprError();
5921 LHSExp = Result.get();
5922 }
5923 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5924 if (Result.isInvalid())
5925 return ExprError();
5926 RHSExp = Result.get();
5927
5928 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5929
5930 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5931 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5932 // in the subscript position. As a result, we need to derive the array base
5933 // and index from the expression types.
5934 Expr *BaseExpr, *IndexExpr;
5935 QualType ResultType;
5936 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5937 BaseExpr = LHSExp;
5938 IndexExpr = RHSExp;
5939 ResultType =
5940 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5941 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5942 BaseExpr = LHSExp;
5943 IndexExpr = RHSExp;
5944 ResultType = PTy->getPointeeType();
5945 } else if (const ObjCObjectPointerType *PTy =
5946 LHSTy->getAs<ObjCObjectPointerType>()) {
5947 BaseExpr = LHSExp;
5948 IndexExpr = RHSExp;
5949
5950 // Use custom logic if this should be the pseudo-object subscript
5951 // expression.
5952 if (!LangOpts.isSubscriptPointerArithmetic())
5953 return BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr, getterMethod: nullptr,
5954 setterMethod: nullptr);
5955
5956 ResultType = PTy->getPointeeType();
5957 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5958 // Handle the uncommon case of "123[Ptr]".
5959 BaseExpr = RHSExp;
5960 IndexExpr = LHSExp;
5961 ResultType = PTy->getPointeeType();
5962 } else if (const ObjCObjectPointerType *PTy =
5963 RHSTy->getAs<ObjCObjectPointerType>()) {
5964 // Handle the uncommon case of "123[Ptr]".
5965 BaseExpr = RHSExp;
5966 IndexExpr = LHSExp;
5967 ResultType = PTy->getPointeeType();
5968 if (!LangOpts.isSubscriptPointerArithmetic()) {
5969 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5970 << ResultType << BaseExpr->getSourceRange();
5971 return ExprError();
5972 }
5973 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5974 BaseExpr = LHSExp; // vectors: V[123]
5975 IndexExpr = RHSExp;
5976 // We apply C++ DR1213 to vector subscripting too.
5977 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5978 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5979 if (Materialized.isInvalid())
5980 return ExprError();
5981 LHSExp = Materialized.get();
5982 }
5983 VK = LHSExp->getValueKind();
5984 if (VK != VK_PRValue)
5985 OK = OK_VectorComponent;
5986
5987 ResultType = VTy->getElementType();
5988 QualType BaseType = BaseExpr->getType();
5989 Qualifiers BaseQuals = BaseType.getQualifiers();
5990 Qualifiers MemberQuals = ResultType.getQualifiers();
5991 Qualifiers Combined = BaseQuals + MemberQuals;
5992 if (Combined != MemberQuals)
5993 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5994 } else if (LHSTy->isBuiltinType() &&
5995 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5996 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5997 if (BTy->isSVEBool())
5998 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5999 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
6000
6001 BaseExpr = LHSExp;
6002 IndexExpr = RHSExp;
6003 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
6004 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
6005 if (Materialized.isInvalid())
6006 return ExprError();
6007 LHSExp = Materialized.get();
6008 }
6009 VK = LHSExp->getValueKind();
6010 if (VK != VK_PRValue)
6011 OK = OK_VectorComponent;
6012
6013 ResultType = BTy->getSveEltType(Context);
6014
6015 QualType BaseType = BaseExpr->getType();
6016 Qualifiers BaseQuals = BaseType.getQualifiers();
6017 Qualifiers MemberQuals = ResultType.getQualifiers();
6018 Qualifiers Combined = BaseQuals + MemberQuals;
6019 if (Combined != MemberQuals)
6020 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
6021 } else if (LHSTy->isArrayType()) {
6022 // If we see an array that wasn't promoted by
6023 // DefaultFunctionArrayLvalueConversion, it must be an array that
6024 // wasn't promoted because of the C90 rule that doesn't
6025 // allow promoting non-lvalue arrays. Warn, then
6026 // force the promotion here.
6027 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6028 << LHSExp->getSourceRange();
6029 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
6030 CK: CK_ArrayToPointerDecay).get();
6031 LHSTy = LHSExp->getType();
6032
6033 BaseExpr = LHSExp;
6034 IndexExpr = RHSExp;
6035 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
6036 } else if (RHSTy->isArrayType()) {
6037 // Same as previous, except for 123[f().a] case
6038 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6039 << RHSExp->getSourceRange();
6040 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
6041 CK: CK_ArrayToPointerDecay).get();
6042 RHSTy = RHSExp->getType();
6043
6044 BaseExpr = RHSExp;
6045 IndexExpr = LHSExp;
6046 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
6047 } else {
6048 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
6049 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
6050 }
6051 // C99 6.5.2.1p1
6052 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
6053 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
6054 << IndexExpr->getSourceRange());
6055
6056 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
6057 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
6058 !IndexExpr->isTypeDependent()) {
6059 std::optional<llvm::APSInt> IntegerContantExpr =
6060 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
6061 if (!IntegerContantExpr.has_value() ||
6062 IntegerContantExpr.value().isNegative())
6063 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
6064 }
6065
6066 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
6067 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
6068 // type. Note that Functions are not objects, and that (in C99 parlance)
6069 // incomplete types are not object types.
6070 if (ResultType->isFunctionType()) {
6071 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
6072 << ResultType << BaseExpr->getSourceRange();
6073 return ExprError();
6074 }
6075
6076 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
6077 // GNU extension: subscripting on pointer to void
6078 Diag(LLoc, diag::ext_gnu_subscript_void_type)
6079 << BaseExpr->getSourceRange();
6080
6081 // C forbids expressions of unqualified void type from being l-values.
6082 // See IsCForbiddenLValueType.
6083 if (!ResultType.hasQualifiers())
6084 VK = VK_PRValue;
6085 } else if (!ResultType->isDependentType() &&
6086 !ResultType.isWebAssemblyReferenceType() &&
6087 RequireCompleteSizedType(
6088 LLoc, ResultType,
6089 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
6090 return ExprError();
6091
6092 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
6093 !ResultType.isCForbiddenLValueType());
6094
6095 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
6096 FunctionScopes.size() > 1) {
6097 if (auto *TT =
6098 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
6099 for (auto I = FunctionScopes.rbegin(),
6100 E = std::prev(x: FunctionScopes.rend());
6101 I != E; ++I) {
6102 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
6103 if (CSI == nullptr)
6104 break;
6105 DeclContext *DC = nullptr;
6106 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
6107 DC = LSI->CallOperator;
6108 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
6109 DC = CRSI->TheCapturedDecl;
6110 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
6111 DC = BSI->TheDecl;
6112 if (DC) {
6113 if (DC->containsDecl(TT->getDecl()))
6114 break;
6115 captureVariablyModifiedType(
6116 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
6117 }
6118 }
6119 }
6120 }
6121
6122 return new (Context)
6123 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
6124}
6125
6126bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6127 ParmVarDecl *Param, Expr *RewrittenInit,
6128 bool SkipImmediateInvocations) {
6129 if (Param->hasUnparsedDefaultArg()) {
6130 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
6131 // If we've already cleared out the location for the default argument,
6132 // that means we're parsing it right now.
6133 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
6134 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
6135 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
6136 Param->setInvalidDecl();
6137 return true;
6138 }
6139
6140 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
6141 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
6142 Diag(UnparsedDefaultArgLocs[Param],
6143 diag::note_default_argument_declared_here);
6144 return true;
6145 }
6146
6147 if (Param->hasUninstantiatedDefaultArg()) {
6148 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
6149 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6150 return true;
6151 }
6152
6153 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
6154 assert(Init && "default argument but no initializer?");
6155
6156 // If the default expression creates temporaries, we need to
6157 // push them to the current stack of expression temporaries so they'll
6158 // be properly destroyed.
6159 // FIXME: We should really be rebuilding the default argument with new
6160 // bound temporaries; see the comment in PR5810.
6161 // We don't need to do that with block decls, though, because
6162 // blocks in default argument expression can never capture anything.
6163 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
6164 // Set the "needs cleanups" bit regardless of whether there are
6165 // any explicit objects.
6166 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
6167 // Append all the objects to the cleanup list. Right now, this
6168 // should always be a no-op, because blocks in default argument
6169 // expressions should never be able to capture anything.
6170 assert(!InitWithCleanup->getNumObjects() &&
6171 "default argument expression has capturing blocks?");
6172 }
6173 // C++ [expr.const]p15.1:
6174 // An expression or conversion is in an immediate function context if it is
6175 // potentially evaluated and [...] its innermost enclosing non-block scope
6176 // is a function parameter scope of an immediate function.
6177 EnterExpressionEvaluationContext EvalContext(
6178 *this,
6179 FD->isImmediateFunction()
6180 ? ExpressionEvaluationContext::ImmediateFunctionContext
6181 : ExpressionEvaluationContext::PotentiallyEvaluated,
6182 Param);
6183 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6184 SkipImmediateInvocations;
6185 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
6186 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
6187 });
6188 return false;
6189}
6190
6191struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
6192 const ASTContext &Context;
6193 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
6194
6195 bool HasImmediateCalls = false;
6196 bool shouldVisitImplicitCode() const { return true; }
6197
6198 bool VisitCallExpr(CallExpr *E) {
6199 if (const FunctionDecl *FD = E->getDirectCallee())
6200 HasImmediateCalls |= FD->isImmediateFunction();
6201 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6202 }
6203
6204 // SourceLocExpr are not immediate invocations
6205 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6206 // need to be rebuilt so that they refer to the correct SourceLocation and
6207 // DeclContext.
6208 bool VisitSourceLocExpr(SourceLocExpr *E) {
6209 HasImmediateCalls = true;
6210 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6211 }
6212
6213 // A nested lambda might have parameters with immediate invocations
6214 // in their default arguments.
6215 // The compound statement is not visited (as it does not constitute a
6216 // subexpression).
6217 // FIXME: We should consider visiting and transforming captures
6218 // with init expressions.
6219 bool VisitLambdaExpr(LambdaExpr *E) {
6220 return VisitCXXMethodDecl(E->getCallOperator());
6221 }
6222
6223 // Blocks don't support default parameters, and, as for lambdas,
6224 // we don't consider their body a subexpression.
6225 bool VisitBlockDecl(BlockDecl *B) { return false; }
6226
6227 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
6228
6229 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6230 return TraverseStmt(E->getExpr());
6231 }
6232
6233 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
6234 return TraverseStmt(E->getExpr());
6235 }
6236};
6237
6238struct EnsureImmediateInvocationInDefaultArgs
6239 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
6240 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
6241 : TreeTransform(SemaRef) {}
6242
6243 // Lambda can only have immediate invocations in the default
6244 // args of their parameters, which is transformed upon calling the closure.
6245 // The body is not a subexpression, so we have nothing to do.
6246 // FIXME: Immediate calls in capture initializers should be transformed.
6247 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
6248 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
6249
6250 // Make sure we don't rebuild the this pointer as it would
6251 // cause it to incorrectly point it to the outermost class
6252 // in the case of nested struct initialization.
6253 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
6254};
6255
6256ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6257 FunctionDecl *FD, ParmVarDecl *Param,
6258 Expr *Init) {
6259 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
6260
6261 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6262 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
6263 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6264 InitializationContext =
6265 OutermostDeclarationWithDelayedImmediateInvocations();
6266 if (!InitializationContext.has_value())
6267 InitializationContext.emplace(CallLoc, Param, CurContext);
6268
6269 if (!Init && !Param->hasUnparsedDefaultArg()) {
6270 // Mark that we are replacing a default argument first.
6271 // If we are instantiating a template we won't have to
6272 // retransform immediate calls.
6273 // C++ [expr.const]p15.1:
6274 // An expression or conversion is in an immediate function context if it
6275 // is potentially evaluated and [...] its innermost enclosing non-block
6276 // scope is a function parameter scope of an immediate function.
6277 EnterExpressionEvaluationContext EvalContext(
6278 *this,
6279 FD->isImmediateFunction()
6280 ? ExpressionEvaluationContext::ImmediateFunctionContext
6281 : ExpressionEvaluationContext::PotentiallyEvaluated,
6282 Param);
6283
6284 if (Param->hasUninstantiatedDefaultArg()) {
6285 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6286 return ExprError();
6287 }
6288 // CWG2631
6289 // An immediate invocation that is not evaluated where it appears is
6290 // evaluated and checked for whether it is a constant expression at the
6291 // point where the enclosing initializer is used in a function call.
6292 ImmediateCallVisitor V(getASTContext());
6293 if (!NestedDefaultChecking)
6294 V.TraverseDecl(Param);
6295
6296 // Rewrite the call argument that was created from the corresponding
6297 // parameter's default argument.
6298 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
6299 if (V.HasImmediateCalls)
6300 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6301 CallLoc, Param, CurContext};
6302 // Pass down lifetime extending flag, and collect temporaries in
6303 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
6304 keepInLifetimeExtendingContext();
6305 keepInMaterializeTemporaryObjectContext();
6306 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6307 ExprResult Res;
6308 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
6309 Res = Immediate.TransformInitializer(Param->getInit(),
6310 /*NotCopy=*/false);
6311 });
6312 if (Res.isInvalid())
6313 return ExprError();
6314 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
6315 EqualLoc: Res.get()->getBeginLoc());
6316 if (Res.isInvalid())
6317 return ExprError();
6318 Init = Res.get();
6319 }
6320 }
6321
6322 if (CheckCXXDefaultArgExpr(
6323 CallLoc, FD, Param, RewrittenInit: Init,
6324 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6325 return ExprError();
6326
6327 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
6328 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
6329}
6330
6331ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6332 assert(Field->hasInClassInitializer());
6333
6334 // If we might have already tried and failed to instantiate, don't try again.
6335 if (Field->isInvalidDecl())
6336 return ExprError();
6337
6338 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6339
6340 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
6341
6342 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6343 InitializationContext =
6344 OutermostDeclarationWithDelayedImmediateInvocations();
6345 if (!InitializationContext.has_value())
6346 InitializationContext.emplace(Loc, Field, CurContext);
6347
6348 Expr *Init = nullptr;
6349
6350 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6351
6352 EnterExpressionEvaluationContext EvalContext(
6353 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6354
6355 if (!Field->getInClassInitializer()) {
6356 // Maybe we haven't instantiated the in-class initializer. Go check the
6357 // pattern FieldDecl to see if it has one.
6358 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
6359 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6360 DeclContext::lookup_result Lookup =
6361 ClassPattern->lookup(Name: Field->getDeclName());
6362
6363 FieldDecl *Pattern = nullptr;
6364 for (auto *L : Lookup) {
6365 if ((Pattern = dyn_cast<FieldDecl>(L)))
6366 break;
6367 }
6368 assert(Pattern && "We must have set the Pattern!");
6369 if (!Pattern->hasInClassInitializer() ||
6370 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
6371 TemplateArgs: getTemplateInstantiationArgs(Field))) {
6372 Field->setInvalidDecl();
6373 return ExprError();
6374 }
6375 }
6376 }
6377
6378 // CWG2631
6379 // An immediate invocation that is not evaluated where it appears is
6380 // evaluated and checked for whether it is a constant expression at the
6381 // point where the enclosing initializer is used in a [...] a constructor
6382 // definition, or an aggregate initialization.
6383 ImmediateCallVisitor V(getASTContext());
6384 if (!NestedDefaultChecking)
6385 V.TraverseDecl(Field);
6386 if (V.HasImmediateCalls) {
6387 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6388 CurContext};
6389 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6390 NestedDefaultChecking;
6391
6392 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6393 ExprResult Res;
6394 runWithSufficientStackSpace(Loc, Fn: [&] {
6395 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6396 /*CXXDirectInit=*/false);
6397 });
6398 if (!Res.isInvalid())
6399 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
6400 if (Res.isInvalid()) {
6401 Field->setInvalidDecl();
6402 return ExprError();
6403 }
6404 Init = Res.get();
6405 }
6406
6407 if (Field->getInClassInitializer()) {
6408 Expr *E = Init ? Init : Field->getInClassInitializer();
6409 if (!NestedDefaultChecking)
6410 runWithSufficientStackSpace(Loc, Fn: [&] {
6411 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6412 });
6413 // C++11 [class.base.init]p7:
6414 // The initialization of each base and member constitutes a
6415 // full-expression.
6416 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
6417 if (Res.isInvalid()) {
6418 Field->setInvalidDecl();
6419 return ExprError();
6420 }
6421 Init = Res.get();
6422
6423 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
6424 Field, UsedContext: InitializationContext->Context,
6425 RewrittenInitExpr: Init);
6426 }
6427
6428 // DR1351:
6429 // If the brace-or-equal-initializer of a non-static data member
6430 // invokes a defaulted default constructor of its class or of an
6431 // enclosing class in a potentially evaluated subexpression, the
6432 // program is ill-formed.
6433 //
6434 // This resolution is unworkable: the exception specification of the
6435 // default constructor can be needed in an unevaluated context, in
6436 // particular, in the operand of a noexcept-expression, and we can be
6437 // unable to compute an exception specification for an enclosed class.
6438 //
6439 // Any attempt to resolve the exception specification of a defaulted default
6440 // constructor before the initializer is lexically complete will ultimately
6441 // come here at which point we can diagnose it.
6442 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6443 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6444 << OutermostClass << Field;
6445 Diag(Field->getEndLoc(),
6446 diag::note_default_member_initializer_not_yet_parsed);
6447 // Recover by marking the field invalid, unless we're in a SFINAE context.
6448 if (!isSFINAEContext())
6449 Field->setInvalidDecl();
6450 return ExprError();
6451}
6452
6453Sema::VariadicCallType
6454Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6455 Expr *Fn) {
6456 if (Proto && Proto->isVariadic()) {
6457 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6458 return VariadicConstructor;
6459 else if (Fn && Fn->getType()->isBlockPointerType())
6460 return VariadicBlock;
6461 else if (FDecl) {
6462 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6463 if (Method->isInstance())
6464 return VariadicMethod;
6465 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6466 return VariadicMethod;
6467 return VariadicFunction;
6468 }
6469 return VariadicDoesNotApply;
6470}
6471
6472namespace {
6473class FunctionCallCCC final : public FunctionCallFilterCCC {
6474public:
6475 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6476 unsigned NumArgs, MemberExpr *ME)
6477 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6478 FunctionName(FuncName) {}
6479
6480 bool ValidateCandidate(const TypoCorrection &candidate) override {
6481 if (!candidate.getCorrectionSpecifier() ||
6482 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6483 return false;
6484 }
6485
6486 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6487 }
6488
6489 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6490 return std::make_unique<FunctionCallCCC>(args&: *this);
6491 }
6492
6493private:
6494 const IdentifierInfo *const FunctionName;
6495};
6496}
6497
6498static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6499 FunctionDecl *FDecl,
6500 ArrayRef<Expr *> Args) {
6501 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6502 DeclarationName FuncName = FDecl->getDeclName();
6503 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6504
6505 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6506 if (TypoCorrection Corrected = S.CorrectTypo(
6507 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6508 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6509 Mode: Sema::CTK_ErrorRecovery)) {
6510 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6511 if (Corrected.isOverloaded()) {
6512 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6513 OverloadCandidateSet::iterator Best;
6514 for (NamedDecl *CD : Corrected) {
6515 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6516 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6517 OCS);
6518 }
6519 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6520 case OR_Success:
6521 ND = Best->FoundDecl;
6522 Corrected.setCorrectionDecl(ND);
6523 break;
6524 default:
6525 break;
6526 }
6527 }
6528 ND = ND->getUnderlyingDecl();
6529 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6530 return Corrected;
6531 }
6532 }
6533 return TypoCorrection();
6534}
6535
6536/// ConvertArgumentsForCall - Converts the arguments specified in
6537/// Args/NumArgs to the parameter types of the function FDecl with
6538/// function prototype Proto. Call is the call expression itself, and
6539/// Fn is the function expression. For a C++ member function, this
6540/// routine does not attempt to convert the object argument. Returns
6541/// true if the call is ill-formed.
6542bool
6543Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6544 FunctionDecl *FDecl,
6545 const FunctionProtoType *Proto,
6546 ArrayRef<Expr *> Args,
6547 SourceLocation RParenLoc,
6548 bool IsExecConfig) {
6549 // Bail out early if calling a builtin with custom typechecking.
6550 if (FDecl)
6551 if (unsigned ID = FDecl->getBuiltinID())
6552 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6553 return false;
6554
6555 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6556 // assignment, to the types of the corresponding parameter, ...
6557 bool HasExplicitObjectParameter =
6558 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6559 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6560 unsigned NumParams = Proto->getNumParams();
6561 bool Invalid = false;
6562 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6563 unsigned FnKind = Fn->getType()->isBlockPointerType()
6564 ? 1 /* block */
6565 : (IsExecConfig ? 3 /* kernel function (exec config) */
6566 : 0 /* function */);
6567
6568 // If too few arguments are available (and we don't have default
6569 // arguments for the remaining parameters), don't make the call.
6570 if (Args.size() < NumParams) {
6571 if (Args.size() < MinArgs) {
6572 TypoCorrection TC;
6573 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6574 unsigned diag_id =
6575 MinArgs == NumParams && !Proto->isVariadic()
6576 ? diag::err_typecheck_call_too_few_args_suggest
6577 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6578 diagnoseTypo(
6579 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6580 << FnKind << MinArgs - ExplicitObjectParameterOffset
6581 << static_cast<unsigned>(Args.size()) -
6582 ExplicitObjectParameterOffset
6583 << HasExplicitObjectParameter << TC.getCorrectionRange());
6584 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6585 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6586 ->getDeclName())
6587 Diag(RParenLoc,
6588 MinArgs == NumParams && !Proto->isVariadic()
6589 ? diag::err_typecheck_call_too_few_args_one
6590 : diag::err_typecheck_call_too_few_args_at_least_one)
6591 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6592 << HasExplicitObjectParameter << Fn->getSourceRange();
6593 else
6594 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6595 ? diag::err_typecheck_call_too_few_args
6596 : diag::err_typecheck_call_too_few_args_at_least)
6597 << FnKind << MinArgs - ExplicitObjectParameterOffset
6598 << static_cast<unsigned>(Args.size()) -
6599 ExplicitObjectParameterOffset
6600 << HasExplicitObjectParameter << Fn->getSourceRange();
6601
6602 // Emit the location of the prototype.
6603 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6604 Diag(FDecl->getLocation(), diag::note_callee_decl)
6605 << FDecl << FDecl->getParametersSourceRange();
6606
6607 return true;
6608 }
6609 // We reserve space for the default arguments when we create
6610 // the call expression, before calling ConvertArgumentsForCall.
6611 assert((Call->getNumArgs() == NumParams) &&
6612 "We should have reserved space for the default arguments before!");
6613 }
6614
6615 // If too many are passed and not variadic, error on the extras and drop
6616 // them.
6617 if (Args.size() > NumParams) {
6618 if (!Proto->isVariadic()) {
6619 TypoCorrection TC;
6620 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6621 unsigned diag_id =
6622 MinArgs == NumParams && !Proto->isVariadic()
6623 ? diag::err_typecheck_call_too_many_args_suggest
6624 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6625 diagnoseTypo(
6626 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6627 << FnKind << NumParams - ExplicitObjectParameterOffset
6628 << static_cast<unsigned>(Args.size()) -
6629 ExplicitObjectParameterOffset
6630 << HasExplicitObjectParameter << TC.getCorrectionRange());
6631 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6632 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6633 ->getDeclName())
6634 Diag(Args[NumParams]->getBeginLoc(),
6635 MinArgs == NumParams
6636 ? diag::err_typecheck_call_too_many_args_one
6637 : diag::err_typecheck_call_too_many_args_at_most_one)
6638 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6639 << static_cast<unsigned>(Args.size()) -
6640 ExplicitObjectParameterOffset
6641 << HasExplicitObjectParameter << Fn->getSourceRange()
6642 << SourceRange(Args[NumParams]->getBeginLoc(),
6643 Args.back()->getEndLoc());
6644 else
6645 Diag(Args[NumParams]->getBeginLoc(),
6646 MinArgs == NumParams
6647 ? diag::err_typecheck_call_too_many_args
6648 : diag::err_typecheck_call_too_many_args_at_most)
6649 << FnKind << NumParams - ExplicitObjectParameterOffset
6650 << static_cast<unsigned>(Args.size()) -
6651 ExplicitObjectParameterOffset
6652 << HasExplicitObjectParameter << Fn->getSourceRange()
6653 << SourceRange(Args[NumParams]->getBeginLoc(),
6654 Args.back()->getEndLoc());
6655
6656 // Emit the location of the prototype.
6657 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6658 Diag(FDecl->getLocation(), diag::note_callee_decl)
6659 << FDecl << FDecl->getParametersSourceRange();
6660
6661 // This deletes the extra arguments.
6662 Call->shrinkNumArgs(NewNumArgs: NumParams);
6663 return true;
6664 }
6665 }
6666 SmallVector<Expr *, 8> AllArgs;
6667 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6668
6669 Invalid = GatherArgumentsForCall(CallLoc: Call->getBeginLoc(), FDecl, Proto, FirstParam: 0, Args,
6670 AllArgs, CallType);
6671 if (Invalid)
6672 return true;
6673 unsigned TotalNumArgs = AllArgs.size();
6674 for (unsigned i = 0; i < TotalNumArgs; ++i)
6675 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6676
6677 Call->computeDependence();
6678 return false;
6679}
6680
6681bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6682 const FunctionProtoType *Proto,
6683 unsigned FirstParam, ArrayRef<Expr *> Args,
6684 SmallVectorImpl<Expr *> &AllArgs,
6685 VariadicCallType CallType, bool AllowExplicit,
6686 bool IsListInitialization) {
6687 unsigned NumParams = Proto->getNumParams();
6688 bool Invalid = false;
6689 size_t ArgIx = 0;
6690 // Continue to check argument types (even if we have too few/many args).
6691 for (unsigned i = FirstParam; i < NumParams; i++) {
6692 QualType ProtoArgType = Proto->getParamType(i);
6693
6694 Expr *Arg;
6695 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6696 if (ArgIx < Args.size()) {
6697 Arg = Args[ArgIx++];
6698
6699 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6700 diag::err_call_incomplete_argument, Arg))
6701 return true;
6702
6703 // Strip the unbridged-cast placeholder expression off, if applicable.
6704 bool CFAudited = false;
6705 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6706 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6707 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6708 Arg = stripARCUnbridgedCast(e: Arg);
6709 else if (getLangOpts().ObjCAutoRefCount &&
6710 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6711 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6712 CFAudited = true;
6713
6714 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6715 ProtoArgType->isBlockPointerType())
6716 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6717 BE->getBlockDecl()->setDoesNotEscape();
6718
6719 InitializedEntity Entity =
6720 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6721 Type: ProtoArgType)
6722 : InitializedEntity::InitializeParameter(
6723 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6724
6725 // Remember that parameter belongs to a CF audited API.
6726 if (CFAudited)
6727 Entity.setParameterCFAudited();
6728
6729 ExprResult ArgE = PerformCopyInitialization(
6730 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6731 if (ArgE.isInvalid())
6732 return true;
6733
6734 Arg = ArgE.getAs<Expr>();
6735 } else {
6736 assert(Param && "can't use default arguments without a known callee");
6737
6738 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6739 if (ArgExpr.isInvalid())
6740 return true;
6741
6742 Arg = ArgExpr.getAs<Expr>();
6743 }
6744
6745 // Check for array bounds violations for each argument to the call. This
6746 // check only triggers warnings when the argument isn't a more complex Expr
6747 // with its own checking, such as a BinaryOperator.
6748 CheckArrayAccess(E: Arg);
6749
6750 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6751 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6752
6753 AllArgs.push_back(Elt: Arg);
6754 }
6755
6756 // If this is a variadic call, handle args passed through "...".
6757 if (CallType != VariadicDoesNotApply) {
6758 // Assume that extern "C" functions with variadic arguments that
6759 // return __unknown_anytype aren't *really* variadic.
6760 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6761 FDecl->isExternC()) {
6762 for (Expr *A : Args.slice(N: ArgIx)) {
6763 QualType paramType; // ignored
6764 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6765 Invalid |= arg.isInvalid();
6766 AllArgs.push_back(Elt: arg.get());
6767 }
6768
6769 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6770 } else {
6771 for (Expr *A : Args.slice(N: ArgIx)) {
6772 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6773 Invalid |= Arg.isInvalid();
6774 AllArgs.push_back(Elt: Arg.get());
6775 }
6776 }
6777
6778 // Check for array bounds violations.
6779 for (Expr *A : Args.slice(N: ArgIx))
6780 CheckArrayAccess(E: A);
6781 }
6782 return Invalid;
6783}
6784
6785static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6786 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6787 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6788 TL = DTL.getOriginalLoc();
6789 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6790 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6791 << ATL.getLocalSourceRange();
6792}
6793
6794/// CheckStaticArrayArgument - If the given argument corresponds to a static
6795/// array parameter, check that it is non-null, and that if it is formed by
6796/// array-to-pointer decay, the underlying array is sufficiently large.
6797///
6798/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6799/// array type derivation, then for each call to the function, the value of the
6800/// corresponding actual argument shall provide access to the first element of
6801/// an array with at least as many elements as specified by the size expression.
6802void
6803Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6804 ParmVarDecl *Param,
6805 const Expr *ArgExpr) {
6806 // Static array parameters are not supported in C++.
6807 if (!Param || getLangOpts().CPlusPlus)
6808 return;
6809
6810 QualType OrigTy = Param->getOriginalType();
6811
6812 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6813 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6814 return;
6815
6816 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6817 NPC: Expr::NPC_NeverValueDependent)) {
6818 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6819 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6820 return;
6821 }
6822
6823 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6824 if (!CAT)
6825 return;
6826
6827 const ConstantArrayType *ArgCAT =
6828 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6829 if (!ArgCAT)
6830 return;
6831
6832 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6833 T2: ArgCAT->getElementType())) {
6834 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6835 Diag(CallLoc, diag::warn_static_array_too_small)
6836 << ArgExpr->getSourceRange()
6837 << (unsigned)ArgCAT->getSize().getZExtValue()
6838 << (unsigned)CAT->getSize().getZExtValue() << 0;
6839 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6840 }
6841 return;
6842 }
6843
6844 std::optional<CharUnits> ArgSize =
6845 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6846 std::optional<CharUnits> ParmSize =
6847 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6848 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6849 Diag(CallLoc, diag::warn_static_array_too_small)
6850 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6851 << (unsigned)ParmSize->getQuantity() << 1;
6852 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6853 }
6854}
6855
6856/// Given a function expression of unknown-any type, try to rebuild it
6857/// to have a function type.
6858static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6859
6860/// Is the given type a placeholder that we need to lower out
6861/// immediately during argument processing?
6862static bool isPlaceholderToRemoveAsArg(QualType type) {
6863 // Placeholders are never sugared.
6864 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6865 if (!placeholder) return false;
6866
6867 switch (placeholder->getKind()) {
6868 // Ignore all the non-placeholder types.
6869#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6870 case BuiltinType::Id:
6871#include "clang/Basic/OpenCLImageTypes.def"
6872#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6873 case BuiltinType::Id:
6874#include "clang/Basic/OpenCLExtensionTypes.def"
6875 // In practice we'll never use this, since all SVE types are sugared
6876 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6877#define SVE_TYPE(Name, Id, SingletonId) \
6878 case BuiltinType::Id:
6879#include "clang/Basic/AArch64SVEACLETypes.def"
6880#define PPC_VECTOR_TYPE(Name, Id, Size) \
6881 case BuiltinType::Id:
6882#include "clang/Basic/PPCTypes.def"
6883#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6884#include "clang/Basic/RISCVVTypes.def"
6885#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6886#include "clang/Basic/WebAssemblyReferenceTypes.def"
6887#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6888#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6889#include "clang/AST/BuiltinTypes.def"
6890 return false;
6891
6892 // We cannot lower out overload sets; they might validly be resolved
6893 // by the call machinery.
6894 case BuiltinType::Overload:
6895 return false;
6896
6897 // Unbridged casts in ARC can be handled in some call positions and
6898 // should be left in place.
6899 case BuiltinType::ARCUnbridgedCast:
6900 return false;
6901
6902 // Pseudo-objects should be converted as soon as possible.
6903 case BuiltinType::PseudoObject:
6904 return true;
6905
6906 // The debugger mode could theoretically but currently does not try
6907 // to resolve unknown-typed arguments based on known parameter types.
6908 case BuiltinType::UnknownAny:
6909 return true;
6910
6911 // These are always invalid as call arguments and should be reported.
6912 case BuiltinType::BoundMember:
6913 case BuiltinType::BuiltinFn:
6914 case BuiltinType::IncompleteMatrixIdx:
6915 case BuiltinType::OMPArraySection:
6916 case BuiltinType::OMPArrayShaping:
6917 case BuiltinType::OMPIterator:
6918 return true;
6919
6920 }
6921 llvm_unreachable("bad builtin type kind");
6922}
6923
6924bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6925 // Apply this processing to all the arguments at once instead of
6926 // dying at the first failure.
6927 bool hasInvalid = false;
6928 for (size_t i = 0, e = args.size(); i != e; i++) {
6929 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6930 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6931 if (result.isInvalid()) hasInvalid = true;
6932 else args[i] = result.get();
6933 }
6934 }
6935 return hasInvalid;
6936}
6937
6938/// If a builtin function has a pointer argument with no explicit address
6939/// space, then it should be able to accept a pointer to any address
6940/// space as input. In order to do this, we need to replace the
6941/// standard builtin declaration with one that uses the same address space
6942/// as the call.
6943///
6944/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6945/// it does not contain any pointer arguments without
6946/// an address space qualifer. Otherwise the rewritten
6947/// FunctionDecl is returned.
6948/// TODO: Handle pointer return types.
6949static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6950 FunctionDecl *FDecl,
6951 MultiExprArg ArgExprs) {
6952
6953 QualType DeclType = FDecl->getType();
6954 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6955
6956 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6957 ArgExprs.size() < FT->getNumParams())
6958 return nullptr;
6959
6960 bool NeedsNewDecl = false;
6961 unsigned i = 0;
6962 SmallVector<QualType, 8> OverloadParams;
6963
6964 for (QualType ParamType : FT->param_types()) {
6965
6966 // Convert array arguments to pointer to simplify type lookup.
6967 ExprResult ArgRes =
6968 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6969 if (ArgRes.isInvalid())
6970 return nullptr;
6971 Expr *Arg = ArgRes.get();
6972 QualType ArgType = Arg->getType();
6973 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6974 !ArgType->isPointerType() ||
6975 !ArgType->getPointeeType().hasAddressSpace() ||
6976 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6977 OverloadParams.push_back(ParamType);
6978 continue;
6979 }
6980
6981 QualType PointeeType = ParamType->getPointeeType();
6982 if (PointeeType.hasAddressSpace())
6983 continue;
6984
6985 NeedsNewDecl = true;
6986 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6987
6988 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6989 OverloadParams.push_back(Context.getPointerType(PointeeType));
6990 }
6991
6992 if (!NeedsNewDecl)
6993 return nullptr;
6994
6995 FunctionProtoType::ExtProtoInfo EPI;
6996 EPI.Variadic = FT->isVariadic();
6997 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6998 Args: OverloadParams, EPI);
6999 DeclContext *Parent = FDecl->getParent();
7000 FunctionDecl *OverloadDecl = FunctionDecl::Create(
7001 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
7002 FDecl->getIdentifier(), OverloadTy,
7003 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
7004 false,
7005 /*hasPrototype=*/true);
7006 SmallVector<ParmVarDecl*, 16> Params;
7007 FT = cast<FunctionProtoType>(Val&: OverloadTy);
7008 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
7009 QualType ParamType = FT->getParamType(i);
7010 ParmVarDecl *Parm =
7011 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
7012 SourceLocation(), nullptr, ParamType,
7013 /*TInfo=*/nullptr, SC_None, nullptr);
7014 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
7015 Params.push_back(Elt: Parm);
7016 }
7017 OverloadDecl->setParams(Params);
7018 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
7019 return OverloadDecl;
7020}
7021
7022static void checkDirectCallValidity(Sema &S, const Expr *Fn,
7023 FunctionDecl *Callee,
7024 MultiExprArg ArgExprs) {
7025 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
7026 // similar attributes) really don't like it when functions are called with an
7027 // invalid number of args.
7028 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
7029 /*PartialOverloading=*/false) &&
7030 !Callee->isVariadic())
7031 return;
7032 if (Callee->getMinRequiredArguments() > ArgExprs.size())
7033 return;
7034
7035 if (const EnableIfAttr *Attr =
7036 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
7037 S.Diag(Fn->getBeginLoc(),
7038 isa<CXXMethodDecl>(Callee)
7039 ? diag::err_ovl_no_viable_member_function_in_call
7040 : diag::err_ovl_no_viable_function_in_call)
7041 << Callee << Callee->getSourceRange();
7042 S.Diag(Callee->getLocation(),
7043 diag::note_ovl_candidate_disabled_by_function_cond_attr)
7044 << Attr->getCond()->getSourceRange() << Attr->getMessage();
7045 return;
7046 }
7047}
7048
7049static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
7050 const UnresolvedMemberExpr *const UME, Sema &S) {
7051
7052 const auto GetFunctionLevelDCIfCXXClass =
7053 [](Sema &S) -> const CXXRecordDecl * {
7054 const DeclContext *const DC = S.getFunctionLevelDeclContext();
7055 if (!DC || !DC->getParent())
7056 return nullptr;
7057
7058 // If the call to some member function was made from within a member
7059 // function body 'M' return return 'M's parent.
7060 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
7061 return MD->getParent()->getCanonicalDecl();
7062 // else the call was made from within a default member initializer of a
7063 // class, so return the class.
7064 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
7065 return RD->getCanonicalDecl();
7066 return nullptr;
7067 };
7068 // If our DeclContext is neither a member function nor a class (in the
7069 // case of a lambda in a default member initializer), we can't have an
7070 // enclosing 'this'.
7071
7072 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
7073 if (!CurParentClass)
7074 return false;
7075
7076 // The naming class for implicit member functions call is the class in which
7077 // name lookup starts.
7078 const CXXRecordDecl *const NamingClass =
7079 UME->getNamingClass()->getCanonicalDecl();
7080 assert(NamingClass && "Must have naming class even for implicit access");
7081
7082 // If the unresolved member functions were found in a 'naming class' that is
7083 // related (either the same or derived from) to the class that contains the
7084 // member function that itself contained the implicit member access.
7085
7086 return CurParentClass == NamingClass ||
7087 CurParentClass->isDerivedFrom(Base: NamingClass);
7088}
7089
7090static void
7091tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7092 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
7093
7094 if (!UME)
7095 return;
7096
7097 LambdaScopeInfo *const CurLSI = S.getCurLambda();
7098 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
7099 // already been captured, or if this is an implicit member function call (if
7100 // it isn't, an attempt to capture 'this' should already have been made).
7101 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
7102 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
7103 return;
7104
7105 // Check if the naming class in which the unresolved members were found is
7106 // related (same as or is a base of) to the enclosing class.
7107
7108 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
7109 return;
7110
7111
7112 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
7113 // If the enclosing function is not dependent, then this lambda is
7114 // capture ready, so if we can capture this, do so.
7115 if (!EnclosingFunctionCtx->isDependentContext()) {
7116 // If the current lambda and all enclosing lambdas can capture 'this' -
7117 // then go ahead and capture 'this' (since our unresolved overload set
7118 // contains at least one non-static member function).
7119 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
7120 S.CheckCXXThisCapture(Loc: CallLoc);
7121 } else if (S.CurContext->isDependentContext()) {
7122 // ... since this is an implicit member reference, that might potentially
7123 // involve a 'this' capture, mark 'this' for potential capture in
7124 // enclosing lambdas.
7125 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
7126 CurLSI->addPotentialThisCapture(Loc: CallLoc);
7127 }
7128}
7129
7130// Once a call is fully resolved, warn for unqualified calls to specific
7131// C++ standard functions, like move and forward.
7132static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
7133 const CallExpr *Call) {
7134 // We are only checking unary move and forward so exit early here.
7135 if (Call->getNumArgs() != 1)
7136 return;
7137
7138 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
7139 if (!E || isa<UnresolvedLookupExpr>(Val: E))
7140 return;
7141 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
7142 if (!DRE || !DRE->getLocation().isValid())
7143 return;
7144
7145 if (DRE->getQualifier())
7146 return;
7147
7148 const FunctionDecl *FD = Call->getDirectCallee();
7149 if (!FD)
7150 return;
7151
7152 // Only warn for some functions deemed more frequent or problematic.
7153 unsigned BuiltinID = FD->getBuiltinID();
7154 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7155 return;
7156
7157 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
7158 << FD->getQualifiedNameAsString()
7159 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
7160}
7161
7162ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7163 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7164 Expr *ExecConfig) {
7165 ExprResult Call =
7166 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7167 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7168 if (Call.isInvalid())
7169 return Call;
7170
7171 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7172 // language modes.
7173 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
7174 ULE && ULE->hasExplicitTemplateArgs() &&
7175 ULE->decls_begin() == ULE->decls_end()) {
7176 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
7177 ? diag::warn_cxx17_compat_adl_only_template_id
7178 : diag::ext_adl_only_template_id)
7179 << ULE->getName();
7180 }
7181
7182 if (LangOpts.OpenMP)
7183 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7184 ExecConfig);
7185 if (LangOpts.CPlusPlus) {
7186 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
7187 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
7188 }
7189 return Call;
7190}
7191
7192/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7193/// This provides the location of the left/right parens and a list of comma
7194/// locations.
7195ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7196 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7197 Expr *ExecConfig, bool IsExecConfig,
7198 bool AllowRecovery) {
7199 // Since this might be a postfix expression, get rid of ParenListExprs.
7200 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
7201 if (Result.isInvalid()) return ExprError();
7202 Fn = Result.get();
7203
7204 if (CheckArgsForPlaceholders(args: ArgExprs))
7205 return ExprError();
7206
7207 if (getLangOpts().CPlusPlus) {
7208 // If this is a pseudo-destructor expression, build the call immediately.
7209 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
7210 if (!ArgExprs.empty()) {
7211 // Pseudo-destructor calls should not have any arguments.
7212 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7213 << FixItHint::CreateRemoval(
7214 SourceRange(ArgExprs.front()->getBeginLoc(),
7215 ArgExprs.back()->getEndLoc()));
7216 }
7217
7218 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
7219 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7220 }
7221 if (Fn->getType() == Context.PseudoObjectTy) {
7222 ExprResult result = CheckPlaceholderExpr(E: Fn);
7223 if (result.isInvalid()) return ExprError();
7224 Fn = result.get();
7225 }
7226
7227 // Determine whether this is a dependent call inside a C++ template,
7228 // in which case we won't do any semantic analysis now.
7229 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
7230 if (ExecConfig) {
7231 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
7232 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
7233 Ty: Context.DependentTy, VK: VK_PRValue,
7234 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
7235 } else {
7236
7237 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7238 *this, dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
7239 Fn->getBeginLoc());
7240
7241 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7242 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7243 }
7244 }
7245
7246 // Determine whether this is a call to an object (C++ [over.call.object]).
7247 if (Fn->getType()->isRecordType())
7248 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
7249 RParenLoc);
7250
7251 if (Fn->getType() == Context.UnknownAnyTy) {
7252 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7253 if (result.isInvalid()) return ExprError();
7254 Fn = result.get();
7255 }
7256
7257 if (Fn->getType() == Context.BoundMemberTy) {
7258 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7259 RParenLoc, ExecConfig, IsExecConfig,
7260 AllowRecovery);
7261 }
7262 }
7263
7264 // Check for overloaded calls. This can happen even in C due to extensions.
7265 if (Fn->getType() == Context.OverloadTy) {
7266 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
7267
7268 // We aren't supposed to apply this logic if there's an '&' involved.
7269 if (!find.HasFormOfMemberPointer) {
7270 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
7271 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7272 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7273 OverloadExpr *ovl = find.Expression;
7274 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
7275 return BuildOverloadedCallExpr(
7276 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
7277 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
7278 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7279 RParenLoc, ExecConfig, IsExecConfig,
7280 AllowRecovery);
7281 }
7282 }
7283
7284 // If we're directly calling a function, get the appropriate declaration.
7285 if (Fn->getType() == Context.UnknownAnyTy) {
7286 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7287 if (result.isInvalid()) return ExprError();
7288 Fn = result.get();
7289 }
7290
7291 Expr *NakedFn = Fn->IgnoreParens();
7292
7293 bool CallingNDeclIndirectly = false;
7294 NamedDecl *NDecl = nullptr;
7295 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
7296 if (UnOp->getOpcode() == UO_AddrOf) {
7297 CallingNDeclIndirectly = true;
7298 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7299 }
7300 }
7301
7302 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
7303 NDecl = DRE->getDecl();
7304
7305 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
7306 if (FDecl && FDecl->getBuiltinID()) {
7307 // Rewrite the function decl for this builtin by replacing parameters
7308 // with no explicit address space with the address space of the arguments
7309 // in ArgExprs.
7310 if ((FDecl =
7311 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
7312 NDecl = FDecl;
7313 Fn = DeclRefExpr::Create(
7314 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7315 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7316 nullptr, DRE->isNonOdrUse());
7317 }
7318 }
7319 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
7320 NDecl = ME->getMemberDecl();
7321
7322 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7323 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7324 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7325 return ExprError();
7326
7327 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7328
7329 // If this expression is a call to a builtin function in HIP device
7330 // compilation, allow a pointer-type argument to default address space to be
7331 // passed as a pointer-type parameter to a non-default address space.
7332 // If Arg is declared in the default address space and Param is declared
7333 // in a non-default address space, perform an implicit address space cast to
7334 // the parameter type.
7335 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7336 FD->getBuiltinID()) {
7337 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7338 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7339 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7340 !ArgExprs[Idx]->getType()->isPointerType())
7341 continue;
7342
7343 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7344 auto ArgTy = ArgExprs[Idx]->getType();
7345 auto ArgPtTy = ArgTy->getPointeeType();
7346 auto ArgAS = ArgPtTy.getAddressSpace();
7347
7348 // Add address space cast if target address spaces are different
7349 bool NeedImplicitASC =
7350 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7351 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7352 // or from specific AS which has target AS matching that of Param.
7353 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7354 if (!NeedImplicitASC)
7355 continue;
7356
7357 // First, ensure that the Arg is an RValue.
7358 if (ArgExprs[Idx]->isGLValue()) {
7359 ArgExprs[Idx] = ImplicitCastExpr::Create(
7360 Context, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx],
7361 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7362 }
7363
7364 // Construct a new arg type with address space of Param
7365 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7366 ArgPtQuals.setAddressSpace(ParamAS);
7367 auto NewArgPtTy =
7368 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7369 auto NewArgTy =
7370 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7371 Qs: ArgTy.getQualifiers());
7372
7373 // Finally perform an implicit address space cast
7374 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7375 CK: CK_AddressSpaceConversion)
7376 .get();
7377 }
7378 }
7379 }
7380
7381 if (Context.isDependenceAllowed() &&
7382 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7383 assert(!getLangOpts().CPlusPlus);
7384 assert((Fn->containsErrors() ||
7385 llvm::any_of(ArgExprs,
7386 [](clang::Expr *E) { return E->containsErrors(); })) &&
7387 "should only occur in error-recovery path.");
7388 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7389 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7390 }
7391 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7392 Config: ExecConfig, IsExecConfig);
7393}
7394
7395/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7396// with the specified CallArgs
7397Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7398 MultiExprArg CallArgs) {
7399 StringRef Name = Context.BuiltinInfo.getName(ID: Id);
7400 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7401 Sema::LookupOrdinaryName);
7402 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7403
7404 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7405 assert(BuiltInDecl && "failed to find builtin declaration");
7406
7407 ExprResult DeclRef =
7408 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7409 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7410
7411 ExprResult Call =
7412 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7413
7414 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7415 return Call.get();
7416}
7417
7418/// Parse a __builtin_astype expression.
7419///
7420/// __builtin_astype( value, dst type )
7421///
7422ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7423 SourceLocation BuiltinLoc,
7424 SourceLocation RParenLoc) {
7425 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7426 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7427}
7428
7429/// Create a new AsTypeExpr node (bitcast) from the arguments.
7430ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7431 SourceLocation BuiltinLoc,
7432 SourceLocation RParenLoc) {
7433 ExprValueKind VK = VK_PRValue;
7434 ExprObjectKind OK = OK_Ordinary;
7435 QualType SrcTy = E->getType();
7436 if (!SrcTy->isDependentType() &&
7437 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7438 return ExprError(
7439 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7440 << DestTy << SrcTy << E->getSourceRange());
7441 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7442}
7443
7444/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7445/// provided arguments.
7446///
7447/// __builtin_convertvector( value, dst type )
7448///
7449ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7450 SourceLocation BuiltinLoc,
7451 SourceLocation RParenLoc) {
7452 TypeSourceInfo *TInfo;
7453 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7454 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7455}
7456
7457/// BuildResolvedCallExpr - Build a call to a resolved expression,
7458/// i.e. an expression not of \p OverloadTy. The expression should
7459/// unary-convert to an expression of function-pointer or
7460/// block-pointer type.
7461///
7462/// \param NDecl the declaration being called, if available
7463ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7464 SourceLocation LParenLoc,
7465 ArrayRef<Expr *> Args,
7466 SourceLocation RParenLoc, Expr *Config,
7467 bool IsExecConfig, ADLCallKind UsesADL) {
7468 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7469 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7470
7471 // Functions with 'interrupt' attribute cannot be called directly.
7472 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7473 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7474 return ExprError();
7475 }
7476
7477 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7478 // so there's some risk when calling out to non-interrupt handler functions
7479 // that the callee might not preserve them. This is easy to diagnose here,
7480 // but can be very challenging to debug.
7481 // Likewise, X86 interrupt handlers may only call routines with attribute
7482 // no_caller_saved_registers since there is no efficient way to
7483 // save and restore the non-GPR state.
7484 if (auto *Caller = getCurFunctionDecl()) {
7485 if (Caller->hasAttr<ARMInterruptAttr>()) {
7486 bool VFP = Context.getTargetInfo().hasFeature(Feature: "vfp");
7487 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7488 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7489 if (FDecl)
7490 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7491 }
7492 }
7493 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7494 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7495 const TargetInfo &TI = Context.getTargetInfo();
7496 bool HasNonGPRRegisters =
7497 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7498 if (HasNonGPRRegisters &&
7499 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7500 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7501 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7502 if (FDecl)
7503 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7504 }
7505 }
7506 }
7507
7508 // Promote the function operand.
7509 // We special-case function promotion here because we only allow promoting
7510 // builtin functions to function pointers in the callee of a call.
7511 ExprResult Result;
7512 QualType ResultTy;
7513 if (BuiltinID &&
7514 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7515 // Extract the return type from the (builtin) function pointer type.
7516 // FIXME Several builtins still have setType in
7517 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7518 // Builtins.td to ensure they are correct before removing setType calls.
7519 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7520 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7521 ResultTy = FDecl->getCallResultType();
7522 } else {
7523 Result = CallExprUnaryConversions(E: Fn);
7524 ResultTy = Context.BoolTy;
7525 }
7526 if (Result.isInvalid())
7527 return ExprError();
7528 Fn = Result.get();
7529
7530 // Check for a valid function type, but only if it is not a builtin which
7531 // requires custom type checking. These will be handled by
7532 // CheckBuiltinFunctionCall below just after creation of the call expression.
7533 const FunctionType *FuncT = nullptr;
7534 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7535 retry:
7536 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7537 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7538 // have type pointer to function".
7539 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7540 if (!FuncT)
7541 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7542 << Fn->getType() << Fn->getSourceRange());
7543 } else if (const BlockPointerType *BPT =
7544 Fn->getType()->getAs<BlockPointerType>()) {
7545 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7546 } else {
7547 // Handle calls to expressions of unknown-any type.
7548 if (Fn->getType() == Context.UnknownAnyTy) {
7549 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7550 if (rewrite.isInvalid())
7551 return ExprError();
7552 Fn = rewrite.get();
7553 goto retry;
7554 }
7555
7556 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7557 << Fn->getType() << Fn->getSourceRange());
7558 }
7559 }
7560
7561 // Get the number of parameters in the function prototype, if any.
7562 // We will allocate space for max(Args.size(), NumParams) arguments
7563 // in the call expression.
7564 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7565 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7566
7567 CallExpr *TheCall;
7568 if (Config) {
7569 assert(UsesADL == ADLCallKind::NotADL &&
7570 "CUDAKernelCallExpr should not use ADL");
7571 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7572 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7573 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7574 } else {
7575 TheCall =
7576 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7577 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7578 }
7579
7580 if (!Context.isDependenceAllowed()) {
7581 // Forget about the nulled arguments since typo correction
7582 // do not handle them well.
7583 TheCall->shrinkNumArgs(NewNumArgs: Args.size());
7584 // C cannot always handle TypoExpr nodes in builtin calls and direct
7585 // function calls as their argument checking don't necessarily handle
7586 // dependent types properly, so make sure any TypoExprs have been
7587 // dealt with.
7588 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7589 if (!Result.isUsable()) return ExprError();
7590 CallExpr *TheOldCall = TheCall;
7591 TheCall = dyn_cast<CallExpr>(Val: Result.get());
7592 bool CorrectedTypos = TheCall != TheOldCall;
7593 if (!TheCall) return Result;
7594 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7595
7596 // A new call expression node was created if some typos were corrected.
7597 // However it may not have been constructed with enough storage. In this
7598 // case, rebuild the node with enough storage. The waste of space is
7599 // immaterial since this only happens when some typos were corrected.
7600 if (CorrectedTypos && Args.size() < NumParams) {
7601 if (Config)
7602 TheCall = CUDAKernelCallExpr::Create(
7603 Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), Args, Ty: ResultTy, VK: VK_PRValue,
7604 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7605 else
7606 TheCall =
7607 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7608 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7609 }
7610 // We can now handle the nulled arguments for the default arguments.
7611 TheCall->setNumArgsUnsafe(std::max<unsigned>(a: Args.size(), b: NumParams));
7612 }
7613
7614 // Bail out early if calling a builtin with custom type checking.
7615 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID))
7616 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7617
7618 if (getLangOpts().CUDA) {
7619 if (Config) {
7620 // CUDA: Kernel calls must be to global functions
7621 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7622 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7623 << FDecl << Fn->getSourceRange());
7624
7625 // CUDA: Kernel function must have 'void' return type
7626 if (!FuncT->getReturnType()->isVoidType() &&
7627 !FuncT->getReturnType()->getAs<AutoType>() &&
7628 !FuncT->getReturnType()->isInstantiationDependentType())
7629 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7630 << Fn->getType() << Fn->getSourceRange());
7631 } else {
7632 // CUDA: Calls to global functions must be configured
7633 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7634 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7635 << FDecl << Fn->getSourceRange());
7636 }
7637 }
7638
7639 // Check for a valid return type
7640 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7641 FD: FDecl))
7642 return ExprError();
7643
7644 // We know the result type of the call, set it.
7645 TheCall->setType(FuncT->getCallResultType(Context));
7646 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7647
7648 // WebAssembly tables can't be used as arguments.
7649 if (Context.getTargetInfo().getTriple().isWasm()) {
7650 for (const Expr *Arg : Args) {
7651 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7652 return ExprError(Diag(Arg->getExprLoc(),
7653 diag::err_wasm_table_as_function_parameter));
7654 }
7655 }
7656 }
7657
7658 if (Proto) {
7659 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7660 IsExecConfig))
7661 return ExprError();
7662 } else {
7663 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7664
7665 if (FDecl) {
7666 // Check if we have too few/too many template arguments, based
7667 // on our knowledge of the function definition.
7668 const FunctionDecl *Def = nullptr;
7669 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7670 Proto = Def->getType()->getAs<FunctionProtoType>();
7671 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7672 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7673 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7674 }
7675
7676 // If the function we're calling isn't a function prototype, but we have
7677 // a function prototype from a prior declaratiom, use that prototype.
7678 if (!FDecl->hasPrototype())
7679 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7680 }
7681
7682 // If we still haven't found a prototype to use but there are arguments to
7683 // the call, diagnose this as calling a function without a prototype.
7684 // However, if we found a function declaration, check to see if
7685 // -Wdeprecated-non-prototype was disabled where the function was declared.
7686 // If so, we will silence the diagnostic here on the assumption that this
7687 // interface is intentional and the user knows what they're doing. We will
7688 // also silence the diagnostic if there is a function declaration but it
7689 // was implicitly defined (the user already gets diagnostics about the
7690 // creation of the implicit function declaration, so the additional warning
7691 // is not helpful).
7692 if (!Proto && !Args.empty() &&
7693 (!FDecl || (!FDecl->isImplicit() &&
7694 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7695 FDecl->getLocation()))))
7696 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7697 << (FDecl != nullptr) << FDecl;
7698
7699 // Promote the arguments (C99 6.5.2.2p6).
7700 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7701 Expr *Arg = Args[i];
7702
7703 if (Proto && i < Proto->getNumParams()) {
7704 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7705 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7706 ExprResult ArgE =
7707 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7708 if (ArgE.isInvalid())
7709 return true;
7710
7711 Arg = ArgE.getAs<Expr>();
7712
7713 } else {
7714 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7715
7716 if (ArgE.isInvalid())
7717 return true;
7718
7719 Arg = ArgE.getAs<Expr>();
7720 }
7721
7722 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7723 diag::err_call_incomplete_argument, Arg))
7724 return ExprError();
7725
7726 TheCall->setArg(Arg: i, ArgExpr: Arg);
7727 }
7728 TheCall->computeDependence();
7729 }
7730
7731 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7732 if (Method->isImplicitObjectMemberFunction())
7733 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7734 << Fn->getSourceRange() << 0);
7735
7736 // Check for sentinels
7737 if (NDecl)
7738 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7739
7740 // Warn for unions passing across security boundary (CMSE).
7741 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7742 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7743 if (const auto *RT =
7744 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7745 if (RT->getDecl()->isOrContainsUnion())
7746 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7747 << 0 << i;
7748 }
7749 }
7750 }
7751
7752 // Do special checking on direct calls to functions.
7753 if (FDecl) {
7754 if (CheckFunctionCall(FDecl, TheCall, Proto))
7755 return ExprError();
7756
7757 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7758
7759 if (BuiltinID)
7760 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7761 } else if (NDecl) {
7762 if (CheckPointerCall(NDecl, TheCall, Proto))
7763 return ExprError();
7764 } else {
7765 if (CheckOtherCall(TheCall, Proto))
7766 return ExprError();
7767 }
7768
7769 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), Decl: FDecl);
7770}
7771
7772ExprResult
7773Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7774 SourceLocation RParenLoc, Expr *InitExpr) {
7775 assert(Ty && "ActOnCompoundLiteral(): missing type");
7776 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7777
7778 TypeSourceInfo *TInfo;
7779 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7780 if (!TInfo)
7781 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7782
7783 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7784}
7785
7786ExprResult
7787Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7788 SourceLocation RParenLoc, Expr *LiteralExpr) {
7789 QualType literalType = TInfo->getType();
7790
7791 if (literalType->isArrayType()) {
7792 if (RequireCompleteSizedType(
7793 LParenLoc, Context.getBaseElementType(literalType),
7794 diag::err_array_incomplete_or_sizeless_type,
7795 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7796 return ExprError();
7797 if (literalType->isVariableArrayType()) {
7798 // C23 6.7.10p4: An entity of variable length array type shall not be
7799 // initialized except by an empty initializer.
7800 //
7801 // The C extension warnings are issued from ParseBraceInitializer() and
7802 // do not need to be issued here. However, we continue to issue an error
7803 // in the case there are initializers or we are compiling C++. We allow
7804 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7805 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7806 // FIXME: should we allow this construct in C++ when it makes sense to do
7807 // so?
7808 std::optional<unsigned> NumInits;
7809 if (const auto *ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7810 NumInits = ILE->getNumInits();
7811 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7812 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7813 diag::err_variable_object_no_init))
7814 return ExprError();
7815 }
7816 } else if (!literalType->isDependentType() &&
7817 RequireCompleteType(LParenLoc, literalType,
7818 diag::err_typecheck_decl_incomplete_type,
7819 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7820 return ExprError();
7821
7822 InitializedEntity Entity
7823 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7824 InitializationKind Kind
7825 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7826 TypeRange: SourceRange(LParenLoc, RParenLoc),
7827 /*InitList=*/true);
7828 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7829 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7830 ResultType: &literalType);
7831 if (Result.isInvalid())
7832 return ExprError();
7833 LiteralExpr = Result.get();
7834
7835 bool isFileScope = !CurContext->isFunctionOrMethod();
7836
7837 // In C, compound literals are l-values for some reason.
7838 // For GCC compatibility, in C++, file-scope array compound literals with
7839 // constant initializers are also l-values, and compound literals are
7840 // otherwise prvalues.
7841 //
7842 // (GCC also treats C++ list-initialized file-scope array prvalues with
7843 // constant initializers as l-values, but that's non-conforming, so we don't
7844 // follow it there.)
7845 //
7846 // FIXME: It would be better to handle the lvalue cases as materializing and
7847 // lifetime-extending a temporary object, but our materialized temporaries
7848 // representation only supports lifetime extension from a variable, not "out
7849 // of thin air".
7850 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7851 // is bound to the result of applying array-to-pointer decay to the compound
7852 // literal.
7853 // FIXME: GCC supports compound literals of reference type, which should
7854 // obviously have a value kind derived from the kind of reference involved.
7855 ExprValueKind VK =
7856 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7857 ? VK_PRValue
7858 : VK_LValue;
7859
7860 if (isFileScope)
7861 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7862 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7863 Expr *Init = ILE->getInit(Init: i);
7864 ILE->setInit(i, ConstantExpr::Create(Context, E: Init));
7865 }
7866
7867 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7868 VK, LiteralExpr, isFileScope);
7869 if (isFileScope) {
7870 if (!LiteralExpr->isTypeDependent() &&
7871 !LiteralExpr->isValueDependent() &&
7872 !literalType->isDependentType()) // C99 6.5.2.5p3
7873 if (CheckForConstantInitializer(e: LiteralExpr, t: literalType))
7874 return ExprError();
7875 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7876 literalType.getAddressSpace() != LangAS::Default) {
7877 // Embedded-C extensions to C99 6.5.2.5:
7878 // "If the compound literal occurs inside the body of a function, the
7879 // type name shall not be qualified by an address-space qualifier."
7880 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7881 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7882 return ExprError();
7883 }
7884
7885 if (!isFileScope && !getLangOpts().CPlusPlus) {
7886 // Compound literals that have automatic storage duration are destroyed at
7887 // the end of the scope in C; in C++, they're just temporaries.
7888
7889 // Emit diagnostics if it is or contains a C union type that is non-trivial
7890 // to destruct.
7891 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7892 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7893 UseContext: NTCUC_CompoundLiteral, NonTrivialKind: NTCUK_Destruct);
7894
7895 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7896 if (literalType.isDestructedType()) {
7897 Cleanup.setExprNeedsCleanups(true);
7898 ExprCleanupObjects.push_back(Elt: E);
7899 getCurFunction()->setHasBranchProtectedScope();
7900 }
7901 }
7902
7903 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7904 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7905 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7906 Loc: E->getInitializer()->getExprLoc());
7907
7908 return MaybeBindToTemporary(E);
7909}
7910
7911ExprResult
7912Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7913 SourceLocation RBraceLoc) {
7914 // Only produce each kind of designated initialization diagnostic once.
7915 SourceLocation FirstDesignator;
7916 bool DiagnosedArrayDesignator = false;
7917 bool DiagnosedNestedDesignator = false;
7918 bool DiagnosedMixedDesignator = false;
7919
7920 // Check that any designated initializers are syntactically valid in the
7921 // current language mode.
7922 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7923 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7924 if (FirstDesignator.isInvalid())
7925 FirstDesignator = DIE->getBeginLoc();
7926
7927 if (!getLangOpts().CPlusPlus)
7928 break;
7929
7930 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7931 DiagnosedNestedDesignator = true;
7932 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7933 << DIE->getDesignatorsSourceRange();
7934 }
7935
7936 for (auto &Desig : DIE->designators()) {
7937 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7938 DiagnosedArrayDesignator = true;
7939 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7940 << Desig.getSourceRange();
7941 }
7942 }
7943
7944 if (!DiagnosedMixedDesignator &&
7945 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7946 DiagnosedMixedDesignator = true;
7947 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7948 << DIE->getSourceRange();
7949 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7950 << InitArgList[0]->getSourceRange();
7951 }
7952 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7953 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7954 DiagnosedMixedDesignator = true;
7955 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7956 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7957 << DIE->getSourceRange();
7958 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7959 << InitArgList[I]->getSourceRange();
7960 }
7961 }
7962
7963 if (FirstDesignator.isValid()) {
7964 // Only diagnose designated initiaization as a C++20 extension if we didn't
7965 // already diagnose use of (non-C++20) C99 designator syntax.
7966 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7967 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7968 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7969 ? diag::warn_cxx17_compat_designated_init
7970 : diag::ext_cxx_designated_init);
7971 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7972 Diag(FirstDesignator, diag::ext_designated_init);
7973 }
7974 }
7975
7976 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7977}
7978
7979ExprResult
7980Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7981 SourceLocation RBraceLoc) {
7982 // Semantic analysis for initializers is done by ActOnDeclarator() and
7983 // CheckInitializer() - it requires knowledge of the object being initialized.
7984
7985 // Immediately handle non-overload placeholders. Overloads can be
7986 // resolved contextually, but everything else here can't.
7987 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7988 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7989 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7990
7991 // Ignore failures; dropping the entire initializer list because
7992 // of one failure would be terrible for indexing/etc.
7993 if (result.isInvalid()) continue;
7994
7995 InitArgList[I] = result.get();
7996 }
7997 }
7998
7999 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
8000 RBraceLoc);
8001 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
8002 return E;
8003}
8004
8005/// Do an explicit extend of the given block pointer if we're in ARC.
8006void Sema::maybeExtendBlockObject(ExprResult &E) {
8007 assert(E.get()->getType()->isBlockPointerType());
8008 assert(E.get()->isPRValue());
8009
8010 // Only do this in an r-value context.
8011 if (!getLangOpts().ObjCAutoRefCount) return;
8012
8013 E = ImplicitCastExpr::Create(
8014 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
8015 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
8016 Cleanup.setExprNeedsCleanups(true);
8017}
8018
8019/// Prepare a conversion of the given expression to an ObjC object
8020/// pointer type.
8021CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
8022 QualType type = E.get()->getType();
8023 if (type->isObjCObjectPointerType()) {
8024 return CK_BitCast;
8025 } else if (type->isBlockPointerType()) {
8026 maybeExtendBlockObject(E);
8027 return CK_BlockPointerToObjCPointerCast;
8028 } else {
8029 assert(type->isPointerType());
8030 return CK_CPointerToObjCPointerCast;
8031 }
8032}
8033
8034/// Prepares for a scalar cast, performing all the necessary stages
8035/// except the final cast and returning the kind required.
8036CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
8037 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
8038 // Also, callers should have filtered out the invalid cases with
8039 // pointers. Everything else should be possible.
8040
8041 QualType SrcTy = Src.get()->getType();
8042 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
8043 return CK_NoOp;
8044
8045 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
8046 case Type::STK_MemberPointer:
8047 llvm_unreachable("member pointer type in C");
8048
8049 case Type::STK_CPointer:
8050 case Type::STK_BlockPointer:
8051 case Type::STK_ObjCObjectPointer:
8052 switch (DestTy->getScalarTypeKind()) {
8053 case Type::STK_CPointer: {
8054 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
8055 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
8056 if (SrcAS != DestAS)
8057 return CK_AddressSpaceConversion;
8058 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
8059 return CK_NoOp;
8060 return CK_BitCast;
8061 }
8062 case Type::STK_BlockPointer:
8063 return (SrcKind == Type::STK_BlockPointer
8064 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
8065 case Type::STK_ObjCObjectPointer:
8066 if (SrcKind == Type::STK_ObjCObjectPointer)
8067 return CK_BitCast;
8068 if (SrcKind == Type::STK_CPointer)
8069 return CK_CPointerToObjCPointerCast;
8070 maybeExtendBlockObject(E&: Src);
8071 return CK_BlockPointerToObjCPointerCast;
8072 case Type::STK_Bool:
8073 return CK_PointerToBoolean;
8074 case Type::STK_Integral:
8075 return CK_PointerToIntegral;
8076 case Type::STK_Floating:
8077 case Type::STK_FloatingComplex:
8078 case Type::STK_IntegralComplex:
8079 case Type::STK_MemberPointer:
8080 case Type::STK_FixedPoint:
8081 llvm_unreachable("illegal cast from pointer");
8082 }
8083 llvm_unreachable("Should have returned before this");
8084
8085 case Type::STK_FixedPoint:
8086 switch (DestTy->getScalarTypeKind()) {
8087 case Type::STK_FixedPoint:
8088 return CK_FixedPointCast;
8089 case Type::STK_Bool:
8090 return CK_FixedPointToBoolean;
8091 case Type::STK_Integral:
8092 return CK_FixedPointToIntegral;
8093 case Type::STK_Floating:
8094 return CK_FixedPointToFloating;
8095 case Type::STK_IntegralComplex:
8096 case Type::STK_FloatingComplex:
8097 Diag(Src.get()->getExprLoc(),
8098 diag::err_unimplemented_conversion_with_fixed_point_type)
8099 << DestTy;
8100 return CK_IntegralCast;
8101 case Type::STK_CPointer:
8102 case Type::STK_ObjCObjectPointer:
8103 case Type::STK_BlockPointer:
8104 case Type::STK_MemberPointer:
8105 llvm_unreachable("illegal cast to pointer type");
8106 }
8107 llvm_unreachable("Should have returned before this");
8108
8109 case Type::STK_Bool: // casting from bool is like casting from an integer
8110 case Type::STK_Integral:
8111 switch (DestTy->getScalarTypeKind()) {
8112 case Type::STK_CPointer:
8113 case Type::STK_ObjCObjectPointer:
8114 case Type::STK_BlockPointer:
8115 if (Src.get()->isNullPointerConstant(Ctx&: Context,
8116 NPC: Expr::NPC_ValueDependentIsNull))
8117 return CK_NullToPointer;
8118 return CK_IntegralToPointer;
8119 case Type::STK_Bool:
8120 return CK_IntegralToBoolean;
8121 case Type::STK_Integral:
8122 return CK_IntegralCast;
8123 case Type::STK_Floating:
8124 return CK_IntegralToFloating;
8125 case Type::STK_IntegralComplex:
8126 Src = ImpCastExprToType(E: Src.get(),
8127 Type: DestTy->castAs<ComplexType>()->getElementType(),
8128 CK: CK_IntegralCast);
8129 return CK_IntegralRealToComplex;
8130 case Type::STK_FloatingComplex:
8131 Src = ImpCastExprToType(E: Src.get(),
8132 Type: DestTy->castAs<ComplexType>()->getElementType(),
8133 CK: CK_IntegralToFloating);
8134 return CK_FloatingRealToComplex;
8135 case Type::STK_MemberPointer:
8136 llvm_unreachable("member pointer type in C");
8137 case Type::STK_FixedPoint:
8138 return CK_IntegralToFixedPoint;
8139 }
8140 llvm_unreachable("Should have returned before this");
8141
8142 case Type::STK_Floating:
8143 switch (DestTy->getScalarTypeKind()) {
8144 case Type::STK_Floating:
8145 return CK_FloatingCast;
8146 case Type::STK_Bool:
8147 return CK_FloatingToBoolean;
8148 case Type::STK_Integral:
8149 return CK_FloatingToIntegral;
8150 case Type::STK_FloatingComplex:
8151 Src = ImpCastExprToType(E: Src.get(),
8152 Type: DestTy->castAs<ComplexType>()->getElementType(),
8153 CK: CK_FloatingCast);
8154 return CK_FloatingRealToComplex;
8155 case Type::STK_IntegralComplex:
8156 Src = ImpCastExprToType(E: Src.get(),
8157 Type: DestTy->castAs<ComplexType>()->getElementType(),
8158 CK: CK_FloatingToIntegral);
8159 return CK_IntegralRealToComplex;
8160 case Type::STK_CPointer:
8161 case Type::STK_ObjCObjectPointer:
8162 case Type::STK_BlockPointer:
8163 llvm_unreachable("valid float->pointer cast?");
8164 case Type::STK_MemberPointer:
8165 llvm_unreachable("member pointer type in C");
8166 case Type::STK_FixedPoint:
8167 return CK_FloatingToFixedPoint;
8168 }
8169 llvm_unreachable("Should have returned before this");
8170
8171 case Type::STK_FloatingComplex:
8172 switch (DestTy->getScalarTypeKind()) {
8173 case Type::STK_FloatingComplex:
8174 return CK_FloatingComplexCast;
8175 case Type::STK_IntegralComplex:
8176 return CK_FloatingComplexToIntegralComplex;
8177 case Type::STK_Floating: {
8178 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8179 if (Context.hasSameType(T1: ET, T2: DestTy))
8180 return CK_FloatingComplexToReal;
8181 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
8182 return CK_FloatingCast;
8183 }
8184 case Type::STK_Bool:
8185 return CK_FloatingComplexToBoolean;
8186 case Type::STK_Integral:
8187 Src = ImpCastExprToType(E: Src.get(),
8188 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8189 CK: CK_FloatingComplexToReal);
8190 return CK_FloatingToIntegral;
8191 case Type::STK_CPointer:
8192 case Type::STK_ObjCObjectPointer:
8193 case Type::STK_BlockPointer:
8194 llvm_unreachable("valid complex float->pointer cast?");
8195 case Type::STK_MemberPointer:
8196 llvm_unreachable("member pointer type in C");
8197 case Type::STK_FixedPoint:
8198 Diag(Src.get()->getExprLoc(),
8199 diag::err_unimplemented_conversion_with_fixed_point_type)
8200 << SrcTy;
8201 return CK_IntegralCast;
8202 }
8203 llvm_unreachable("Should have returned before this");
8204
8205 case Type::STK_IntegralComplex:
8206 switch (DestTy->getScalarTypeKind()) {
8207 case Type::STK_FloatingComplex:
8208 return CK_IntegralComplexToFloatingComplex;
8209 case Type::STK_IntegralComplex:
8210 return CK_IntegralComplexCast;
8211 case Type::STK_Integral: {
8212 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8213 if (Context.hasSameType(T1: ET, T2: DestTy))
8214 return CK_IntegralComplexToReal;
8215 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
8216 return CK_IntegralCast;
8217 }
8218 case Type::STK_Bool:
8219 return CK_IntegralComplexToBoolean;
8220 case Type::STK_Floating:
8221 Src = ImpCastExprToType(E: Src.get(),
8222 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8223 CK: CK_IntegralComplexToReal);
8224 return CK_IntegralToFloating;
8225 case Type::STK_CPointer:
8226 case Type::STK_ObjCObjectPointer:
8227 case Type::STK_BlockPointer:
8228 llvm_unreachable("valid complex int->pointer cast?");
8229 case Type::STK_MemberPointer:
8230 llvm_unreachable("member pointer type in C");
8231 case Type::STK_FixedPoint:
8232 Diag(Src.get()->getExprLoc(),
8233 diag::err_unimplemented_conversion_with_fixed_point_type)
8234 << SrcTy;
8235 return CK_IntegralCast;
8236 }
8237 llvm_unreachable("Should have returned before this");
8238 }
8239
8240 llvm_unreachable("Unhandled scalar cast");
8241}
8242
8243static bool breakDownVectorType(QualType type, uint64_t &len,
8244 QualType &eltType) {
8245 // Vectors are simple.
8246 if (const VectorType *vecType = type->getAs<VectorType>()) {
8247 len = vecType->getNumElements();
8248 eltType = vecType->getElementType();
8249 assert(eltType->isScalarType());
8250 return true;
8251 }
8252
8253 // We allow lax conversion to and from non-vector types, but only if
8254 // they're real types (i.e. non-complex, non-pointer scalar types).
8255 if (!type->isRealType()) return false;
8256
8257 len = 1;
8258 eltType = type;
8259 return true;
8260}
8261
8262/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8263/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8264/// allowed?
8265///
8266/// This will also return false if the two given types do not make sense from
8267/// the perspective of SVE bitcasts.
8268bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8269 assert(srcTy->isVectorType() || destTy->isVectorType());
8270
8271 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8272 if (!FirstType->isSVESizelessBuiltinType())
8273 return false;
8274
8275 const auto *VecTy = SecondType->getAs<VectorType>();
8276 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8277 };
8278
8279 return ValidScalableConversion(srcTy, destTy) ||
8280 ValidScalableConversion(destTy, srcTy);
8281}
8282
8283/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8284/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8285/// VLS type) allowed?
8286///
8287/// This will also return false if the two given types do not make sense from
8288/// the perspective of RVV bitcasts.
8289bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
8290 assert(srcTy->isVectorType() || destTy->isVectorType());
8291
8292 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8293 if (!FirstType->isRVVSizelessBuiltinType())
8294 return false;
8295
8296 const auto *VecTy = SecondType->getAs<VectorType>();
8297 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
8298 };
8299
8300 return ValidScalableConversion(srcTy, destTy) ||
8301 ValidScalableConversion(destTy, srcTy);
8302}
8303
8304/// Are the two types matrix types and do they have the same dimensions i.e.
8305/// do they have the same number of rows and the same number of columns?
8306bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8307 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8308 return false;
8309
8310 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8311 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8312
8313 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8314 matSrcType->getNumColumns() == matDestType->getNumColumns();
8315}
8316
8317bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8318 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8319
8320 uint64_t SrcLen, DestLen;
8321 QualType SrcEltTy, DestEltTy;
8322 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
8323 return false;
8324 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
8325 return false;
8326
8327 // ASTContext::getTypeSize will return the size rounded up to a
8328 // power of 2, so instead of using that, we need to use the raw
8329 // element size multiplied by the element count.
8330 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
8331 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
8332
8333 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8334}
8335
8336// This returns true if at least one of the types is an altivec vector.
8337bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8338 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8339 "expected at least one type to be a vector here");
8340
8341 bool IsSrcTyAltivec =
8342 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8343 VectorKind::AltiVecVector) ||
8344 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8345 VectorKind::AltiVecBool) ||
8346 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8347 VectorKind::AltiVecPixel));
8348
8349 bool IsDestTyAltivec = DestTy->isVectorType() &&
8350 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8351 VectorKind::AltiVecVector) ||
8352 (DestTy->castAs<VectorType>()->getVectorKind() ==
8353 VectorKind::AltiVecBool) ||
8354 (DestTy->castAs<VectorType>()->getVectorKind() ==
8355 VectorKind::AltiVecPixel));
8356
8357 return (IsSrcTyAltivec || IsDestTyAltivec);
8358}
8359
8360/// Are the two types lax-compatible vector types? That is, given
8361/// that one of them is a vector, do they have equal storage sizes,
8362/// where the storage size is the number of elements times the element
8363/// size?
8364///
8365/// This will also return false if either of the types is neither a
8366/// vector nor a real type.
8367bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8368 assert(destTy->isVectorType() || srcTy->isVectorType());
8369
8370 // Disallow lax conversions between scalars and ExtVectors (these
8371 // conversions are allowed for other vector types because common headers
8372 // depend on them). Most scalar OP ExtVector cases are handled by the
8373 // splat path anyway, which does what we want (convert, not bitcast).
8374 // What this rules out for ExtVectors is crazy things like char4*float.
8375 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8376 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8377
8378 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8379}
8380
8381/// Is this a legal conversion between two types, one of which is
8382/// known to be a vector type?
8383bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8384 assert(destTy->isVectorType() || srcTy->isVectorType());
8385
8386 switch (Context.getLangOpts().getLaxVectorConversions()) {
8387 case LangOptions::LaxVectorConversionKind::None:
8388 return false;
8389
8390 case LangOptions::LaxVectorConversionKind::Integer:
8391 if (!srcTy->isIntegralOrEnumerationType()) {
8392 auto *Vec = srcTy->getAs<VectorType>();
8393 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8394 return false;
8395 }
8396 if (!destTy->isIntegralOrEnumerationType()) {
8397 auto *Vec = destTy->getAs<VectorType>();
8398 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8399 return false;
8400 }
8401 // OK, integer (vector) -> integer (vector) bitcast.
8402 break;
8403
8404 case LangOptions::LaxVectorConversionKind::All:
8405 break;
8406 }
8407
8408 return areLaxCompatibleVectorTypes(srcTy, destTy);
8409}
8410
8411bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8412 CastKind &Kind) {
8413 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8414 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8415 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8416 << DestTy << SrcTy << R;
8417 }
8418 } else if (SrcTy->isMatrixType()) {
8419 return Diag(R.getBegin(),
8420 diag::err_invalid_conversion_between_matrix_and_type)
8421 << SrcTy << DestTy << R;
8422 } else if (DestTy->isMatrixType()) {
8423 return Diag(R.getBegin(),
8424 diag::err_invalid_conversion_between_matrix_and_type)
8425 << DestTy << SrcTy << R;
8426 }
8427
8428 Kind = CK_MatrixCast;
8429 return false;
8430}
8431
8432bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8433 CastKind &Kind) {
8434 assert(VectorTy->isVectorType() && "Not a vector type!");
8435
8436 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8437 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8438 return Diag(R.getBegin(),
8439 Ty->isVectorType() ?
8440 diag::err_invalid_conversion_between_vectors :
8441 diag::err_invalid_conversion_between_vector_and_integer)
8442 << VectorTy << Ty << R;
8443 } else
8444 return Diag(R.getBegin(),
8445 diag::err_invalid_conversion_between_vector_and_scalar)
8446 << VectorTy << Ty << R;
8447
8448 Kind = CK_BitCast;
8449 return false;
8450}
8451
8452ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8453 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8454
8455 if (DestElemTy == SplattedExpr->getType())
8456 return SplattedExpr;
8457
8458 assert(DestElemTy->isFloatingType() ||
8459 DestElemTy->isIntegralOrEnumerationType());
8460
8461 CastKind CK;
8462 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8463 // OpenCL requires that we convert `true` boolean expressions to -1, but
8464 // only when splatting vectors.
8465 if (DestElemTy->isFloatingType()) {
8466 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8467 // in two steps: boolean to signed integral, then to floating.
8468 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8469 CK: CK_BooleanToSignedIntegral);
8470 SplattedExpr = CastExprRes.get();
8471 CK = CK_IntegralToFloating;
8472 } else {
8473 CK = CK_BooleanToSignedIntegral;
8474 }
8475 } else {
8476 ExprResult CastExprRes = SplattedExpr;
8477 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8478 if (CastExprRes.isInvalid())
8479 return ExprError();
8480 SplattedExpr = CastExprRes.get();
8481 }
8482 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8483}
8484
8485ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8486 Expr *CastExpr, CastKind &Kind) {
8487 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8488
8489 QualType SrcTy = CastExpr->getType();
8490
8491 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8492 // an ExtVectorType.
8493 // In OpenCL, casts between vectors of different types are not allowed.
8494 // (See OpenCL 6.2).
8495 if (SrcTy->isVectorType()) {
8496 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8497 (getLangOpts().OpenCL &&
8498 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy))) {
8499 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8500 << DestTy << SrcTy << R;
8501 return ExprError();
8502 }
8503 Kind = CK_BitCast;
8504 return CastExpr;
8505 }
8506
8507 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8508 // conversion will take place first from scalar to elt type, and then
8509 // splat from elt type to vector.
8510 if (SrcTy->isPointerType())
8511 return Diag(R.getBegin(),
8512 diag::err_invalid_conversion_between_vector_and_scalar)
8513 << DestTy << SrcTy << R;
8514
8515 Kind = CK_VectorSplat;
8516 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8517}
8518
8519ExprResult
8520Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8521 Declarator &D, ParsedType &Ty,
8522 SourceLocation RParenLoc, Expr *CastExpr) {
8523 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8524 "ActOnCastExpr(): missing type or expr");
8525
8526 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8527 if (D.isInvalidType())
8528 return ExprError();
8529
8530 if (getLangOpts().CPlusPlus) {
8531 // Check that there are no default arguments (C++ only).
8532 CheckExtraCXXDefaultArguments(D);
8533 } else {
8534 // Make sure any TypoExprs have been dealt with.
8535 ExprResult Res = CorrectDelayedTyposInExpr(E: CastExpr);
8536 if (!Res.isUsable())
8537 return ExprError();
8538 CastExpr = Res.get();
8539 }
8540
8541 checkUnusedDeclAttributes(D);
8542
8543 QualType castType = castTInfo->getType();
8544 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8545
8546 bool isVectorLiteral = false;
8547
8548 // Check for an altivec or OpenCL literal,
8549 // i.e. all the elements are integer constants.
8550 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8551 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8552 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8553 && castType->isVectorType() && (PE || PLE)) {
8554 if (PLE && PLE->getNumExprs() == 0) {
8555 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8556 return ExprError();
8557 }
8558 if (PE || PLE->getNumExprs() == 1) {
8559 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8560 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8561 isVectorLiteral = true;
8562 }
8563 else
8564 isVectorLiteral = true;
8565 }
8566
8567 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8568 // then handle it as such.
8569 if (isVectorLiteral)
8570 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8571
8572 // If the Expr being casted is a ParenListExpr, handle it specially.
8573 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8574 // sequence of BinOp comma operators.
8575 if (isa<ParenListExpr>(Val: CastExpr)) {
8576 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8577 if (Result.isInvalid()) return ExprError();
8578 CastExpr = Result.get();
8579 }
8580
8581 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8582 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8583
8584 CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8585
8586 CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8587
8588 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8589
8590 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8591}
8592
8593ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8594 SourceLocation RParenLoc, Expr *E,
8595 TypeSourceInfo *TInfo) {
8596 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8597 "Expected paren or paren list expression");
8598
8599 Expr **exprs;
8600 unsigned numExprs;
8601 Expr *subExpr;
8602 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8603 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8604 LiteralLParenLoc = PE->getLParenLoc();
8605 LiteralRParenLoc = PE->getRParenLoc();
8606 exprs = PE->getExprs();
8607 numExprs = PE->getNumExprs();
8608 } else { // isa<ParenExpr> by assertion at function entrance
8609 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8610 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8611 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8612 exprs = &subExpr;
8613 numExprs = 1;
8614 }
8615
8616 QualType Ty = TInfo->getType();
8617 assert(Ty->isVectorType() && "Expected vector type");
8618
8619 SmallVector<Expr *, 8> initExprs;
8620 const VectorType *VTy = Ty->castAs<VectorType>();
8621 unsigned numElems = VTy->getNumElements();
8622
8623 // '(...)' form of vector initialization in AltiVec: the number of
8624 // initializers must be one or must match the size of the vector.
8625 // If a single value is specified in the initializer then it will be
8626 // replicated to all the components of the vector
8627 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8628 SrcTy: VTy->getElementType()))
8629 return ExprError();
8630 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8631 // The number of initializers must be one or must match the size of the
8632 // vector. If a single value is specified in the initializer then it will
8633 // be replicated to all the components of the vector
8634 if (numExprs == 1) {
8635 QualType ElemTy = VTy->getElementType();
8636 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8637 if (Literal.isInvalid())
8638 return ExprError();
8639 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8640 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8641 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8642 }
8643 else if (numExprs < numElems) {
8644 Diag(E->getExprLoc(),
8645 diag::err_incorrect_number_of_vector_initializers);
8646 return ExprError();
8647 }
8648 else
8649 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8650 }
8651 else {
8652 // For OpenCL, when the number of initializers is a single value,
8653 // it will be replicated to all components of the vector.
8654 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8655 numExprs == 1) {
8656 QualType ElemTy = VTy->getElementType();
8657 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8658 if (Literal.isInvalid())
8659 return ExprError();
8660 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8661 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8662 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8663 }
8664
8665 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8666 }
8667 // FIXME: This means that pretty-printing the final AST will produce curly
8668 // braces instead of the original commas.
8669 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8670 initExprs, LiteralRParenLoc);
8671 initE->setType(Ty);
8672 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8673}
8674
8675/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8676/// the ParenListExpr into a sequence of comma binary operators.
8677ExprResult
8678Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8679 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8680 if (!E)
8681 return OrigExpr;
8682
8683 ExprResult Result(E->getExpr(Init: 0));
8684
8685 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8686 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8687 RHSExpr: E->getExpr(Init: i));
8688
8689 if (Result.isInvalid()) return ExprError();
8690
8691 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8692}
8693
8694ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8695 SourceLocation R,
8696 MultiExprArg Val) {
8697 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8698}
8699
8700/// Emit a specialized diagnostic when one expression is a null pointer
8701/// constant and the other is not a pointer. Returns true if a diagnostic is
8702/// emitted.
8703bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8704 SourceLocation QuestionLoc) {
8705 const Expr *NullExpr = LHSExpr;
8706 const Expr *NonPointerExpr = RHSExpr;
8707 Expr::NullPointerConstantKind NullKind =
8708 NullExpr->isNullPointerConstant(Ctx&: Context,
8709 NPC: Expr::NPC_ValueDependentIsNotNull);
8710
8711 if (NullKind == Expr::NPCK_NotNull) {
8712 NullExpr = RHSExpr;
8713 NonPointerExpr = LHSExpr;
8714 NullKind =
8715 NullExpr->isNullPointerConstant(Ctx&: Context,
8716 NPC: Expr::NPC_ValueDependentIsNotNull);
8717 }
8718
8719 if (NullKind == Expr::NPCK_NotNull)
8720 return false;
8721
8722 if (NullKind == Expr::NPCK_ZeroExpression)
8723 return false;
8724
8725 if (NullKind == Expr::NPCK_ZeroLiteral) {
8726 // In this case, check to make sure that we got here from a "NULL"
8727 // string in the source code.
8728 NullExpr = NullExpr->IgnoreParenImpCasts();
8729 SourceLocation loc = NullExpr->getExprLoc();
8730 if (!findMacroSpelling(loc, name: "NULL"))
8731 return false;
8732 }
8733
8734 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8735 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8736 << NonPointerExpr->getType() << DiagType
8737 << NonPointerExpr->getSourceRange();
8738 return true;
8739}
8740
8741/// Return false if the condition expression is valid, true otherwise.
8742static bool checkCondition(Sema &S, const Expr *Cond,
8743 SourceLocation QuestionLoc) {
8744 QualType CondTy = Cond->getType();
8745
8746 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8747 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8748 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8749 << CondTy << Cond->getSourceRange();
8750 return true;
8751 }
8752
8753 // C99 6.5.15p2
8754 if (CondTy->isScalarType()) return false;
8755
8756 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8757 << CondTy << Cond->getSourceRange();
8758 return true;
8759}
8760
8761/// Return false if the NullExpr can be promoted to PointerTy,
8762/// true otherwise.
8763static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8764 QualType PointerTy) {
8765 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8766 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8767 NPC: Expr::NPC_ValueDependentIsNull))
8768 return true;
8769
8770 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8771 return false;
8772}
8773
8774/// Checks compatibility between two pointers and return the resulting
8775/// type.
8776static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8777 ExprResult &RHS,
8778 SourceLocation Loc) {
8779 QualType LHSTy = LHS.get()->getType();
8780 QualType RHSTy = RHS.get()->getType();
8781
8782 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8783 // Two identical pointers types are always compatible.
8784 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8785 }
8786
8787 QualType lhptee, rhptee;
8788
8789 // Get the pointee types.
8790 bool IsBlockPointer = false;
8791 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8792 lhptee = LHSBTy->getPointeeType();
8793 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8794 IsBlockPointer = true;
8795 } else {
8796 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8797 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8798 }
8799
8800 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8801 // differently qualified versions of compatible types, the result type is
8802 // a pointer to an appropriately qualified version of the composite
8803 // type.
8804
8805 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8806 // clause doesn't make sense for our extensions. E.g. address space 2 should
8807 // be incompatible with address space 3: they may live on different devices or
8808 // anything.
8809 Qualifiers lhQual = lhptee.getQualifiers();
8810 Qualifiers rhQual = rhptee.getQualifiers();
8811
8812 LangAS ResultAddrSpace = LangAS::Default;
8813 LangAS LAddrSpace = lhQual.getAddressSpace();
8814 LangAS RAddrSpace = rhQual.getAddressSpace();
8815
8816 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8817 // spaces is disallowed.
8818 if (lhQual.isAddressSpaceSupersetOf(other: rhQual))
8819 ResultAddrSpace = LAddrSpace;
8820 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual))
8821 ResultAddrSpace = RAddrSpace;
8822 else {
8823 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8824 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8825 << RHS.get()->getSourceRange();
8826 return QualType();
8827 }
8828
8829 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8830 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8831 lhQual.removeCVRQualifiers();
8832 rhQual.removeCVRQualifiers();
8833
8834 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8835 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8836 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8837 // qual types are compatible iff
8838 // * corresponded types are compatible
8839 // * CVR qualifiers are equal
8840 // * address spaces are equal
8841 // Thus for conditional operator we merge CVR and address space unqualified
8842 // pointees and if there is a composite type we return a pointer to it with
8843 // merged qualifiers.
8844 LHSCastKind =
8845 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8846 RHSCastKind =
8847 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8848 lhQual.removeAddressSpace();
8849 rhQual.removeAddressSpace();
8850
8851 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8852 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8853
8854 QualType CompositeTy = S.Context.mergeTypes(
8855 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8856 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8857
8858 if (CompositeTy.isNull()) {
8859 // In this situation, we assume void* type. No especially good
8860 // reason, but this is what gcc does, and we do have to pick
8861 // to get a consistent AST.
8862 QualType incompatTy;
8863 incompatTy = S.Context.getPointerType(
8864 S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8865 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8866 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8867
8868 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8869 // for casts between types with incompatible address space qualifiers.
8870 // For the following code the compiler produces casts between global and
8871 // local address spaces of the corresponded innermost pointees:
8872 // local int *global *a;
8873 // global int *global *b;
8874 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8875 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8876 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8877 << RHS.get()->getSourceRange();
8878
8879 return incompatTy;
8880 }
8881
8882 // The pointer types are compatible.
8883 // In case of OpenCL ResultTy should have the address space qualifier
8884 // which is a superset of address spaces of both the 2nd and the 3rd
8885 // operands of the conditional operator.
8886 QualType ResultTy = [&, ResultAddrSpace]() {
8887 if (S.getLangOpts().OpenCL) {
8888 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8889 CompositeQuals.setAddressSpace(ResultAddrSpace);
8890 return S.Context
8891 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8892 .withCVRQualifiers(CVR: MergedCVRQual);
8893 }
8894 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8895 }();
8896 if (IsBlockPointer)
8897 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8898 else
8899 ResultTy = S.Context.getPointerType(T: ResultTy);
8900
8901 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8902 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8903 return ResultTy;
8904}
8905
8906/// Return the resulting type when the operands are both block pointers.
8907static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8908 ExprResult &LHS,
8909 ExprResult &RHS,
8910 SourceLocation Loc) {
8911 QualType LHSTy = LHS.get()->getType();
8912 QualType RHSTy = RHS.get()->getType();
8913
8914 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8915 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8916 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8917 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8918 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8919 return destType;
8920 }
8921 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8922 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8923 << RHS.get()->getSourceRange();
8924 return QualType();
8925 }
8926
8927 // We have 2 block pointer types.
8928 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8929}
8930
8931/// Return the resulting type when the operands are both pointers.
8932static QualType
8933checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8934 ExprResult &RHS,
8935 SourceLocation Loc) {
8936 // get the pointer types
8937 QualType LHSTy = LHS.get()->getType();
8938 QualType RHSTy = RHS.get()->getType();
8939
8940 // get the "pointed to" types
8941 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8942 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8943
8944 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8945 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8946 // Figure out necessary qualifiers (C99 6.5.15p6)
8947 QualType destPointee
8948 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8949 QualType destType = S.Context.getPointerType(T: destPointee);
8950 // Add qualifiers if necessary.
8951 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8952 // Promote to void*.
8953 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8954 return destType;
8955 }
8956 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8957 QualType destPointee
8958 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8959 QualType destType = S.Context.getPointerType(T: destPointee);
8960 // Add qualifiers if necessary.
8961 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8962 // Promote to void*.
8963 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8964 return destType;
8965 }
8966
8967 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8968}
8969
8970/// Return false if the first expression is not an integer and the second
8971/// expression is not a pointer, true otherwise.
8972static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8973 Expr* PointerExpr, SourceLocation Loc,
8974 bool IsIntFirstExpr) {
8975 if (!PointerExpr->getType()->isPointerType() ||
8976 !Int.get()->getType()->isIntegerType())
8977 return false;
8978
8979 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8980 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8981
8982 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8983 << Expr1->getType() << Expr2->getType()
8984 << Expr1->getSourceRange() << Expr2->getSourceRange();
8985 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8986 CK: CK_IntegralToPointer);
8987 return true;
8988}
8989
8990/// Simple conversion between integer and floating point types.
8991///
8992/// Used when handling the OpenCL conditional operator where the
8993/// condition is a vector while the other operands are scalar.
8994///
8995/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8996/// types are either integer or floating type. Between the two
8997/// operands, the type with the higher rank is defined as the "result
8998/// type". The other operand needs to be promoted to the same type. No
8999/// other type promotion is allowed. We cannot use
9000/// UsualArithmeticConversions() for this purpose, since it always
9001/// promotes promotable types.
9002static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
9003 ExprResult &RHS,
9004 SourceLocation QuestionLoc) {
9005 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
9006 if (LHS.isInvalid())
9007 return QualType();
9008 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
9009 if (RHS.isInvalid())
9010 return QualType();
9011
9012 // For conversion purposes, we ignore any qualifiers.
9013 // For example, "const float" and "float" are equivalent.
9014 QualType LHSType =
9015 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
9016 QualType RHSType =
9017 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
9018
9019 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
9020 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9021 << LHSType << LHS.get()->getSourceRange();
9022 return QualType();
9023 }
9024
9025 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
9026 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9027 << RHSType << RHS.get()->getSourceRange();
9028 return QualType();
9029 }
9030
9031 // If both types are identical, no conversion is needed.
9032 if (LHSType == RHSType)
9033 return LHSType;
9034
9035 // Now handle "real" floating types (i.e. float, double, long double).
9036 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
9037 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
9038 /*IsCompAssign = */ false);
9039
9040 // Finally, we have two differing integer types.
9041 return handleIntegerConversion<doIntegralCast, doIntegralCast>
9042 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
9043}
9044
9045/// Convert scalar operands to a vector that matches the
9046/// condition in length.
9047///
9048/// Used when handling the OpenCL conditional operator where the
9049/// condition is a vector while the other operands are scalar.
9050///
9051/// We first compute the "result type" for the scalar operands
9052/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
9053/// into a vector of that type where the length matches the condition
9054/// vector type. s6.11.6 requires that the element types of the result
9055/// and the condition must have the same number of bits.
9056static QualType
9057OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
9058 QualType CondTy, SourceLocation QuestionLoc) {
9059 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
9060 if (ResTy.isNull()) return QualType();
9061
9062 const VectorType *CV = CondTy->getAs<VectorType>();
9063 assert(CV);
9064
9065 // Determine the vector result type
9066 unsigned NumElements = CV->getNumElements();
9067 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
9068
9069 // Ensure that all types have the same number of bits
9070 if (S.Context.getTypeSize(T: CV->getElementType())
9071 != S.Context.getTypeSize(T: ResTy)) {
9072 // Since VectorTy is created internally, it does not pretty print
9073 // with an OpenCL name. Instead, we just print a description.
9074 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
9075 SmallString<64> Str;
9076 llvm::raw_svector_ostream OS(Str);
9077 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
9078 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9079 << CondTy << OS.str();
9080 return QualType();
9081 }
9082
9083 // Convert operands to the vector result type
9084 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
9085 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
9086
9087 return VectorTy;
9088}
9089
9090/// Return false if this is a valid OpenCL condition vector
9091static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
9092 SourceLocation QuestionLoc) {
9093 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9094 // integral type.
9095 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9096 assert(CondTy);
9097 QualType EleTy = CondTy->getElementType();
9098 if (EleTy->isIntegerType()) return false;
9099
9100 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
9101 << Cond->getType() << Cond->getSourceRange();
9102 return true;
9103}
9104
9105/// Return false if the vector condition type and the vector
9106/// result type are compatible.
9107///
9108/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9109/// number of elements, and their element types have the same number
9110/// of bits.
9111static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9112 SourceLocation QuestionLoc) {
9113 const VectorType *CV = CondTy->getAs<VectorType>();
9114 const VectorType *RV = VecResTy->getAs<VectorType>();
9115 assert(CV && RV);
9116
9117 if (CV->getNumElements() != RV->getNumElements()) {
9118 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
9119 << CondTy << VecResTy;
9120 return true;
9121 }
9122
9123 QualType CVE = CV->getElementType();
9124 QualType RVE = RV->getElementType();
9125
9126 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE)) {
9127 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9128 << CondTy << VecResTy;
9129 return true;
9130 }
9131
9132 return false;
9133}
9134
9135/// Return the resulting type for the conditional operator in
9136/// OpenCL (aka "ternary selection operator", OpenCL v1.1
9137/// s6.3.i) when the condition is a vector type.
9138static QualType
9139OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9140 ExprResult &LHS, ExprResult &RHS,
9141 SourceLocation QuestionLoc) {
9142 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
9143 if (Cond.isInvalid())
9144 return QualType();
9145 QualType CondTy = Cond.get()->getType();
9146
9147 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
9148 return QualType();
9149
9150 // If either operand is a vector then find the vector type of the
9151 // result as specified in OpenCL v1.1 s6.3.i.
9152 if (LHS.get()->getType()->isVectorType() ||
9153 RHS.get()->getType()->isVectorType()) {
9154 bool IsBoolVecLang =
9155 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9156 QualType VecResTy =
9157 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
9158 /*isCompAssign*/ IsCompAssign: false,
9159 /*AllowBothBool*/ true,
9160 /*AllowBoolConversions*/ AllowBoolConversion: false,
9161 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
9162 /*ReportInvalid*/ true);
9163 if (VecResTy.isNull())
9164 return QualType();
9165 // The result type must match the condition type as specified in
9166 // OpenCL v1.1 s6.11.6.
9167 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9168 return QualType();
9169 return VecResTy;
9170 }
9171
9172 // Both operands are scalar.
9173 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9174}
9175
9176/// Return true if the Expr is block type
9177static bool checkBlockType(Sema &S, const Expr *E) {
9178 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
9179 QualType Ty = CE->getCallee()->getType();
9180 if (Ty->isBlockPointerType()) {
9181 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9182 return true;
9183 }
9184 }
9185 return false;
9186}
9187
9188/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9189/// In that case, LHS = cond.
9190/// C99 6.5.15
9191QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9192 ExprResult &RHS, ExprValueKind &VK,
9193 ExprObjectKind &OK,
9194 SourceLocation QuestionLoc) {
9195
9196 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
9197 if (!LHSResult.isUsable()) return QualType();
9198 LHS = LHSResult;
9199
9200 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
9201 if (!RHSResult.isUsable()) return QualType();
9202 RHS = RHSResult;
9203
9204 // C++ is sufficiently different to merit its own checker.
9205 if (getLangOpts().CPlusPlus)
9206 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
9207
9208 VK = VK_PRValue;
9209 OK = OK_Ordinary;
9210
9211 if (Context.isDependenceAllowed() &&
9212 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9213 RHS.get()->isTypeDependent())) {
9214 assert(!getLangOpts().CPlusPlus);
9215 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9216 RHS.get()->containsErrors()) &&
9217 "should only occur in error-recovery path.");
9218 return Context.DependentTy;
9219 }
9220
9221 // The OpenCL operator with a vector condition is sufficiently
9222 // different to merit its own checker.
9223 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9224 Cond.get()->getType()->isExtVectorType())
9225 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
9226
9227 // First, check the condition.
9228 Cond = UsualUnaryConversions(E: Cond.get());
9229 if (Cond.isInvalid())
9230 return QualType();
9231 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
9232 return QualType();
9233
9234 // Handle vectors.
9235 if (LHS.get()->getType()->isVectorType() ||
9236 RHS.get()->getType()->isVectorType())
9237 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
9238 /*AllowBothBool*/ true,
9239 /*AllowBoolConversions*/ AllowBoolConversion: false,
9240 /*AllowBooleanOperation*/ AllowBoolOperation: false,
9241 /*ReportInvalid*/ true);
9242
9243 QualType ResTy =
9244 UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, ACK: ACK_Conditional);
9245 if (LHS.isInvalid() || RHS.isInvalid())
9246 return QualType();
9247
9248 // WebAssembly tables are not allowed as conditional LHS or RHS.
9249 QualType LHSTy = LHS.get()->getType();
9250 QualType RHSTy = RHS.get()->getType();
9251 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9252 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9253 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9254 return QualType();
9255 }
9256
9257 // Diagnose attempts to convert between __ibm128, __float128 and long double
9258 // where such conversions currently can't be handled.
9259 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
9260 Diag(QuestionLoc,
9261 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9263 return QualType();
9264 }
9265
9266 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9267 // selection operator (?:).
9268 if (getLangOpts().OpenCL &&
9269 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
9270 return QualType();
9271 }
9272
9273 // If both operands have arithmetic type, do the usual arithmetic conversions
9274 // to find a common type: C99 6.5.15p3,5.
9275 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9276 // Disallow invalid arithmetic conversions, such as those between bit-
9277 // precise integers types of different sizes, or between a bit-precise
9278 // integer and another type.
9279 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9280 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9281 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9282 << RHS.get()->getSourceRange();
9283 return QualType();
9284 }
9285
9286 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9287 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9288
9289 return ResTy;
9290 }
9291
9292 // If both operands are the same structure or union type, the result is that
9293 // type.
9294 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
9295 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9296 if (LHSRT->getDecl() == RHSRT->getDecl())
9297 // "If both the operands have structure or union type, the result has
9298 // that type." This implies that CV qualifiers are dropped.
9299 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9300 Y: RHSTy.getUnqualifiedType());
9301 // FIXME: Type of conditional expression must be complete in C mode.
9302 }
9303
9304 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9305 // The following || allows only one side to be void (a GCC-ism).
9306 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9307 QualType ResTy;
9308 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9309 ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9310 } else if (RHSTy->isVoidType()) {
9311 ResTy = RHSTy;
9312 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9313 << RHS.get()->getSourceRange();
9314 } else {
9315 ResTy = LHSTy;
9316 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9317 << LHS.get()->getSourceRange();
9318 }
9319 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9320 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9321 return ResTy;
9322 }
9323
9324 // C23 6.5.15p7:
9325 // ... if both the second and third operands have nullptr_t type, the
9326 // result also has that type.
9327 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9328 return ResTy;
9329
9330 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9331 // the type of the other operand."
9332 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9333 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9334
9335 // All objective-c pointer type analysis is done here.
9336 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9337 QuestionLoc);
9338 if (LHS.isInvalid() || RHS.isInvalid())
9339 return QualType();
9340 if (!compositeType.isNull())
9341 return compositeType;
9342
9343
9344 // Handle block pointer types.
9345 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9346 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9347 Loc: QuestionLoc);
9348
9349 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9350 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9351 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9352 Loc: QuestionLoc);
9353
9354 // GCC compatibility: soften pointer/integer mismatch. Note that
9355 // null pointers have been filtered out by this point.
9356 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9357 /*IsIntFirstExpr=*/true))
9358 return RHSTy;
9359 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9360 /*IsIntFirstExpr=*/false))
9361 return LHSTy;
9362
9363 // Emit a better diagnostic if one of the expressions is a null pointer
9364 // constant and the other is not a pointer type. In this case, the user most
9365 // likely forgot to take the address of the other expression.
9366 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9367 return QualType();
9368
9369 // Finally, if the LHS and RHS types are canonically the same type, we can
9370 // use the common sugared type.
9371 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9372 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9373
9374 // Otherwise, the operands are not compatible.
9375 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9376 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9377 << RHS.get()->getSourceRange();
9378 return QualType();
9379}
9380
9381/// FindCompositeObjCPointerType - Helper method to find composite type of
9382/// two objective-c pointer types of the two input expressions.
9383QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9384 SourceLocation QuestionLoc) {
9385 QualType LHSTy = LHS.get()->getType();
9386 QualType RHSTy = RHS.get()->getType();
9387
9388 // Handle things like Class and struct objc_class*. Here we case the result
9389 // to the pseudo-builtin, because that will be implicitly cast back to the
9390 // redefinition type if an attempt is made to access its fields.
9391 if (LHSTy->isObjCClassType() &&
9392 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCClassRedefinitionType()))) {
9393 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_CPointerToObjCPointerCast);
9394 return LHSTy;
9395 }
9396 if (RHSTy->isObjCClassType() &&
9397 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCClassRedefinitionType()))) {
9398 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: CK_CPointerToObjCPointerCast);
9399 return RHSTy;
9400 }
9401 // And the same for struct objc_object* / id
9402 if (LHSTy->isObjCIdType() &&
9403 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCIdRedefinitionType()))) {
9404 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_CPointerToObjCPointerCast);
9405 return LHSTy;
9406 }
9407 if (RHSTy->isObjCIdType() &&
9408 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCIdRedefinitionType()))) {
9409 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: CK_CPointerToObjCPointerCast);
9410 return RHSTy;
9411 }
9412 // And the same for struct objc_selector* / SEL
9413 if (Context.isObjCSelType(T: LHSTy) &&
9414 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCSelRedefinitionType()))) {
9415 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_BitCast);
9416 return LHSTy;
9417 }
9418 if (Context.isObjCSelType(T: RHSTy) &&
9419 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCSelRedefinitionType()))) {
9420 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: CK_BitCast);
9421 return RHSTy;
9422 }
9423 // Check constraints for Objective-C object pointers types.
9424 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9425
9426 if (Context.getCanonicalType(T: LHSTy) == Context.getCanonicalType(T: RHSTy)) {
9427 // Two identical object pointer types are always compatible.
9428 return LHSTy;
9429 }
9430 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9431 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9432 QualType compositeType = LHSTy;
9433
9434 // If both operands are interfaces and either operand can be
9435 // assigned to the other, use that type as the composite
9436 // type. This allows
9437 // xxx ? (A*) a : (B*) b
9438 // where B is a subclass of A.
9439 //
9440 // Additionally, as for assignment, if either type is 'id'
9441 // allow silent coercion. Finally, if the types are
9442 // incompatible then make sure to use 'id' as the composite
9443 // type so the result is acceptable for sending messages to.
9444
9445 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9446 // It could return the composite type.
9447 if (!(compositeType =
9448 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9449 // Nothing more to do.
9450 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9451 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9452 } else if (Context.canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT)) {
9453 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9454 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9455 RHSOPT->isObjCQualifiedIdType()) &&
9456 Context.ObjCQualifiedIdTypesAreCompatible(LHS: LHSOPT, RHS: RHSOPT,
9457 ForCompare: true)) {
9458 // Need to handle "id<xx>" explicitly.
9459 // GCC allows qualified id and any Objective-C type to devolve to
9460 // id. Currently localizing to here until clear this should be
9461 // part of ObjCQualifiedIdTypesAreCompatible.
9462 compositeType = Context.getObjCIdType();
9463 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9464 compositeType = Context.getObjCIdType();
9465 } else {
9466 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9467 << LHSTy << RHSTy
9468 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9469 QualType incompatTy = Context.getObjCIdType();
9470 LHS = ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: CK_BitCast);
9471 RHS = ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: CK_BitCast);
9472 return incompatTy;
9473 }
9474 // The object pointer types are compatible.
9475 LHS = ImpCastExprToType(E: LHS.get(), Type: compositeType, CK: CK_BitCast);
9476 RHS = ImpCastExprToType(E: RHS.get(), Type: compositeType, CK: CK_BitCast);
9477 return compositeType;
9478 }
9479 // Check Objective-C object pointer types and 'void *'
9480 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9481 if (getLangOpts().ObjCAutoRefCount) {
9482 // ARC forbids the implicit conversion of object pointers to 'void *',
9483 // so these types are not compatible.
9484 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9485 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9486 LHS = RHS = true;
9487 return QualType();
9488 }
9489 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9490 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9491 QualType destPointee
9492 = Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
9493 QualType destType = Context.getPointerType(T: destPointee);
9494 // Add qualifiers if necessary.
9495 LHS = ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
9496 // Promote to void*.
9497 RHS = ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
9498 return destType;
9499 }
9500 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9501 if (getLangOpts().ObjCAutoRefCount) {
9502 // ARC forbids the implicit conversion of object pointers to 'void *',
9503 // so these types are not compatible.
9504 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9505 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9506 LHS = RHS = true;
9507 return QualType();
9508 }
9509 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9510 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9511 QualType destPointee
9512 = Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
9513 QualType destType = Context.getPointerType(T: destPointee);
9514 // Add qualifiers if necessary.
9515 RHS = ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
9516 // Promote to void*.
9517 LHS = ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
9518 return destType;
9519 }
9520 return QualType();
9521}
9522
9523/// SuggestParentheses - Emit a note with a fixit hint that wraps
9524/// ParenRange in parentheses.
9525static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9526 const PartialDiagnostic &Note,
9527 SourceRange ParenRange) {
9528 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9529 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9530 EndLoc.isValid()) {
9531 Self.Diag(Loc, PD: Note)
9532 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9533 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9534 } else {
9535 // We can't display the parentheses, so just show the bare note.
9536 Self.Diag(Loc, PD: Note) << ParenRange;
9537 }
9538}
9539
9540static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9541 return BinaryOperator::isAdditiveOp(Opc) ||
9542 BinaryOperator::isMultiplicativeOp(Opc) ||
9543 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9544 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9545 // not any of the logical operators. Bitwise-xor is commonly used as a
9546 // logical-xor because there is no logical-xor operator. The logical
9547 // operators, including uses of xor, have a high false positive rate for
9548 // precedence warnings.
9549}
9550
9551/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9552/// expression, either using a built-in or overloaded operator,
9553/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9554/// expression.
9555static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9556 const Expr **RHSExprs) {
9557 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9558 E = E->IgnoreImpCasts();
9559 E = E->IgnoreConversionOperatorSingleStep();
9560 E = E->IgnoreImpCasts();
9561 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9562 E = MTE->getSubExpr();
9563 E = E->IgnoreImpCasts();
9564 }
9565
9566 // Built-in binary operator.
9567 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9568 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9569 *Opcode = OP->getOpcode();
9570 *RHSExprs = OP->getRHS();
9571 return true;
9572 }
9573
9574 // Overloaded operator.
9575 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9576 if (Call->getNumArgs() != 2)
9577 return false;
9578
9579 // Make sure this is really a binary operator that is safe to pass into
9580 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9581 OverloadedOperatorKind OO = Call->getOperator();
9582 if (OO < OO_Plus || OO > OO_Arrow ||
9583 OO == OO_PlusPlus || OO == OO_MinusMinus)
9584 return false;
9585
9586 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9587 if (IsArithmeticOp(Opc: OpKind)) {
9588 *Opcode = OpKind;
9589 *RHSExprs = Call->getArg(1);
9590 return true;
9591 }
9592 }
9593
9594 return false;
9595}
9596
9597/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9598/// or is a logical expression such as (x==y) which has int type, but is
9599/// commonly interpreted as boolean.
9600static bool ExprLooksBoolean(const Expr *E) {
9601 E = E->IgnoreParenImpCasts();
9602
9603 if (E->getType()->isBooleanType())
9604 return true;
9605 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9606 return OP->isComparisonOp() || OP->isLogicalOp();
9607 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9608 return OP->getOpcode() == UO_LNot;
9609 if (E->getType()->isPointerType())
9610 return true;
9611 // FIXME: What about overloaded operator calls returning "unspecified boolean
9612 // type"s (commonly pointer-to-members)?
9613
9614 return false;
9615}
9616
9617/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9618/// and binary operator are mixed in a way that suggests the programmer assumed
9619/// the conditional operator has higher precedence, for example:
9620/// "int x = a + someBinaryCondition ? 1 : 2".
9621static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9622 Expr *Condition, const Expr *LHSExpr,
9623 const Expr *RHSExpr) {
9624 BinaryOperatorKind CondOpcode;
9625 const Expr *CondRHS;
9626
9627 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9628 return;
9629 if (!ExprLooksBoolean(E: CondRHS))
9630 return;
9631
9632 // The condition is an arithmetic binary expression, with a right-
9633 // hand side that looks boolean, so warn.
9634
9635 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9636 ? diag::warn_precedence_bitwise_conditional
9637 : diag::warn_precedence_conditional;
9638
9639 Self.Diag(Loc: OpLoc, DiagID)
9640 << Condition->getSourceRange()
9641 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9642
9643 SuggestParentheses(
9644 Self, OpLoc,
9645 Self.PDiag(diag::note_precedence_silence)
9646 << BinaryOperator::getOpcodeStr(CondOpcode),
9647 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9648
9649 SuggestParentheses(Self, OpLoc,
9650 Self.PDiag(diag::note_precedence_conditional_first),
9651 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9652}
9653
9654/// Compute the nullability of a conditional expression.
9655static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9656 QualType LHSTy, QualType RHSTy,
9657 ASTContext &Ctx) {
9658 if (!ResTy->isAnyPointerType())
9659 return ResTy;
9660
9661 auto GetNullability = [](QualType Ty) {
9662 std::optional<NullabilityKind> Kind = Ty->getNullability();
9663 if (Kind) {
9664 // For our purposes, treat _Nullable_result as _Nullable.
9665 if (*Kind == NullabilityKind::NullableResult)
9666 return NullabilityKind::Nullable;
9667 return *Kind;
9668 }
9669 return NullabilityKind::Unspecified;
9670 };
9671
9672 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9673 NullabilityKind MergedKind;
9674
9675 // Compute nullability of a binary conditional expression.
9676 if (IsBin) {
9677 if (LHSKind == NullabilityKind::NonNull)
9678 MergedKind = NullabilityKind::NonNull;
9679 else
9680 MergedKind = RHSKind;
9681 // Compute nullability of a normal conditional expression.
9682 } else {
9683 if (LHSKind == NullabilityKind::Nullable ||
9684 RHSKind == NullabilityKind::Nullable)
9685 MergedKind = NullabilityKind::Nullable;
9686 else if (LHSKind == NullabilityKind::NonNull)
9687 MergedKind = RHSKind;
9688 else if (RHSKind == NullabilityKind::NonNull)
9689 MergedKind = LHSKind;
9690 else
9691 MergedKind = NullabilityKind::Unspecified;
9692 }
9693
9694 // Return if ResTy already has the correct nullability.
9695 if (GetNullability(ResTy) == MergedKind)
9696 return ResTy;
9697
9698 // Strip all nullability from ResTy.
9699 while (ResTy->getNullability())
9700 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9701
9702 // Create a new AttributedType with the new nullability kind.
9703 auto NewAttr = AttributedType::getNullabilityAttrKind(kind: MergedKind);
9704 return Ctx.getAttributedType(attrKind: NewAttr, modifiedType: ResTy, equivalentType: ResTy);
9705}
9706
9707/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9708/// in the case of a the GNU conditional expr extension.
9709ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9710 SourceLocation ColonLoc,
9711 Expr *CondExpr, Expr *LHSExpr,
9712 Expr *RHSExpr) {
9713 if (!Context.isDependenceAllowed()) {
9714 // C cannot handle TypoExpr nodes in the condition because it
9715 // doesn't handle dependent types properly, so make sure any TypoExprs have
9716 // been dealt with before checking the operands.
9717 ExprResult CondResult = CorrectDelayedTyposInExpr(E: CondExpr);
9718 ExprResult LHSResult = CorrectDelayedTyposInExpr(E: LHSExpr);
9719 ExprResult RHSResult = CorrectDelayedTyposInExpr(E: RHSExpr);
9720
9721 if (!CondResult.isUsable())
9722 return ExprError();
9723
9724 if (LHSExpr) {
9725 if (!LHSResult.isUsable())
9726 return ExprError();
9727 }
9728
9729 if (!RHSResult.isUsable())
9730 return ExprError();
9731
9732 CondExpr = CondResult.get();
9733 LHSExpr = LHSResult.get();
9734 RHSExpr = RHSResult.get();
9735 }
9736
9737 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9738 // was the condition.
9739 OpaqueValueExpr *opaqueValue = nullptr;
9740 Expr *commonExpr = nullptr;
9741 if (!LHSExpr) {
9742 commonExpr = CondExpr;
9743 // Lower out placeholder types first. This is important so that we don't
9744 // try to capture a placeholder. This happens in few cases in C++; such
9745 // as Objective-C++'s dictionary subscripting syntax.
9746 if (commonExpr->hasPlaceholderType()) {
9747 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9748 if (!result.isUsable()) return ExprError();
9749 commonExpr = result.get();
9750 }
9751 // We usually want to apply unary conversions *before* saving, except
9752 // in the special case of a C++ l-value conditional.
9753 if (!(getLangOpts().CPlusPlus
9754 && !commonExpr->isTypeDependent()
9755 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9756 && commonExpr->isGLValue()
9757 && commonExpr->isOrdinaryOrBitFieldObject()
9758 && RHSExpr->isOrdinaryOrBitFieldObject()
9759 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9760 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9761 if (commonRes.isInvalid())
9762 return ExprError();
9763 commonExpr = commonRes.get();
9764 }
9765
9766 // If the common expression is a class or array prvalue, materialize it
9767 // so that we can safely refer to it multiple times.
9768 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9769 commonExpr->getType()->isArrayType())) {
9770 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9771 if (MatExpr.isInvalid())
9772 return ExprError();
9773 commonExpr = MatExpr.get();
9774 }
9775
9776 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9777 commonExpr->getType(),
9778 commonExpr->getValueKind(),
9779 commonExpr->getObjectKind(),
9780 commonExpr);
9781 LHSExpr = CondExpr = opaqueValue;
9782 }
9783
9784 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9785 ExprValueKind VK = VK_PRValue;
9786 ExprObjectKind OK = OK_Ordinary;
9787 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9788 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9789 VK, OK, QuestionLoc);
9790 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9791 RHS.isInvalid())
9792 return ExprError();
9793
9794 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9795 RHSExpr: RHS.get());
9796
9797 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9798
9799 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9800 Ctx&: Context);
9801
9802 if (!commonExpr)
9803 return new (Context)
9804 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9805 RHS.get(), result, VK, OK);
9806
9807 return new (Context) BinaryConditionalOperator(
9808 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9809 ColonLoc, result, VK, OK);
9810}
9811
9812// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9813bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9814 unsigned FromAttributes = 0, ToAttributes = 0;
9815 if (const auto *FromFn =
9816 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9817 FromAttributes =
9818 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9819 if (const auto *ToFn =
9820 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9821 ToAttributes =
9822 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9823
9824 return FromAttributes != ToAttributes;
9825}
9826
9827// Check if we have a conversion between incompatible cmse function pointer
9828// types, that is, a conversion between a function pointer with the
9829// cmse_nonsecure_call attribute and one without.
9830static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9831 QualType ToType) {
9832 if (const auto *ToFn =
9833 dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: ToType))) {
9834 if (const auto *FromFn =
9835 dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: FromType))) {
9836 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9837 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9838
9839 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9840 }
9841 }
9842 return false;
9843}
9844
9845// checkPointerTypesForAssignment - This is a very tricky routine (despite
9846// being closely modeled after the C99 spec:-). The odd characteristic of this
9847// routine is it effectively iqnores the qualifiers on the top level pointee.
9848// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9849// FIXME: add a couple examples in this comment.
9850static Sema::AssignConvertType
9851checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9852 SourceLocation Loc) {
9853 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9854 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9855
9856 // get the "pointed to" type (ignoring qualifiers at the top level)
9857 const Type *lhptee, *rhptee;
9858 Qualifiers lhq, rhq;
9859 std::tie(args&: lhptee, args&: lhq) =
9860 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9861 std::tie(args&: rhptee, args&: rhq) =
9862 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9863
9864 Sema::AssignConvertType ConvTy = Sema::Compatible;
9865
9866 // C99 6.5.16.1p1: This following citation is common to constraints
9867 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9868 // qualifiers of the type *pointed to* by the right;
9869
9870 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9871 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9872 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9873 // Ignore lifetime for further calculation.
9874 lhq.removeObjCLifetime();
9875 rhq.removeObjCLifetime();
9876 }
9877
9878 if (!lhq.compatiblyIncludes(other: rhq)) {
9879 // Treat address-space mismatches as fatal.
9880 if (!lhq.isAddressSpaceSupersetOf(other: rhq))
9881 return Sema::IncompatiblePointerDiscardsQualifiers;
9882
9883 // It's okay to add or remove GC or lifetime qualifiers when converting to
9884 // and from void*.
9885 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9886 .compatiblyIncludes(
9887 other: rhq.withoutObjCGCAttr().withoutObjCLifetime())
9888 && (lhptee->isVoidType() || rhptee->isVoidType()))
9889 ; // keep old
9890
9891 // Treat lifetime mismatches as fatal.
9892 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9893 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9894
9895 // For GCC/MS compatibility, other qualifier mismatches are treated
9896 // as still compatible in C.
9897 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9898 }
9899
9900 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9901 // incomplete type and the other is a pointer to a qualified or unqualified
9902 // version of void...
9903 if (lhptee->isVoidType()) {
9904 if (rhptee->isIncompleteOrObjectType())
9905 return ConvTy;
9906
9907 // As an extension, we allow cast to/from void* to function pointer.
9908 assert(rhptee->isFunctionType());
9909 return Sema::FunctionVoidPointer;
9910 }
9911
9912 if (rhptee->isVoidType()) {
9913 if (lhptee->isIncompleteOrObjectType())
9914 return ConvTy;
9915
9916 // As an extension, we allow cast to/from void* to function pointer.
9917 assert(lhptee->isFunctionType());
9918 return Sema::FunctionVoidPointer;
9919 }
9920
9921 if (!S.Diags.isIgnored(
9922 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9923 Loc) &&
9924 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9925 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9926 return Sema::IncompatibleFunctionPointerStrict;
9927
9928 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9929 // unqualified versions of compatible types, ...
9930 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9931 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9932 // Check if the pointee types are compatible ignoring the sign.
9933 // We explicitly check for char so that we catch "char" vs
9934 // "unsigned char" on systems where "char" is unsigned.
9935 if (lhptee->isCharType())
9936 ltrans = S.Context.UnsignedCharTy;
9937 else if (lhptee->hasSignedIntegerRepresentation())
9938 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9939
9940 if (rhptee->isCharType())
9941 rtrans = S.Context.UnsignedCharTy;
9942 else if (rhptee->hasSignedIntegerRepresentation())
9943 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9944
9945 if (ltrans == rtrans) {
9946 // Types are compatible ignoring the sign. Qualifier incompatibility
9947 // takes priority over sign incompatibility because the sign
9948 // warning can be disabled.
9949 if (ConvTy != Sema::Compatible)
9950 return ConvTy;
9951
9952 return Sema::IncompatiblePointerSign;
9953 }
9954
9955 // If we are a multi-level pointer, it's possible that our issue is simply
9956 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9957 // the eventual target type is the same and the pointers have the same
9958 // level of indirection, this must be the issue.
9959 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9960 do {
9961 std::tie(args&: lhptee, args&: lhq) =
9962 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9963 std::tie(args&: rhptee, args&: rhq) =
9964 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9965
9966 // Inconsistent address spaces at this point is invalid, even if the
9967 // address spaces would be compatible.
9968 // FIXME: This doesn't catch address space mismatches for pointers of
9969 // different nesting levels, like:
9970 // __local int *** a;
9971 // int ** b = a;
9972 // It's not clear how to actually determine when such pointers are
9973 // invalidly incompatible.
9974 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9975 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9976
9977 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9978
9979 if (lhptee == rhptee)
9980 return Sema::IncompatibleNestedPointerQualifiers;
9981 }
9982
9983 // General pointer incompatibility takes priority over qualifiers.
9984 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9985 return Sema::IncompatibleFunctionPointer;
9986 return Sema::IncompatiblePointer;
9987 }
9988 if (!S.getLangOpts().CPlusPlus &&
9989 S.IsFunctionConversion(FromType: ltrans, ToType: rtrans, ResultTy&: ltrans))
9990 return Sema::IncompatibleFunctionPointer;
9991 if (IsInvalidCmseNSCallConversion(S, FromType: ltrans, ToType: rtrans))
9992 return Sema::IncompatibleFunctionPointer;
9993 if (S.IsInvalidSMECallConversion(FromType: rtrans, ToType: ltrans))
9994 return Sema::IncompatibleFunctionPointer;
9995 return ConvTy;
9996}
9997
9998/// checkBlockPointerTypesForAssignment - This routine determines whether two
9999/// block pointer types are compatible or whether a block and normal pointer
10000/// are compatible. It is more restrict than comparing two function pointer
10001// types.
10002static Sema::AssignConvertType
10003checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
10004 QualType RHSType) {
10005 assert(LHSType.isCanonical() && "LHS not canonicalized!");
10006 assert(RHSType.isCanonical() && "RHS not canonicalized!");
10007
10008 QualType lhptee, rhptee;
10009
10010 // get the "pointed to" type (ignoring qualifiers at the top level)
10011 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
10012 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
10013
10014 // In C++, the types have to match exactly.
10015 if (S.getLangOpts().CPlusPlus)
10016 return Sema::IncompatibleBlockPointer;
10017
10018 Sema::AssignConvertType ConvTy = Sema::Compatible;
10019
10020 // For blocks we enforce that qualifiers are identical.
10021 Qualifiers LQuals = lhptee.getLocalQualifiers();
10022 Qualifiers RQuals = rhptee.getLocalQualifiers();
10023 if (S.getLangOpts().OpenCL) {
10024 LQuals.removeAddressSpace();
10025 RQuals.removeAddressSpace();
10026 }
10027 if (LQuals != RQuals)
10028 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
10029
10030 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
10031 // assignment.
10032 // The current behavior is similar to C++ lambdas. A block might be
10033 // assigned to a variable iff its return type and parameters are compatible
10034 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
10035 // an assignment. Presumably it should behave in way that a function pointer
10036 // assignment does in C, so for each parameter and return type:
10037 // * CVR and address space of LHS should be a superset of CVR and address
10038 // space of RHS.
10039 // * unqualified types should be compatible.
10040 if (S.getLangOpts().OpenCL) {
10041 if (!S.Context.typesAreBlockPointerCompatible(
10042 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
10043 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
10044 return Sema::IncompatibleBlockPointer;
10045 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
10046 return Sema::IncompatibleBlockPointer;
10047
10048 return ConvTy;
10049}
10050
10051/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
10052/// for assignment compatibility.
10053static Sema::AssignConvertType
10054checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
10055 QualType RHSType) {
10056 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
10057 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
10058
10059 if (LHSType->isObjCBuiltinType()) {
10060 // Class is not compatible with ObjC object pointers.
10061 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
10062 !RHSType->isObjCQualifiedClassType())
10063 return Sema::IncompatiblePointer;
10064 return Sema::Compatible;
10065 }
10066 if (RHSType->isObjCBuiltinType()) {
10067 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
10068 !LHSType->isObjCQualifiedClassType())
10069 return Sema::IncompatiblePointer;
10070 return Sema::Compatible;
10071 }
10072 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10073 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10074
10075 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee) &&
10076 // make an exception for id<P>
10077 !LHSType->isObjCQualifiedIdType())
10078 return Sema::CompatiblePointerDiscardsQualifiers;
10079
10080 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
10081 return Sema::Compatible;
10082 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
10083 return Sema::IncompatibleObjCQualifiedId;
10084 return Sema::IncompatiblePointer;
10085}
10086
10087Sema::AssignConvertType
10088Sema::CheckAssignmentConstraints(SourceLocation Loc,
10089 QualType LHSType, QualType RHSType) {
10090 // Fake up an opaque expression. We don't actually care about what
10091 // cast operations are required, so if CheckAssignmentConstraints
10092 // adds casts to this they'll be wasted, but fortunately that doesn't
10093 // usually happen on valid code.
10094 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
10095 ExprResult RHSPtr = &RHSExpr;
10096 CastKind K;
10097
10098 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
10099}
10100
10101/// This helper function returns true if QT is a vector type that has element
10102/// type ElementType.
10103static bool isVector(QualType QT, QualType ElementType) {
10104 if (const VectorType *VT = QT->getAs<VectorType>())
10105 return VT->getElementType().getCanonicalType() == ElementType;
10106 return false;
10107}
10108
10109/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
10110/// has code to accommodate several GCC extensions when type checking
10111/// pointers. Here are some objectionable examples that GCC considers warnings:
10112///
10113/// int a, *pint;
10114/// short *pshort;
10115/// struct foo *pfoo;
10116///
10117/// pint = pshort; // warning: assignment from incompatible pointer type
10118/// a = pint; // warning: assignment makes integer from pointer without a cast
10119/// pint = a; // warning: assignment makes pointer from integer without a cast
10120/// pint = pfoo; // warning: assignment from incompatible pointer type
10121///
10122/// As a result, the code for dealing with pointers is more complex than the
10123/// C99 spec dictates.
10124///
10125/// Sets 'Kind' for any result kind except Incompatible.
10126Sema::AssignConvertType
10127Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
10128 CastKind &Kind, bool ConvertRHS) {
10129 QualType RHSType = RHS.get()->getType();
10130 QualType OrigLHSType = LHSType;
10131
10132 // Get canonical types. We're not formatting these types, just comparing
10133 // them.
10134 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
10135 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
10136
10137 // Common case: no conversion required.
10138 if (LHSType == RHSType) {
10139 Kind = CK_NoOp;
10140 return Compatible;
10141 }
10142
10143 // If the LHS has an __auto_type, there are no additional type constraints
10144 // to be worried about.
10145 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
10146 if (AT->isGNUAutoType()) {
10147 Kind = CK_NoOp;
10148 return Compatible;
10149 }
10150 }
10151
10152 // If we have an atomic type, try a non-atomic assignment, then just add an
10153 // atomic qualification step.
10154 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
10155 Sema::AssignConvertType result =
10156 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
10157 if (result != Compatible)
10158 return result;
10159 if (Kind != CK_NoOp && ConvertRHS)
10160 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
10161 Kind = CK_NonAtomicToAtomic;
10162 return Compatible;
10163 }
10164
10165 // If the left-hand side is a reference type, then we are in a
10166 // (rare!) case where we've allowed the use of references in C,
10167 // e.g., as a parameter type in a built-in function. In this case,
10168 // just make sure that the type referenced is compatible with the
10169 // right-hand side type. The caller is responsible for adjusting
10170 // LHSType so that the resulting expression does not have reference
10171 // type.
10172 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10173 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
10174 Kind = CK_LValueBitCast;
10175 return Compatible;
10176 }
10177 return Incompatible;
10178 }
10179
10180 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10181 // to the same ExtVector type.
10182 if (LHSType->isExtVectorType()) {
10183 if (RHSType->isExtVectorType())
10184 return Incompatible;
10185 if (RHSType->isArithmeticType()) {
10186 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10187 if (ConvertRHS)
10188 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
10189 Kind = CK_VectorSplat;
10190 return Compatible;
10191 }
10192 }
10193
10194 // Conversions to or from vector type.
10195 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10196 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10197 // Allow assignments of an AltiVec vector type to an equivalent GCC
10198 // vector type and vice versa
10199 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10200 Kind = CK_BitCast;
10201 return Compatible;
10202 }
10203
10204 // If we are allowing lax vector conversions, and LHS and RHS are both
10205 // vectors, the total size only needs to be the same. This is a bitcast;
10206 // no bits are changed but the result type is different.
10207 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
10208 // The default for lax vector conversions with Altivec vectors will
10209 // change, so if we are converting between vector types where
10210 // at least one is an Altivec vector, emit a warning.
10211 if (Context.getTargetInfo().getTriple().isPPC() &&
10212 anyAltivecTypes(RHSType, LHSType) &&
10213 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10214 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10215 << RHSType << LHSType;
10216 Kind = CK_BitCast;
10217 return IncompatibleVectors;
10218 }
10219 }
10220
10221 // When the RHS comes from another lax conversion (e.g. binops between
10222 // scalars and vectors) the result is canonicalized as a vector. When the
10223 // LHS is also a vector, the lax is allowed by the condition above. Handle
10224 // the case where LHS is a scalar.
10225 if (LHSType->isScalarType()) {
10226 const VectorType *VecType = RHSType->getAs<VectorType>();
10227 if (VecType && VecType->getNumElements() == 1 &&
10228 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
10229 if (Context.getTargetInfo().getTriple().isPPC() &&
10230 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
10231 VecType->getVectorKind() == VectorKind::AltiVecBool ||
10232 VecType->getVectorKind() == VectorKind::AltiVecPixel))
10233 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10234 << RHSType << LHSType;
10235 ExprResult *VecExpr = &RHS;
10236 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
10237 Kind = CK_BitCast;
10238 return Compatible;
10239 }
10240 }
10241
10242 // Allow assignments between fixed-length and sizeless SVE vectors.
10243 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10244 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10245 if (Context.areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
10246 Context.areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
10247 Kind = CK_BitCast;
10248 return Compatible;
10249 }
10250
10251 // Allow assignments between fixed-length and sizeless RVV vectors.
10252 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10253 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10254 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
10255 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
10256 Kind = CK_BitCast;
10257 return Compatible;
10258 }
10259 }
10260
10261 return Incompatible;
10262 }
10263
10264 // Diagnose attempts to convert between __ibm128, __float128 and long double
10265 // where such conversions currently can't be handled.
10266 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
10267 return Incompatible;
10268
10269 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10270 // discards the imaginary part.
10271 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10272 !LHSType->getAs<ComplexType>())
10273 return Incompatible;
10274
10275 // Arithmetic conversions.
10276 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10277 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10278 if (ConvertRHS)
10279 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
10280 return Compatible;
10281 }
10282
10283 // Conversions to normal pointers.
10284 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
10285 // U* -> T*
10286 if (isa<PointerType>(Val: RHSType)) {
10287 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10288 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10289 if (AddrSpaceL != AddrSpaceR)
10290 Kind = CK_AddressSpaceConversion;
10291 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
10292 Kind = CK_NoOp;
10293 else
10294 Kind = CK_BitCast;
10295 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10296 RHS.get()->getBeginLoc());
10297 }
10298
10299 // int -> T*
10300 if (RHSType->isIntegerType()) {
10301 Kind = CK_IntegralToPointer; // FIXME: null?
10302 return IntToPointer;
10303 }
10304
10305 // C pointers are not compatible with ObjC object pointers,
10306 // with two exceptions:
10307 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10308 // - conversions to void*
10309 if (LHSPointer->getPointeeType()->isVoidType()) {
10310 Kind = CK_BitCast;
10311 return Compatible;
10312 }
10313
10314 // - conversions from 'Class' to the redefinition type
10315 if (RHSType->isObjCClassType() &&
10316 Context.hasSameType(T1: LHSType,
10317 T2: Context.getObjCClassRedefinitionType())) {
10318 Kind = CK_BitCast;
10319 return Compatible;
10320 }
10321
10322 Kind = CK_BitCast;
10323 return IncompatiblePointer;
10324 }
10325
10326 // U^ -> void*
10327 if (RHSType->getAs<BlockPointerType>()) {
10328 if (LHSPointer->getPointeeType()->isVoidType()) {
10329 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10330 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10331 ->getPointeeType()
10332 .getAddressSpace();
10333 Kind =
10334 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10335 return Compatible;
10336 }
10337 }
10338
10339 return Incompatible;
10340 }
10341
10342 // Conversions to block pointers.
10343 if (isa<BlockPointerType>(Val: LHSType)) {
10344 // U^ -> T^
10345 if (RHSType->isBlockPointerType()) {
10346 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10347 ->getPointeeType()
10348 .getAddressSpace();
10349 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10350 ->getPointeeType()
10351 .getAddressSpace();
10352 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10353 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10354 }
10355
10356 // int or null -> T^
10357 if (RHSType->isIntegerType()) {
10358 Kind = CK_IntegralToPointer; // FIXME: null
10359 return IntToBlockPointer;
10360 }
10361
10362 // id -> T^
10363 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10364 Kind = CK_AnyPointerToBlockPointerCast;
10365 return Compatible;
10366 }
10367
10368 // void* -> T^
10369 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10370 if (RHSPT->getPointeeType()->isVoidType()) {
10371 Kind = CK_AnyPointerToBlockPointerCast;
10372 return Compatible;
10373 }
10374
10375 return Incompatible;
10376 }
10377
10378 // Conversions to Objective-C pointers.
10379 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10380 // A* -> B*
10381 if (RHSType->isObjCObjectPointerType()) {
10382 Kind = CK_BitCast;
10383 Sema::AssignConvertType result =
10384 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10385 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10386 result == Compatible &&
10387 !CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10388 result = IncompatibleObjCWeakRef;
10389 return result;
10390 }
10391
10392 // int or null -> A*
10393 if (RHSType->isIntegerType()) {
10394 Kind = CK_IntegralToPointer; // FIXME: null
10395 return IntToPointer;
10396 }
10397
10398 // In general, C pointers are not compatible with ObjC object pointers,
10399 // with two exceptions:
10400 if (isa<PointerType>(Val: RHSType)) {
10401 Kind = CK_CPointerToObjCPointerCast;
10402
10403 // - conversions from 'void*'
10404 if (RHSType->isVoidPointerType()) {
10405 return Compatible;
10406 }
10407
10408 // - conversions to 'Class' from its redefinition type
10409 if (LHSType->isObjCClassType() &&
10410 Context.hasSameType(T1: RHSType,
10411 T2: Context.getObjCClassRedefinitionType())) {
10412 return Compatible;
10413 }
10414
10415 return IncompatiblePointer;
10416 }
10417
10418 // Only under strict condition T^ is compatible with an Objective-C pointer.
10419 if (RHSType->isBlockPointerType() &&
10420 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10421 if (ConvertRHS)
10422 maybeExtendBlockObject(E&: RHS);
10423 Kind = CK_BlockPointerToObjCPointerCast;
10424 return Compatible;
10425 }
10426
10427 return Incompatible;
10428 }
10429
10430 // Conversion to nullptr_t (C23 only)
10431 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10432 RHS.get()->isNullPointerConstant(Ctx&: Context,
10433 NPC: Expr::NPC_ValueDependentIsNull)) {
10434 // null -> nullptr_t
10435 Kind = CK_NullToPointer;
10436 return Compatible;
10437 }
10438
10439 // Conversions from pointers that are not covered by the above.
10440 if (isa<PointerType>(Val: RHSType)) {
10441 // T* -> _Bool
10442 if (LHSType == Context.BoolTy) {
10443 Kind = CK_PointerToBoolean;
10444 return Compatible;
10445 }
10446
10447 // T* -> int
10448 if (LHSType->isIntegerType()) {
10449 Kind = CK_PointerToIntegral;
10450 return PointerToInt;
10451 }
10452
10453 return Incompatible;
10454 }
10455
10456 // Conversions from Objective-C pointers that are not covered by the above.
10457 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10458 // T* -> _Bool
10459 if (LHSType == Context.BoolTy) {
10460 Kind = CK_PointerToBoolean;
10461 return Compatible;
10462 }
10463
10464 // T* -> int
10465 if (LHSType->isIntegerType()) {
10466 Kind = CK_PointerToIntegral;
10467 return PointerToInt;
10468 }
10469
10470 return Incompatible;
10471 }
10472
10473 // struct A -> struct B
10474 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10475 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10476 Kind = CK_NoOp;
10477 return Compatible;
10478 }
10479 }
10480
10481 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10482 Kind = CK_IntToOCLSampler;
10483 return Compatible;
10484 }
10485
10486 return Incompatible;
10487}
10488
10489/// Constructs a transparent union from an expression that is
10490/// used to initialize the transparent union.
10491static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10492 ExprResult &EResult, QualType UnionType,
10493 FieldDecl *Field) {
10494 // Build an initializer list that designates the appropriate member
10495 // of the transparent union.
10496 Expr *E = EResult.get();
10497 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10498 E, SourceLocation());
10499 Initializer->setType(UnionType);
10500 Initializer->setInitializedFieldInUnion(Field);
10501
10502 // Build a compound literal constructing a value of the transparent
10503 // union type from this initializer list.
10504 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10505 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10506 VK_PRValue, Initializer, false);
10507}
10508
10509Sema::AssignConvertType
10510Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10511 ExprResult &RHS) {
10512 QualType RHSType = RHS.get()->getType();
10513
10514 // If the ArgType is a Union type, we want to handle a potential
10515 // transparent_union GCC extension.
10516 const RecordType *UT = ArgType->getAsUnionType();
10517 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10518 return Incompatible;
10519
10520 // The field to initialize within the transparent union.
10521 RecordDecl *UD = UT->getDecl();
10522 FieldDecl *InitField = nullptr;
10523 // It's compatible if the expression matches any of the fields.
10524 for (auto *it : UD->fields()) {
10525 if (it->getType()->isPointerType()) {
10526 // If the transparent union contains a pointer type, we allow:
10527 // 1) void pointer
10528 // 2) null pointer constant
10529 if (RHSType->isPointerType())
10530 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10531 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10532 InitField = it;
10533 break;
10534 }
10535
10536 if (RHS.get()->isNullPointerConstant(Context,
10537 Expr::NPC_ValueDependentIsNull)) {
10538 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10539 CK_NullToPointer);
10540 InitField = it;
10541 break;
10542 }
10543 }
10544
10545 CastKind Kind;
10546 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10547 == Compatible) {
10548 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10549 InitField = it;
10550 break;
10551 }
10552 }
10553
10554 if (!InitField)
10555 return Incompatible;
10556
10557 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10558 return Compatible;
10559}
10560
10561Sema::AssignConvertType
10562Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10563 bool Diagnose,
10564 bool DiagnoseCFAudited,
10565 bool ConvertRHS) {
10566 // We need to be able to tell the caller whether we diagnosed a problem, if
10567 // they ask us to issue diagnostics.
10568 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10569
10570 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10571 // we can't avoid *all* modifications at the moment, so we need some somewhere
10572 // to put the updated value.
10573 ExprResult LocalRHS = CallerRHS;
10574 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10575
10576 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10577 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10578 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10579 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10580 Diag(RHS.get()->getExprLoc(),
10581 diag::warn_noderef_to_dereferenceable_pointer)
10582 << RHS.get()->getSourceRange();
10583 }
10584 }
10585 }
10586
10587 if (getLangOpts().CPlusPlus) {
10588 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10589 // C++ 5.17p3: If the left operand is not of class type, the
10590 // expression is implicitly converted (C++ 4) to the
10591 // cv-unqualified type of the left operand.
10592 QualType RHSType = RHS.get()->getType();
10593 if (Diagnose) {
10594 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10595 Action: AA_Assigning);
10596 } else {
10597 ImplicitConversionSequence ICS =
10598 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10599 /*SuppressUserConversions=*/false,
10600 AllowExplicit: AllowedExplicit::None,
10601 /*InOverloadResolution=*/false,
10602 /*CStyle=*/false,
10603 /*AllowObjCWritebackConversion=*/false);
10604 if (ICS.isFailure())
10605 return Incompatible;
10606 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10607 ICS, Action: AA_Assigning);
10608 }
10609 if (RHS.isInvalid())
10610 return Incompatible;
10611 Sema::AssignConvertType result = Compatible;
10612 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10613 !CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10614 result = IncompatibleObjCWeakRef;
10615 return result;
10616 }
10617
10618 // FIXME: Currently, we fall through and treat C++ classes like C
10619 // structures.
10620 // FIXME: We also fall through for atomics; not sure what should
10621 // happen there, though.
10622 } else if (RHS.get()->getType() == Context.OverloadTy) {
10623 // As a set of extensions to C, we support overloading on functions. These
10624 // functions need to be resolved here.
10625 DeclAccessPair DAP;
10626 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10627 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10628 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10629 else
10630 return Incompatible;
10631 }
10632
10633 // This check seems unnatural, however it is necessary to ensure the proper
10634 // conversion of functions/arrays. If the conversion were done for all
10635 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10636 // expressions that suppress this implicit conversion (&, sizeof). This needs
10637 // to happen before we check for null pointer conversions because C does not
10638 // undergo the same implicit conversions as C++ does above (by the calls to
10639 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10640 // lvalue to rvalue cast before checking for null pointer constraints. This
10641 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10642 //
10643 // Suppress this for references: C++ 8.5.3p5.
10644 if (!LHSType->isReferenceType()) {
10645 // FIXME: We potentially allocate here even if ConvertRHS is false.
10646 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10647 if (RHS.isInvalid())
10648 return Incompatible;
10649 }
10650
10651 // The constraints are expressed in terms of the atomic, qualified, or
10652 // unqualified type of the LHS.
10653 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10654
10655 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10656 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10657 if ((LHSTypeAfterConversion->isPointerType() ||
10658 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10659 LHSTypeAfterConversion->isBlockPointerType()) &&
10660 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10661 RHS.get()->isNullPointerConstant(Ctx&: Context,
10662 NPC: Expr::NPC_ValueDependentIsNull))) {
10663 if (Diagnose || ConvertRHS) {
10664 CastKind Kind;
10665 CXXCastPath Path;
10666 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10667 /*IgnoreBaseAccess=*/false, Diagnose);
10668 if (ConvertRHS)
10669 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10670 }
10671 return Compatible;
10672 }
10673 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10674 // unqualified bool, and the right operand is a pointer or its type is
10675 // nullptr_t.
10676 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10677 RHS.get()->getType()->isNullPtrType()) {
10678 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10679 // only handles nullptr -> _Bool due to needing an extra conversion
10680 // step.
10681 // We model this by converting from nullptr -> void * and then let the
10682 // conversion from void * -> _Bool happen naturally.
10683 if (Diagnose || ConvertRHS) {
10684 CastKind Kind;
10685 CXXCastPath Path;
10686 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10687 /*IgnoreBaseAccess=*/false, Diagnose);
10688 if (ConvertRHS)
10689 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10690 BasePath: &Path);
10691 }
10692 }
10693
10694 // OpenCL queue_t type assignment.
10695 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10696 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10697 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10698 return Compatible;
10699 }
10700
10701 CastKind Kind;
10702 Sema::AssignConvertType result =
10703 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10704
10705 // C99 6.5.16.1p2: The value of the right operand is converted to the
10706 // type of the assignment expression.
10707 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10708 // so that we can use references in built-in functions even in C.
10709 // The getNonReferenceType() call makes sure that the resulting expression
10710 // does not have reference type.
10711 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10712 QualType Ty = LHSType.getNonLValueExprType(Context);
10713 Expr *E = RHS.get();
10714
10715 // Check for various Objective-C errors. If we are not reporting
10716 // diagnostics and just checking for errors, e.g., during overload
10717 // resolution, return Incompatible to indicate the failure.
10718 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10719 CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E, CCK: CCK_ImplicitConversion,
10720 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10721 if (!Diagnose)
10722 return Incompatible;
10723 }
10724 if (getLangOpts().ObjC &&
10725 (CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10726 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10727 CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10728 if (!Diagnose)
10729 return Incompatible;
10730 // Replace the expression with a corrected version and continue so we
10731 // can find further errors.
10732 RHS = E;
10733 return Compatible;
10734 }
10735
10736 if (ConvertRHS)
10737 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10738 }
10739
10740 return result;
10741}
10742
10743namespace {
10744/// The original operand to an operator, prior to the application of the usual
10745/// arithmetic conversions and converting the arguments of a builtin operator
10746/// candidate.
10747struct OriginalOperand {
10748 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10749 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10750 Op = MTE->getSubExpr();
10751 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10752 Op = BTE->getSubExpr();
10753 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10754 Orig = ICE->getSubExprAsWritten();
10755 Conversion = ICE->getConversionFunction();
10756 }
10757 }
10758
10759 QualType getType() const { return Orig->getType(); }
10760
10761 Expr *Orig;
10762 NamedDecl *Conversion;
10763};
10764}
10765
10766QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10767 ExprResult &RHS) {
10768 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10769
10770 Diag(Loc, diag::err_typecheck_invalid_operands)
10771 << OrigLHS.getType() << OrigRHS.getType()
10772 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10773
10774 // If a user-defined conversion was applied to either of the operands prior
10775 // to applying the built-in operator rules, tell the user about it.
10776 if (OrigLHS.Conversion) {
10777 Diag(OrigLHS.Conversion->getLocation(),
10778 diag::note_typecheck_invalid_operands_converted)
10779 << 0 << LHS.get()->getType();
10780 }
10781 if (OrigRHS.Conversion) {
10782 Diag(OrigRHS.Conversion->getLocation(),
10783 diag::note_typecheck_invalid_operands_converted)
10784 << 1 << RHS.get()->getType();
10785 }
10786
10787 return QualType();
10788}
10789
10790// Diagnose cases where a scalar was implicitly converted to a vector and
10791// diagnose the underlying types. Otherwise, diagnose the error
10792// as invalid vector logical operands for non-C++ cases.
10793QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10794 ExprResult &RHS) {
10795 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10796 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10797
10798 bool LHSNatVec = LHSType->isVectorType();
10799 bool RHSNatVec = RHSType->isVectorType();
10800
10801 if (!(LHSNatVec && RHSNatVec)) {
10802 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10803 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10804 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10805 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10806 << Vector->getSourceRange();
10807 return QualType();
10808 }
10809
10810 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10811 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10812 << RHS.get()->getSourceRange();
10813
10814 return QualType();
10815}
10816
10817/// Try to convert a value of non-vector type to a vector type by converting
10818/// the type to the element type of the vector and then performing a splat.
10819/// If the language is OpenCL, we only use conversions that promote scalar
10820/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10821/// for float->int.
10822///
10823/// OpenCL V2.0 6.2.6.p2:
10824/// An error shall occur if any scalar operand type has greater rank
10825/// than the type of the vector element.
10826///
10827/// \param scalar - if non-null, actually perform the conversions
10828/// \return true if the operation fails (but without diagnosing the failure)
10829static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10830 QualType scalarTy,
10831 QualType vectorEltTy,
10832 QualType vectorTy,
10833 unsigned &DiagID) {
10834 // The conversion to apply to the scalar before splatting it,
10835 // if necessary.
10836 CastKind scalarCast = CK_NoOp;
10837
10838 if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10839 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10840 (scalarTy->isIntegerType() &&
10841 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10842 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10843 return true;
10844 }
10845 if (!scalarTy->isIntegralType(Ctx: S.Context))
10846 return true;
10847 scalarCast = CK_IntegralCast;
10848 } else if (vectorEltTy->isRealFloatingType()) {
10849 if (scalarTy->isRealFloatingType()) {
10850 if (S.getLangOpts().OpenCL &&
10851 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10852 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10853 return true;
10854 }
10855 scalarCast = CK_FloatingCast;
10856 }
10857 else if (scalarTy->isIntegralType(Ctx: S.Context))
10858 scalarCast = CK_IntegralToFloating;
10859 else
10860 return true;
10861 } else {
10862 return true;
10863 }
10864
10865 // Adjust scalar if desired.
10866 if (scalar) {
10867 if (scalarCast != CK_NoOp)
10868 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10869 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10870 }
10871 return false;
10872}
10873
10874/// Convert vector E to a vector with the same number of elements but different
10875/// element type.
10876static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10877 const auto *VecTy = E->getType()->getAs<VectorType>();
10878 assert(VecTy && "Expression E must be a vector");
10879 QualType NewVecTy =
10880 VecTy->isExtVectorType()
10881 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10882 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10883 VecKind: VecTy->getVectorKind());
10884
10885 // Look through the implicit cast. Return the subexpression if its type is
10886 // NewVecTy.
10887 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10888 if (ICE->getSubExpr()->getType() == NewVecTy)
10889 return ICE->getSubExpr();
10890
10891 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10892 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10893}
10894
10895/// Test if a (constant) integer Int can be casted to another integer type
10896/// IntTy without losing precision.
10897static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10898 QualType OtherIntTy) {
10899 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10900
10901 // Reject cases where the value of the Int is unknown as that would
10902 // possibly cause truncation, but accept cases where the scalar can be
10903 // demoted without loss of precision.
10904 Expr::EvalResult EVResult;
10905 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10906 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10907 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10908 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10909
10910 if (CstInt) {
10911 // If the scalar is constant and is of a higher order and has more active
10912 // bits that the vector element type, reject it.
10913 llvm::APSInt Result = EVResult.Val.getInt();
10914 unsigned NumBits = IntSigned
10915 ? (Result.isNegative() ? Result.getSignificantBits()
10916 : Result.getActiveBits())
10917 : Result.getActiveBits();
10918 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10919 return true;
10920
10921 // If the signedness of the scalar type and the vector element type
10922 // differs and the number of bits is greater than that of the vector
10923 // element reject it.
10924 return (IntSigned != OtherIntSigned &&
10925 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10926 }
10927
10928 // Reject cases where the value of the scalar is not constant and it's
10929 // order is greater than that of the vector element type.
10930 return (Order < 0);
10931}
10932
10933/// Test if a (constant) integer Int can be casted to floating point type
10934/// FloatTy without losing precision.
10935static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10936 QualType FloatTy) {
10937 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10938
10939 // Determine if the integer constant can be expressed as a floating point
10940 // number of the appropriate type.
10941 Expr::EvalResult EVResult;
10942 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10943
10944 uint64_t Bits = 0;
10945 if (CstInt) {
10946 // Reject constants that would be truncated if they were converted to
10947 // the floating point type. Test by simple to/from conversion.
10948 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10949 // could be avoided if there was a convertFromAPInt method
10950 // which could signal back if implicit truncation occurred.
10951 llvm::APSInt Result = EVResult.Val.getInt();
10952 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10953 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10954 RM: llvm::APFloat::rmTowardZero);
10955 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10956 !IntTy->hasSignedIntegerRepresentation());
10957 bool Ignored = false;
10958 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10959 IsExact: &Ignored);
10960 if (Result != ConvertBack)
10961 return true;
10962 } else {
10963 // Reject types that cannot be fully encoded into the mantissa of
10964 // the float.
10965 Bits = S.Context.getTypeSize(T: IntTy);
10966 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10967 S.Context.getFloatTypeSemantics(T: FloatTy));
10968 if (Bits > FloatPrec)
10969 return true;
10970 }
10971
10972 return false;
10973}
10974
10975/// Attempt to convert and splat Scalar into a vector whose types matches
10976/// Vector following GCC conversion rules. The rule is that implicit
10977/// conversion can occur when Scalar can be casted to match Vector's element
10978/// type without causing truncation of Scalar.
10979static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10980 ExprResult *Vector) {
10981 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10982 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10983 QualType VectorEltTy;
10984
10985 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10986 assert(!isa<ExtVectorType>(VT) &&
10987 "ExtVectorTypes should not be handled here!");
10988 VectorEltTy = VT->getElementType();
10989 } else if (VectorTy->isSveVLSBuiltinType()) {
10990 VectorEltTy =
10991 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10992 } else {
10993 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10994 }
10995
10996 // Reject cases where the vector element type or the scalar element type are
10997 // not integral or floating point types.
10998 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10999 return true;
11000
11001 // The conversion to apply to the scalar before splatting it,
11002 // if necessary.
11003 CastKind ScalarCast = CK_NoOp;
11004
11005 // Accept cases where the vector elements are integers and the scalar is
11006 // an integer.
11007 // FIXME: Notionally if the scalar was a floating point value with a precise
11008 // integral representation, we could cast it to an appropriate integer
11009 // type and then perform the rest of the checks here. GCC will perform
11010 // this conversion in some cases as determined by the input language.
11011 // We should accept it on a language independent basis.
11012 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
11013 ScalarTy->isIntegralType(Ctx: S.Context) &&
11014 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
11015
11016 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
11017 return true;
11018
11019 ScalarCast = CK_IntegralCast;
11020 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
11021 ScalarTy->isRealFloatingType()) {
11022 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
11023 ScalarCast = CK_FloatingToIntegral;
11024 else
11025 return true;
11026 } else if (VectorEltTy->isRealFloatingType()) {
11027 if (ScalarTy->isRealFloatingType()) {
11028
11029 // Reject cases where the scalar type is not a constant and has a higher
11030 // Order than the vector element type.
11031 llvm::APFloat Result(0.0);
11032
11033 // Determine whether this is a constant scalar. In the event that the
11034 // value is dependent (and thus cannot be evaluated by the constant
11035 // evaluator), skip the evaluation. This will then diagnose once the
11036 // expression is instantiated.
11037 bool CstScalar = Scalar->get()->isValueDependent() ||
11038 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
11039 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
11040 if (!CstScalar && Order < 0)
11041 return true;
11042
11043 // If the scalar cannot be safely casted to the vector element type,
11044 // reject it.
11045 if (CstScalar) {
11046 bool Truncated = false;
11047 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
11048 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
11049 if (Truncated)
11050 return true;
11051 }
11052
11053 ScalarCast = CK_FloatingCast;
11054 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
11055 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
11056 return true;
11057
11058 ScalarCast = CK_IntegralToFloating;
11059 } else
11060 return true;
11061 } else if (ScalarTy->isEnumeralType())
11062 return true;
11063
11064 // Adjust scalar if desired.
11065 if (ScalarCast != CK_NoOp)
11066 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
11067 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
11068 return false;
11069}
11070
11071QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11072 SourceLocation Loc, bool IsCompAssign,
11073 bool AllowBothBool,
11074 bool AllowBoolConversions,
11075 bool AllowBoolOperation,
11076 bool ReportInvalid) {
11077 if (!IsCompAssign) {
11078 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11079 if (LHS.isInvalid())
11080 return QualType();
11081 }
11082 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11083 if (RHS.isInvalid())
11084 return QualType();
11085
11086 // For conversion purposes, we ignore any qualifiers.
11087 // For example, "const float" and "float" are equivalent.
11088 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11089 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11090
11091 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
11092 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
11093 assert(LHSVecType || RHSVecType);
11094
11095 // AltiVec-style "vector bool op vector bool" combinations are allowed
11096 // for some operators but not others.
11097 if (!AllowBothBool && LHSVecType &&
11098 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
11099 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11100 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11101
11102 // This operation may not be performed on boolean vectors.
11103 if (!AllowBoolOperation &&
11104 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11105 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11106
11107 // If the vector types are identical, return.
11108 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11109 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
11110
11111 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11112 if (LHSVecType && RHSVecType &&
11113 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
11114 if (isa<ExtVectorType>(Val: LHSVecType)) {
11115 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
11116 return LHSType;
11117 }
11118
11119 if (!IsCompAssign)
11120 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
11121 return RHSType;
11122 }
11123
11124 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11125 // can be mixed, with the result being the non-bool type. The non-bool
11126 // operand must have integer element type.
11127 if (AllowBoolConversions && LHSVecType && RHSVecType &&
11128 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11129 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
11130 Context.getTypeSize(T: RHSVecType->getElementType()))) {
11131 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11132 LHSVecType->getElementType()->isIntegerType() &&
11133 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
11134 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
11135 return LHSType;
11136 }
11137 if (!IsCompAssign &&
11138 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
11139 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11140 RHSVecType->getElementType()->isIntegerType()) {
11141 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
11142 return RHSType;
11143 }
11144 }
11145
11146 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11147 // invalid since the ambiguity can affect the ABI.
11148 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11149 unsigned &SVEorRVV) {
11150 const VectorType *VecType = SecondType->getAs<VectorType>();
11151 SVEorRVV = 0;
11152 if (FirstType->isSizelessBuiltinType() && VecType) {
11153 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11154 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
11155 return true;
11156 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
11157 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
11158 SVEorRVV = 1;
11159 return true;
11160 }
11161 }
11162
11163 return false;
11164 };
11165
11166 unsigned SVEorRVV;
11167 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11168 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11169 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11170 << SVEorRVV << LHSType << RHSType;
11171 return QualType();
11172 }
11173
11174 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11175 // invalid since the ambiguity can affect the ABI.
11176 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11177 unsigned &SVEorRVV) {
11178 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11179 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11180
11181 SVEorRVV = 0;
11182 if (FirstVecType && SecondVecType) {
11183 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11184 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11185 SecondVecType->getVectorKind() ==
11186 VectorKind::SveFixedLengthPredicate)
11187 return true;
11188 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
11189 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
11190 SVEorRVV = 1;
11191 return true;
11192 }
11193 }
11194 return false;
11195 }
11196
11197 if (SecondVecType &&
11198 SecondVecType->getVectorKind() == VectorKind::Generic) {
11199 if (FirstType->isSVESizelessBuiltinType())
11200 return true;
11201 if (FirstType->isRVVSizelessBuiltinType()) {
11202 SVEorRVV = 1;
11203 return true;
11204 }
11205 }
11206
11207 return false;
11208 };
11209
11210 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11211 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11212 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11213 << SVEorRVV << LHSType << RHSType;
11214 return QualType();
11215 }
11216
11217 // If there's a vector type and a scalar, try to convert the scalar to
11218 // the vector element type and splat.
11219 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11220 if (!RHSVecType) {
11221 if (isa<ExtVectorType>(Val: LHSVecType)) {
11222 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
11223 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
11224 DiagID))
11225 return LHSType;
11226 } else {
11227 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11228 return LHSType;
11229 }
11230 }
11231 if (!LHSVecType) {
11232 if (isa<ExtVectorType>(Val: RHSVecType)) {
11233 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
11234 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
11235 vectorTy: RHSType, DiagID))
11236 return RHSType;
11237 } else {
11238 if (LHS.get()->isLValue() ||
11239 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11240 return RHSType;
11241 }
11242 }
11243
11244 // FIXME: The code below also handles conversion between vectors and
11245 // non-scalars, we should break this down into fine grained specific checks
11246 // and emit proper diagnostics.
11247 QualType VecType = LHSVecType ? LHSType : RHSType;
11248 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11249 QualType OtherType = LHSVecType ? RHSType : LHSType;
11250 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11251 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
11252 if (Context.getTargetInfo().getTriple().isPPC() &&
11253 anyAltivecTypes(RHSType, LHSType) &&
11254 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11255 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11256 // If we're allowing lax vector conversions, only the total (data) size
11257 // needs to be the same. For non compound assignment, if one of the types is
11258 // scalar, the result is always the vector type.
11259 if (!IsCompAssign) {
11260 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
11261 return VecType;
11262 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11263 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11264 // type. Note that this is already done by non-compound assignments in
11265 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11266 // <1 x T> -> T. The result is also a vector type.
11267 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11268 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11269 ExprResult *RHSExpr = &RHS;
11270 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
11271 return VecType;
11272 }
11273 }
11274
11275 // Okay, the expression is invalid.
11276
11277 // If there's a non-vector, non-real operand, diagnose that.
11278 if ((!RHSVecType && !RHSType->isRealType()) ||
11279 (!LHSVecType && !LHSType->isRealType())) {
11280 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11281 << LHSType << RHSType
11282 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11283 return QualType();
11284 }
11285
11286 // OpenCL V1.1 6.2.6.p1:
11287 // If the operands are of more than one vector type, then an error shall
11288 // occur. Implicit conversions between vector types are not permitted, per
11289 // section 6.2.1.
11290 if (getLangOpts().OpenCL &&
11291 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11292 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11293 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11294 << RHSType;
11295 return QualType();
11296 }
11297
11298
11299 // If there is a vector type that is not a ExtVector and a scalar, we reach
11300 // this point if scalar could not be converted to the vector's element type
11301 // without truncation.
11302 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11303 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11304 QualType Scalar = LHSVecType ? RHSType : LHSType;
11305 QualType Vector = LHSVecType ? LHSType : RHSType;
11306 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11307 Diag(Loc,
11308 diag::err_typecheck_vector_not_convertable_implict_truncation)
11309 << ScalarOrVector << Scalar << Vector;
11310
11311 return QualType();
11312 }
11313
11314 // Otherwise, use the generic diagnostic.
11315 Diag(Loc, DiagID)
11316 << LHSType << RHSType
11317 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11318 return QualType();
11319}
11320
11321QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11322 SourceLocation Loc,
11323 bool IsCompAssign,
11324 ArithConvKind OperationKind) {
11325 if (!IsCompAssign) {
11326 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11327 if (LHS.isInvalid())
11328 return QualType();
11329 }
11330 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11331 if (RHS.isInvalid())
11332 return QualType();
11333
11334 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11335 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11336
11337 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11338 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11339
11340 unsigned DiagID = diag::err_typecheck_invalid_operands;
11341 if ((OperationKind == ACK_Arithmetic) &&
11342 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11343 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11344 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11345 << RHS.get()->getSourceRange();
11346 return QualType();
11347 }
11348
11349 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11350 return LHSType;
11351
11352 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11353 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11354 return LHSType;
11355 }
11356 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11357 if (LHS.get()->isLValue() ||
11358 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11359 return RHSType;
11360 }
11361
11362 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11363 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11364 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11365 << LHSType << RHSType << LHS.get()->getSourceRange()
11366 << RHS.get()->getSourceRange();
11367 return QualType();
11368 }
11369
11370 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11371 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11372 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11373 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11374 << LHSType << RHSType << LHS.get()->getSourceRange()
11375 << RHS.get()->getSourceRange();
11376 return QualType();
11377 }
11378
11379 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11380 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11381 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11382 bool ScalarOrVector =
11383 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11384
11385 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11386 << ScalarOrVector << Scalar << Vector;
11387
11388 return QualType();
11389 }
11390
11391 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11392 << RHS.get()->getSourceRange();
11393 return QualType();
11394}
11395
11396// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11397// expression. These are mainly cases where the null pointer is used as an
11398// integer instead of a pointer.
11399static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11400 SourceLocation Loc, bool IsCompare) {
11401 // The canonical way to check for a GNU null is with isNullPointerConstant,
11402 // but we use a bit of a hack here for speed; this is a relatively
11403 // hot path, and isNullPointerConstant is slow.
11404 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11405 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11406
11407 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11408
11409 // Avoid analyzing cases where the result will either be invalid (and
11410 // diagnosed as such) or entirely valid and not something to warn about.
11411 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11412 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11413 return;
11414
11415 // Comparison operations would not make sense with a null pointer no matter
11416 // what the other expression is.
11417 if (!IsCompare) {
11418 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11419 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11420 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11421 return;
11422 }
11423
11424 // The rest of the operations only make sense with a null pointer
11425 // if the other expression is a pointer.
11426 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11427 NonNullType->canDecayToPointerType())
11428 return;
11429
11430 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11431 << LHSNull /* LHS is NULL */ << NonNullType
11432 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11433}
11434
11435static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11436 SourceLocation Loc) {
11437 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11438 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11439 if (!LUE || !RUE)
11440 return;
11441 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11442 RUE->getKind() != UETT_SizeOf)
11443 return;
11444
11445 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11446 QualType LHSTy = LHSArg->getType();
11447 QualType RHSTy;
11448
11449 if (RUE->isArgumentType())
11450 RHSTy = RUE->getArgumentType().getNonReferenceType();
11451 else
11452 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11453
11454 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11455 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11456 return;
11457
11458 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11459 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11460 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11461 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11462 << LHSArgDecl;
11463 }
11464 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11465 QualType ArrayElemTy = ArrayTy->getElementType();
11466 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11467 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11468 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11469 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11470 return;
11471 S.Diag(Loc, diag::warn_division_sizeof_array)
11472 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11473 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11474 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11475 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11476 << LHSArgDecl;
11477 }
11478
11479 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11480 }
11481}
11482
11483static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11484 ExprResult &RHS,
11485 SourceLocation Loc, bool IsDiv) {
11486 // Check for division/remainder by zero.
11487 Expr::EvalResult RHSValue;
11488 if (!RHS.get()->isValueDependent() &&
11489 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11490 RHSValue.Val.getInt() == 0)
11491 S.DiagRuntimeBehavior(Loc, RHS.get(),
11492 S.PDiag(diag::warn_remainder_division_by_zero)
11493 << IsDiv << RHS.get()->getSourceRange());
11494}
11495
11496QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11497 SourceLocation Loc,
11498 bool IsCompAssign, bool IsDiv) {
11499 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11500
11501 QualType LHSTy = LHS.get()->getType();
11502 QualType RHSTy = RHS.get()->getType();
11503 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11504 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11505 /*AllowBothBool*/ getLangOpts().AltiVec,
11506 /*AllowBoolConversions*/ false,
11507 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11508 /*ReportInvalid*/ true);
11509 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11510 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11511 OperationKind: ACK_Arithmetic);
11512 if (!IsDiv &&
11513 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11514 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11515 // For division, only matrix-by-scalar is supported. Other combinations with
11516 // matrix types are invalid.
11517 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11518 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11519
11520 QualType compType = UsualArithmeticConversions(
11521 LHS, RHS, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11522 if (LHS.isInvalid() || RHS.isInvalid())
11523 return QualType();
11524
11525
11526 if (compType.isNull() || !compType->isArithmeticType())
11527 return InvalidOperands(Loc, LHS, RHS);
11528 if (IsDiv) {
11529 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11530 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11531 }
11532 return compType;
11533}
11534
11535QualType Sema::CheckRemainderOperands(
11536 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11537 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11538
11539 if (LHS.get()->getType()->isVectorType() ||
11540 RHS.get()->getType()->isVectorType()) {
11541 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11542 RHS.get()->getType()->hasIntegerRepresentation())
11543 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11544 /*AllowBothBool*/ getLangOpts().AltiVec,
11545 /*AllowBoolConversions*/ false,
11546 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11547 /*ReportInvalid*/ true);
11548 return InvalidOperands(Loc, LHS, RHS);
11549 }
11550
11551 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11552 RHS.get()->getType()->isSveVLSBuiltinType()) {
11553 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11554 RHS.get()->getType()->hasIntegerRepresentation())
11555 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11556 OperationKind: ACK_Arithmetic);
11557
11558 return InvalidOperands(Loc, LHS, RHS);
11559 }
11560
11561 QualType compType = UsualArithmeticConversions(
11562 LHS, RHS, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11563 if (LHS.isInvalid() || RHS.isInvalid())
11564 return QualType();
11565
11566 if (compType.isNull() || !compType->isIntegerType())
11567 return InvalidOperands(Loc, LHS, RHS);
11568 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11569 return compType;
11570}
11571
11572/// Diagnose invalid arithmetic on two void pointers.
11573static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11574 Expr *LHSExpr, Expr *RHSExpr) {
11575 S.Diag(Loc, S.getLangOpts().CPlusPlus
11576 ? diag::err_typecheck_pointer_arith_void_type
11577 : diag::ext_gnu_void_ptr)
11578 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11579 << RHSExpr->getSourceRange();
11580}
11581
11582/// Diagnose invalid arithmetic on a void pointer.
11583static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11584 Expr *Pointer) {
11585 S.Diag(Loc, S.getLangOpts().CPlusPlus
11586 ? diag::err_typecheck_pointer_arith_void_type
11587 : diag::ext_gnu_void_ptr)
11588 << 0 /* one pointer */ << Pointer->getSourceRange();
11589}
11590
11591/// Diagnose invalid arithmetic on a null pointer.
11592///
11593/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11594/// idiom, which we recognize as a GNU extension.
11595///
11596static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11597 Expr *Pointer, bool IsGNUIdiom) {
11598 if (IsGNUIdiom)
11599 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11600 << Pointer->getSourceRange();
11601 else
11602 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11603 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11604}
11605
11606/// Diagnose invalid subraction on a null pointer.
11607///
11608static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11609 Expr *Pointer, bool BothNull) {
11610 // Null - null is valid in C++ [expr.add]p7
11611 if (BothNull && S.getLangOpts().CPlusPlus)
11612 return;
11613
11614 // Is this s a macro from a system header?
11615 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11616 return;
11617
11618 S.DiagRuntimeBehavior(Loc, Pointer,
11619 S.PDiag(diag::warn_pointer_sub_null_ptr)
11620 << S.getLangOpts().CPlusPlus
11621 << Pointer->getSourceRange());
11622}
11623
11624/// Diagnose invalid arithmetic on two function pointers.
11625static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11626 Expr *LHS, Expr *RHS) {
11627 assert(LHS->getType()->isAnyPointerType());
11628 assert(RHS->getType()->isAnyPointerType());
11629 S.Diag(Loc, S.getLangOpts().CPlusPlus
11630 ? diag::err_typecheck_pointer_arith_function_type
11631 : diag::ext_gnu_ptr_func_arith)
11632 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11633 // We only show the second type if it differs from the first.
11634 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11635 RHS->getType())
11636 << RHS->getType()->getPointeeType()
11637 << LHS->getSourceRange() << RHS->getSourceRange();
11638}
11639
11640/// Diagnose invalid arithmetic on a function pointer.
11641static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11642 Expr *Pointer) {
11643 assert(Pointer->getType()->isAnyPointerType());
11644 S.Diag(Loc, S.getLangOpts().CPlusPlus
11645 ? diag::err_typecheck_pointer_arith_function_type
11646 : diag::ext_gnu_ptr_func_arith)
11647 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11648 << 0 /* one pointer, so only one type */
11649 << Pointer->getSourceRange();
11650}
11651
11652/// Emit error if Operand is incomplete pointer type
11653///
11654/// \returns True if pointer has incomplete type
11655static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11656 Expr *Operand) {
11657 QualType ResType = Operand->getType();
11658 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11659 ResType = ResAtomicType->getValueType();
11660
11661 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11662 QualType PointeeTy = ResType->getPointeeType();
11663 return S.RequireCompleteSizedType(
11664 Loc, PointeeTy,
11665 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11666 Operand->getSourceRange());
11667}
11668
11669/// Check the validity of an arithmetic pointer operand.
11670///
11671/// If the operand has pointer type, this code will check for pointer types
11672/// which are invalid in arithmetic operations. These will be diagnosed
11673/// appropriately, including whether or not the use is supported as an
11674/// extension.
11675///
11676/// \returns True when the operand is valid to use (even if as an extension).
11677static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11678 Expr *Operand) {
11679 QualType ResType = Operand->getType();
11680 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11681 ResType = ResAtomicType->getValueType();
11682
11683 if (!ResType->isAnyPointerType()) return true;
11684
11685 QualType PointeeTy = ResType->getPointeeType();
11686 if (PointeeTy->isVoidType()) {
11687 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11688 return !S.getLangOpts().CPlusPlus;
11689 }
11690 if (PointeeTy->isFunctionType()) {
11691 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11692 return !S.getLangOpts().CPlusPlus;
11693 }
11694
11695 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11696
11697 return true;
11698}
11699
11700/// Check the validity of a binary arithmetic operation w.r.t. pointer
11701/// operands.
11702///
11703/// This routine will diagnose any invalid arithmetic on pointer operands much
11704/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11705/// for emitting a single diagnostic even for operations where both LHS and RHS
11706/// are (potentially problematic) pointers.
11707///
11708/// \returns True when the operand is valid to use (even if as an extension).
11709static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11710 Expr *LHSExpr, Expr *RHSExpr) {
11711 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11712 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11713 if (!isLHSPointer && !isRHSPointer) return true;
11714
11715 QualType LHSPointeeTy, RHSPointeeTy;
11716 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11717 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11718
11719 // if both are pointers check if operation is valid wrt address spaces
11720 if (isLHSPointer && isRHSPointer) {
11721 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy)) {
11722 S.Diag(Loc,
11723 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11724 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11725 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11726 return false;
11727 }
11728 }
11729
11730 // Check for arithmetic on pointers to incomplete types.
11731 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11732 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11733 if (isLHSVoidPtr || isRHSVoidPtr) {
11734 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11735 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11736 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11737
11738 return !S.getLangOpts().CPlusPlus;
11739 }
11740
11741 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11742 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11743 if (isLHSFuncPtr || isRHSFuncPtr) {
11744 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11745 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11746 Pointer: RHSExpr);
11747 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11748
11749 return !S.getLangOpts().CPlusPlus;
11750 }
11751
11752 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11753 return false;
11754 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11755 return false;
11756
11757 return true;
11758}
11759
11760/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11761/// literal.
11762static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11763 Expr *LHSExpr, Expr *RHSExpr) {
11764 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11765 Expr* IndexExpr = RHSExpr;
11766 if (!StrExpr) {
11767 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11768 IndexExpr = LHSExpr;
11769 }
11770
11771 bool IsStringPlusInt = StrExpr &&
11772 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11773 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11774 return;
11775
11776 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11777 Self.Diag(OpLoc, diag::warn_string_plus_int)
11778 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11779
11780 // Only print a fixit for "str" + int, not for int + "str".
11781 if (IndexExpr == RHSExpr) {
11782 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11783 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11784 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11785 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11786 << FixItHint::CreateInsertion(EndLoc, "]");
11787 } else
11788 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11789}
11790
11791/// Emit a warning when adding a char literal to a string.
11792static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11793 Expr *LHSExpr, Expr *RHSExpr) {
11794 const Expr *StringRefExpr = LHSExpr;
11795 const CharacterLiteral *CharExpr =
11796 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11797
11798 if (!CharExpr) {
11799 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11800 StringRefExpr = RHSExpr;
11801 }
11802
11803 if (!CharExpr || !StringRefExpr)
11804 return;
11805
11806 const QualType StringType = StringRefExpr->getType();
11807
11808 // Return if not a PointerType.
11809 if (!StringType->isAnyPointerType())
11810 return;
11811
11812 // Return if not a CharacterType.
11813 if (!StringType->getPointeeType()->isAnyCharacterType())
11814 return;
11815
11816 ASTContext &Ctx = Self.getASTContext();
11817 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11818
11819 const QualType CharType = CharExpr->getType();
11820 if (!CharType->isAnyCharacterType() &&
11821 CharType->isIntegerType() &&
11822 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11823 Self.Diag(OpLoc, diag::warn_string_plus_char)
11824 << DiagRange << Ctx.CharTy;
11825 } else {
11826 Self.Diag(OpLoc, diag::warn_string_plus_char)
11827 << DiagRange << CharExpr->getType();
11828 }
11829
11830 // Only print a fixit for str + char, not for char + str.
11831 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11832 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11833 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11834 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11835 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11836 << FixItHint::CreateInsertion(EndLoc, "]");
11837 } else {
11838 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11839 }
11840}
11841
11842/// Emit error when two pointers are incompatible.
11843static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11844 Expr *LHSExpr, Expr *RHSExpr) {
11845 assert(LHSExpr->getType()->isAnyPointerType());
11846 assert(RHSExpr->getType()->isAnyPointerType());
11847 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11848 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11849 << RHSExpr->getSourceRange();
11850}
11851
11852// C99 6.5.6
11853QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11854 SourceLocation Loc, BinaryOperatorKind Opc,
11855 QualType* CompLHSTy) {
11856 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11857
11858 if (LHS.get()->getType()->isVectorType() ||
11859 RHS.get()->getType()->isVectorType()) {
11860 QualType compType =
11861 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11862 /*AllowBothBool*/ getLangOpts().AltiVec,
11863 /*AllowBoolConversions*/ getLangOpts().ZVector,
11864 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11865 /*ReportInvalid*/ true);
11866 if (CompLHSTy) *CompLHSTy = compType;
11867 return compType;
11868 }
11869
11870 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11871 RHS.get()->getType()->isSveVLSBuiltinType()) {
11872 QualType compType =
11873 CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, OperationKind: ACK_Arithmetic);
11874 if (CompLHSTy)
11875 *CompLHSTy = compType;
11876 return compType;
11877 }
11878
11879 if (LHS.get()->getType()->isConstantMatrixType() ||
11880 RHS.get()->getType()->isConstantMatrixType()) {
11881 QualType compType =
11882 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11883 if (CompLHSTy)
11884 *CompLHSTy = compType;
11885 return compType;
11886 }
11887
11888 QualType compType = UsualArithmeticConversions(
11889 LHS, RHS, Loc, ACK: CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11890 if (LHS.isInvalid() || RHS.isInvalid())
11891 return QualType();
11892
11893 // Diagnose "string literal" '+' int and string '+' "char literal".
11894 if (Opc == BO_Add) {
11895 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11896 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11897 }
11898
11899 // handle the common case first (both operands are arithmetic).
11900 if (!compType.isNull() && compType->isArithmeticType()) {
11901 if (CompLHSTy) *CompLHSTy = compType;
11902 return compType;
11903 }
11904
11905 // Type-checking. Ultimately the pointer's going to be in PExp;
11906 // note that we bias towards the LHS being the pointer.
11907 Expr *PExp = LHS.get(), *IExp = RHS.get();
11908
11909 bool isObjCPointer;
11910 if (PExp->getType()->isPointerType()) {
11911 isObjCPointer = false;
11912 } else if (PExp->getType()->isObjCObjectPointerType()) {
11913 isObjCPointer = true;
11914 } else {
11915 std::swap(a&: PExp, b&: IExp);
11916 if (PExp->getType()->isPointerType()) {
11917 isObjCPointer = false;
11918 } else if (PExp->getType()->isObjCObjectPointerType()) {
11919 isObjCPointer = true;
11920 } else {
11921 return InvalidOperands(Loc, LHS, RHS);
11922 }
11923 }
11924 assert(PExp->getType()->isAnyPointerType());
11925
11926 if (!IExp->getType()->isIntegerType())
11927 return InvalidOperands(Loc, LHS, RHS);
11928
11929 // Adding to a null pointer results in undefined behavior.
11930 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11931 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11932 // In C++ adding zero to a null pointer is defined.
11933 Expr::EvalResult KnownVal;
11934 if (!getLangOpts().CPlusPlus ||
11935 (!IExp->isValueDependent() &&
11936 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11937 KnownVal.Val.getInt() != 0))) {
11938 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11939 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11940 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11941 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11942 }
11943 }
11944
11945 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11946 return QualType();
11947
11948 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11949 return QualType();
11950
11951 // Check array bounds for pointer arithemtic
11952 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11953
11954 if (CompLHSTy) {
11955 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11956 if (LHSTy.isNull()) {
11957 LHSTy = LHS.get()->getType();
11958 if (Context.isPromotableIntegerType(T: LHSTy))
11959 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11960 }
11961 *CompLHSTy = LHSTy;
11962 }
11963
11964 return PExp->getType();
11965}
11966
11967// C99 6.5.6
11968QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11969 SourceLocation Loc,
11970 QualType* CompLHSTy) {
11971 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11972
11973 if (LHS.get()->getType()->isVectorType() ||
11974 RHS.get()->getType()->isVectorType()) {
11975 QualType compType =
11976 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11977 /*AllowBothBool*/ getLangOpts().AltiVec,
11978 /*AllowBoolConversions*/ getLangOpts().ZVector,
11979 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11980 /*ReportInvalid*/ true);
11981 if (CompLHSTy) *CompLHSTy = compType;
11982 return compType;
11983 }
11984
11985 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11986 RHS.get()->getType()->isSveVLSBuiltinType()) {
11987 QualType compType =
11988 CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, OperationKind: ACK_Arithmetic);
11989 if (CompLHSTy)
11990 *CompLHSTy = compType;
11991 return compType;
11992 }
11993
11994 if (LHS.get()->getType()->isConstantMatrixType() ||
11995 RHS.get()->getType()->isConstantMatrixType()) {
11996 QualType compType =
11997 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11998 if (CompLHSTy)
11999 *CompLHSTy = compType;
12000 return compType;
12001 }
12002
12003 QualType compType = UsualArithmeticConversions(
12004 LHS, RHS, Loc, ACK: CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
12005 if (LHS.isInvalid() || RHS.isInvalid())
12006 return QualType();
12007
12008 // Enforce type constraints: C99 6.5.6p3.
12009
12010 // Handle the common case first (both operands are arithmetic).
12011 if (!compType.isNull() && compType->isArithmeticType()) {
12012 if (CompLHSTy) *CompLHSTy = compType;
12013 return compType;
12014 }
12015
12016 // Either ptr - int or ptr - ptr.
12017 if (LHS.get()->getType()->isAnyPointerType()) {
12018 QualType lpointee = LHS.get()->getType()->getPointeeType();
12019
12020 // Diagnose bad cases where we step over interface counts.
12021 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12022 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
12023 return QualType();
12024
12025 // The result type of a pointer-int computation is the pointer type.
12026 if (RHS.get()->getType()->isIntegerType()) {
12027 // Subtracting from a null pointer should produce a warning.
12028 // The last argument to the diagnose call says this doesn't match the
12029 // GNU int-to-pointer idiom.
12030 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
12031 NPC: Expr::NPC_ValueDependentIsNotNull)) {
12032 // In C++ adding zero to a null pointer is defined.
12033 Expr::EvalResult KnownVal;
12034 if (!getLangOpts().CPlusPlus ||
12035 (!RHS.get()->isValueDependent() &&
12036 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
12037 KnownVal.Val.getInt() != 0))) {
12038 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
12039 }
12040 }
12041
12042 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
12043 return QualType();
12044
12045 // Check array bounds for pointer arithemtic
12046 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
12047 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12048
12049 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12050 return LHS.get()->getType();
12051 }
12052
12053 // Handle pointer-pointer subtractions.
12054 if (const PointerType *RHSPTy
12055 = RHS.get()->getType()->getAs<PointerType>()) {
12056 QualType rpointee = RHSPTy->getPointeeType();
12057
12058 if (getLangOpts().CPlusPlus) {
12059 // Pointee types must be the same: C++ [expr.add]
12060 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
12061 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12062 }
12063 } else {
12064 // Pointee types must be compatible C99 6.5.6p3
12065 if (!Context.typesAreCompatible(
12066 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
12067 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
12068 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12069 return QualType();
12070 }
12071 }
12072
12073 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
12074 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
12075 return QualType();
12076
12077 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12078 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12079 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12080 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12081
12082 // Subtracting nullptr or from nullptr is suspect
12083 if (LHSIsNullPtr)
12084 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
12085 if (RHSIsNullPtr)
12086 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
12087
12088 // The pointee type may have zero size. As an extension, a structure or
12089 // union may have zero size or an array may have zero length. In this
12090 // case subtraction does not make sense.
12091 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
12092 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
12093 if (ElementSize.isZero()) {
12094 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
12095 << rpointee.getUnqualifiedType()
12096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12097 }
12098 }
12099
12100 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12101 return Context.getPointerDiffType();
12102 }
12103 }
12104
12105 return InvalidOperands(Loc, LHS, RHS);
12106}
12107
12108static bool isScopedEnumerationType(QualType T) {
12109 if (const EnumType *ET = T->getAs<EnumType>())
12110 return ET->getDecl()->isScoped();
12111 return false;
12112}
12113
12114static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12115 SourceLocation Loc, BinaryOperatorKind Opc,
12116 QualType LHSType) {
12117 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12118 // so skip remaining warnings as we don't want to modify values within Sema.
12119 if (S.getLangOpts().OpenCL)
12120 return;
12121
12122 // Check right/shifter operand
12123 Expr::EvalResult RHSResult;
12124 if (RHS.get()->isValueDependent() ||
12125 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
12126 return;
12127 llvm::APSInt Right = RHSResult.Val.getInt();
12128
12129 if (Right.isNegative()) {
12130 S.DiagRuntimeBehavior(Loc, RHS.get(),
12131 S.PDiag(diag::warn_shift_negative)
12132 << RHS.get()->getSourceRange());
12133 return;
12134 }
12135
12136 QualType LHSExprType = LHS.get()->getType();
12137 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
12138 if (LHSExprType->isBitIntType())
12139 LeftSize = S.Context.getIntWidth(T: LHSExprType);
12140 else if (LHSExprType->isFixedPointType()) {
12141 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
12142 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12143 }
12144 if (Right.uge(RHS: LeftSize)) {
12145 S.DiagRuntimeBehavior(Loc, RHS.get(),
12146 S.PDiag(diag::warn_shift_gt_typewidth)
12147 << RHS.get()->getSourceRange());
12148 return;
12149 }
12150
12151 // FIXME: We probably need to handle fixed point types specially here.
12152 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12153 return;
12154
12155 // When left shifting an ICE which is signed, we can check for overflow which
12156 // according to C++ standards prior to C++2a has undefined behavior
12157 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12158 // more than the maximum value representable in the result type, so never
12159 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12160 // expression is still probably a bug.)
12161 Expr::EvalResult LHSResult;
12162 if (LHS.get()->isValueDependent() ||
12163 LHSType->hasUnsignedIntegerRepresentation() ||
12164 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12165 return;
12166 llvm::APSInt Left = LHSResult.Val.getInt();
12167
12168 // Don't warn if signed overflow is defined, then all the rest of the
12169 // diagnostics will not be triggered because the behavior is defined.
12170 // Also don't warn in C++20 mode (and newer), as signed left shifts
12171 // always wrap and never overflow.
12172 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12173 return;
12174
12175 // If LHS does not have a non-negative value then, the
12176 // behavior is undefined before C++2a. Warn about it.
12177 if (Left.isNegative()) {
12178 S.DiagRuntimeBehavior(Loc, LHS.get(),
12179 S.PDiag(diag::warn_shift_lhs_negative)
12180 << LHS.get()->getSourceRange());
12181 return;
12182 }
12183
12184 llvm::APInt ResultBits =
12185 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12186 if (ResultBits.ule(RHS: LeftSize))
12187 return;
12188 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12189 Result = Result.shl(ShiftAmt: Right);
12190
12191 // Print the bit representation of the signed integer as an unsigned
12192 // hexadecimal number.
12193 SmallString<40> HexResult;
12194 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12195
12196 // If we are only missing a sign bit, this is less likely to result in actual
12197 // bugs -- if the result is cast back to an unsigned type, it will have the
12198 // expected value. Thus we place this behind a different warning that can be
12199 // turned off separately if needed.
12200 if (ResultBits - 1 == LeftSize) {
12201 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12202 << HexResult << LHSType
12203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12204 return;
12205 }
12206
12207 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12208 << HexResult.str() << Result.getSignificantBits() << LHSType
12209 << Left.getBitWidth() << LHS.get()->getSourceRange()
12210 << RHS.get()->getSourceRange();
12211}
12212
12213/// Return the resulting type when a vector is shifted
12214/// by a scalar or vector shift amount.
12215static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12216 SourceLocation Loc, bool IsCompAssign) {
12217 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12218 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12219 !LHS.get()->getType()->isVectorType()) {
12220 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12221 << RHS.get()->getType() << LHS.get()->getType()
12222 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12223 return QualType();
12224 }
12225
12226 if (!IsCompAssign) {
12227 LHS = S.UsualUnaryConversions(E: LHS.get());
12228 if (LHS.isInvalid()) return QualType();
12229 }
12230
12231 RHS = S.UsualUnaryConversions(E: RHS.get());
12232 if (RHS.isInvalid()) return QualType();
12233
12234 QualType LHSType = LHS.get()->getType();
12235 // Note that LHS might be a scalar because the routine calls not only in
12236 // OpenCL case.
12237 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12238 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12239
12240 // Note that RHS might not be a vector.
12241 QualType RHSType = RHS.get()->getType();
12242 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12243 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12244
12245 // Do not allow shifts for boolean vectors.
12246 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12247 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12248 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12249 << LHS.get()->getType() << RHS.get()->getType()
12250 << LHS.get()->getSourceRange();
12251 return QualType();
12252 }
12253
12254 // The operands need to be integers.
12255 if (!LHSEleType->isIntegerType()) {
12256 S.Diag(Loc, diag::err_typecheck_expect_int)
12257 << LHS.get()->getType() << LHS.get()->getSourceRange();
12258 return QualType();
12259 }
12260
12261 if (!RHSEleType->isIntegerType()) {
12262 S.Diag(Loc, diag::err_typecheck_expect_int)
12263 << RHS.get()->getType() << RHS.get()->getSourceRange();
12264 return QualType();
12265 }
12266
12267 if (!LHSVecTy) {
12268 assert(RHSVecTy);
12269 if (IsCompAssign)
12270 return RHSType;
12271 if (LHSEleType != RHSEleType) {
12272 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12273 LHSEleType = RHSEleType;
12274 }
12275 QualType VecTy =
12276 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12277 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12278 LHSType = VecTy;
12279 } else if (RHSVecTy) {
12280 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12281 // are applied component-wise. So if RHS is a vector, then ensure
12282 // that the number of elements is the same as LHS...
12283 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12284 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12285 << LHS.get()->getType() << RHS.get()->getType()
12286 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12287 return QualType();
12288 }
12289 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12290 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12291 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12292 if (LHSBT != RHSBT &&
12293 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12294 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12295 << LHS.get()->getType() << RHS.get()->getType()
12296 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12297 }
12298 }
12299 } else {
12300 // ...else expand RHS to match the number of elements in LHS.
12301 QualType VecTy =
12302 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12303 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12304 }
12305
12306 return LHSType;
12307}
12308
12309static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12310 ExprResult &RHS, SourceLocation Loc,
12311 bool IsCompAssign) {
12312 if (!IsCompAssign) {
12313 LHS = S.UsualUnaryConversions(E: LHS.get());
12314 if (LHS.isInvalid())
12315 return QualType();
12316 }
12317
12318 RHS = S.UsualUnaryConversions(E: RHS.get());
12319 if (RHS.isInvalid())
12320 return QualType();
12321
12322 QualType LHSType = LHS.get()->getType();
12323 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12324 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12325 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12326 : LHSType;
12327
12328 // Note that RHS might not be a vector
12329 QualType RHSType = RHS.get()->getType();
12330 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12331 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12332 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12333 : RHSType;
12334
12335 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12336 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12337 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12338 << LHSType << RHSType << LHS.get()->getSourceRange();
12339 return QualType();
12340 }
12341
12342 if (!LHSEleType->isIntegerType()) {
12343 S.Diag(Loc, diag::err_typecheck_expect_int)
12344 << LHS.get()->getType() << LHS.get()->getSourceRange();
12345 return QualType();
12346 }
12347
12348 if (!RHSEleType->isIntegerType()) {
12349 S.Diag(Loc, diag::err_typecheck_expect_int)
12350 << RHS.get()->getType() << RHS.get()->getSourceRange();
12351 return QualType();
12352 }
12353
12354 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12355 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12356 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12357 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12358 << LHSType << RHSType << LHS.get()->getSourceRange()
12359 << RHS.get()->getSourceRange();
12360 return QualType();
12361 }
12362
12363 if (!LHSType->isSveVLSBuiltinType()) {
12364 assert(RHSType->isSveVLSBuiltinType());
12365 if (IsCompAssign)
12366 return RHSType;
12367 if (LHSEleType != RHSEleType) {
12368 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12369 LHSEleType = RHSEleType;
12370 }
12371 const llvm::ElementCount VecSize =
12372 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12373 QualType VecTy =
12374 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12375 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12376 LHSType = VecTy;
12377 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12378 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12379 S.Context.getTypeSize(LHSBuiltinTy)) {
12380 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12381 << LHSType << RHSType << LHS.get()->getSourceRange()
12382 << RHS.get()->getSourceRange();
12383 return QualType();
12384 }
12385 } else {
12386 const llvm::ElementCount VecSize =
12387 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12388 if (LHSEleType != RHSEleType) {
12389 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12390 RHSEleType = LHSEleType;
12391 }
12392 QualType VecTy =
12393 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12394 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12395 }
12396
12397 return LHSType;
12398}
12399
12400// C99 6.5.7
12401QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12402 SourceLocation Loc, BinaryOperatorKind Opc,
12403 bool IsCompAssign) {
12404 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12405
12406 // Vector shifts promote their scalar inputs to vector type.
12407 if (LHS.get()->getType()->isVectorType() ||
12408 RHS.get()->getType()->isVectorType()) {
12409 if (LangOpts.ZVector) {
12410 // The shift operators for the z vector extensions work basically
12411 // like general shifts, except that neither the LHS nor the RHS is
12412 // allowed to be a "vector bool".
12413 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12414 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12415 return InvalidOperands(Loc, LHS, RHS);
12416 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12417 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12418 return InvalidOperands(Loc, LHS, RHS);
12419 }
12420 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12421 }
12422
12423 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12424 RHS.get()->getType()->isSveVLSBuiltinType())
12425 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12426
12427 // Shifts don't perform usual arithmetic conversions, they just do integer
12428 // promotions on each operand. C99 6.5.7p3
12429
12430 // For the LHS, do usual unary conversions, but then reset them away
12431 // if this is a compound assignment.
12432 ExprResult OldLHS = LHS;
12433 LHS = UsualUnaryConversions(E: LHS.get());
12434 if (LHS.isInvalid())
12435 return QualType();
12436 QualType LHSType = LHS.get()->getType();
12437 if (IsCompAssign) LHS = OldLHS;
12438
12439 // The RHS is simpler.
12440 RHS = UsualUnaryConversions(E: RHS.get());
12441 if (RHS.isInvalid())
12442 return QualType();
12443 QualType RHSType = RHS.get()->getType();
12444
12445 // C99 6.5.7p2: Each of the operands shall have integer type.
12446 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12447 if ((!LHSType->isFixedPointOrIntegerType() &&
12448 !LHSType->hasIntegerRepresentation()) ||
12449 !RHSType->hasIntegerRepresentation())
12450 return InvalidOperands(Loc, LHS, RHS);
12451
12452 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12453 // hasIntegerRepresentation() above instead of this.
12454 if (isScopedEnumerationType(T: LHSType) ||
12455 isScopedEnumerationType(T: RHSType)) {
12456 return InvalidOperands(Loc, LHS, RHS);
12457 }
12458 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12459
12460 // "The type of the result is that of the promoted left operand."
12461 return LHSType;
12462}
12463
12464/// Diagnose bad pointer comparisons.
12465static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12466 ExprResult &LHS, ExprResult &RHS,
12467 bool IsError) {
12468 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12469 : diag::ext_typecheck_comparison_of_distinct_pointers)
12470 << LHS.get()->getType() << RHS.get()->getType()
12471 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12472}
12473
12474/// Returns false if the pointers are converted to a composite type,
12475/// true otherwise.
12476static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12477 ExprResult &LHS, ExprResult &RHS) {
12478 // C++ [expr.rel]p2:
12479 // [...] Pointer conversions (4.10) and qualification
12480 // conversions (4.4) are performed on pointer operands (or on
12481 // a pointer operand and a null pointer constant) to bring
12482 // them to their composite pointer type. [...]
12483 //
12484 // C++ [expr.eq]p1 uses the same notion for (in)equality
12485 // comparisons of pointers.
12486
12487 QualType LHSType = LHS.get()->getType();
12488 QualType RHSType = RHS.get()->getType();
12489 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12490 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12491
12492 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12493 if (T.isNull()) {
12494 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12495 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12496 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12497 else
12498 S.InvalidOperands(Loc, LHS, RHS);
12499 return true;
12500 }
12501
12502 return false;
12503}
12504
12505static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12506 ExprResult &LHS,
12507 ExprResult &RHS,
12508 bool IsError) {
12509 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12510 : diag::ext_typecheck_comparison_of_fptr_to_void)
12511 << LHS.get()->getType() << RHS.get()->getType()
12512 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12513}
12514
12515static bool isObjCObjectLiteral(ExprResult &E) {
12516 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12517 case Stmt::ObjCArrayLiteralClass:
12518 case Stmt::ObjCDictionaryLiteralClass:
12519 case Stmt::ObjCStringLiteralClass:
12520 case Stmt::ObjCBoxedExprClass:
12521 return true;
12522 default:
12523 // Note that ObjCBoolLiteral is NOT an object literal!
12524 return false;
12525 }
12526}
12527
12528static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12529 const ObjCObjectPointerType *Type =
12530 LHS->getType()->getAs<ObjCObjectPointerType>();
12531
12532 // If this is not actually an Objective-C object, bail out.
12533 if (!Type)
12534 return false;
12535
12536 // Get the LHS object's interface type.
12537 QualType InterfaceType = Type->getPointeeType();
12538
12539 // If the RHS isn't an Objective-C object, bail out.
12540 if (!RHS->getType()->isObjCObjectPointerType())
12541 return false;
12542
12543 // Try to find the -isEqual: method.
12544 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12545 ObjCMethodDecl *Method = S.LookupMethodInObjectType(Sel: IsEqualSel,
12546 Ty: InterfaceType,
12547 /*IsInstance=*/true);
12548 if (!Method) {
12549 if (Type->isObjCIdType()) {
12550 // For 'id', just check the global pool.
12551 Method = S.LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12552 /*receiverId=*/receiverIdOrClass: true);
12553 } else {
12554 // Check protocols.
12555 Method = S.LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12556 /*IsInstance=*/true);
12557 }
12558 }
12559
12560 if (!Method)
12561 return false;
12562
12563 QualType T = Method->parameters()[0]->getType();
12564 if (!T->isObjCObjectPointerType())
12565 return false;
12566
12567 QualType R = Method->getReturnType();
12568 if (!R->isScalarType())
12569 return false;
12570
12571 return true;
12572}
12573
12574Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12575 FromE = FromE->IgnoreParenImpCasts();
12576 switch (FromE->getStmtClass()) {
12577 default:
12578 break;
12579 case Stmt::ObjCStringLiteralClass:
12580 // "string literal"
12581 return LK_String;
12582 case Stmt::ObjCArrayLiteralClass:
12583 // "array literal"
12584 return LK_Array;
12585 case Stmt::ObjCDictionaryLiteralClass:
12586 // "dictionary literal"
12587 return LK_Dictionary;
12588 case Stmt::BlockExprClass:
12589 return LK_Block;
12590 case Stmt::ObjCBoxedExprClass: {
12591 Expr *Inner = cast<ObjCBoxedExpr>(Val: FromE)->getSubExpr()->IgnoreParens();
12592 switch (Inner->getStmtClass()) {
12593 case Stmt::IntegerLiteralClass:
12594 case Stmt::FloatingLiteralClass:
12595 case Stmt::CharacterLiteralClass:
12596 case Stmt::ObjCBoolLiteralExprClass:
12597 case Stmt::CXXBoolLiteralExprClass:
12598 // "numeric literal"
12599 return LK_Numeric;
12600 case Stmt::ImplicitCastExprClass: {
12601 CastKind CK = cast<CastExpr>(Val: Inner)->getCastKind();
12602 // Boolean literals can be represented by implicit casts.
12603 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12604 return LK_Numeric;
12605 break;
12606 }
12607 default:
12608 break;
12609 }
12610 return LK_Boxed;
12611 }
12612 }
12613 return LK_None;
12614}
12615
12616static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12617 ExprResult &LHS, ExprResult &RHS,
12618 BinaryOperator::Opcode Opc){
12619 Expr *Literal;
12620 Expr *Other;
12621 if (isObjCObjectLiteral(E&: LHS)) {
12622 Literal = LHS.get();
12623 Other = RHS.get();
12624 } else {
12625 Literal = RHS.get();
12626 Other = LHS.get();
12627 }
12628
12629 // Don't warn on comparisons against nil.
12630 Other = Other->IgnoreParenCasts();
12631 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12632 NPC: Expr::NPC_ValueDependentIsNotNull))
12633 return;
12634
12635 // This should be kept in sync with warn_objc_literal_comparison.
12636 // LK_String should always be after the other literals, since it has its own
12637 // warning flag.
12638 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(FromE: Literal);
12639 assert(LiteralKind != Sema::LK_Block);
12640 if (LiteralKind == Sema::LK_None) {
12641 llvm_unreachable("Unknown Objective-C object literal kind");
12642 }
12643
12644 if (LiteralKind == Sema::LK_String)
12645 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12646 << Literal->getSourceRange();
12647 else
12648 S.Diag(Loc, diag::warn_objc_literal_comparison)
12649 << LiteralKind << Literal->getSourceRange();
12650
12651 if (BinaryOperator::isEqualityOp(Opc) &&
12652 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12653 SourceLocation Start = LHS.get()->getBeginLoc();
12654 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12655 CharSourceRange OpRange =
12656 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12657
12658 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12659 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12660 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12661 << FixItHint::CreateInsertion(End, "]");
12662 }
12663}
12664
12665/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12666static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12667 ExprResult &RHS, SourceLocation Loc,
12668 BinaryOperatorKind Opc) {
12669 // Check that left hand side is !something.
12670 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12671 if (!UO || UO->getOpcode() != UO_LNot) return;
12672
12673 // Only check if the right hand side is non-bool arithmetic type.
12674 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12675
12676 // Make sure that the something in !something is not bool.
12677 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12678 if (SubExpr->isKnownToHaveBooleanValue()) return;
12679
12680 // Emit warning.
12681 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12682 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12683 << Loc << IsBitwiseOp;
12684
12685 // First note suggest !(x < y)
12686 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12687 SourceLocation FirstClose = RHS.get()->getEndLoc();
12688 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12689 if (FirstClose.isInvalid())
12690 FirstOpen = SourceLocation();
12691 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12692 << IsBitwiseOp
12693 << FixItHint::CreateInsertion(FirstOpen, "(")
12694 << FixItHint::CreateInsertion(FirstClose, ")");
12695
12696 // Second note suggests (!x) < y
12697 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12698 SourceLocation SecondClose = LHS.get()->getEndLoc();
12699 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12700 if (SecondClose.isInvalid())
12701 SecondOpen = SourceLocation();
12702 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12703 << FixItHint::CreateInsertion(SecondOpen, "(")
12704 << FixItHint::CreateInsertion(SecondClose, ")");
12705}
12706
12707// Returns true if E refers to a non-weak array.
12708static bool checkForArray(const Expr *E) {
12709 const ValueDecl *D = nullptr;
12710 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12711 D = DR->getDecl();
12712 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12713 if (Mem->isImplicitAccess())
12714 D = Mem->getMemberDecl();
12715 }
12716 if (!D)
12717 return false;
12718 return D->getType()->isArrayType() && !D->isWeak();
12719}
12720
12721/// Diagnose some forms of syntactically-obvious tautological comparison.
12722static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12723 Expr *LHS, Expr *RHS,
12724 BinaryOperatorKind Opc) {
12725 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12726 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12727
12728 QualType LHSType = LHS->getType();
12729 QualType RHSType = RHS->getType();
12730 if (LHSType->hasFloatingRepresentation() ||
12731 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12732 S.inTemplateInstantiation())
12733 return;
12734
12735 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12736 // Tautological diagnostics.
12737 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12738 return;
12739
12740 // Comparisons between two array types are ill-formed for operator<=>, so
12741 // we shouldn't emit any additional warnings about it.
12742 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12743 return;
12744
12745 // For non-floating point types, check for self-comparisons of the form
12746 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12747 // often indicate logic errors in the program.
12748 //
12749 // NOTE: Don't warn about comparison expressions resulting from macro
12750 // expansion. Also don't warn about comparisons which are only self
12751 // comparisons within a template instantiation. The warnings should catch
12752 // obvious cases in the definition of the template anyways. The idea is to
12753 // warn when the typed comparison operator will always evaluate to the same
12754 // result.
12755
12756 // Used for indexing into %select in warn_comparison_always
12757 enum {
12758 AlwaysConstant,
12759 AlwaysTrue,
12760 AlwaysFalse,
12761 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12762 };
12763
12764 // C++2a [depr.array.comp]:
12765 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12766 // operands of array type are deprecated.
12767 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12768 RHSStripped->getType()->isArrayType()) {
12769 S.Diag(Loc, diag::warn_depr_array_comparison)
12770 << LHS->getSourceRange() << RHS->getSourceRange()
12771 << LHSStripped->getType() << RHSStripped->getType();
12772 // Carry on to produce the tautological comparison warning, if this
12773 // expression is potentially-evaluated, we can resolve the array to a
12774 // non-weak declaration, and so on.
12775 }
12776
12777 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12778 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12779 unsigned Result;
12780 switch (Opc) {
12781 case BO_EQ:
12782 case BO_LE:
12783 case BO_GE:
12784 Result = AlwaysTrue;
12785 break;
12786 case BO_NE:
12787 case BO_LT:
12788 case BO_GT:
12789 Result = AlwaysFalse;
12790 break;
12791 case BO_Cmp:
12792 Result = AlwaysEqual;
12793 break;
12794 default:
12795 Result = AlwaysConstant;
12796 break;
12797 }
12798 S.DiagRuntimeBehavior(Loc, nullptr,
12799 S.PDiag(diag::warn_comparison_always)
12800 << 0 /*self-comparison*/
12801 << Result);
12802 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12803 // What is it always going to evaluate to?
12804 unsigned Result;
12805 switch (Opc) {
12806 case BO_EQ: // e.g. array1 == array2
12807 Result = AlwaysFalse;
12808 break;
12809 case BO_NE: // e.g. array1 != array2
12810 Result = AlwaysTrue;
12811 break;
12812 default: // e.g. array1 <= array2
12813 // The best we can say is 'a constant'
12814 Result = AlwaysConstant;
12815 break;
12816 }
12817 S.DiagRuntimeBehavior(Loc, nullptr,
12818 S.PDiag(diag::warn_comparison_always)
12819 << 1 /*array comparison*/
12820 << Result);
12821 }
12822 }
12823
12824 if (isa<CastExpr>(Val: LHSStripped))
12825 LHSStripped = LHSStripped->IgnoreParenCasts();
12826 if (isa<CastExpr>(Val: RHSStripped))
12827 RHSStripped = RHSStripped->IgnoreParenCasts();
12828
12829 // Warn about comparisons against a string constant (unless the other
12830 // operand is null); the user probably wants string comparison function.
12831 Expr *LiteralString = nullptr;
12832 Expr *LiteralStringStripped = nullptr;
12833 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12834 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12835 NPC: Expr::NPC_ValueDependentIsNull)) {
12836 LiteralString = LHS;
12837 LiteralStringStripped = LHSStripped;
12838 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12839 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12840 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12841 NPC: Expr::NPC_ValueDependentIsNull)) {
12842 LiteralString = RHS;
12843 LiteralStringStripped = RHSStripped;
12844 }
12845
12846 if (LiteralString) {
12847 S.DiagRuntimeBehavior(Loc, nullptr,
12848 S.PDiag(diag::warn_stringcompare)
12849 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12850 << LiteralString->getSourceRange());
12851 }
12852}
12853
12854static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12855 switch (CK) {
12856 default: {
12857#ifndef NDEBUG
12858 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12859 << "\n";
12860#endif
12861 llvm_unreachable("unhandled cast kind");
12862 }
12863 case CK_UserDefinedConversion:
12864 return ICK_Identity;
12865 case CK_LValueToRValue:
12866 return ICK_Lvalue_To_Rvalue;
12867 case CK_ArrayToPointerDecay:
12868 return ICK_Array_To_Pointer;
12869 case CK_FunctionToPointerDecay:
12870 return ICK_Function_To_Pointer;
12871 case CK_IntegralCast:
12872 return ICK_Integral_Conversion;
12873 case CK_FloatingCast:
12874 return ICK_Floating_Conversion;
12875 case CK_IntegralToFloating:
12876 case CK_FloatingToIntegral:
12877 return ICK_Floating_Integral;
12878 case CK_IntegralComplexCast:
12879 case CK_FloatingComplexCast:
12880 case CK_FloatingComplexToIntegralComplex:
12881 case CK_IntegralComplexToFloatingComplex:
12882 return ICK_Complex_Conversion;
12883 case CK_FloatingComplexToReal:
12884 case CK_FloatingRealToComplex:
12885 case CK_IntegralComplexToReal:
12886 case CK_IntegralRealToComplex:
12887 return ICK_Complex_Real;
12888 }
12889}
12890
12891static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12892 QualType FromType,
12893 SourceLocation Loc) {
12894 // Check for a narrowing implicit conversion.
12895 StandardConversionSequence SCS;
12896 SCS.setAsIdentityConversion();
12897 SCS.setToType(Idx: 0, T: FromType);
12898 SCS.setToType(Idx: 1, T: ToType);
12899 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12900 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12901
12902 APValue PreNarrowingValue;
12903 QualType PreNarrowingType;
12904 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12905 ConstantType&: PreNarrowingType,
12906 /*IgnoreFloatToIntegralConversion*/ true)) {
12907 case NK_Dependent_Narrowing:
12908 // Implicit conversion to a narrower type, but the expression is
12909 // value-dependent so we can't tell whether it's actually narrowing.
12910 case NK_Not_Narrowing:
12911 return false;
12912
12913 case NK_Constant_Narrowing:
12914 // Implicit conversion to a narrower type, and the value is not a constant
12915 // expression.
12916 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12917 << /*Constant*/ 1
12918 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12919 return true;
12920
12921 case NK_Variable_Narrowing:
12922 // Implicit conversion to a narrower type, and the value is not a constant
12923 // expression.
12924 case NK_Type_Narrowing:
12925 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12926 << /*Constant*/ 0 << FromType << ToType;
12927 // TODO: It's not a constant expression, but what if the user intended it
12928 // to be? Can we produce notes to help them figure out why it isn't?
12929 return true;
12930 }
12931 llvm_unreachable("unhandled case in switch");
12932}
12933
12934static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12935 ExprResult &LHS,
12936 ExprResult &RHS,
12937 SourceLocation Loc) {
12938 QualType LHSType = LHS.get()->getType();
12939 QualType RHSType = RHS.get()->getType();
12940 // Dig out the original argument type and expression before implicit casts
12941 // were applied. These are the types/expressions we need to check the
12942 // [expr.spaceship] requirements against.
12943 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12944 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12945 QualType LHSStrippedType = LHSStripped.get()->getType();
12946 QualType RHSStrippedType = RHSStripped.get()->getType();
12947
12948 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12949 // other is not, the program is ill-formed.
12950 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12951 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12952 return QualType();
12953 }
12954
12955 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12956 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12957 RHSStrippedType->isEnumeralType();
12958 if (NumEnumArgs == 1) {
12959 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12960 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12961 if (OtherTy->hasFloatingRepresentation()) {
12962 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12963 return QualType();
12964 }
12965 }
12966 if (NumEnumArgs == 2) {
12967 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12968 // type E, the operator yields the result of converting the operands
12969 // to the underlying type of E and applying <=> to the converted operands.
12970 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12971 S.InvalidOperands(Loc, LHS, RHS);
12972 return QualType();
12973 }
12974 QualType IntType =
12975 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12976 assert(IntType->isArithmeticType());
12977
12978 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12979 // promote the boolean type, and all other promotable integer types, to
12980 // avoid this.
12981 if (S.Context.isPromotableIntegerType(T: IntType))
12982 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12983
12984 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12985 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12986 LHSType = RHSType = IntType;
12987 }
12988
12989 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12990 // usual arithmetic conversions are applied to the operands.
12991 QualType Type =
12992 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison);
12993 if (LHS.isInvalid() || RHS.isInvalid())
12994 return QualType();
12995 if (Type.isNull())
12996 return S.InvalidOperands(Loc, LHS, RHS);
12997
12998 std::optional<ComparisonCategoryType> CCT =
12999 getComparisonCategoryForBuiltinCmp(T: Type);
13000 if (!CCT)
13001 return S.InvalidOperands(Loc, LHS, RHS);
13002
13003 bool HasNarrowing = checkThreeWayNarrowingConversion(
13004 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
13005 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
13006 RHS.get()->getBeginLoc());
13007 if (HasNarrowing)
13008 return QualType();
13009
13010 assert(!Type.isNull() && "composite type for <=> has not been set");
13011
13012 return S.CheckComparisonCategoryType(
13013 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
13014}
13015
13016static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13017 ExprResult &RHS,
13018 SourceLocation Loc,
13019 BinaryOperatorKind Opc) {
13020 if (Opc == BO_Cmp)
13021 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13022
13023 // C99 6.5.8p3 / C99 6.5.9p4
13024 QualType Type =
13025 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison);
13026 if (LHS.isInvalid() || RHS.isInvalid())
13027 return QualType();
13028 if (Type.isNull())
13029 return S.InvalidOperands(Loc, LHS, RHS);
13030 assert(Type->isArithmeticType() || Type->isEnumeralType());
13031
13032 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13033 return S.InvalidOperands(Loc, LHS, RHS);
13034
13035 // Check for comparisons of floating point operands using != and ==.
13036 if (Type->hasFloatingRepresentation())
13037 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13038
13039 // The result of comparisons is 'bool' in C++, 'int' in C.
13040 return S.Context.getLogicalOperationType();
13041}
13042
13043void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13044 if (!NullE.get()->getType()->isAnyPointerType())
13045 return;
13046 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
13047 if (!E.get()->getType()->isAnyPointerType() &&
13048 E.get()->isNullPointerConstant(Ctx&: Context,
13049 NPC: Expr::NPC_ValueDependentIsNotNull) ==
13050 Expr::NPCK_ZeroExpression) {
13051 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
13052 if (CL->getValue() == 0)
13053 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13054 << NullValue
13055 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13056 NullValue ? "NULL" : "(void *)0");
13057 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
13058 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13059 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
13060 if (T == Context.CharTy)
13061 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13062 << NullValue
13063 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13064 NullValue ? "NULL" : "(void *)0");
13065 }
13066 }
13067}
13068
13069// C99 6.5.8, C++ [expr.rel]
13070QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13071 SourceLocation Loc,
13072 BinaryOperatorKind Opc) {
13073 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13074 bool IsThreeWay = Opc == BO_Cmp;
13075 bool IsOrdered = IsRelational || IsThreeWay;
13076 auto IsAnyPointerType = [](ExprResult E) {
13077 QualType Ty = E.get()->getType();
13078 return Ty->isPointerType() || Ty->isMemberPointerType();
13079 };
13080
13081 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13082 // type, array-to-pointer, ..., conversions are performed on both operands to
13083 // bring them to their composite type.
13084 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13085 // any type-related checks.
13086 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13087 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13088 if (LHS.isInvalid())
13089 return QualType();
13090 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13091 if (RHS.isInvalid())
13092 return QualType();
13093 } else {
13094 LHS = DefaultLvalueConversion(E: LHS.get());
13095 if (LHS.isInvalid())
13096 return QualType();
13097 RHS = DefaultLvalueConversion(E: RHS.get());
13098 if (RHS.isInvalid())
13099 return QualType();
13100 }
13101
13102 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
13103 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13104 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
13105 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
13106 }
13107
13108 // Handle vector comparisons separately.
13109 if (LHS.get()->getType()->isVectorType() ||
13110 RHS.get()->getType()->isVectorType())
13111 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13112
13113 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13114 RHS.get()->getType()->isSveVLSBuiltinType())
13115 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13116
13117 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13118 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13119
13120 QualType LHSType = LHS.get()->getType();
13121 QualType RHSType = RHS.get()->getType();
13122 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13123 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13124 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13125
13126 if ((LHSType->isPointerType() &&
13127 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13128 (RHSType->isPointerType() &&
13129 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13130 return InvalidOperands(Loc, LHS, RHS);
13131
13132 const Expr::NullPointerConstantKind LHSNullKind =
13133 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13134 const Expr::NullPointerConstantKind RHSNullKind =
13135 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13136 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13137 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13138
13139 auto computeResultTy = [&]() {
13140 if (Opc != BO_Cmp)
13141 return Context.getLogicalOperationType();
13142 assert(getLangOpts().CPlusPlus);
13143 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13144
13145 QualType CompositeTy = LHS.get()->getType();
13146 assert(!CompositeTy->isReferenceType());
13147
13148 std::optional<ComparisonCategoryType> CCT =
13149 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13150 if (!CCT)
13151 return InvalidOperands(Loc, LHS, RHS);
13152
13153 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13154 // P0946R0: Comparisons between a null pointer constant and an object
13155 // pointer result in std::strong_equality, which is ill-formed under
13156 // P1959R0.
13157 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13158 << (LHSIsNull ? LHS.get()->getSourceRange()
13159 : RHS.get()->getSourceRange());
13160 return QualType();
13161 }
13162
13163 return CheckComparisonCategoryType(
13164 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13165 };
13166
13167 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13168 bool IsEquality = Opc == BO_EQ;
13169 if (RHSIsNull)
13170 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13171 Range: RHS.get()->getSourceRange());
13172 else
13173 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13174 Range: LHS.get()->getSourceRange());
13175 }
13176
13177 if (IsOrdered && LHSType->isFunctionPointerType() &&
13178 RHSType->isFunctionPointerType()) {
13179 // Valid unless a relational comparison of function pointers
13180 bool IsError = Opc == BO_Cmp;
13181 auto DiagID =
13182 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13183 : getLangOpts().CPlusPlus
13184 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13185 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13186 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13187 << RHS.get()->getSourceRange();
13188 if (IsError)
13189 return QualType();
13190 }
13191
13192 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13193 (RHSType->isIntegerType() && !RHSIsNull)) {
13194 // Skip normal pointer conversion checks in this case; we have better
13195 // diagnostics for this below.
13196 } else if (getLangOpts().CPlusPlus) {
13197 // Equality comparison of a function pointer to a void pointer is invalid,
13198 // but we allow it as an extension.
13199 // FIXME: If we really want to allow this, should it be part of composite
13200 // pointer type computation so it works in conditionals too?
13201 if (!IsOrdered &&
13202 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13203 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13204 // This is a gcc extension compatibility comparison.
13205 // In a SFINAE context, we treat this as a hard error to maintain
13206 // conformance with the C++ standard.
13207 diagnoseFunctionPointerToVoidComparison(
13208 S&: *this, Loc, LHS, RHS, /*isError*/ IsError: (bool)isSFINAEContext());
13209
13210 if (isSFINAEContext())
13211 return QualType();
13212
13213 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13214 return computeResultTy();
13215 }
13216
13217 // C++ [expr.eq]p2:
13218 // If at least one operand is a pointer [...] bring them to their
13219 // composite pointer type.
13220 // C++ [expr.spaceship]p6
13221 // If at least one of the operands is of pointer type, [...] bring them
13222 // to their composite pointer type.
13223 // C++ [expr.rel]p2:
13224 // If both operands are pointers, [...] bring them to their composite
13225 // pointer type.
13226 // For <=>, the only valid non-pointer types are arrays and functions, and
13227 // we already decayed those, so this is really the same as the relational
13228 // comparison rule.
13229 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13230 (IsOrdered ? 2 : 1) &&
13231 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13232 RHSType->isObjCObjectPointerType()))) {
13233 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13234 return QualType();
13235 return computeResultTy();
13236 }
13237 } else if (LHSType->isPointerType() &&
13238 RHSType->isPointerType()) { // C99 6.5.8p2
13239 // All of the following pointer-related warnings are GCC extensions, except
13240 // when handling null pointer constants.
13241 QualType LCanPointeeTy =
13242 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13243 QualType RCanPointeeTy =
13244 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13245
13246 // C99 6.5.9p2 and C99 6.5.8p2
13247 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13248 T2: RCanPointeeTy.getUnqualifiedType())) {
13249 if (IsRelational) {
13250 // Pointers both need to point to complete or incomplete types
13251 if ((LCanPointeeTy->isIncompleteType() !=
13252 RCanPointeeTy->isIncompleteType()) &&
13253 !getLangOpts().C11) {
13254 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13255 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13256 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13257 << RCanPointeeTy->isIncompleteType();
13258 }
13259 }
13260 } else if (!IsRelational &&
13261 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13262 // Valid unless comparison between non-null pointer and function pointer
13263 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13264 && !LHSIsNull && !RHSIsNull)
13265 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13266 /*isError*/IsError: false);
13267 } else {
13268 // Invalid
13269 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13270 }
13271 if (LCanPointeeTy != RCanPointeeTy) {
13272 // Treat NULL constant as a special case in OpenCL.
13273 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13274 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy)) {
13275 Diag(Loc,
13276 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13277 << LHSType << RHSType << 0 /* comparison */
13278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13279 }
13280 }
13281 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13282 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13283 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13284 : CK_BitCast;
13285 if (LHSIsNull && !RHSIsNull)
13286 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13287 else
13288 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13289 }
13290 return computeResultTy();
13291 }
13292
13293
13294 // C++ [expr.eq]p4:
13295 // Two operands of type std::nullptr_t or one operand of type
13296 // std::nullptr_t and the other a null pointer constant compare
13297 // equal.
13298 // C23 6.5.9p5:
13299 // If both operands have type nullptr_t or one operand has type nullptr_t
13300 // and the other is a null pointer constant, they compare equal if the
13301 // former is a null pointer.
13302 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13303 if (LHSType->isNullPtrType()) {
13304 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13305 return computeResultTy();
13306 }
13307 if (RHSType->isNullPtrType()) {
13308 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13309 return computeResultTy();
13310 }
13311 }
13312
13313 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13314 // C23 6.5.9p6:
13315 // Otherwise, at least one operand is a pointer. If one is a pointer and
13316 // the other is a null pointer constant or has type nullptr_t, they
13317 // compare equal
13318 if (LHSIsNull && RHSType->isPointerType()) {
13319 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13320 return computeResultTy();
13321 }
13322 if (RHSIsNull && LHSType->isPointerType()) {
13323 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13324 return computeResultTy();
13325 }
13326 }
13327
13328 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13329 // These aren't covered by the composite pointer type rules.
13330 if (!IsOrdered && RHSType->isNullPtrType() &&
13331 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13332 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13333 return computeResultTy();
13334 }
13335 if (!IsOrdered && LHSType->isNullPtrType() &&
13336 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13337 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13338 return computeResultTy();
13339 }
13340
13341 if (getLangOpts().CPlusPlus) {
13342 if (IsRelational &&
13343 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13344 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13345 // HACK: Relational comparison of nullptr_t against a pointer type is
13346 // invalid per DR583, but we allow it within std::less<> and friends,
13347 // since otherwise common uses of it break.
13348 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13349 // friends to have std::nullptr_t overload candidates.
13350 DeclContext *DC = CurContext;
13351 if (isa<FunctionDecl>(Val: DC))
13352 DC = DC->getParent();
13353 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13354 if (CTSD->isInStdNamespace() &&
13355 llvm::StringSwitch<bool>(CTSD->getName())
13356 .Cases(S0: "less", S1: "less_equal", S2: "greater", S3: "greater_equal", Value: true)
13357 .Default(Value: false)) {
13358 if (RHSType->isNullPtrType())
13359 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13360 else
13361 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13362 return computeResultTy();
13363 }
13364 }
13365 }
13366
13367 // C++ [expr.eq]p2:
13368 // If at least one operand is a pointer to member, [...] bring them to
13369 // their composite pointer type.
13370 if (!IsOrdered &&
13371 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13372 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13373 return QualType();
13374 else
13375 return computeResultTy();
13376 }
13377 }
13378
13379 // Handle block pointer types.
13380 if (!IsOrdered && LHSType->isBlockPointerType() &&
13381 RHSType->isBlockPointerType()) {
13382 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13383 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13384
13385 if (!LHSIsNull && !RHSIsNull &&
13386 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13387 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13388 << LHSType << RHSType << LHS.get()->getSourceRange()
13389 << RHS.get()->getSourceRange();
13390 }
13391 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13392 return computeResultTy();
13393 }
13394
13395 // Allow block pointers to be compared with null pointer constants.
13396 if (!IsOrdered
13397 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13398 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13399 if (!LHSIsNull && !RHSIsNull) {
13400 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13401 ->getPointeeType()->isVoidType())
13402 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13403 ->getPointeeType()->isVoidType())))
13404 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13405 << LHSType << RHSType << LHS.get()->getSourceRange()
13406 << RHS.get()->getSourceRange();
13407 }
13408 if (LHSIsNull && !RHSIsNull)
13409 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13410 CK: RHSType->isPointerType() ? CK_BitCast
13411 : CK_AnyPointerToBlockPointerCast);
13412 else
13413 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13414 CK: LHSType->isPointerType() ? CK_BitCast
13415 : CK_AnyPointerToBlockPointerCast);
13416 return computeResultTy();
13417 }
13418
13419 if (LHSType->isObjCObjectPointerType() ||
13420 RHSType->isObjCObjectPointerType()) {
13421 const PointerType *LPT = LHSType->getAs<PointerType>();
13422 const PointerType *RPT = RHSType->getAs<PointerType>();
13423 if (LPT || RPT) {
13424 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13425 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13426
13427 if (!LPtrToVoid && !RPtrToVoid &&
13428 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13429 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13430 /*isError*/IsError: false);
13431 }
13432 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13433 // the RHS, but we have test coverage for this behavior.
13434 // FIXME: Consider using convertPointersToCompositeType in C++.
13435 if (LHSIsNull && !RHSIsNull) {
13436 Expr *E = LHS.get();
13437 if (getLangOpts().ObjCAutoRefCount)
13438 CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13439 CCK: CCK_ImplicitConversion);
13440 LHS = ImpCastExprToType(E, Type: RHSType,
13441 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13442 }
13443 else {
13444 Expr *E = RHS.get();
13445 if (getLangOpts().ObjCAutoRefCount)
13446 CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E, CCK: CCK_ImplicitConversion,
13447 /*Diagnose=*/true,
13448 /*DiagnoseCFAudited=*/false, Opc);
13449 RHS = ImpCastExprToType(E, Type: LHSType,
13450 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13451 }
13452 return computeResultTy();
13453 }
13454 if (LHSType->isObjCObjectPointerType() &&
13455 RHSType->isObjCObjectPointerType()) {
13456 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13457 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13458 /*isError*/IsError: false);
13459 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13460 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13461
13462 if (LHSIsNull && !RHSIsNull)
13463 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13464 else
13465 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13466 return computeResultTy();
13467 }
13468
13469 if (!IsOrdered && LHSType->isBlockPointerType() &&
13470 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13471 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13472 CK: CK_BlockPointerToObjCPointerCast);
13473 return computeResultTy();
13474 } else if (!IsOrdered &&
13475 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13476 RHSType->isBlockPointerType()) {
13477 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13478 CK: CK_BlockPointerToObjCPointerCast);
13479 return computeResultTy();
13480 }
13481 }
13482 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13483 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13484 unsigned DiagID = 0;
13485 bool isError = false;
13486 if (LangOpts.DebuggerSupport) {
13487 // Under a debugger, allow the comparison of pointers to integers,
13488 // since users tend to want to compare addresses.
13489 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13490 (RHSIsNull && RHSType->isIntegerType())) {
13491 if (IsOrdered) {
13492 isError = getLangOpts().CPlusPlus;
13493 DiagID =
13494 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13495 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13496 }
13497 } else if (getLangOpts().CPlusPlus) {
13498 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13499 isError = true;
13500 } else if (IsOrdered)
13501 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13502 else
13503 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13504
13505 if (DiagID) {
13506 Diag(Loc, DiagID)
13507 << LHSType << RHSType << LHS.get()->getSourceRange()
13508 << RHS.get()->getSourceRange();
13509 if (isError)
13510 return QualType();
13511 }
13512
13513 if (LHSType->isIntegerType())
13514 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13515 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13516 else
13517 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13518 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13519 return computeResultTy();
13520 }
13521
13522 // Handle block pointers.
13523 if (!IsOrdered && RHSIsNull
13524 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13525 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13526 return computeResultTy();
13527 }
13528 if (!IsOrdered && LHSIsNull
13529 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13530 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13531 return computeResultTy();
13532 }
13533
13534 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13535 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13536 return computeResultTy();
13537 }
13538
13539 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13540 return computeResultTy();
13541 }
13542
13543 if (LHSIsNull && RHSType->isQueueT()) {
13544 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13545 return computeResultTy();
13546 }
13547
13548 if (LHSType->isQueueT() && RHSIsNull) {
13549 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13550 return computeResultTy();
13551 }
13552 }
13553
13554 return InvalidOperands(Loc, LHS, RHS);
13555}
13556
13557// Return a signed ext_vector_type that is of identical size and number of
13558// elements. For floating point vectors, return an integer type of identical
13559// size and number of elements. In the non ext_vector_type case, search from
13560// the largest type to the smallest type to avoid cases where long long == long,
13561// where long gets picked over long long.
13562QualType Sema::GetSignedVectorType(QualType V) {
13563 const VectorType *VTy = V->castAs<VectorType>();
13564 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13565
13566 if (isa<ExtVectorType>(Val: VTy)) {
13567 if (VTy->isExtVectorBoolType())
13568 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13569 if (TypeSize == Context.getTypeSize(Context.CharTy))
13570 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13571 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13572 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13573 if (TypeSize == Context.getTypeSize(Context.IntTy))
13574 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13575 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13576 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13577 if (TypeSize == Context.getTypeSize(Context.LongTy))
13578 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13579 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13580 "Unhandled vector element size in vector compare");
13581 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13582 }
13583
13584 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13585 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13586 VecKind: VectorKind::Generic);
13587 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13588 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13589 VecKind: VectorKind::Generic);
13590 if (TypeSize == Context.getTypeSize(Context.LongTy))
13591 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13592 VecKind: VectorKind::Generic);
13593 if (TypeSize == Context.getTypeSize(Context.IntTy))
13594 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13595 VecKind: VectorKind::Generic);
13596 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13597 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13598 VecKind: VectorKind::Generic);
13599 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13600 "Unhandled vector element size in vector compare");
13601 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13602 VecKind: VectorKind::Generic);
13603}
13604
13605QualType Sema::GetSignedSizelessVectorType(QualType V) {
13606 const BuiltinType *VTy = V->castAs<BuiltinType>();
13607 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13608
13609 const QualType ETy = V->getSveEltType(Ctx: Context);
13610 const auto TypeSize = Context.getTypeSize(T: ETy);
13611
13612 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13613 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13614 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13615}
13616
13617/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13618/// operates on extended vector types. Instead of producing an IntTy result,
13619/// like a scalar comparison, a vector comparison produces a vector of integer
13620/// types.
13621QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13622 SourceLocation Loc,
13623 BinaryOperatorKind Opc) {
13624 if (Opc == BO_Cmp) {
13625 Diag(Loc, diag::err_three_way_vector_comparison);
13626 return QualType();
13627 }
13628
13629 // Check to make sure we're operating on vectors of the same type and width,
13630 // Allowing one side to be a scalar of element type.
13631 QualType vType =
13632 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13633 /*AllowBothBool*/ true,
13634 /*AllowBoolConversions*/ getLangOpts().ZVector,
13635 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13636 /*ReportInvalid*/ true);
13637 if (vType.isNull())
13638 return vType;
13639
13640 QualType LHSType = LHS.get()->getType();
13641
13642 // Determine the return type of a vector compare. By default clang will return
13643 // a scalar for all vector compares except vector bool and vector pixel.
13644 // With the gcc compiler we will always return a vector type and with the xl
13645 // compiler we will always return a scalar type. This switch allows choosing
13646 // which behavior is prefered.
13647 if (getLangOpts().AltiVec) {
13648 switch (getLangOpts().getAltivecSrcCompat()) {
13649 case LangOptions::AltivecSrcCompatKind::Mixed:
13650 // If AltiVec, the comparison results in a numeric type, i.e.
13651 // bool for C++, int for C
13652 if (vType->castAs<VectorType>()->getVectorKind() ==
13653 VectorKind::AltiVecVector)
13654 return Context.getLogicalOperationType();
13655 else
13656 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13657 break;
13658 case LangOptions::AltivecSrcCompatKind::GCC:
13659 // For GCC we always return the vector type.
13660 break;
13661 case LangOptions::AltivecSrcCompatKind::XL:
13662 return Context.getLogicalOperationType();
13663 break;
13664 }
13665 }
13666
13667 // For non-floating point types, check for self-comparisons of the form
13668 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13669 // often indicate logic errors in the program.
13670 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13671
13672 // Check for comparisons of floating point operands using != and ==.
13673 if (LHSType->hasFloatingRepresentation()) {
13674 assert(RHS.get()->getType()->hasFloatingRepresentation());
13675 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13676 }
13677
13678 // Return a signed type for the vector.
13679 return GetSignedVectorType(V: vType);
13680}
13681
13682QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13683 ExprResult &RHS,
13684 SourceLocation Loc,
13685 BinaryOperatorKind Opc) {
13686 if (Opc == BO_Cmp) {
13687 Diag(Loc, diag::err_three_way_vector_comparison);
13688 return QualType();
13689 }
13690
13691 // Check to make sure we're operating on vectors of the same type and width,
13692 // Allowing one side to be a scalar of element type.
13693 QualType vType = CheckSizelessVectorOperands(
13694 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ACK_Comparison);
13695
13696 if (vType.isNull())
13697 return vType;
13698
13699 QualType LHSType = LHS.get()->getType();
13700
13701 // For non-floating point types, check for self-comparisons of the form
13702 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13703 // often indicate logic errors in the program.
13704 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13705
13706 // Check for comparisons of floating point operands using != and ==.
13707 if (LHSType->hasFloatingRepresentation()) {
13708 assert(RHS.get()->getType()->hasFloatingRepresentation());
13709 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13710 }
13711
13712 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13713 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13714
13715 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13716 RHSBuiltinTy->isSVEBool())
13717 return LHSType;
13718
13719 // Return a signed type for the vector.
13720 return GetSignedSizelessVectorType(V: vType);
13721}
13722
13723static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13724 const ExprResult &XorRHS,
13725 const SourceLocation Loc) {
13726 // Do not diagnose macros.
13727 if (Loc.isMacroID())
13728 return;
13729
13730 // Do not diagnose if both LHS and RHS are macros.
13731 if (XorLHS.get()->getExprLoc().isMacroID() &&
13732 XorRHS.get()->getExprLoc().isMacroID())
13733 return;
13734
13735 bool Negative = false;
13736 bool ExplicitPlus = false;
13737 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13738 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13739
13740 if (!LHSInt)
13741 return;
13742 if (!RHSInt) {
13743 // Check negative literals.
13744 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13745 UnaryOperatorKind Opc = UO->getOpcode();
13746 if (Opc != UO_Minus && Opc != UO_Plus)
13747 return;
13748 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13749 if (!RHSInt)
13750 return;
13751 Negative = (Opc == UO_Minus);
13752 ExplicitPlus = !Negative;
13753 } else {
13754 return;
13755 }
13756 }
13757
13758 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13759 llvm::APInt RightSideValue = RHSInt->getValue();
13760 if (LeftSideValue != 2 && LeftSideValue != 10)
13761 return;
13762
13763 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13764 return;
13765
13766 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13767 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13768 llvm::StringRef ExprStr =
13769 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13770
13771 CharSourceRange XorRange =
13772 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13773 llvm::StringRef XorStr =
13774 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13775 // Do not diagnose if xor keyword/macro is used.
13776 if (XorStr == "xor")
13777 return;
13778
13779 std::string LHSStr = std::string(Lexer::getSourceText(
13780 Range: CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13781 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13782 std::string RHSStr = std::string(Lexer::getSourceText(
13783 Range: CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13784 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13785
13786 if (Negative) {
13787 RightSideValue = -RightSideValue;
13788 RHSStr = "-" + RHSStr;
13789 } else if (ExplicitPlus) {
13790 RHSStr = "+" + RHSStr;
13791 }
13792
13793 StringRef LHSStrRef = LHSStr;
13794 StringRef RHSStrRef = RHSStr;
13795 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13796 // literals.
13797 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13798 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13799 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13800 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13801 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13802 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13803 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13804 return;
13805
13806 bool SuggestXor =
13807 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13808 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13809 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13810 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13811 std::string SuggestedExpr = "1 << " + RHSStr;
13812 bool Overflow = false;
13813 llvm::APInt One = (LeftSideValue - 1);
13814 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13815 if (Overflow) {
13816 if (RightSideIntValue < 64)
13817 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13818 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13819 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13820 else if (RightSideIntValue == 64)
13821 S.Diag(Loc, diag::warn_xor_used_as_pow)
13822 << ExprStr << toString(XorValue, 10, true);
13823 else
13824 return;
13825 } else {
13826 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13827 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13828 << toString(PowValue, 10, true)
13829 << FixItHint::CreateReplacement(
13830 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13831 }
13832
13833 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13834 << ("0x2 ^ " + RHSStr) << SuggestXor;
13835 } else if (LeftSideValue == 10) {
13836 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13837 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13838 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13839 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13840 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13841 << ("0xA ^ " + RHSStr) << SuggestXor;
13842 }
13843}
13844
13845QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13846 SourceLocation Loc) {
13847 // Ensure that either both operands are of the same vector type, or
13848 // one operand is of a vector type and the other is of its element type.
13849 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13850 /*AllowBothBool*/ true,
13851 /*AllowBoolConversions*/ false,
13852 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13853 /*ReportInvalid*/ false);
13854 if (vType.isNull())
13855 return InvalidOperands(Loc, LHS, RHS);
13856 if (getLangOpts().OpenCL &&
13857 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13858 vType->hasFloatingRepresentation())
13859 return InvalidOperands(Loc, LHS, RHS);
13860 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13861 // usage of the logical operators && and || with vectors in C. This
13862 // check could be notionally dropped.
13863 if (!getLangOpts().CPlusPlus &&
13864 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13865 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13866
13867 return GetSignedVectorType(V: LHS.get()->getType());
13868}
13869
13870QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13871 SourceLocation Loc,
13872 bool IsCompAssign) {
13873 if (!IsCompAssign) {
13874 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13875 if (LHS.isInvalid())
13876 return QualType();
13877 }
13878 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13879 if (RHS.isInvalid())
13880 return QualType();
13881
13882 // For conversion purposes, we ignore any qualifiers.
13883 // For example, "const float" and "float" are equivalent.
13884 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13885 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13886
13887 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13888 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13889 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13890
13891 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13892 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13893
13894 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13895 // case we have to return InvalidOperands.
13896 ExprResult OriginalLHS = LHS;
13897 ExprResult OriginalRHS = RHS;
13898 if (LHSMatType && !RHSMatType) {
13899 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13900 if (!RHS.isInvalid())
13901 return LHSType;
13902
13903 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13904 }
13905
13906 if (!LHSMatType && RHSMatType) {
13907 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13908 if (!LHS.isInvalid())
13909 return RHSType;
13910 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13911 }
13912
13913 return InvalidOperands(Loc, LHS, RHS);
13914}
13915
13916QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13917 SourceLocation Loc,
13918 bool IsCompAssign) {
13919 if (!IsCompAssign) {
13920 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13921 if (LHS.isInvalid())
13922 return QualType();
13923 }
13924 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13925 if (RHS.isInvalid())
13926 return QualType();
13927
13928 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13929 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13930 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13931
13932 if (LHSMatType && RHSMatType) {
13933 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13934 return InvalidOperands(Loc, LHS, RHS);
13935
13936 if (Context.hasSameType(LHSMatType, RHSMatType))
13937 return Context.getCommonSugaredType(
13938 X: LHS.get()->getType().getUnqualifiedType(),
13939 Y: RHS.get()->getType().getUnqualifiedType());
13940
13941 QualType LHSELTy = LHSMatType->getElementType(),
13942 RHSELTy = RHSMatType->getElementType();
13943 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13944 return InvalidOperands(Loc, LHS, RHS);
13945
13946 return Context.getConstantMatrixType(
13947 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13948 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13949 }
13950 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13951}
13952
13953static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13954 switch (Opc) {
13955 default:
13956 return false;
13957 case BO_And:
13958 case BO_AndAssign:
13959 case BO_Or:
13960 case BO_OrAssign:
13961 case BO_Xor:
13962 case BO_XorAssign:
13963 return true;
13964 }
13965}
13966
13967inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13968 SourceLocation Loc,
13969 BinaryOperatorKind Opc) {
13970 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13971
13972 bool IsCompAssign =
13973 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13974
13975 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13976
13977 if (LHS.get()->getType()->isVectorType() ||
13978 RHS.get()->getType()->isVectorType()) {
13979 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13980 RHS.get()->getType()->hasIntegerRepresentation())
13981 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13982 /*AllowBothBool*/ true,
13983 /*AllowBoolConversions*/ getLangOpts().ZVector,
13984 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13985 /*ReportInvalid*/ true);
13986 return InvalidOperands(Loc, LHS, RHS);
13987 }
13988
13989 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13990 RHS.get()->getType()->isSveVLSBuiltinType()) {
13991 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13992 RHS.get()->getType()->hasIntegerRepresentation())
13993 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13994 OperationKind: ACK_BitwiseOp);
13995 return InvalidOperands(Loc, LHS, RHS);
13996 }
13997
13998 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13999 RHS.get()->getType()->isSveVLSBuiltinType()) {
14000 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14001 RHS.get()->getType()->hasIntegerRepresentation())
14002 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14003 OperationKind: ACK_BitwiseOp);
14004 return InvalidOperands(Loc, LHS, RHS);
14005 }
14006
14007 if (Opc == BO_And)
14008 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
14009
14010 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14011 RHS.get()->getType()->hasFloatingRepresentation())
14012 return InvalidOperands(Loc, LHS, RHS);
14013
14014 ExprResult LHSResult = LHS, RHSResult = RHS;
14015 QualType compType = UsualArithmeticConversions(
14016 LHS&: LHSResult, RHS&: RHSResult, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
14017 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14018 return QualType();
14019 LHS = LHSResult.get();
14020 RHS = RHSResult.get();
14021
14022 if (Opc == BO_Xor)
14023 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
14024
14025 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14026 return compType;
14027 return InvalidOperands(Loc, LHS, RHS);
14028}
14029
14030// C99 6.5.[13,14]
14031inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14032 SourceLocation Loc,
14033 BinaryOperatorKind Opc) {
14034 // Check vector operands differently.
14035 if (LHS.get()->getType()->isVectorType() ||
14036 RHS.get()->getType()->isVectorType())
14037 return CheckVectorLogicalOperands(LHS, RHS, Loc);
14038
14039 bool EnumConstantInBoolContext = false;
14040 for (const ExprResult &HS : {LHS, RHS}) {
14041 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
14042 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
14043 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14044 EnumConstantInBoolContext = true;
14045 }
14046 }
14047
14048 if (EnumConstantInBoolContext)
14049 Diag(Loc, diag::warn_enum_constant_in_bool_context);
14050
14051 // WebAssembly tables can't be used with logical operators.
14052 QualType LHSTy = LHS.get()->getType();
14053 QualType RHSTy = RHS.get()->getType();
14054 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
14055 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
14056 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14057 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14058 return InvalidOperands(Loc, LHS, RHS);
14059 }
14060
14061 // Diagnose cases where the user write a logical and/or but probably meant a
14062 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14063 // is a constant.
14064 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14065 !LHS.get()->getType()->isBooleanType() &&
14066 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14067 // Don't warn in macros or template instantiations.
14068 !Loc.isMacroID() && !inTemplateInstantiation()) {
14069 // If the RHS can be constant folded, and if it constant folds to something
14070 // that isn't 0 or 1 (which indicate a potential logical operation that
14071 // happened to fold to true/false) then warn.
14072 // Parens on the RHS are ignored.
14073 Expr::EvalResult EVResult;
14074 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14075 llvm::APSInt Result = EVResult.Val.getInt();
14076 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14077 !RHS.get()->getExprLoc().isMacroID()) ||
14078 (Result != 0 && Result != 1)) {
14079 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14080 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14081 // Suggest replacing the logical operator with the bitwise version
14082 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14083 << (Opc == BO_LAnd ? "&" : "|")
14084 << FixItHint::CreateReplacement(
14085 SourceRange(Loc, getLocForEndOfToken(Loc)),
14086 Opc == BO_LAnd ? "&" : "|");
14087 if (Opc == BO_LAnd)
14088 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14089 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14090 << FixItHint::CreateRemoval(
14091 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
14092 RHS.get()->getEndLoc()));
14093 }
14094 }
14095 }
14096
14097 if (!Context.getLangOpts().CPlusPlus) {
14098 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14099 // not operate on the built-in scalar and vector float types.
14100 if (Context.getLangOpts().OpenCL &&
14101 Context.getLangOpts().OpenCLVersion < 120) {
14102 if (LHS.get()->getType()->isFloatingType() ||
14103 RHS.get()->getType()->isFloatingType())
14104 return InvalidOperands(Loc, LHS, RHS);
14105 }
14106
14107 LHS = UsualUnaryConversions(E: LHS.get());
14108 if (LHS.isInvalid())
14109 return QualType();
14110
14111 RHS = UsualUnaryConversions(E: RHS.get());
14112 if (RHS.isInvalid())
14113 return QualType();
14114
14115 if (!LHS.get()->getType()->isScalarType() ||
14116 !RHS.get()->getType()->isScalarType())
14117 return InvalidOperands(Loc, LHS, RHS);
14118
14119 return Context.IntTy;
14120 }
14121
14122 // The following is safe because we only use this method for
14123 // non-overloadable operands.
14124
14125 // C++ [expr.log.and]p1
14126 // C++ [expr.log.or]p1
14127 // The operands are both contextually converted to type bool.
14128 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14129 if (LHSRes.isInvalid())
14130 return InvalidOperands(Loc, LHS, RHS);
14131 LHS = LHSRes;
14132
14133 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14134 if (RHSRes.isInvalid())
14135 return InvalidOperands(Loc, LHS, RHS);
14136 RHS = RHSRes;
14137
14138 // C++ [expr.log.and]p2
14139 // C++ [expr.log.or]p2
14140 // The result is a bool.
14141 return Context.BoolTy;
14142}
14143
14144static bool IsReadonlyMessage(Expr *E, Sema &S) {
14145 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14146 if (!ME) return false;
14147 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14148 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14149 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14150 if (!Base) return false;
14151 return Base->getMethodDecl() != nullptr;
14152}
14153
14154/// Is the given expression (which must be 'const') a reference to a
14155/// variable which was originally non-const, but which has become
14156/// 'const' due to being captured within a block?
14157enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14158static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14159 assert(E->isLValue() && E->getType().isConstQualified());
14160 E = E->IgnoreParens();
14161
14162 // Must be a reference to a declaration from an enclosing scope.
14163 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14164 if (!DRE) return NCCK_None;
14165 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14166
14167 // The declaration must be a variable which is not declared 'const'.
14168 VarDecl *var = dyn_cast<VarDecl>(Val: DRE->getDecl());
14169 if (!var) return NCCK_None;
14170 if (var->getType().isConstQualified()) return NCCK_None;
14171 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
14172
14173 // Decide whether the first capture was for a block or a lambda.
14174 DeclContext *DC = S.CurContext, *Prev = nullptr;
14175 // Decide whether the first capture was for a block or a lambda.
14176 while (DC) {
14177 // For init-capture, it is possible that the variable belongs to the
14178 // template pattern of the current context.
14179 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14180 if (var->isInitCapture() &&
14181 FD->getTemplateInstantiationPattern() == var->getDeclContext())
14182 break;
14183 if (DC == var->getDeclContext())
14184 break;
14185 Prev = DC;
14186 DC = DC->getParent();
14187 }
14188 // Unless we have an init-capture, we've gone one step too far.
14189 if (!var->isInitCapture())
14190 DC = Prev;
14191 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14192}
14193
14194static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14195 Ty = Ty.getNonReferenceType();
14196 if (IsDereference && Ty->isPointerType())
14197 Ty = Ty->getPointeeType();
14198 return !Ty.isConstQualified();
14199}
14200
14201// Update err_typecheck_assign_const and note_typecheck_assign_const
14202// when this enum is changed.
14203enum {
14204 ConstFunction,
14205 ConstVariable,
14206 ConstMember,
14207 ConstMethod,
14208 NestedConstMember,
14209 ConstUnknown, // Keep as last element
14210};
14211
14212/// Emit the "read-only variable not assignable" error and print notes to give
14213/// more information about why the variable is not assignable, such as pointing
14214/// to the declaration of a const variable, showing that a method is const, or
14215/// that the function is returning a const reference.
14216static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14217 SourceLocation Loc) {
14218 SourceRange ExprRange = E->getSourceRange();
14219
14220 // Only emit one error on the first const found. All other consts will emit
14221 // a note to the error.
14222 bool DiagnosticEmitted = false;
14223
14224 // Track if the current expression is the result of a dereference, and if the
14225 // next checked expression is the result of a dereference.
14226 bool IsDereference = false;
14227 bool NextIsDereference = false;
14228
14229 // Loop to process MemberExpr chains.
14230 while (true) {
14231 IsDereference = NextIsDereference;
14232
14233 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14235 NextIsDereference = ME->isArrow();
14236 const ValueDecl *VD = ME->getMemberDecl();
14237 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14238 // Mutable fields can be modified even if the class is const.
14239 if (Field->isMutable()) {
14240 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14241 break;
14242 }
14243
14244 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14245 if (!DiagnosticEmitted) {
14246 S.Diag(Loc, diag::err_typecheck_assign_const)
14247 << ExprRange << ConstMember << false /*static*/ << Field
14248 << Field->getType();
14249 DiagnosticEmitted = true;
14250 }
14251 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14252 << ConstMember << false /*static*/ << Field << Field->getType()
14253 << Field->getSourceRange();
14254 }
14255 E = ME->getBase();
14256 continue;
14257 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14258 if (VDecl->getType().isConstQualified()) {
14259 if (!DiagnosticEmitted) {
14260 S.Diag(Loc, diag::err_typecheck_assign_const)
14261 << ExprRange << ConstMember << true /*static*/ << VDecl
14262 << VDecl->getType();
14263 DiagnosticEmitted = true;
14264 }
14265 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14266 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14267 << VDecl->getSourceRange();
14268 }
14269 // Static fields do not inherit constness from parents.
14270 break;
14271 }
14272 break; // End MemberExpr
14273 } else if (const ArraySubscriptExpr *ASE =
14274 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14275 E = ASE->getBase()->IgnoreParenImpCasts();
14276 continue;
14277 } else if (const ExtVectorElementExpr *EVE =
14278 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14279 E = EVE->getBase()->IgnoreParenImpCasts();
14280 continue;
14281 }
14282 break;
14283 }
14284
14285 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14286 // Function calls
14287 const FunctionDecl *FD = CE->getDirectCallee();
14288 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14289 if (!DiagnosticEmitted) {
14290 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14291 << ConstFunction << FD;
14292 DiagnosticEmitted = true;
14293 }
14294 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
14295 diag::note_typecheck_assign_const)
14296 << ConstFunction << FD << FD->getReturnType()
14297 << FD->getReturnTypeSourceRange();
14298 }
14299 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14300 // Point to variable declaration.
14301 if (const ValueDecl *VD = DRE->getDecl()) {
14302 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14303 if (!DiagnosticEmitted) {
14304 S.Diag(Loc, diag::err_typecheck_assign_const)
14305 << ExprRange << ConstVariable << VD << VD->getType();
14306 DiagnosticEmitted = true;
14307 }
14308 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14309 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14310 }
14311 }
14312 } else if (isa<CXXThisExpr>(Val: E)) {
14313 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14314 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14315 if (MD->isConst()) {
14316 if (!DiagnosticEmitted) {
14317 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14318 << ConstMethod << MD;
14319 DiagnosticEmitted = true;
14320 }
14321 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
14322 << ConstMethod << MD << MD->getSourceRange();
14323 }
14324 }
14325 }
14326 }
14327
14328 if (DiagnosticEmitted)
14329 return;
14330
14331 // Can't determine a more specific message, so display the generic error.
14332 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14333}
14334
14335enum OriginalExprKind {
14336 OEK_Variable,
14337 OEK_Member,
14338 OEK_LValue
14339};
14340
14341static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14342 const RecordType *Ty,
14343 SourceLocation Loc, SourceRange Range,
14344 OriginalExprKind OEK,
14345 bool &DiagnosticEmitted) {
14346 std::vector<const RecordType *> RecordTypeList;
14347 RecordTypeList.push_back(x: Ty);
14348 unsigned NextToCheckIndex = 0;
14349 // We walk the record hierarchy breadth-first to ensure that we print
14350 // diagnostics in field nesting order.
14351 while (RecordTypeList.size() > NextToCheckIndex) {
14352 bool IsNested = NextToCheckIndex > 0;
14353 for (const FieldDecl *Field :
14354 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14355 // First, check every field for constness.
14356 QualType FieldTy = Field->getType();
14357 if (FieldTy.isConstQualified()) {
14358 if (!DiagnosticEmitted) {
14359 S.Diag(Loc, diag::err_typecheck_assign_const)
14360 << Range << NestedConstMember << OEK << VD
14361 << IsNested << Field;
14362 DiagnosticEmitted = true;
14363 }
14364 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14365 << NestedConstMember << IsNested << Field
14366 << FieldTy << Field->getSourceRange();
14367 }
14368
14369 // Then we append it to the list to check next in order.
14370 FieldTy = FieldTy.getCanonicalType();
14371 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14372 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14373 RecordTypeList.push_back(FieldRecTy);
14374 }
14375 }
14376 ++NextToCheckIndex;
14377 }
14378}
14379
14380/// Emit an error for the case where a record we are trying to assign to has a
14381/// const-qualified field somewhere in its hierarchy.
14382static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14383 SourceLocation Loc) {
14384 QualType Ty = E->getType();
14385 assert(Ty->isRecordType() && "lvalue was not record?");
14386 SourceRange Range = E->getSourceRange();
14387 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14388 bool DiagEmitted = false;
14389
14390 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14391 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14392 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14393 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14394 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14395 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14396 else
14397 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14398 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14399 if (!DiagEmitted)
14400 DiagnoseConstAssignment(S, E, Loc);
14401}
14402
14403/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14404/// emit an error and return true. If so, return false.
14405static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14406 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14407
14408 S.CheckShadowingDeclModification(E, Loc);
14409
14410 SourceLocation OrigLoc = Loc;
14411 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14412 Loc: &Loc);
14413 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14414 IsLV = Expr::MLV_InvalidMessageExpression;
14415 if (IsLV == Expr::MLV_Valid)
14416 return false;
14417
14418 unsigned DiagID = 0;
14419 bool NeedType = false;
14420 switch (IsLV) { // C99 6.5.16p2
14421 case Expr::MLV_ConstQualified:
14422 // Use a specialized diagnostic when we're assigning to an object
14423 // from an enclosing function or block.
14424 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14425 if (NCCK == NCCK_Block)
14426 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14427 else
14428 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14429 break;
14430 }
14431
14432 // In ARC, use some specialized diagnostics for occasions where we
14433 // infer 'const'. These are always pseudo-strong variables.
14434 if (S.getLangOpts().ObjCAutoRefCount) {
14435 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14436 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14437 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14438
14439 // Use the normal diagnostic if it's pseudo-__strong but the
14440 // user actually wrote 'const'.
14441 if (var->isARCPseudoStrong() &&
14442 (!var->getTypeSourceInfo() ||
14443 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14444 // There are three pseudo-strong cases:
14445 // - self
14446 ObjCMethodDecl *method = S.getCurMethodDecl();
14447 if (method && var == method->getSelfDecl()) {
14448 DiagID = method->isClassMethod()
14449 ? diag::err_typecheck_arc_assign_self_class_method
14450 : diag::err_typecheck_arc_assign_self;
14451
14452 // - Objective-C externally_retained attribute.
14453 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14454 isa<ParmVarDecl>(var)) {
14455 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14456
14457 // - fast enumeration variables
14458 } else {
14459 DiagID = diag::err_typecheck_arr_assign_enumeration;
14460 }
14461
14462 SourceRange Assign;
14463 if (Loc != OrigLoc)
14464 Assign = SourceRange(OrigLoc, OrigLoc);
14465 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14466 // We need to preserve the AST regardless, so migration tool
14467 // can do its job.
14468 return false;
14469 }
14470 }
14471 }
14472
14473 // If none of the special cases above are triggered, then this is a
14474 // simple const assignment.
14475 if (DiagID == 0) {
14476 DiagnoseConstAssignment(S, E, Loc);
14477 return true;
14478 }
14479
14480 break;
14481 case Expr::MLV_ConstAddrSpace:
14482 DiagnoseConstAssignment(S, E, Loc);
14483 return true;
14484 case Expr::MLV_ConstQualifiedField:
14485 DiagnoseRecursiveConstFields(S, E, Loc);
14486 return true;
14487 case Expr::MLV_ArrayType:
14488 case Expr::MLV_ArrayTemporary:
14489 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14490 NeedType = true;
14491 break;
14492 case Expr::MLV_NotObjectType:
14493 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14494 NeedType = true;
14495 break;
14496 case Expr::MLV_LValueCast:
14497 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14498 break;
14499 case Expr::MLV_Valid:
14500 llvm_unreachable("did not take early return for MLV_Valid");
14501 case Expr::MLV_InvalidExpression:
14502 case Expr::MLV_MemberFunction:
14503 case Expr::MLV_ClassTemporary:
14504 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14505 break;
14506 case Expr::MLV_IncompleteType:
14507 case Expr::MLV_IncompleteVoidType:
14508 return S.RequireCompleteType(Loc, E->getType(),
14509 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14510 case Expr::MLV_DuplicateVectorComponents:
14511 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14512 break;
14513 case Expr::MLV_NoSetterProperty:
14514 llvm_unreachable("readonly properties should be processed differently");
14515 case Expr::MLV_InvalidMessageExpression:
14516 DiagID = diag::err_readonly_message_assignment;
14517 break;
14518 case Expr::MLV_SubObjCPropertySetting:
14519 DiagID = diag::err_no_subobject_property_setting;
14520 break;
14521 }
14522
14523 SourceRange Assign;
14524 if (Loc != OrigLoc)
14525 Assign = SourceRange(OrigLoc, OrigLoc);
14526 if (NeedType)
14527 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14528 else
14529 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14530 return true;
14531}
14532
14533static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14534 SourceLocation Loc,
14535 Sema &Sema) {
14536 if (Sema.inTemplateInstantiation())
14537 return;
14538 if (Sema.isUnevaluatedContext())
14539 return;
14540 if (Loc.isInvalid() || Loc.isMacroID())
14541 return;
14542 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14543 return;
14544
14545 // C / C++ fields
14546 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14547 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14548 if (ML && MR) {
14549 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14550 return;
14551 const ValueDecl *LHSDecl =
14552 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14553 const ValueDecl *RHSDecl =
14554 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14555 if (LHSDecl != RHSDecl)
14556 return;
14557 if (LHSDecl->getType().isVolatileQualified())
14558 return;
14559 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14560 if (RefTy->getPointeeType().isVolatileQualified())
14561 return;
14562
14563 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14564 }
14565
14566 // Objective-C instance variables
14567 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14568 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14569 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14570 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14571 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14572 if (RL && RR && RL->getDecl() == RR->getDecl())
14573 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14574 }
14575}
14576
14577// C99 6.5.16.1
14578QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14579 SourceLocation Loc,
14580 QualType CompoundType,
14581 BinaryOperatorKind Opc) {
14582 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14583
14584 // Verify that LHS is a modifiable lvalue, and emit error if not.
14585 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14586 return QualType();
14587
14588 QualType LHSType = LHSExpr->getType();
14589 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14590 CompoundType;
14591 // OpenCL v1.2 s6.1.1.1 p2:
14592 // The half data type can only be used to declare a pointer to a buffer that
14593 // contains half values
14594 if (getLangOpts().OpenCL &&
14595 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14596 LHSType->isHalfType()) {
14597 Diag(Loc, diag::err_opencl_half_load_store) << 1
14598 << LHSType.getUnqualifiedType();
14599 return QualType();
14600 }
14601
14602 // WebAssembly tables can't be used on RHS of an assignment expression.
14603 if (RHSType->isWebAssemblyTableType()) {
14604 Diag(Loc, diag::err_wasm_table_art) << 0;
14605 return QualType();
14606 }
14607
14608 AssignConvertType ConvTy;
14609 if (CompoundType.isNull()) {
14610 Expr *RHSCheck = RHS.get();
14611
14612 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14613
14614 QualType LHSTy(LHSType);
14615 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14616 if (RHS.isInvalid())
14617 return QualType();
14618 // Special case of NSObject attributes on c-style pointer types.
14619 if (ConvTy == IncompatiblePointer &&
14620 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14621 RHSType->isObjCObjectPointerType()) ||
14622 (Context.isObjCNSObjectType(Ty: RHSType) &&
14623 LHSType->isObjCObjectPointerType())))
14624 ConvTy = Compatible;
14625
14626 if (ConvTy == Compatible &&
14627 LHSType->isObjCObjectType())
14628 Diag(Loc, diag::err_objc_object_assignment)
14629 << LHSType;
14630
14631 // If the RHS is a unary plus or minus, check to see if they = and + are
14632 // right next to each other. If so, the user may have typo'd "x =+ 4"
14633 // instead of "x += 4".
14634 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14635 RHSCheck = ICE->getSubExpr();
14636 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14637 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14638 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14639 // Only if the two operators are exactly adjacent.
14640 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14641 // And there is a space or other character before the subexpr of the
14642 // unary +/-. We don't want to warn on "x=-1".
14643 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14644 UO->getSubExpr()->getBeginLoc().isFileID()) {
14645 Diag(Loc, diag::warn_not_compound_assign)
14646 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14647 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14648 }
14649 }
14650
14651 if (ConvTy == Compatible) {
14652 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14653 // Warn about retain cycles where a block captures the LHS, but
14654 // not if the LHS is a simple variable into which the block is
14655 // being stored...unless that variable can be captured by reference!
14656 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14657 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14658 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14659 checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14660 }
14661
14662 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14663 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14664 // It is safe to assign a weak reference into a strong variable.
14665 // Although this code can still have problems:
14666 // id x = self.weakProp;
14667 // id y = self.weakProp;
14668 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14669 // paths through the function. This should be revisited if
14670 // -Wrepeated-use-of-weak is made flow-sensitive.
14671 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14672 // variable, which will be valid for the current autorelease scope.
14673 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14674 RHS.get()->getBeginLoc()))
14675 getCurFunction()->markSafeWeakUse(E: RHS.get());
14676
14677 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14678 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14679 }
14680 }
14681 } else {
14682 // Compound assignment "x += y"
14683 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14684 }
14685
14686 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType,
14687 SrcExpr: RHS.get(), Action: AA_Assigning))
14688 return QualType();
14689
14690 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14691
14692 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14693 if (CompoundType.isNull()) {
14694 // C++2a [expr.ass]p5:
14695 // A simple-assignment whose left operand is of a volatile-qualified
14696 // type is deprecated unless the assignment is either a discarded-value
14697 // expression or an unevaluated operand
14698 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14699 }
14700 }
14701
14702 // C11 6.5.16p3: The type of an assignment expression is the type of the
14703 // left operand would have after lvalue conversion.
14704 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14705 // qualified type, the value has the unqualified version of the type of the
14706 // lvalue; additionally, if the lvalue has atomic type, the value has the
14707 // non-atomic version of the type of the lvalue.
14708 // C++ 5.17p1: the type of the assignment expression is that of its left
14709 // operand.
14710 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14711}
14712
14713// Scenarios to ignore if expression E is:
14714// 1. an explicit cast expression into void
14715// 2. a function call expression that returns void
14716static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14717 E = E->IgnoreParens();
14718
14719 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14720 if (CE->getCastKind() == CK_ToVoid) {
14721 return true;
14722 }
14723
14724 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14725 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14726 CE->getSubExpr()->getType()->isDependentType()) {
14727 return true;
14728 }
14729 }
14730
14731 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14732 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14733 return false;
14734}
14735
14736// Look for instances where it is likely the comma operator is confused with
14737// another operator. There is an explicit list of acceptable expressions for
14738// the left hand side of the comma operator, otherwise emit a warning.
14739void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14740 // No warnings in macros
14741 if (Loc.isMacroID())
14742 return;
14743
14744 // Don't warn in template instantiations.
14745 if (inTemplateInstantiation())
14746 return;
14747
14748 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14749 // instead, skip more than needed, then call back into here with the
14750 // CommaVisitor in SemaStmt.cpp.
14751 // The listed locations are the initialization and increment portions
14752 // of a for loop. The additional checks are on the condition of
14753 // if statements, do/while loops, and for loops.
14754 // Differences in scope flags for C89 mode requires the extra logic.
14755 const unsigned ForIncrementFlags =
14756 getLangOpts().C99 || getLangOpts().CPlusPlus
14757 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14758 : Scope::ContinueScope | Scope::BreakScope;
14759 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14760 const unsigned ScopeFlags = getCurScope()->getFlags();
14761 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14762 (ScopeFlags & ForInitFlags) == ForInitFlags)
14763 return;
14764
14765 // If there are multiple comma operators used together, get the RHS of the
14766 // of the comma operator as the LHS.
14767 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14768 if (BO->getOpcode() != BO_Comma)
14769 break;
14770 LHS = BO->getRHS();
14771 }
14772
14773 // Only allow some expressions on LHS to not warn.
14774 if (IgnoreCommaOperand(E: LHS, Context))
14775 return;
14776
14777 Diag(Loc, diag::warn_comma_operator);
14778 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14779 << LHS->getSourceRange()
14780 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14781 LangOpts.CPlusPlus ? "static_cast<void>("
14782 : "(void)(")
14783 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14784 ")");
14785}
14786
14787// C99 6.5.17
14788static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14789 SourceLocation Loc) {
14790 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14791 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14792 if (LHS.isInvalid() || RHS.isInvalid())
14793 return QualType();
14794
14795 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14796 // operands, but not unary promotions.
14797 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14798
14799 // So we treat the LHS as a ignored value, and in C++ we allow the
14800 // containing site to determine what should be done with the RHS.
14801 LHS = S.IgnoredValueConversions(E: LHS.get());
14802 if (LHS.isInvalid())
14803 return QualType();
14804
14805 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14806
14807 if (!S.getLangOpts().CPlusPlus) {
14808 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14809 if (RHS.isInvalid())
14810 return QualType();
14811 if (!RHS.get()->getType()->isVoidType())
14812 S.RequireCompleteType(Loc, RHS.get()->getType(),
14813 diag::err_incomplete_type);
14814 }
14815
14816 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14817 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14818
14819 return RHS.get()->getType();
14820}
14821
14822/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14823/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14824static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14825 ExprValueKind &VK,
14826 ExprObjectKind &OK,
14827 SourceLocation OpLoc,
14828 bool IsInc, bool IsPrefix) {
14829 if (Op->isTypeDependent())
14830 return S.Context.DependentTy;
14831
14832 QualType ResType = Op->getType();
14833 // Atomic types can be used for increment / decrement where the non-atomic
14834 // versions can, so ignore the _Atomic() specifier for the purpose of
14835 // checking.
14836 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14837 ResType = ResAtomicType->getValueType();
14838
14839 assert(!ResType.isNull() && "no type for increment/decrement expression");
14840
14841 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14842 // Decrement of bool is not allowed.
14843 if (!IsInc) {
14844 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14845 return QualType();
14846 }
14847 // Increment of bool sets it to true, but is deprecated.
14848 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14849 : diag::warn_increment_bool)
14850 << Op->getSourceRange();
14851 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14852 // Error on enum increments and decrements in C++ mode
14853 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14854 return QualType();
14855 } else if (ResType->isRealType()) {
14856 // OK!
14857 } else if (ResType->isPointerType()) {
14858 // C99 6.5.2.4p2, 6.5.6p2
14859 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14860 return QualType();
14861 } else if (ResType->isObjCObjectPointerType()) {
14862 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14863 // Otherwise, we just need a complete type.
14864 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14865 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14866 return QualType();
14867 } else if (ResType->isAnyComplexType()) {
14868 // C99 does not support ++/-- on complex types, we allow as an extension.
14869 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14870 << ResType << Op->getSourceRange();
14871 } else if (ResType->isPlaceholderType()) {
14872 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14873 if (PR.isInvalid()) return QualType();
14874 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14875 IsInc, IsPrefix);
14876 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14877 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14878 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14879 (ResType->castAs<VectorType>()->getVectorKind() !=
14880 VectorKind::AltiVecBool)) {
14881 // The z vector extensions allow ++ and -- for non-bool vectors.
14882 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14883 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14884 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14885 } else {
14886 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14887 << ResType << int(IsInc) << Op->getSourceRange();
14888 return QualType();
14889 }
14890 // At this point, we know we have a real, complex or pointer type.
14891 // Now make sure the operand is a modifiable lvalue.
14892 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14893 return QualType();
14894 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14895 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14896 // An operand with volatile-qualified type is deprecated
14897 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14898 << IsInc << ResType;
14899 }
14900 // In C++, a prefix increment is the same type as the operand. Otherwise
14901 // (in C or with postfix), the increment is the unqualified type of the
14902 // operand.
14903 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14904 VK = VK_LValue;
14905 OK = Op->getObjectKind();
14906 return ResType;
14907 } else {
14908 VK = VK_PRValue;
14909 return ResType.getUnqualifiedType();
14910 }
14911}
14912
14913
14914/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14915/// This routine allows us to typecheck complex/recursive expressions
14916/// where the declaration is needed for type checking. We only need to
14917/// handle cases when the expression references a function designator
14918/// or is an lvalue. Here are some examples:
14919/// - &(x) => x
14920/// - &*****f => f for f a function designator.
14921/// - &s.xx => s
14922/// - &s.zz[1].yy -> s, if zz is an array
14923/// - *(x + 1) -> x, if x is an array
14924/// - &"123"[2] -> 0
14925/// - & __real__ x -> x
14926///
14927/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14928/// members.
14929static ValueDecl *getPrimaryDecl(Expr *E) {
14930 switch (E->getStmtClass()) {
14931 case Stmt::DeclRefExprClass:
14932 return cast<DeclRefExpr>(Val: E)->getDecl();
14933 case Stmt::MemberExprClass:
14934 // If this is an arrow operator, the address is an offset from
14935 // the base's value, so the object the base refers to is
14936 // irrelevant.
14937 if (cast<MemberExpr>(Val: E)->isArrow())
14938 return nullptr;
14939 // Otherwise, the expression refers to a part of the base
14940 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14941 case Stmt::ArraySubscriptExprClass: {
14942 // FIXME: This code shouldn't be necessary! We should catch the implicit
14943 // promotion of register arrays earlier.
14944 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14945 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14946 if (ICE->getSubExpr()->getType()->isArrayType())
14947 return getPrimaryDecl(ICE->getSubExpr());
14948 }
14949 return nullptr;
14950 }
14951 case Stmt::UnaryOperatorClass: {
14952 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14953
14954 switch(UO->getOpcode()) {
14955 case UO_Real:
14956 case UO_Imag:
14957 case UO_Extension:
14958 return getPrimaryDecl(E: UO->getSubExpr());
14959 default:
14960 return nullptr;
14961 }
14962 }
14963 case Stmt::ParenExprClass:
14964 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14965 case Stmt::ImplicitCastExprClass:
14966 // If the result of an implicit cast is an l-value, we care about
14967 // the sub-expression; otherwise, the result here doesn't matter.
14968 return getPrimaryDecl(cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14969 case Stmt::CXXUuidofExprClass:
14970 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14971 default:
14972 return nullptr;
14973 }
14974}
14975
14976namespace {
14977enum {
14978 AO_Bit_Field = 0,
14979 AO_Vector_Element = 1,
14980 AO_Property_Expansion = 2,
14981 AO_Register_Variable = 3,
14982 AO_Matrix_Element = 4,
14983 AO_No_Error = 5
14984};
14985}
14986/// Diagnose invalid operand for address of operations.
14987///
14988/// \param Type The type of operand which cannot have its address taken.
14989static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14990 Expr *E, unsigned Type) {
14991 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14992}
14993
14994bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14995 const Expr *Op,
14996 const CXXMethodDecl *MD) {
14997 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14998
14999 if (Op != DRE)
15000 return Diag(OpLoc, diag::err_parens_pointer_member_function)
15001 << Op->getSourceRange();
15002
15003 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15004 if (isa<CXXDestructorDecl>(MD))
15005 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
15006 << DRE->getSourceRange();
15007
15008 if (DRE->getQualifier())
15009 return false;
15010
15011 if (MD->getParent()->getName().empty())
15012 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15013 << DRE->getSourceRange();
15014
15015 SmallString<32> Str;
15016 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15017 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15018 << DRE->getSourceRange()
15019 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15020}
15021
15022/// CheckAddressOfOperand - The operand of & must be either a function
15023/// designator or an lvalue designating an object. If it is an lvalue, the
15024/// object cannot be declared with storage class register or be a bit field.
15025/// Note: The usual conversions are *not* applied to the operand of the &
15026/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
15027/// In C++, the operand might be an overloaded function name, in which case
15028/// we allow the '&' but retain the overloaded-function type.
15029QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15030 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15031 if (PTy->getKind() == BuiltinType::Overload) {
15032 Expr *E = OrigOp.get()->IgnoreParens();
15033 if (!isa<OverloadExpr>(Val: E)) {
15034 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15035 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15036 << OrigOp.get()->getSourceRange();
15037 return QualType();
15038 }
15039
15040 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15041 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15042 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15043 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15044 << OrigOp.get()->getSourceRange();
15045 return QualType();
15046 }
15047
15048 return Context.OverloadTy;
15049 }
15050
15051 if (PTy->getKind() == BuiltinType::UnknownAny)
15052 return Context.UnknownAnyTy;
15053
15054 if (PTy->getKind() == BuiltinType::BoundMember) {
15055 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15056 << OrigOp.get()->getSourceRange();
15057 return QualType();
15058 }
15059
15060 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15061 if (OrigOp.isInvalid()) return QualType();
15062 }
15063
15064 if (OrigOp.get()->isTypeDependent())
15065 return Context.DependentTy;
15066
15067 assert(!OrigOp.get()->hasPlaceholderType());
15068
15069 // Make sure to ignore parentheses in subsequent checks
15070 Expr *op = OrigOp.get()->IgnoreParens();
15071
15072 // In OpenCL captures for blocks called as lambda functions
15073 // are located in the private address space. Blocks used in
15074 // enqueue_kernel can be located in a different address space
15075 // depending on a vendor implementation. Thus preventing
15076 // taking an address of the capture to avoid invalid AS casts.
15077 if (LangOpts.OpenCL) {
15078 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15079 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15080 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15081 return QualType();
15082 }
15083 }
15084
15085 if (getLangOpts().C99) {
15086 // Implement C99-only parts of addressof rules.
15087 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15088 if (uOp->getOpcode() == UO_Deref)
15089 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15090 // (assuming the deref expression is valid).
15091 return uOp->getSubExpr()->getType();
15092 }
15093 // Technically, there should be a check for array subscript
15094 // expressions here, but the result of one is always an lvalue anyway.
15095 }
15096 ValueDecl *dcl = getPrimaryDecl(E: op);
15097
15098 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15099 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15100 Loc: op->getBeginLoc()))
15101 return QualType();
15102
15103 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15104 unsigned AddressOfError = AO_No_Error;
15105
15106 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15107 bool sfinae = (bool)isSFINAEContext();
15108 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
15109 : diag::ext_typecheck_addrof_temporary)
15110 << op->getType() << op->getSourceRange();
15111 if (sfinae)
15112 return QualType();
15113 // Materialize the temporary as an lvalue so that we can take its address.
15114 OrigOp = op =
15115 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15116 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15117 return Context.getPointerType(T: op->getType());
15118 } else if (lval == Expr::LV_MemberFunction) {
15119 // If it's an instance method, make a member pointer.
15120 // The expression must have exactly the form &A::foo.
15121
15122 // If the underlying expression isn't a decl ref, give up.
15123 if (!isa<DeclRefExpr>(Val: op)) {
15124 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15125 << OrigOp.get()->getSourceRange();
15126 return QualType();
15127 }
15128 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15129 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15130
15131 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15132
15133 QualType MPTy = Context.getMemberPointerType(
15134 T: op->getType(), Cls: Context.getTypeDeclType(MD->getParent()).getTypePtr());
15135 // Under the MS ABI, lock down the inheritance model now.
15136 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15137 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15138 return MPTy;
15139 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15140 // C99 6.5.3.2p1
15141 // The operand must be either an l-value or a function designator
15142 if (!op->getType()->isFunctionType()) {
15143 // Use a special diagnostic for loads from property references.
15144 if (isa<PseudoObjectExpr>(Val: op)) {
15145 AddressOfError = AO_Property_Expansion;
15146 } else {
15147 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15148 << op->getType() << op->getSourceRange();
15149 return QualType();
15150 }
15151 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15152 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15153 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15154 }
15155
15156 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15157 // The operand cannot be a bit-field
15158 AddressOfError = AO_Bit_Field;
15159 } else if (op->getObjectKind() == OK_VectorComponent) {
15160 // The operand cannot be an element of a vector
15161 AddressOfError = AO_Vector_Element;
15162 } else if (op->getObjectKind() == OK_MatrixComponent) {
15163 // The operand cannot be an element of a matrix.
15164 AddressOfError = AO_Matrix_Element;
15165 } else if (dcl) { // C99 6.5.3.2p1
15166 // We have an lvalue with a decl. Make sure the decl is not declared
15167 // with the register storage-class specifier.
15168 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15169 // in C++ it is not error to take address of a register
15170 // variable (c++03 7.1.1P3)
15171 if (vd->getStorageClass() == SC_Register &&
15172 !getLangOpts().CPlusPlus) {
15173 AddressOfError = AO_Register_Variable;
15174 }
15175 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15176 AddressOfError = AO_Property_Expansion;
15177 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15178 return Context.OverloadTy;
15179 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15180 // Okay: we can take the address of a field.
15181 // Could be a pointer to member, though, if there is an explicit
15182 // scope qualifier for the class.
15183 if (isa<DeclRefExpr>(Val: op) && cast<DeclRefExpr>(Val: op)->getQualifier()) {
15184 DeclContext *Ctx = dcl->getDeclContext();
15185 if (Ctx && Ctx->isRecord()) {
15186 if (dcl->getType()->isReferenceType()) {
15187 Diag(OpLoc,
15188 diag::err_cannot_form_pointer_to_member_of_reference_type)
15189 << dcl->getDeclName() << dcl->getType();
15190 return QualType();
15191 }
15192
15193 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15194 Ctx = Ctx->getParent();
15195
15196 QualType MPTy = Context.getMemberPointerType(
15197 T: op->getType(),
15198 Cls: Context.getTypeDeclType(cast<RecordDecl>(Val: Ctx)).getTypePtr());
15199 // Under the MS ABI, lock down the inheritance model now.
15200 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15201 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15202 return MPTy;
15203 }
15204 }
15205 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
15206 MSGuidDecl, UnnamedGlobalConstantDecl>(Val: dcl))
15207 llvm_unreachable("Unknown/unexpected decl type");
15208 }
15209
15210 if (AddressOfError != AO_No_Error) {
15211 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15212 return QualType();
15213 }
15214
15215 if (lval == Expr::LV_IncompleteVoidType) {
15216 // Taking the address of a void variable is technically illegal, but we
15217 // allow it in cases which are otherwise valid.
15218 // Example: "extern void x; void* y = &x;".
15219 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15220 }
15221
15222 // If the operand has type "type", the result has type "pointer to type".
15223 if (op->getType()->isObjCObjectType())
15224 return Context.getObjCObjectPointerType(OIT: op->getType());
15225
15226 // Cannot take the address of WebAssembly references or tables.
15227 if (Context.getTargetInfo().getTriple().isWasm()) {
15228 QualType OpTy = op->getType();
15229 if (OpTy.isWebAssemblyReferenceType()) {
15230 Diag(OpLoc, diag::err_wasm_ca_reference)
15231 << 1 << OrigOp.get()->getSourceRange();
15232 return QualType();
15233 }
15234 if (OpTy->isWebAssemblyTableType()) {
15235 Diag(OpLoc, diag::err_wasm_table_pr)
15236 << 1 << OrigOp.get()->getSourceRange();
15237 return QualType();
15238 }
15239 }
15240
15241 CheckAddressOfPackedMember(rhs: op);
15242
15243 return Context.getPointerType(T: op->getType());
15244}
15245
15246static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15247 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15248 if (!DRE)
15249 return;
15250 const Decl *D = DRE->getDecl();
15251 if (!D)
15252 return;
15253 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15254 if (!Param)
15255 return;
15256 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15257 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15258 return;
15259 if (FunctionScopeInfo *FD = S.getCurFunction())
15260 FD->ModifiedNonNullParams.insert(Ptr: Param);
15261}
15262
15263/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15264static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15265 SourceLocation OpLoc,
15266 bool IsAfterAmp = false) {
15267 if (Op->isTypeDependent())
15268 return S.Context.DependentTy;
15269
15270 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15271 if (ConvResult.isInvalid())
15272 return QualType();
15273 Op = ConvResult.get();
15274 QualType OpTy = Op->getType();
15275 QualType Result;
15276
15277 if (isa<CXXReinterpretCastExpr>(Val: Op)) {
15278 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15279 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15280 Range: Op->getSourceRange());
15281 }
15282
15283 if (const PointerType *PT = OpTy->getAs<PointerType>())
15284 {
15285 Result = PT->getPointeeType();
15286 }
15287 else if (const ObjCObjectPointerType *OPT =
15288 OpTy->getAs<ObjCObjectPointerType>())
15289 Result = OPT->getPointeeType();
15290 else {
15291 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15292 if (PR.isInvalid()) return QualType();
15293 if (PR.get() != Op)
15294 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15295 }
15296
15297 if (Result.isNull()) {
15298 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15299 << OpTy << Op->getSourceRange();
15300 return QualType();
15301 }
15302
15303 if (Result->isVoidType()) {
15304 // C++ [expr.unary.op]p1:
15305 // [...] the expression to which [the unary * operator] is applied shall
15306 // be a pointer to an object type, or a pointer to a function type
15307 LangOptions LO = S.getLangOpts();
15308 if (LO.CPlusPlus)
15309 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15310 << OpTy << Op->getSourceRange();
15311 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15312 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15313 << OpTy << Op->getSourceRange();
15314 }
15315
15316 // Dereferences are usually l-values...
15317 VK = VK_LValue;
15318
15319 // ...except that certain expressions are never l-values in C.
15320 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15321 VK = VK_PRValue;
15322
15323 return Result;
15324}
15325
15326BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15327 BinaryOperatorKind Opc;
15328 switch (Kind) {
15329 default: llvm_unreachable("Unknown binop!");
15330 case tok::periodstar: Opc = BO_PtrMemD; break;
15331 case tok::arrowstar: Opc = BO_PtrMemI; break;
15332 case tok::star: Opc = BO_Mul; break;
15333 case tok::slash: Opc = BO_Div; break;
15334 case tok::percent: Opc = BO_Rem; break;
15335 case tok::plus: Opc = BO_Add; break;
15336 case tok::minus: Opc = BO_Sub; break;
15337 case tok::lessless: Opc = BO_Shl; break;
15338 case tok::greatergreater: Opc = BO_Shr; break;
15339 case tok::lessequal: Opc = BO_LE; break;
15340 case tok::less: Opc = BO_LT; break;
15341 case tok::greaterequal: Opc = BO_GE; break;
15342 case tok::greater: Opc = BO_GT; break;
15343 case tok::exclaimequal: Opc = BO_NE; break;
15344 case tok::equalequal: Opc = BO_EQ; break;
15345 case tok::spaceship: Opc = BO_Cmp; break;
15346 case tok::amp: Opc = BO_And; break;
15347 case tok::caret: Opc = BO_Xor; break;
15348 case tok::pipe: Opc = BO_Or; break;
15349 case tok::ampamp: Opc = BO_LAnd; break;
15350 case tok::pipepipe: Opc = BO_LOr; break;
15351 case tok::equal: Opc = BO_Assign; break;
15352 case tok::starequal: Opc = BO_MulAssign; break;
15353 case tok::slashequal: Opc = BO_DivAssign; break;
15354 case tok::percentequal: Opc = BO_RemAssign; break;
15355 case tok::plusequal: Opc = BO_AddAssign; break;
15356 case tok::minusequal: Opc = BO_SubAssign; break;
15357 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15358 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15359 case tok::ampequal: Opc = BO_AndAssign; break;
15360 case tok::caretequal: Opc = BO_XorAssign; break;
15361 case tok::pipeequal: Opc = BO_OrAssign; break;
15362 case tok::comma: Opc = BO_Comma; break;
15363 }
15364 return Opc;
15365}
15366
15367static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15368 tok::TokenKind Kind) {
15369 UnaryOperatorKind Opc;
15370 switch (Kind) {
15371 default: llvm_unreachable("Unknown unary op!");
15372 case tok::plusplus: Opc = UO_PreInc; break;
15373 case tok::minusminus: Opc = UO_PreDec; break;
15374 case tok::amp: Opc = UO_AddrOf; break;
15375 case tok::star: Opc = UO_Deref; break;
15376 case tok::plus: Opc = UO_Plus; break;
15377 case tok::minus: Opc = UO_Minus; break;
15378 case tok::tilde: Opc = UO_Not; break;
15379 case tok::exclaim: Opc = UO_LNot; break;
15380 case tok::kw___real: Opc = UO_Real; break;
15381 case tok::kw___imag: Opc = UO_Imag; break;
15382 case tok::kw___extension__: Opc = UO_Extension; break;
15383 }
15384 return Opc;
15385}
15386
15387const FieldDecl *
15388Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15389 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15390 // common for setters.
15391 // struct A {
15392 // int X;
15393 // -void setX(int X) { X = X; }
15394 // +void setX(int X) { this->X = X; }
15395 // };
15396
15397 // Only consider parameters for self assignment fixes.
15398 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15399 return nullptr;
15400 const auto *Method =
15401 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15402 if (!Method)
15403 return nullptr;
15404
15405 const CXXRecordDecl *Parent = Method->getParent();
15406 // In theory this is fixable if the lambda explicitly captures this, but
15407 // that's added complexity that's rarely going to be used.
15408 if (Parent->isLambda())
15409 return nullptr;
15410
15411 // FIXME: Use an actual Lookup operation instead of just traversing fields
15412 // in order to get base class fields.
15413 auto Field =
15414 llvm::find_if(Parent->fields(),
15415 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15416 return F->getDeclName() == Name;
15417 });
15418 return (Field != Parent->field_end()) ? *Field : nullptr;
15419}
15420
15421/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15422/// This warning suppressed in the event of macro expansions.
15423static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15424 SourceLocation OpLoc, bool IsBuiltin) {
15425 if (S.inTemplateInstantiation())
15426 return;
15427 if (S.isUnevaluatedContext())
15428 return;
15429 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15430 return;
15431 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15432 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15433 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15434 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15435 if (!LHSDeclRef || !RHSDeclRef ||
15436 LHSDeclRef->getLocation().isMacroID() ||
15437 RHSDeclRef->getLocation().isMacroID())
15438 return;
15439 const ValueDecl *LHSDecl =
15440 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15441 const ValueDecl *RHSDecl =
15442 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15443 if (LHSDecl != RHSDecl)
15444 return;
15445 if (LHSDecl->getType().isVolatileQualified())
15446 return;
15447 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15448 if (RefTy->getPointeeType().isVolatileQualified())
15449 return;
15450
15451 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15452 : diag::warn_self_assignment_overloaded)
15453 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15454 << RHSExpr->getSourceRange();
15455 if (const FieldDecl *SelfAssignField =
15456 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15457 Diag << 1 << SelfAssignField
15458 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15459 else
15460 Diag << 0;
15461}
15462
15463/// Check if a bitwise-& is performed on an Objective-C pointer. This
15464/// is usually indicative of introspection within the Objective-C pointer.
15465static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15466 SourceLocation OpLoc) {
15467 if (!S.getLangOpts().ObjC)
15468 return;
15469
15470 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15471 const Expr *LHS = L.get();
15472 const Expr *RHS = R.get();
15473
15474 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15475 ObjCPointerExpr = LHS;
15476 OtherExpr = RHS;
15477 }
15478 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15479 ObjCPointerExpr = RHS;
15480 OtherExpr = LHS;
15481 }
15482
15483 // This warning is deliberately made very specific to reduce false
15484 // positives with logic that uses '&' for hashing. This logic mainly
15485 // looks for code trying to introspect into tagged pointers, which
15486 // code should generally never do.
15487 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15488 unsigned Diag = diag::warn_objc_pointer_masking;
15489 // Determine if we are introspecting the result of performSelectorXXX.
15490 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15491 // Special case messages to -performSelector and friends, which
15492 // can return non-pointer values boxed in a pointer value.
15493 // Some clients may wish to silence warnings in this subcase.
15494 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15495 Selector S = ME->getSelector();
15496 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15497 if (SelArg0.starts_with("performSelector"))
15498 Diag = diag::warn_objc_pointer_masking_performSelector;
15499 }
15500
15501 S.Diag(Loc: OpLoc, DiagID: Diag)
15502 << ObjCPointerExpr->getSourceRange();
15503 }
15504}
15505
15506static NamedDecl *getDeclFromExpr(Expr *E) {
15507 if (!E)
15508 return nullptr;
15509 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
15510 return DRE->getDecl();
15511 if (auto *ME = dyn_cast<MemberExpr>(Val: E))
15512 return ME->getMemberDecl();
15513 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: E))
15514 return IRE->getDecl();
15515 return nullptr;
15516}
15517
15518// This helper function promotes a binary operator's operands (which are of a
15519// half vector type) to a vector of floats and then truncates the result to
15520// a vector of either half or short.
15521static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15522 BinaryOperatorKind Opc, QualType ResultTy,
15523 ExprValueKind VK, ExprObjectKind OK,
15524 bool IsCompAssign, SourceLocation OpLoc,
15525 FPOptionsOverride FPFeatures) {
15526 auto &Context = S.getASTContext();
15527 assert((isVector(ResultTy, Context.HalfTy) ||
15528 isVector(ResultTy, Context.ShortTy)) &&
15529 "Result must be a vector of half or short");
15530 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15531 isVector(RHS.get()->getType(), Context.HalfTy) &&
15532 "both operands expected to be a half vector");
15533
15534 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15535 QualType BinOpResTy = RHS.get()->getType();
15536
15537 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15538 // change BinOpResTy to a vector of ints.
15539 if (isVector(ResultTy, Context.ShortTy))
15540 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15541
15542 if (IsCompAssign)
15543 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15544 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15545 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15546
15547 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15548 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15549 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15550 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15551}
15552
15553static std::pair<ExprResult, ExprResult>
15554CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15555 Expr *RHSExpr) {
15556 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15557 if (!S.Context.isDependenceAllowed()) {
15558 // C cannot handle TypoExpr nodes on either side of a binop because it
15559 // doesn't handle dependent types properly, so make sure any TypoExprs have
15560 // been dealt with before checking the operands.
15561 LHS = S.CorrectDelayedTyposInExpr(ER: LHS);
15562 RHS = S.CorrectDelayedTyposInExpr(
15563 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15564 [Opc, LHS](Expr *E) {
15565 if (Opc != BO_Assign)
15566 return ExprResult(E);
15567 // Avoid correcting the RHS to the same Expr as the LHS.
15568 Decl *D = getDeclFromExpr(E);
15569 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15570 });
15571 }
15572 return std::make_pair(x&: LHS, y&: RHS);
15573}
15574
15575/// Returns true if conversion between vectors of halfs and vectors of floats
15576/// is needed.
15577static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15578 Expr *E0, Expr *E1 = nullptr) {
15579 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15580 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15581 return false;
15582
15583 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15584 QualType Ty = E->IgnoreImplicit()->getType();
15585
15586 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15587 // to vectors of floats. Although the element type of the vectors is __fp16,
15588 // the vectors shouldn't be treated as storage-only types. See the
15589 // discussion here: https://reviews.llvm.org/rG825235c140e7
15590 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15591 if (VT->getVectorKind() == VectorKind::Neon)
15592 return false;
15593 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15594 }
15595 return false;
15596 };
15597
15598 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15599}
15600
15601/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15602/// operator @p Opc at location @c TokLoc. This routine only supports
15603/// built-in operations; ActOnBinOp handles overloaded operators.
15604ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15605 BinaryOperatorKind Opc,
15606 Expr *LHSExpr, Expr *RHSExpr) {
15607 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15608 // The syntax only allows initializer lists on the RHS of assignment,
15609 // so we don't need to worry about accepting invalid code for
15610 // non-assignment operators.
15611 // C++11 5.17p9:
15612 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15613 // of x = {} is x = T().
15614 InitializationKind Kind = InitializationKind::CreateDirectList(
15615 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15616 InitializedEntity Entity =
15617 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15618 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15619 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15620 if (Init.isInvalid())
15621 return Init;
15622 RHSExpr = Init.get();
15623 }
15624
15625 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15626 QualType ResultTy; // Result type of the binary operator.
15627 // The following two variables are used for compound assignment operators
15628 QualType CompLHSTy; // Type of LHS after promotions for computation
15629 QualType CompResultTy; // Type of computation result
15630 ExprValueKind VK = VK_PRValue;
15631 ExprObjectKind OK = OK_Ordinary;
15632 bool ConvertHalfVec = false;
15633
15634 std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr);
15635 if (!LHS.isUsable() || !RHS.isUsable())
15636 return ExprError();
15637
15638 if (getLangOpts().OpenCL) {
15639 QualType LHSTy = LHSExpr->getType();
15640 QualType RHSTy = RHSExpr->getType();
15641 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15642 // the ATOMIC_VAR_INIT macro.
15643 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15644 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15645 if (BO_Assign == Opc)
15646 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15647 else
15648 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15649 return ExprError();
15650 }
15651
15652 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15653 // only with a builtin functions and therefore should be disallowed here.
15654 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15655 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15656 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15657 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15658 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15659 return ExprError();
15660 }
15661 }
15662
15663 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15664 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15665
15666 switch (Opc) {
15667 case BO_Assign:
15668 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15669 if (getLangOpts().CPlusPlus &&
15670 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15671 VK = LHS.get()->getValueKind();
15672 OK = LHS.get()->getObjectKind();
15673 }
15674 if (!ResultTy.isNull()) {
15675 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15676 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15677
15678 // Avoid copying a block to the heap if the block is assigned to a local
15679 // auto variable that is declared in the same scope as the block. This
15680 // optimization is unsafe if the local variable is declared in an outer
15681 // scope. For example:
15682 //
15683 // BlockTy b;
15684 // {
15685 // b = ^{...};
15686 // }
15687 // // It is unsafe to invoke the block here if it wasn't copied to the
15688 // // heap.
15689 // b();
15690
15691 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15692 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15693 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15694 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15695 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15696
15697 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15698 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15699 UseContext: NTCUC_Assignment, NonTrivialKind: NTCUK_Copy);
15700 }
15701 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15702 break;
15703 case BO_PtrMemD:
15704 case BO_PtrMemI:
15705 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15706 isIndirect: Opc == BO_PtrMemI);
15707 break;
15708 case BO_Mul:
15709 case BO_Div:
15710 ConvertHalfVec = true;
15711 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: false,
15712 IsDiv: Opc == BO_Div);
15713 break;
15714 case BO_Rem:
15715 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15716 break;
15717 case BO_Add:
15718 ConvertHalfVec = true;
15719 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15720 break;
15721 case BO_Sub:
15722 ConvertHalfVec = true;
15723 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc);
15724 break;
15725 case BO_Shl:
15726 case BO_Shr:
15727 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15728 break;
15729 case BO_LE:
15730 case BO_LT:
15731 case BO_GE:
15732 case BO_GT:
15733 ConvertHalfVec = true;
15734 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15735 break;
15736 case BO_EQ:
15737 case BO_NE:
15738 ConvertHalfVec = true;
15739 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15740 break;
15741 case BO_Cmp:
15742 ConvertHalfVec = true;
15743 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15744 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15745 break;
15746 case BO_And:
15747 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15748 [[fallthrough]];
15749 case BO_Xor:
15750 case BO_Or:
15751 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15752 break;
15753 case BO_LAnd:
15754 case BO_LOr:
15755 ConvertHalfVec = true;
15756 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15757 break;
15758 case BO_MulAssign:
15759 case BO_DivAssign:
15760 ConvertHalfVec = true;
15761 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true,
15762 IsDiv: Opc == BO_DivAssign);
15763 CompLHSTy = CompResultTy;
15764 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15765 ResultTy =
15766 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15767 break;
15768 case BO_RemAssign:
15769 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15770 CompLHSTy = CompResultTy;
15771 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15772 ResultTy =
15773 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15774 break;
15775 case BO_AddAssign:
15776 ConvertHalfVec = true;
15777 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15778 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15779 ResultTy =
15780 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15781 break;
15782 case BO_SubAssign:
15783 ConvertHalfVec = true;
15784 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, CompLHSTy: &CompLHSTy);
15785 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15786 ResultTy =
15787 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15788 break;
15789 case BO_ShlAssign:
15790 case BO_ShrAssign:
15791 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15792 CompLHSTy = CompResultTy;
15793 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15794 ResultTy =
15795 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15796 break;
15797 case BO_AndAssign:
15798 case BO_OrAssign: // fallthrough
15799 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15800 [[fallthrough]];
15801 case BO_XorAssign:
15802 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15803 CompLHSTy = CompResultTy;
15804 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15805 ResultTy =
15806 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15807 break;
15808 case BO_Comma:
15809 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15810 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15811 VK = RHS.get()->getValueKind();
15812 OK = RHS.get()->getObjectKind();
15813 }
15814 break;
15815 }
15816 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15817 return ExprError();
15818
15819 // Some of the binary operations require promoting operands of half vector to
15820 // float vectors and truncating the result back to half vector. For now, we do
15821 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15822 // arm64).
15823 assert(
15824 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15825 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15826 "both sides are half vectors or neither sides are");
15827 ConvertHalfVec =
15828 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15829
15830 // Check for array bounds violations for both sides of the BinaryOperator
15831 CheckArrayAccess(E: LHS.get());
15832 CheckArrayAccess(E: RHS.get());
15833
15834 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15835 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15836 Name: &Context.Idents.get(Name: "object_setClass"),
15837 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15838 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15839 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15840 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15841 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15842 "object_setClass(")
15843 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15844 ",")
15845 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15846 }
15847 else
15848 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15849 }
15850 else if (const ObjCIvarRefExpr *OIRE =
15851 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15852 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15853
15854 // Opc is not a compound assignment if CompResultTy is null.
15855 if (CompResultTy.isNull()) {
15856 if (ConvertHalfVec)
15857 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15858 OpLoc, FPFeatures: CurFPFeatureOverrides());
15859 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15860 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15861 }
15862
15863 // Handle compound assignments.
15864 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15865 OK_ObjCProperty) {
15866 VK = VK_LValue;
15867 OK = LHS.get()->getObjectKind();
15868 }
15869
15870 // The LHS is not converted to the result type for fixed-point compound
15871 // assignment as the common type is computed on demand. Reset the CompLHSTy
15872 // to the LHS type we would have gotten after unary conversions.
15873 if (CompResultTy->isFixedPointType())
15874 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15875
15876 if (ConvertHalfVec)
15877 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15878 OpLoc, FPFeatures: CurFPFeatureOverrides());
15879
15880 return CompoundAssignOperator::Create(
15881 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15882 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15883}
15884
15885/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15886/// operators are mixed in a way that suggests that the programmer forgot that
15887/// comparison operators have higher precedence. The most typical example of
15888/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15889static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15890 SourceLocation OpLoc, Expr *LHSExpr,
15891 Expr *RHSExpr) {
15892 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15893 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15894
15895 // Check that one of the sides is a comparison operator and the other isn't.
15896 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15897 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15898 if (isLeftComp == isRightComp)
15899 return;
15900
15901 // Bitwise operations are sometimes used as eager logical ops.
15902 // Don't diagnose this.
15903 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15904 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15905 if (isLeftBitwise || isRightBitwise)
15906 return;
15907
15908 SourceRange DiagRange = isLeftComp
15909 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15910 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15911 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15912 SourceRange ParensRange =
15913 isLeftComp
15914 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15915 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15916
15917 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15918 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15919 SuggestParentheses(Self, OpLoc,
15920 Self.PDiag(diag::note_precedence_silence) << OpStr,
15921 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15922 SuggestParentheses(Self, OpLoc,
15923 Self.PDiag(diag::note_precedence_bitwise_first)
15924 << BinaryOperator::getOpcodeStr(Opc),
15925 ParensRange);
15926}
15927
15928/// It accepts a '&&' expr that is inside a '||' one.
15929/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15930/// in parentheses.
15931static void
15932EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15933 BinaryOperator *Bop) {
15934 assert(Bop->getOpcode() == BO_LAnd);
15935 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15936 << Bop->getSourceRange() << OpLoc;
15937 SuggestParentheses(Self, Bop->getOperatorLoc(),
15938 Self.PDiag(diag::note_precedence_silence)
15939 << Bop->getOpcodeStr(),
15940 Bop->getSourceRange());
15941}
15942
15943/// Look for '&&' in the left hand of a '||' expr.
15944static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15945 Expr *LHSExpr, Expr *RHSExpr) {
15946 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15947 if (Bop->getOpcode() == BO_LAnd) {
15948 // If it's "string_literal && a || b" don't warn since the precedence
15949 // doesn't matter.
15950 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15951 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15952 } else if (Bop->getOpcode() == BO_LOr) {
15953 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15954 // If it's "a || b && string_literal || c" we didn't warn earlier for
15955 // "a || b && string_literal", but warn now.
15956 if (RBop->getOpcode() == BO_LAnd &&
15957 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15958 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15959 }
15960 }
15961 }
15962}
15963
15964/// Look for '&&' in the right hand of a '||' expr.
15965static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15966 Expr *LHSExpr, Expr *RHSExpr) {
15967 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15968 if (Bop->getOpcode() == BO_LAnd) {
15969 // If it's "a || b && string_literal" don't warn since the precedence
15970 // doesn't matter.
15971 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15972 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15973 }
15974 }
15975}
15976
15977/// Look for bitwise op in the left or right hand of a bitwise op with
15978/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15979/// the '&' expression in parentheses.
15980static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15981 SourceLocation OpLoc, Expr *SubExpr) {
15982 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15983 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15984 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15985 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15986 << Bop->getSourceRange() << OpLoc;
15987 SuggestParentheses(S, Bop->getOperatorLoc(),
15988 S.PDiag(diag::note_precedence_silence)
15989 << Bop->getOpcodeStr(),
15990 Bop->getSourceRange());
15991 }
15992 }
15993}
15994
15995static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15996 Expr *SubExpr, StringRef Shift) {
15997 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15998 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15999 StringRef Op = Bop->getOpcodeStr();
16000 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
16001 << Bop->getSourceRange() << OpLoc << Shift << Op;
16002 SuggestParentheses(S, Bop->getOperatorLoc(),
16003 S.PDiag(diag::note_precedence_silence) << Op,
16004 Bop->getSourceRange());
16005 }
16006 }
16007}
16008
16009static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16010 Expr *LHSExpr, Expr *RHSExpr) {
16011 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
16012 if (!OCE)
16013 return;
16014
16015 FunctionDecl *FD = OCE->getDirectCallee();
16016 if (!FD || !FD->isOverloadedOperator())
16017 return;
16018
16019 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16020 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16021 return;
16022
16023 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16024 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16025 << (Kind == OO_LessLess);
16026 SuggestParentheses(S, OCE->getOperatorLoc(),
16027 S.PDiag(diag::note_precedence_silence)
16028 << (Kind == OO_LessLess ? "<<" : ">>"),
16029 OCE->getSourceRange());
16030 SuggestParentheses(
16031 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16032 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16033}
16034
16035/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16036/// precedence.
16037static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16038 SourceLocation OpLoc, Expr *LHSExpr,
16039 Expr *RHSExpr){
16040 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16041 if (BinaryOperator::isBitwiseOp(Opc))
16042 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16043
16044 // Diagnose "arg1 & arg2 | arg3"
16045 if ((Opc == BO_Or || Opc == BO_Xor) &&
16046 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16047 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16048 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16049 }
16050
16051 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16052 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16053 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16054 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16055 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16056 }
16057
16058 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16059 || Opc == BO_Shr) {
16060 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16061 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16062 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16063 }
16064
16065 // Warn on overloaded shift operators and comparisons, such as:
16066 // cout << 5 == 4;
16067 if (BinaryOperator::isComparisonOp(Opc))
16068 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16069}
16070
16071// Binary Operators. 'Tok' is the token for the operator.
16072ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16073 tok::TokenKind Kind,
16074 Expr *LHSExpr, Expr *RHSExpr) {
16075 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16076 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16077 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16078
16079 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16080 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16081
16082 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16083}
16084
16085void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16086 UnresolvedSetImpl &Functions) {
16087 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16088 if (OverOp != OO_None && OverOp != OO_Equal)
16089 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16090
16091 // In C++20 onwards, we may have a second operator to look up.
16092 if (getLangOpts().CPlusPlus20) {
16093 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16094 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16095 }
16096}
16097
16098/// Build an overloaded binary operator expression in the given scope.
16099static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16100 BinaryOperatorKind Opc,
16101 Expr *LHS, Expr *RHS) {
16102 switch (Opc) {
16103 case BO_Assign:
16104 // In the non-overloaded case, we warn about self-assignment (x = x) for
16105 // both simple assignment and certain compound assignments where algebra
16106 // tells us the operation yields a constant result. When the operator is
16107 // overloaded, we can't do the latter because we don't want to assume that
16108 // those algebraic identities still apply; for example, a path-building
16109 // library might use operator/= to append paths. But it's still reasonable
16110 // to assume that simple assignment is just moving/copying values around
16111 // and so self-assignment is likely a bug.
16112 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16113 [[fallthrough]];
16114 case BO_DivAssign:
16115 case BO_RemAssign:
16116 case BO_SubAssign:
16117 case BO_AndAssign:
16118 case BO_OrAssign:
16119 case BO_XorAssign:
16120 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16121 break;
16122 default:
16123 break;
16124 }
16125
16126 // Find all of the overloaded operators visible from this point.
16127 UnresolvedSet<16> Functions;
16128 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16129
16130 // Build the (potentially-overloaded, potentially-dependent)
16131 // binary operation.
16132 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16133}
16134
16135ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16136 BinaryOperatorKind Opc,
16137 Expr *LHSExpr, Expr *RHSExpr) {
16138 ExprResult LHS, RHS;
16139 std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr);
16140 if (!LHS.isUsable() || !RHS.isUsable())
16141 return ExprError();
16142 LHSExpr = LHS.get();
16143 RHSExpr = RHS.get();
16144
16145 // We want to end up calling one of checkPseudoObjectAssignment
16146 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16147 // both expressions are overloadable or either is type-dependent),
16148 // or CreateBuiltinBinOp (in any other case). We also want to get
16149 // any placeholder types out of the way.
16150
16151 // Handle pseudo-objects in the LHS.
16152 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16153 // Assignments with a pseudo-object l-value need special analysis.
16154 if (pty->getKind() == BuiltinType::PseudoObject &&
16155 BinaryOperator::isAssignmentOp(Opc))
16156 return checkPseudoObjectAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16157
16158 // Don't resolve overloads if the other type is overloadable.
16159 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16160 // We can't actually test that if we still have a placeholder,
16161 // though. Fortunately, none of the exceptions we see in that
16162 // code below are valid when the LHS is an overload set. Note
16163 // that an overload set can be dependently-typed, but it never
16164 // instantiates to having an overloadable type.
16165 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16166 if (resolvedRHS.isInvalid()) return ExprError();
16167 RHSExpr = resolvedRHS.get();
16168
16169 if (RHSExpr->isTypeDependent() ||
16170 RHSExpr->getType()->isOverloadableType())
16171 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16172 }
16173
16174 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16175 // template, diagnose the missing 'template' keyword instead of diagnosing
16176 // an invalid use of a bound member function.
16177 //
16178 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16179 // to C++1z [over.over]/1.4, but we already checked for that case above.
16180 if (Opc == BO_LT && inTemplateInstantiation() &&
16181 (pty->getKind() == BuiltinType::BoundMember ||
16182 pty->getKind() == BuiltinType::Overload)) {
16183 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16184 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16185 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16186 return isa<FunctionTemplateDecl>(Val: ND);
16187 })) {
16188 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16189 : OE->getNameLoc(),
16190 diag::err_template_kw_missing)
16191 << OE->getName().getAsString() << "";
16192 return ExprError();
16193 }
16194 }
16195
16196 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16197 if (LHS.isInvalid()) return ExprError();
16198 LHSExpr = LHS.get();
16199 }
16200
16201 // Handle pseudo-objects in the RHS.
16202 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16203 // An overload in the RHS can potentially be resolved by the type
16204 // being assigned to.
16205 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16206 if (getLangOpts().CPlusPlus &&
16207 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16208 LHSExpr->getType()->isOverloadableType()))
16209 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16210
16211 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16212 }
16213
16214 // Don't resolve overloads if the other type is overloadable.
16215 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16216 LHSExpr->getType()->isOverloadableType())
16217 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16218
16219 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16220 if (!resolvedRHS.isUsable()) return ExprError();
16221 RHSExpr = resolvedRHS.get();
16222 }
16223
16224 if (getLangOpts().CPlusPlus) {
16225 // If either expression is type-dependent, always build an
16226 // overloaded op.
16227 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
16228 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16229
16230 // Otherwise, build an overloaded op if either expression has an
16231 // overloadable type.
16232 if (LHSExpr->getType()->isOverloadableType() ||
16233 RHSExpr->getType()->isOverloadableType())
16234 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16235 }
16236
16237 if (getLangOpts().RecoveryAST &&
16238 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16239 assert(!getLangOpts().CPlusPlus);
16240 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16241 "Should only occur in error-recovery path.");
16242 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16243 // C [6.15.16] p3:
16244 // An assignment expression has the value of the left operand after the
16245 // assignment, but is not an lvalue.
16246 return CompoundAssignOperator::Create(
16247 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16248 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16249 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16250 QualType ResultType;
16251 switch (Opc) {
16252 case BO_Assign:
16253 ResultType = LHSExpr->getType().getUnqualifiedType();
16254 break;
16255 case BO_LT:
16256 case BO_GT:
16257 case BO_LE:
16258 case BO_GE:
16259 case BO_EQ:
16260 case BO_NE:
16261 case BO_LAnd:
16262 case BO_LOr:
16263 // These operators have a fixed result type regardless of operands.
16264 ResultType = Context.IntTy;
16265 break;
16266 case BO_Comma:
16267 ResultType = RHSExpr->getType();
16268 break;
16269 default:
16270 ResultType = Context.DependentTy;
16271 break;
16272 }
16273 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16274 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16275 FPFeatures: CurFPFeatureOverrides());
16276 }
16277
16278 // Build a built-in binary operation.
16279 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16280}
16281
16282static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16283 if (T.isNull() || T->isDependentType())
16284 return false;
16285
16286 if (!Ctx.isPromotableIntegerType(T))
16287 return true;
16288
16289 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16290}
16291
16292ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16293 UnaryOperatorKind Opc, Expr *InputExpr,
16294 bool IsAfterAmp) {
16295 ExprResult Input = InputExpr;
16296 ExprValueKind VK = VK_PRValue;
16297 ExprObjectKind OK = OK_Ordinary;
16298 QualType resultType;
16299 bool CanOverflow = false;
16300
16301 bool ConvertHalfVec = false;
16302 if (getLangOpts().OpenCL) {
16303 QualType Ty = InputExpr->getType();
16304 // The only legal unary operation for atomics is '&'.
16305 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16306 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16307 // only with a builtin functions and therefore should be disallowed here.
16308 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16309 || Ty->isBlockPointerType())) {
16310 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16311 << InputExpr->getType()
16312 << Input.get()->getSourceRange());
16313 }
16314 }
16315
16316 if (getLangOpts().HLSL && OpLoc.isValid()) {
16317 if (Opc == UO_AddrOf)
16318 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16319 if (Opc == UO_Deref)
16320 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16321 }
16322
16323 switch (Opc) {
16324 case UO_PreInc:
16325 case UO_PreDec:
16326 case UO_PostInc:
16327 case UO_PostDec:
16328 resultType = CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK,
16329 OpLoc,
16330 IsInc: Opc == UO_PreInc ||
16331 Opc == UO_PostInc,
16332 IsPrefix: Opc == UO_PreInc ||
16333 Opc == UO_PreDec);
16334 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16335 break;
16336 case UO_AddrOf:
16337 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16338 CheckAddressOfNoDeref(E: InputExpr);
16339 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16340 break;
16341 case UO_Deref: {
16342 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16343 if (Input.isInvalid()) return ExprError();
16344 resultType =
16345 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16346 break;
16347 }
16348 case UO_Plus:
16349 case UO_Minus:
16350 CanOverflow = Opc == UO_Minus &&
16351 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16352 Input = UsualUnaryConversions(E: Input.get());
16353 if (Input.isInvalid()) return ExprError();
16354 // Unary plus and minus require promoting an operand of half vector to a
16355 // float vector and truncating the result back to a half vector. For now, we
16356 // do this only when HalfArgsAndReturns is set (that is, when the target is
16357 // arm or arm64).
16358 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16359
16360 // If the operand is a half vector, promote it to a float vector.
16361 if (ConvertHalfVec)
16362 Input = convertVector(Input.get(), Context.FloatTy, *this);
16363 resultType = Input.get()->getType();
16364 if (resultType->isDependentType())
16365 break;
16366 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16367 break;
16368 else if (resultType->isVectorType() &&
16369 // The z vector extensions don't allow + or - with bool vectors.
16370 (!Context.getLangOpts().ZVector ||
16371 resultType->castAs<VectorType>()->getVectorKind() !=
16372 VectorKind::AltiVecBool))
16373 break;
16374 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16375 break;
16376 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16377 Opc == UO_Plus &&
16378 resultType->isPointerType())
16379 break;
16380
16381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16382 << resultType << Input.get()->getSourceRange());
16383
16384 case UO_Not: // bitwise complement
16385 Input = UsualUnaryConversions(E: Input.get());
16386 if (Input.isInvalid())
16387 return ExprError();
16388 resultType = Input.get()->getType();
16389 if (resultType->isDependentType())
16390 break;
16391 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16392 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16393 // C99 does not support '~' for complex conjugation.
16394 Diag(OpLoc, diag::ext_integer_complement_complex)
16395 << resultType << Input.get()->getSourceRange();
16396 else if (resultType->hasIntegerRepresentation())
16397 break;
16398 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16399 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16400 // on vector float types.
16401 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16402 if (!T->isIntegerType())
16403 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16404 << resultType << Input.get()->getSourceRange());
16405 } else {
16406 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16407 << resultType << Input.get()->getSourceRange());
16408 }
16409 break;
16410
16411 case UO_LNot: // logical negation
16412 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16413 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16414 if (Input.isInvalid()) return ExprError();
16415 resultType = Input.get()->getType();
16416
16417 // Though we still have to promote half FP to float...
16418 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16419 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast).get();
16420 resultType = Context.FloatTy;
16421 }
16422
16423 // WebAsembly tables can't be used in unary expressions.
16424 if (resultType->isPointerType() &&
16425 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16426 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16427 << resultType << Input.get()->getSourceRange());
16428 }
16429
16430 if (resultType->isDependentType())
16431 break;
16432 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16433 // C99 6.5.3.3p1: ok, fallthrough;
16434 if (Context.getLangOpts().CPlusPlus) {
16435 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16436 // operand contextually converted to bool.
16437 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16438 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16439 } else if (Context.getLangOpts().OpenCL &&
16440 Context.getLangOpts().OpenCLVersion < 120) {
16441 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16442 // operate on scalar float types.
16443 if (!resultType->isIntegerType() && !resultType->isPointerType())
16444 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16445 << resultType << Input.get()->getSourceRange());
16446 }
16447 } else if (resultType->isExtVectorType()) {
16448 if (Context.getLangOpts().OpenCL &&
16449 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16450 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16451 // operate on vector float types.
16452 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16453 if (!T->isIntegerType())
16454 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16455 << resultType << Input.get()->getSourceRange());
16456 }
16457 // Vector logical not returns the signed variant of the operand type.
16458 resultType = GetSignedVectorType(V: resultType);
16459 break;
16460 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16461 const VectorType *VTy = resultType->castAs<VectorType>();
16462 if (VTy->getVectorKind() != VectorKind::Generic)
16463 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16464 << resultType << Input.get()->getSourceRange());
16465
16466 // Vector logical not returns the signed variant of the operand type.
16467 resultType = GetSignedVectorType(V: resultType);
16468 break;
16469 } else {
16470 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16471 << resultType << Input.get()->getSourceRange());
16472 }
16473
16474 // LNot always has type int. C99 6.5.3.3p5.
16475 // In C++, it's bool. C++ 5.3.1p8
16476 resultType = Context.getLogicalOperationType();
16477 break;
16478 case UO_Real:
16479 case UO_Imag:
16480 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16481 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16482 // complex l-values to ordinary l-values and all other values to r-values.
16483 if (Input.isInvalid()) return ExprError();
16484 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16485 if (Input.get()->isGLValue() &&
16486 Input.get()->getObjectKind() == OK_Ordinary)
16487 VK = Input.get()->getValueKind();
16488 } else if (!getLangOpts().CPlusPlus) {
16489 // In C, a volatile scalar is read by __imag. In C++, it is not.
16490 Input = DefaultLvalueConversion(E: Input.get());
16491 }
16492 break;
16493 case UO_Extension:
16494 resultType = Input.get()->getType();
16495 VK = Input.get()->getValueKind();
16496 OK = Input.get()->getObjectKind();
16497 break;
16498 case UO_Coawait:
16499 // It's unnecessary to represent the pass-through operator co_await in the
16500 // AST; just return the input expression instead.
16501 assert(!Input.get()->getType()->isDependentType() &&
16502 "the co_await expression must be non-dependant before "
16503 "building operator co_await");
16504 return Input;
16505 }
16506 if (resultType.isNull() || Input.isInvalid())
16507 return ExprError();
16508
16509 // Check for array bounds violations in the operand of the UnaryOperator,
16510 // except for the '*' and '&' operators that have to be handled specially
16511 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16512 // that are explicitly defined as valid by the standard).
16513 if (Opc != UO_AddrOf && Opc != UO_Deref)
16514 CheckArrayAccess(E: Input.get());
16515
16516 auto *UO =
16517 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16518 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16519
16520 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16521 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16522 !isUnevaluatedContext())
16523 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16524
16525 // Convert the result back to a half vector.
16526 if (ConvertHalfVec)
16527 return convertVector(UO, Context.HalfTy, *this);
16528 return UO;
16529}
16530
16531/// Determine whether the given expression is a qualified member
16532/// access expression, of a form that could be turned into a pointer to member
16533/// with the address-of operator.
16534bool Sema::isQualifiedMemberAccess(Expr *E) {
16535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16536 if (!DRE->getQualifier())
16537 return false;
16538
16539 ValueDecl *VD = DRE->getDecl();
16540 if (!VD->isCXXClassMember())
16541 return false;
16542
16543 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16544 return true;
16545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16546 return Method->isImplicitObjectMemberFunction();
16547
16548 return false;
16549 }
16550
16551 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16552 if (!ULE->getQualifier())
16553 return false;
16554
16555 for (NamedDecl *D : ULE->decls()) {
16556 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16557 if (Method->isImplicitObjectMemberFunction())
16558 return true;
16559 } else {
16560 // Overload set does not contain methods.
16561 break;
16562 }
16563 }
16564
16565 return false;
16566 }
16567
16568 return false;
16569}
16570
16571ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16572 UnaryOperatorKind Opc, Expr *Input,
16573 bool IsAfterAmp) {
16574 // First things first: handle placeholders so that the
16575 // overloaded-operator check considers the right type.
16576 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16577 // Increment and decrement of pseudo-object references.
16578 if (pty->getKind() == BuiltinType::PseudoObject &&
16579 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16580 return checkPseudoObjectIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16581
16582 // extension is always a builtin operator.
16583 if (Opc == UO_Extension)
16584 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16585
16586 // & gets special logic for several kinds of placeholder.
16587 // The builtin code knows what to do.
16588 if (Opc == UO_AddrOf &&
16589 (pty->getKind() == BuiltinType::Overload ||
16590 pty->getKind() == BuiltinType::UnknownAny ||
16591 pty->getKind() == BuiltinType::BoundMember))
16592 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16593
16594 // Anything else needs to be handled now.
16595 ExprResult Result = CheckPlaceholderExpr(E: Input);
16596 if (Result.isInvalid()) return ExprError();
16597 Input = Result.get();
16598 }
16599
16600 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16601 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16602 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16603 // Find all of the overloaded operators visible from this point.
16604 UnresolvedSet<16> Functions;
16605 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16606 if (S && OverOp != OO_None)
16607 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16608
16609 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16610 }
16611
16612 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16613}
16614
16615// Unary Operators. 'Tok' is the token for the operator.
16616ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16617 Expr *Input, bool IsAfterAmp) {
16618 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16619 IsAfterAmp);
16620}
16621
16622/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16623ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16624 LabelDecl *TheDecl) {
16625 TheDecl->markUsed(Context);
16626 // Create the AST node. The address of a label always has type 'void*'.
16627 auto *Res = new (Context) AddrLabelExpr(
16628 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16629
16630 if (getCurFunction())
16631 getCurFunction()->AddrLabels.push_back(Elt: Res);
16632
16633 return Res;
16634}
16635
16636void Sema::ActOnStartStmtExpr() {
16637 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16638 // Make sure we diagnose jumping into a statement expression.
16639 setFunctionHasBranchProtectedScope();
16640}
16641
16642void Sema::ActOnStmtExprError() {
16643 // Note that function is also called by TreeTransform when leaving a
16644 // StmtExpr scope without rebuilding anything.
16645
16646 DiscardCleanupsInEvaluationContext();
16647 PopExpressionEvaluationContext();
16648}
16649
16650ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16651 SourceLocation RPLoc) {
16652 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16653}
16654
16655ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16656 SourceLocation RPLoc, unsigned TemplateDepth) {
16657 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16658 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16659
16660 if (hasAnyUnrecoverableErrorsInThisFunction())
16661 DiscardCleanupsInEvaluationContext();
16662 assert(!Cleanup.exprNeedsCleanups() &&
16663 "cleanups within StmtExpr not correctly bound!");
16664 PopExpressionEvaluationContext();
16665
16666 // FIXME: there are a variety of strange constraints to enforce here, for
16667 // example, it is not possible to goto into a stmt expression apparently.
16668 // More semantic analysis is needed.
16669
16670 // If there are sub-stmts in the compound stmt, take the type of the last one
16671 // as the type of the stmtexpr.
16672 QualType Ty = Context.VoidTy;
16673 bool StmtExprMayBindToTemp = false;
16674 if (!Compound->body_empty()) {
16675 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16676 if (const auto *LastStmt =
16677 dyn_cast<ValueStmt>(Val: Compound->getStmtExprResult())) {
16678 if (const Expr *Value = LastStmt->getExprStmt()) {
16679 StmtExprMayBindToTemp = true;
16680 Ty = Value->getType();
16681 }
16682 }
16683 }
16684
16685 // FIXME: Check that expression type is complete/non-abstract; statement
16686 // expressions are not lvalues.
16687 Expr *ResStmtExpr =
16688 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16689 if (StmtExprMayBindToTemp)
16690 return MaybeBindToTemporary(E: ResStmtExpr);
16691 return ResStmtExpr;
16692}
16693
16694ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16695 if (ER.isInvalid())
16696 return ExprError();
16697
16698 // Do function/array conversion on the last expression, but not
16699 // lvalue-to-rvalue. However, initialize an unqualified type.
16700 ER = DefaultFunctionArrayConversion(E: ER.get());
16701 if (ER.isInvalid())
16702 return ExprError();
16703 Expr *E = ER.get();
16704
16705 if (E->isTypeDependent())
16706 return E;
16707
16708 // In ARC, if the final expression ends in a consume, splice
16709 // the consume out and bind it later. In the alternate case
16710 // (when dealing with a retainable type), the result
16711 // initialization will create a produce. In both cases the
16712 // result will be +1, and we'll need to balance that out with
16713 // a bind.
16714 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16715 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16716 return Cast->getSubExpr();
16717
16718 // FIXME: Provide a better location for the initialization.
16719 return PerformCopyInitialization(
16720 Entity: InitializedEntity::InitializeStmtExprResult(
16721 ReturnLoc: E->getBeginLoc(), Type: E->getType().getUnqualifiedType()),
16722 EqualLoc: SourceLocation(), Init: E);
16723}
16724
16725ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16726 TypeSourceInfo *TInfo,
16727 ArrayRef<OffsetOfComponent> Components,
16728 SourceLocation RParenLoc) {
16729 QualType ArgTy = TInfo->getType();
16730 bool Dependent = ArgTy->isDependentType();
16731 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16732
16733 // We must have at least one component that refers to the type, and the first
16734 // one is known to be a field designator. Verify that the ArgTy represents
16735 // a struct/union/class.
16736 if (!Dependent && !ArgTy->isRecordType())
16737 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16738 << ArgTy << TypeRange);
16739
16740 // Type must be complete per C99 7.17p3 because a declaring a variable
16741 // with an incomplete type would be ill-formed.
16742 if (!Dependent
16743 && RequireCompleteType(BuiltinLoc, ArgTy,
16744 diag::err_offsetof_incomplete_type, TypeRange))
16745 return ExprError();
16746
16747 bool DidWarnAboutNonPOD = false;
16748 QualType CurrentType = ArgTy;
16749 SmallVector<OffsetOfNode, 4> Comps;
16750 SmallVector<Expr*, 4> Exprs;
16751 for (const OffsetOfComponent &OC : Components) {
16752 if (OC.isBrackets) {
16753 // Offset of an array sub-field. TODO: Should we allow vector elements?
16754 if (!CurrentType->isDependentType()) {
16755 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16756 if(!AT)
16757 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16758 << CurrentType);
16759 CurrentType = AT->getElementType();
16760 } else
16761 CurrentType = Context.DependentTy;
16762
16763 ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E));
16764 if (IdxRval.isInvalid())
16765 return ExprError();
16766 Expr *Idx = IdxRval.get();
16767
16768 // The expression must be an integral expression.
16769 // FIXME: An integral constant expression?
16770 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16771 !Idx->getType()->isIntegerType())
16772 return ExprError(
16773 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16774 << Idx->getSourceRange());
16775
16776 // Record this array index.
16777 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16778 Exprs.push_back(Elt: Idx);
16779 continue;
16780 }
16781
16782 // Offset of a field.
16783 if (CurrentType->isDependentType()) {
16784 // We have the offset of a field, but we can't look into the dependent
16785 // type. Just record the identifier of the field.
16786 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16787 CurrentType = Context.DependentTy;
16788 continue;
16789 }
16790
16791 // We need to have a complete type to look into.
16792 if (RequireCompleteType(OC.LocStart, CurrentType,
16793 diag::err_offsetof_incomplete_type))
16794 return ExprError();
16795
16796 // Look for the designated field.
16797 const RecordType *RC = CurrentType->getAs<RecordType>();
16798 if (!RC)
16799 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16800 << CurrentType);
16801 RecordDecl *RD = RC->getDecl();
16802
16803 // C++ [lib.support.types]p5:
16804 // The macro offsetof accepts a restricted set of type arguments in this
16805 // International Standard. type shall be a POD structure or a POD union
16806 // (clause 9).
16807 // C++11 [support.types]p4:
16808 // If type is not a standard-layout class (Clause 9), the results are
16809 // undefined.
16810 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16811 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16812 unsigned DiagID =
16813 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16814 : diag::ext_offsetof_non_pod_type;
16815
16816 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16817 Diag(Loc: BuiltinLoc, DiagID)
16818 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16819 DidWarnAboutNonPOD = true;
16820 }
16821 }
16822
16823 // Look for the field.
16824 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16825 LookupQualifiedName(R, RD);
16826 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16827 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16828 if (!MemberDecl) {
16829 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16830 MemberDecl = IndirectMemberDecl->getAnonField();
16831 }
16832
16833 if (!MemberDecl) {
16834 // Lookup could be ambiguous when looking up a placeholder variable
16835 // __builtin_offsetof(S, _).
16836 // In that case we would already have emitted a diagnostic
16837 if (!R.isAmbiguous())
16838 Diag(BuiltinLoc, diag::err_no_member)
16839 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16840 return ExprError();
16841 }
16842
16843 // C99 7.17p3:
16844 // (If the specified member is a bit-field, the behavior is undefined.)
16845 //
16846 // We diagnose this as an error.
16847 if (MemberDecl->isBitField()) {
16848 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16849 << MemberDecl->getDeclName()
16850 << SourceRange(BuiltinLoc, RParenLoc);
16851 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16852 return ExprError();
16853 }
16854
16855 RecordDecl *Parent = MemberDecl->getParent();
16856 if (IndirectMemberDecl)
16857 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16858
16859 // If the member was found in a base class, introduce OffsetOfNodes for
16860 // the base class indirections.
16861 CXXBasePaths Paths;
16862 if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType, Base: Context.getTypeDeclType(Parent),
16863 Paths)) {
16864 if (Paths.getDetectedVirtual()) {
16865 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16866 << MemberDecl->getDeclName()
16867 << SourceRange(BuiltinLoc, RParenLoc);
16868 return ExprError();
16869 }
16870
16871 CXXBasePath &Path = Paths.front();
16872 for (const CXXBasePathElement &B : Path)
16873 Comps.push_back(Elt: OffsetOfNode(B.Base));
16874 }
16875
16876 if (IndirectMemberDecl) {
16877 for (auto *FI : IndirectMemberDecl->chain()) {
16878 assert(isa<FieldDecl>(FI));
16879 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16880 cast<FieldDecl>(Val: FI), OC.LocEnd));
16881 }
16882 } else
16883 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16884
16885 CurrentType = MemberDecl->getType().getNonReferenceType();
16886 }
16887
16888 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16889 comps: Comps, exprs: Exprs, RParenLoc);
16890}
16891
16892ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16893 SourceLocation BuiltinLoc,
16894 SourceLocation TypeLoc,
16895 ParsedType ParsedArgTy,
16896 ArrayRef<OffsetOfComponent> Components,
16897 SourceLocation RParenLoc) {
16898
16899 TypeSourceInfo *ArgTInfo;
16900 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16901 if (ArgTy.isNull())
16902 return ExprError();
16903
16904 if (!ArgTInfo)
16905 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16906
16907 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16908}
16909
16910
16911ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16912 Expr *CondExpr,
16913 Expr *LHSExpr, Expr *RHSExpr,
16914 SourceLocation RPLoc) {
16915 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16916
16917 ExprValueKind VK = VK_PRValue;
16918 ExprObjectKind OK = OK_Ordinary;
16919 QualType resType;
16920 bool CondIsTrue = false;
16921 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16922 resType = Context.DependentTy;
16923 } else {
16924 // The conditional expression is required to be a constant expression.
16925 llvm::APSInt condEval(32);
16926 ExprResult CondICE = VerifyIntegerConstantExpression(
16927 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16928 if (CondICE.isInvalid())
16929 return ExprError();
16930 CondExpr = CondICE.get();
16931 CondIsTrue = condEval.getZExtValue();
16932
16933 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16934 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16935
16936 resType = ActiveExpr->getType();
16937 VK = ActiveExpr->getValueKind();
16938 OK = ActiveExpr->getObjectKind();
16939 }
16940
16941 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16942 resType, VK, OK, RPLoc, CondIsTrue);
16943}
16944
16945//===----------------------------------------------------------------------===//
16946// Clang Extensions.
16947//===----------------------------------------------------------------------===//
16948
16949/// ActOnBlockStart - This callback is invoked when a block literal is started.
16950void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16951 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16952
16953 if (LangOpts.CPlusPlus) {
16954 MangleNumberingContext *MCtx;
16955 Decl *ManglingContextDecl;
16956 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16957 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16958 if (MCtx) {
16959 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16960 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16961 }
16962 }
16963
16964 PushBlockScope(BlockScope: CurScope, Block);
16965 CurContext->addDecl(Block);
16966 if (CurScope)
16967 PushDeclContext(CurScope, Block);
16968 else
16969 CurContext = Block;
16970
16971 getCurBlock()->HasImplicitReturnType = true;
16972
16973 // Enter a new evaluation context to insulate the block from any
16974 // cleanups from the enclosing full-expression.
16975 PushExpressionEvaluationContext(
16976 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16977}
16978
16979void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16980 Scope *CurScope) {
16981 assert(ParamInfo.getIdentifier() == nullptr &&
16982 "block-id should have no identifier!");
16983 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16984 BlockScopeInfo *CurBlock = getCurBlock();
16985
16986 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16987 QualType T = Sig->getType();
16988
16989 // FIXME: We should allow unexpanded parameter packs here, but that would,
16990 // in turn, make the block expression contain unexpanded parameter packs.
16991 if (DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block)) {
16992 // Drop the parameters.
16993 FunctionProtoType::ExtProtoInfo EPI;
16994 EPI.HasTrailingReturn = false;
16995 EPI.TypeQuals.addConst();
16996 T = Context.getFunctionType(ResultTy: Context.DependentTy, Args: std::nullopt, EPI);
16997 Sig = Context.getTrivialTypeSourceInfo(T);
16998 }
16999
17000 // GetTypeForDeclarator always produces a function type for a block
17001 // literal signature. Furthermore, it is always a FunctionProtoType
17002 // unless the function was written with a typedef.
17003 assert(T->isFunctionType() &&
17004 "GetTypeForDeclarator made a non-function block signature");
17005
17006 // Look for an explicit signature in that function type.
17007 FunctionProtoTypeLoc ExplicitSignature;
17008
17009 if ((ExplicitSignature = Sig->getTypeLoc()
17010 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17011
17012 // Check whether that explicit signature was synthesized by
17013 // GetTypeForDeclarator. If so, don't save that as part of the
17014 // written signature.
17015 if (ExplicitSignature.getLocalRangeBegin() ==
17016 ExplicitSignature.getLocalRangeEnd()) {
17017 // This would be much cheaper if we stored TypeLocs instead of
17018 // TypeSourceInfos.
17019 TypeLoc Result = ExplicitSignature.getReturnLoc();
17020 unsigned Size = Result.getFullDataSize();
17021 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17022 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17023
17024 ExplicitSignature = FunctionProtoTypeLoc();
17025 }
17026 }
17027
17028 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17029 CurBlock->FunctionType = T;
17030
17031 const auto *Fn = T->castAs<FunctionType>();
17032 QualType RetTy = Fn->getReturnType();
17033 bool isVariadic =
17034 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17035
17036 CurBlock->TheDecl->setIsVariadic(isVariadic);
17037
17038 // Context.DependentTy is used as a placeholder for a missing block
17039 // return type. TODO: what should we do with declarators like:
17040 // ^ * { ... }
17041 // If the answer is "apply template argument deduction"....
17042 if (RetTy != Context.DependentTy) {
17043 CurBlock->ReturnType = RetTy;
17044 CurBlock->TheDecl->setBlockMissingReturnType(false);
17045 CurBlock->HasImplicitReturnType = false;
17046 }
17047
17048 // Push block parameters from the declarator if we had them.
17049 SmallVector<ParmVarDecl*, 8> Params;
17050 if (ExplicitSignature) {
17051 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17052 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17053 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17054 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17055 // Diagnose this as an extension in C17 and earlier.
17056 if (!getLangOpts().C23)
17057 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17058 }
17059 Params.push_back(Elt: Param);
17060 }
17061
17062 // Fake up parameter variables if we have a typedef, like
17063 // ^ fntype { ... }
17064 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17065 for (const auto &I : Fn->param_types()) {
17066 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17067 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17068 Params.push_back(Elt: Param);
17069 }
17070 }
17071
17072 // Set the parameters on the block decl.
17073 if (!Params.empty()) {
17074 CurBlock->TheDecl->setParams(Params);
17075 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17076 /*CheckParameterNames=*/false);
17077 }
17078
17079 // Finally we can process decl attributes.
17080 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17081
17082 // Put the parameter variables in scope.
17083 for (auto *AI : CurBlock->TheDecl->parameters()) {
17084 AI->setOwningFunction(CurBlock->TheDecl);
17085
17086 // If this has an identifier, add it to the scope stack.
17087 if (AI->getIdentifier()) {
17088 CheckShadow(CurBlock->TheScope, AI);
17089
17090 PushOnScopeChains(AI, CurBlock->TheScope);
17091 }
17092
17093 if (AI->isInvalidDecl())
17094 CurBlock->TheDecl->setInvalidDecl();
17095 }
17096}
17097
17098/// ActOnBlockError - If there is an error parsing a block, this callback
17099/// is invoked to pop the information about the block from the action impl.
17100void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17101 // Leave the expression-evaluation context.
17102 DiscardCleanupsInEvaluationContext();
17103 PopExpressionEvaluationContext();
17104
17105 // Pop off CurBlock, handle nested blocks.
17106 PopDeclContext();
17107 PopFunctionScopeInfo();
17108}
17109
17110/// ActOnBlockStmtExpr - This is called when the body of a block statement
17111/// literal was successfully completed. ^(int x){...}
17112ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17113 Stmt *Body, Scope *CurScope) {
17114 // If blocks are disabled, emit an error.
17115 if (!LangOpts.Blocks)
17116 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17117
17118 // Leave the expression-evaluation context.
17119 if (hasAnyUnrecoverableErrorsInThisFunction())
17120 DiscardCleanupsInEvaluationContext();
17121 assert(!Cleanup.exprNeedsCleanups() &&
17122 "cleanups within block not correctly bound!");
17123 PopExpressionEvaluationContext();
17124
17125 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17126 BlockDecl *BD = BSI->TheDecl;
17127
17128 if (BSI->HasImplicitReturnType)
17129 deduceClosureReturnType(*BSI);
17130
17131 QualType RetTy = Context.VoidTy;
17132 if (!BSI->ReturnType.isNull())
17133 RetTy = BSI->ReturnType;
17134
17135 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17136 QualType BlockTy;
17137
17138 // If the user wrote a function type in some form, try to use that.
17139 if (!BSI->FunctionType.isNull()) {
17140 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17141
17142 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17143 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17144
17145 // Turn protoless block types into nullary block types.
17146 if (isa<FunctionNoProtoType>(Val: FTy)) {
17147 FunctionProtoType::ExtProtoInfo EPI;
17148 EPI.ExtInfo = Ext;
17149 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: std::nullopt, EPI);
17150
17151 // Otherwise, if we don't need to change anything about the function type,
17152 // preserve its sugar structure.
17153 } else if (FTy->getReturnType() == RetTy &&
17154 (!NoReturn || FTy->getNoReturnAttr())) {
17155 BlockTy = BSI->FunctionType;
17156
17157 // Otherwise, make the minimal modifications to the function type.
17158 } else {
17159 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17160 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17161 EPI.TypeQuals = Qualifiers();
17162 EPI.ExtInfo = Ext;
17163 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17164 }
17165
17166 // If we don't have a function type, just build one from nothing.
17167 } else {
17168 FunctionProtoType::ExtProtoInfo EPI;
17169 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17170 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: std::nullopt, EPI);
17171 }
17172
17173 DiagnoseUnusedParameters(Parameters: BD->parameters());
17174 BlockTy = Context.getBlockPointerType(T: BlockTy);
17175
17176 // If needed, diagnose invalid gotos and switches in the block.
17177 if (getCurFunction()->NeedsScopeChecking() &&
17178 !PP.isCodeCompletionEnabled())
17179 DiagnoseInvalidJumps(cast<CompoundStmt>(Val: Body));
17180
17181 BD->setBody(cast<CompoundStmt>(Val: Body));
17182
17183 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17184 DiagnoseUnguardedAvailabilityViolations(BD);
17185
17186 // Try to apply the named return value optimization. We have to check again
17187 // if we can do this, though, because blocks keep return statements around
17188 // to deduce an implicit return type.
17189 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17190 !BD->isDependentContext())
17191 computeNRVO(Body, BSI);
17192
17193 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17194 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17195 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(), UseContext: NTCUC_FunctionReturn,
17196 NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
17197
17198 PopDeclContext();
17199
17200 // Set the captured variables on the block.
17201 SmallVector<BlockDecl::Capture, 4> Captures;
17202 for (Capture &Cap : BSI->Captures) {
17203 if (Cap.isInvalid() || Cap.isThisCapture())
17204 continue;
17205 // Cap.getVariable() is always a VarDecl because
17206 // blocks cannot capture structured bindings or other ValueDecl kinds.
17207 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17208 Expr *CopyExpr = nullptr;
17209 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17210 if (const RecordType *Record =
17211 Cap.getCaptureType()->getAs<RecordType>()) {
17212 // The capture logic needs the destructor, so make sure we mark it.
17213 // Usually this is unnecessary because most local variables have
17214 // their destructors marked at declaration time, but parameters are
17215 // an exception because it's technically only the call site that
17216 // actually requires the destructor.
17217 if (isa<ParmVarDecl>(Val: Var))
17218 FinalizeVarWithDestructor(VD: Var, DeclInitType: Record);
17219
17220 // Enter a separate potentially-evaluated context while building block
17221 // initializers to isolate their cleanups from those of the block
17222 // itself.
17223 // FIXME: Is this appropriate even when the block itself occurs in an
17224 // unevaluated operand?
17225 EnterExpressionEvaluationContext EvalContext(
17226 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17227
17228 SourceLocation Loc = Cap.getLocation();
17229
17230 ExprResult Result = BuildDeclarationNameExpr(
17231 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17232
17233 // According to the blocks spec, the capture of a variable from
17234 // the stack requires a const copy constructor. This is not true
17235 // of the copy/move done to move a __block variable to the heap.
17236 if (!Result.isInvalid() &&
17237 !Result.get()->getType().isConstQualified()) {
17238 Result = ImpCastExprToType(E: Result.get(),
17239 Type: Result.get()->getType().withConst(),
17240 CK: CK_NoOp, VK: VK_LValue);
17241 }
17242
17243 if (!Result.isInvalid()) {
17244 Result = PerformCopyInitialization(
17245 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17246 Type: Cap.getCaptureType()),
17247 EqualLoc: Loc, Init: Result.get());
17248 }
17249
17250 // Build a full-expression copy expression if initialization
17251 // succeeded and used a non-trivial constructor. Recover from
17252 // errors by pretending that the copy isn't necessary.
17253 if (!Result.isInvalid() &&
17254 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17255 ->isTrivial()) {
17256 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17257 CopyExpr = Result.get();
17258 }
17259 }
17260 }
17261
17262 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17263 CopyExpr);
17264 Captures.push_back(Elt: NewCap);
17265 }
17266 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17267
17268 // Pop the block scope now but keep it alive to the end of this function.
17269 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
17270 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17271
17272 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
17273
17274 // If the block isn't obviously global, i.e. it captures anything at
17275 // all, then we need to do a few things in the surrounding context:
17276 if (Result->getBlockDecl()->hasCaptures()) {
17277 // First, this expression has a new cleanup object.
17278 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17279 Cleanup.setExprNeedsCleanups(true);
17280
17281 // It also gets a branch-protected scope if any of the captured
17282 // variables needs destruction.
17283 for (const auto &CI : Result->getBlockDecl()->captures()) {
17284 const VarDecl *var = CI.getVariable();
17285 if (var->getType().isDestructedType() != QualType::DK_none) {
17286 setFunctionHasBranchProtectedScope();
17287 break;
17288 }
17289 }
17290 }
17291
17292 if (getCurFunction())
17293 getCurFunction()->addBlock(BD);
17294
17295 if (BD->isInvalidDecl())
17296 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17297 SubExprs: {Result}, T: Result->getType());
17298 return Result;
17299}
17300
17301ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17302 SourceLocation RPLoc) {
17303 TypeSourceInfo *TInfo;
17304 GetTypeFromParser(Ty, TInfo: &TInfo);
17305 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17306}
17307
17308ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17309 Expr *E, TypeSourceInfo *TInfo,
17310 SourceLocation RPLoc) {
17311 Expr *OrigExpr = E;
17312 bool IsMS = false;
17313
17314 // CUDA device code does not support varargs.
17315 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17316 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17317 CUDAFunctionTarget T = IdentifyCUDATarget(D: F);
17318 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
17319 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17320 }
17321 }
17322
17323 // NVPTX does not support va_arg expression.
17324 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17325 Context.getTargetInfo().getTriple().isNVPTX())
17326 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17327
17328 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17329 // as Microsoft ABI on an actual Microsoft platform, where
17330 // __builtin_ms_va_list and __builtin_va_list are the same.)
17331 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17332 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17333 QualType MSVaListType = Context.getBuiltinMSVaListType();
17334 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17335 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17336 return ExprError();
17337 IsMS = true;
17338 }
17339 }
17340
17341 // Get the va_list type
17342 QualType VaListType = Context.getBuiltinVaListType();
17343 if (!IsMS) {
17344 if (VaListType->isArrayType()) {
17345 // Deal with implicit array decay; for example, on x86-64,
17346 // va_list is an array, but it's supposed to decay to
17347 // a pointer for va_arg.
17348 VaListType = Context.getArrayDecayedType(T: VaListType);
17349 // Make sure the input expression also decays appropriately.
17350 ExprResult Result = UsualUnaryConversions(E);
17351 if (Result.isInvalid())
17352 return ExprError();
17353 E = Result.get();
17354 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17355 // If va_list is a record type and we are compiling in C++ mode,
17356 // check the argument using reference binding.
17357 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17358 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17359 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17360 if (Init.isInvalid())
17361 return ExprError();
17362 E = Init.getAs<Expr>();
17363 } else {
17364 // Otherwise, the va_list argument must be an l-value because
17365 // it is modified by va_arg.
17366 if (!E->isTypeDependent() &&
17367 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17368 return ExprError();
17369 }
17370 }
17371
17372 if (!IsMS && !E->isTypeDependent() &&
17373 !Context.hasSameType(VaListType, E->getType()))
17374 return ExprError(
17375 Diag(E->getBeginLoc(),
17376 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17377 << OrigExpr->getType() << E->getSourceRange());
17378
17379 if (!TInfo->getType()->isDependentType()) {
17380 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17381 diag::err_second_parameter_to_va_arg_incomplete,
17382 TInfo->getTypeLoc()))
17383 return ExprError();
17384
17385 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17386 TInfo->getType(),
17387 diag::err_second_parameter_to_va_arg_abstract,
17388 TInfo->getTypeLoc()))
17389 return ExprError();
17390
17391 if (!TInfo->getType().isPODType(Context)) {
17392 Diag(TInfo->getTypeLoc().getBeginLoc(),
17393 TInfo->getType()->isObjCLifetimeType()
17394 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17395 : diag::warn_second_parameter_to_va_arg_not_pod)
17396 << TInfo->getType()
17397 << TInfo->getTypeLoc().getSourceRange();
17398 }
17399
17400 // Check for va_arg where arguments of the given type will be promoted
17401 // (i.e. this va_arg is guaranteed to have undefined behavior).
17402 QualType PromoteType;
17403 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17404 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17405 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17406 // and C23 7.16.1.1p2 says, in part:
17407 // If type is not compatible with the type of the actual next argument
17408 // (as promoted according to the default argument promotions), the
17409 // behavior is undefined, except for the following cases:
17410 // - both types are pointers to qualified or unqualified versions of
17411 // compatible types;
17412 // - one type is compatible with a signed integer type, the other
17413 // type is compatible with the corresponding unsigned integer type,
17414 // and the value is representable in both types;
17415 // - one type is pointer to qualified or unqualified void and the
17416 // other is a pointer to a qualified or unqualified character type;
17417 // - or, the type of the next argument is nullptr_t and type is a
17418 // pointer type that has the same representation and alignment
17419 // requirements as a pointer to a character type.
17420 // Given that type compatibility is the primary requirement (ignoring
17421 // qualifications), you would think we could call typesAreCompatible()
17422 // directly to test this. However, in C++, that checks for *same type*,
17423 // which causes false positives when passing an enumeration type to
17424 // va_arg. Instead, get the underlying type of the enumeration and pass
17425 // that.
17426 QualType UnderlyingType = TInfo->getType();
17427 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17428 UnderlyingType = ET->getDecl()->getIntegerType();
17429 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17430 /*CompareUnqualified*/ true))
17431 PromoteType = QualType();
17432
17433 // If the types are still not compatible, we need to test whether the
17434 // promoted type and the underlying type are the same except for
17435 // signedness. Ask the AST for the correctly corresponding type and see
17436 // if that's compatible.
17437 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17438 PromoteType->isUnsignedIntegerType() !=
17439 UnderlyingType->isUnsignedIntegerType()) {
17440 UnderlyingType =
17441 UnderlyingType->isUnsignedIntegerType()
17442 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17443 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17444 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17445 /*CompareUnqualified*/ true))
17446 PromoteType = QualType();
17447 }
17448 }
17449 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17450 PromoteType = Context.DoubleTy;
17451 if (!PromoteType.isNull())
17452 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17453 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17454 << TInfo->getType()
17455 << PromoteType
17456 << TInfo->getTypeLoc().getSourceRange());
17457 }
17458
17459 QualType T = TInfo->getType().getNonLValueExprType(Context);
17460 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17461}
17462
17463ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17464 // The type of __null will be int or long, depending on the size of
17465 // pointers on the target.
17466 QualType Ty;
17467 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17468 if (pw == Context.getTargetInfo().getIntWidth())
17469 Ty = Context.IntTy;
17470 else if (pw == Context.getTargetInfo().getLongWidth())
17471 Ty = Context.LongTy;
17472 else if (pw == Context.getTargetInfo().getLongLongWidth())
17473 Ty = Context.LongLongTy;
17474 else {
17475 llvm_unreachable("I don't know size of pointer!");
17476 }
17477
17478 return new (Context) GNUNullExpr(Ty, TokenLoc);
17479}
17480
17481static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17482 CXXRecordDecl *ImplDecl = nullptr;
17483
17484 // Fetch the std::source_location::__impl decl.
17485 if (NamespaceDecl *Std = S.getStdNamespace()) {
17486 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17487 Loc, Sema::LookupOrdinaryName);
17488 if (S.LookupQualifiedName(ResultSL, Std)) {
17489 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17490 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17491 Loc, Sema::LookupOrdinaryName);
17492 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17493 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17494 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17495 }
17496 }
17497 }
17498 }
17499
17500 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17501 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17502 return nullptr;
17503 }
17504
17505 // Verify that __impl is a trivial struct type, with no base classes, and with
17506 // only the four expected fields.
17507 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17508 ImplDecl->getNumBases() != 0) {
17509 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17510 return nullptr;
17511 }
17512
17513 unsigned Count = 0;
17514 for (FieldDecl *F : ImplDecl->fields()) {
17515 StringRef Name = F->getName();
17516
17517 if (Name == "_M_file_name") {
17518 if (F->getType() !=
17519 S.Context.getPointerType(S.Context.CharTy.withConst()))
17520 break;
17521 Count++;
17522 } else if (Name == "_M_function_name") {
17523 if (F->getType() !=
17524 S.Context.getPointerType(S.Context.CharTy.withConst()))
17525 break;
17526 Count++;
17527 } else if (Name == "_M_line") {
17528 if (!F->getType()->isIntegerType())
17529 break;
17530 Count++;
17531 } else if (Name == "_M_column") {
17532 if (!F->getType()->isIntegerType())
17533 break;
17534 Count++;
17535 } else {
17536 Count = 100; // invalid
17537 break;
17538 }
17539 }
17540 if (Count != 4) {
17541 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17542 return nullptr;
17543 }
17544
17545 return ImplDecl;
17546}
17547
17548ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17549 SourceLocation BuiltinLoc,
17550 SourceLocation RPLoc) {
17551 QualType ResultTy;
17552 switch (Kind) {
17553 case SourceLocIdentKind::File:
17554 case SourceLocIdentKind::FileName:
17555 case SourceLocIdentKind::Function:
17556 case SourceLocIdentKind::FuncSig: {
17557 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17558 ResultTy =
17559 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17560 break;
17561 }
17562 case SourceLocIdentKind::Line:
17563 case SourceLocIdentKind::Column:
17564 ResultTy = Context.UnsignedIntTy;
17565 break;
17566 case SourceLocIdentKind::SourceLocStruct:
17567 if (!StdSourceLocationImplDecl) {
17568 StdSourceLocationImplDecl =
17569 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17570 if (!StdSourceLocationImplDecl)
17571 return ExprError();
17572 }
17573 ResultTy = Context.getPointerType(
17574 T: Context.getRecordType(Decl: StdSourceLocationImplDecl).withConst());
17575 break;
17576 }
17577
17578 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17579}
17580
17581ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17582 SourceLocation BuiltinLoc,
17583 SourceLocation RPLoc,
17584 DeclContext *ParentContext) {
17585 return new (Context)
17586 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17587}
17588
17589bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17590 bool Diagnose) {
17591 if (!getLangOpts().ObjC)
17592 return false;
17593
17594 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17595 if (!PT)
17596 return false;
17597 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17598
17599 // Ignore any parens, implicit casts (should only be
17600 // array-to-pointer decays), and not-so-opaque values. The last is
17601 // important for making this trigger for property assignments.
17602 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17603 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(Val: SrcExpr))
17604 if (OV->getSourceExpr())
17605 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17606
17607 if (auto *SL = dyn_cast<StringLiteral>(Val: SrcExpr)) {
17608 if (!PT->isObjCIdType() &&
17609 !(ID && ID->getIdentifier()->isStr("NSString")))
17610 return false;
17611 if (!SL->isOrdinary())
17612 return false;
17613
17614 if (Diagnose) {
17615 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17616 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17617 Exp = BuildObjCStringLiteral(AtLoc: SL->getBeginLoc(), S: SL).get();
17618 }
17619 return true;
17620 }
17621
17622 if ((isa<IntegerLiteral>(Val: SrcExpr) || isa<CharacterLiteral>(Val: SrcExpr) ||
17623 isa<FloatingLiteral>(Val: SrcExpr) || isa<ObjCBoolLiteralExpr>(Val: SrcExpr) ||
17624 isa<CXXBoolLiteralExpr>(Val: SrcExpr)) &&
17625 !SrcExpr->isNullPointerConstant(
17626 Ctx&: getASTContext(), NPC: Expr::NPC_NeverValueDependent)) {
17627 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17628 return false;
17629 if (Diagnose) {
17630 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17631 << /*number*/1
17632 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17633 Expr *NumLit =
17634 BuildObjCNumericLiteral(AtLoc: SrcExpr->getBeginLoc(), Number: SrcExpr).get();
17635 if (NumLit)
17636 Exp = NumLit;
17637 }
17638 return true;
17639 }
17640
17641 return false;
17642}
17643
17644static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17645 const Expr *SrcExpr) {
17646 if (!DstType->isFunctionPointerType() ||
17647 !SrcExpr->getType()->isFunctionType())
17648 return false;
17649
17650 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17651 if (!DRE)
17652 return false;
17653
17654 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17655 if (!FD)
17656 return false;
17657
17658 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17659 /*Complain=*/true,
17660 Loc: SrcExpr->getBeginLoc());
17661}
17662
17663bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17664 SourceLocation Loc,
17665 QualType DstType, QualType SrcType,
17666 Expr *SrcExpr, AssignmentAction Action,
17667 bool *Complained) {
17668 if (Complained)
17669 *Complained = false;
17670
17671 // Decode the result (notice that AST's are still created for extensions).
17672 bool CheckInferredResultType = false;
17673 bool isInvalid = false;
17674 unsigned DiagKind = 0;
17675 ConversionFixItGenerator ConvHints;
17676 bool MayHaveConvFixit = false;
17677 bool MayHaveFunctionDiff = false;
17678 const ObjCInterfaceDecl *IFace = nullptr;
17679 const ObjCProtocolDecl *PDecl = nullptr;
17680
17681 switch (ConvTy) {
17682 case Compatible:
17683 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17684 return false;
17685
17686 case PointerToInt:
17687 if (getLangOpts().CPlusPlus) {
17688 DiagKind = diag::err_typecheck_convert_pointer_int;
17689 isInvalid = true;
17690 } else {
17691 DiagKind = diag::ext_typecheck_convert_pointer_int;
17692 }
17693 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17694 MayHaveConvFixit = true;
17695 break;
17696 case IntToPointer:
17697 if (getLangOpts().CPlusPlus) {
17698 DiagKind = diag::err_typecheck_convert_int_pointer;
17699 isInvalid = true;
17700 } else {
17701 DiagKind = diag::ext_typecheck_convert_int_pointer;
17702 }
17703 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17704 MayHaveConvFixit = true;
17705 break;
17706 case IncompatibleFunctionPointerStrict:
17707 DiagKind =
17708 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17709 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17710 MayHaveConvFixit = true;
17711 break;
17712 case IncompatibleFunctionPointer:
17713 if (getLangOpts().CPlusPlus) {
17714 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17715 isInvalid = true;
17716 } else {
17717 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17718 }
17719 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17720 MayHaveConvFixit = true;
17721 break;
17722 case IncompatiblePointer:
17723 if (Action == AA_Passing_CFAudited) {
17724 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17725 } else if (getLangOpts().CPlusPlus) {
17726 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17727 isInvalid = true;
17728 } else {
17729 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17730 }
17731 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17732 SrcType->isObjCObjectPointerType();
17733 if (!CheckInferredResultType) {
17734 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17735 } else if (CheckInferredResultType) {
17736 SrcType = SrcType.getUnqualifiedType();
17737 DstType = DstType.getUnqualifiedType();
17738 }
17739 MayHaveConvFixit = true;
17740 break;
17741 case IncompatiblePointerSign:
17742 if (getLangOpts().CPlusPlus) {
17743 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17744 isInvalid = true;
17745 } else {
17746 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17747 }
17748 break;
17749 case FunctionVoidPointer:
17750 if (getLangOpts().CPlusPlus) {
17751 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17752 isInvalid = true;
17753 } else {
17754 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17755 }
17756 break;
17757 case IncompatiblePointerDiscardsQualifiers: {
17758 // Perform array-to-pointer decay if necessary.
17759 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType);
17760
17761 isInvalid = true;
17762
17763 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17764 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17765 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17766 DiagKind = diag::err_typecheck_incompatible_address_space;
17767 break;
17768
17769 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17770 DiagKind = diag::err_typecheck_incompatible_ownership;
17771 break;
17772 }
17773
17774 llvm_unreachable("unknown error case for discarding qualifiers!");
17775 // fallthrough
17776 }
17777 case CompatiblePointerDiscardsQualifiers:
17778 // If the qualifiers lost were because we were applying the
17779 // (deprecated) C++ conversion from a string literal to a char*
17780 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17781 // Ideally, this check would be performed in
17782 // checkPointerTypesForAssignment. However, that would require a
17783 // bit of refactoring (so that the second argument is an
17784 // expression, rather than a type), which should be done as part
17785 // of a larger effort to fix checkPointerTypesForAssignment for
17786 // C++ semantics.
17787 if (getLangOpts().CPlusPlus &&
17788 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17789 return false;
17790 if (getLangOpts().CPlusPlus) {
17791 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17792 isInvalid = true;
17793 } else {
17794 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17795 }
17796
17797 break;
17798 case IncompatibleNestedPointerQualifiers:
17799 if (getLangOpts().CPlusPlus) {
17800 isInvalid = true;
17801 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17802 } else {
17803 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17804 }
17805 break;
17806 case IncompatibleNestedPointerAddressSpaceMismatch:
17807 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17808 isInvalid = true;
17809 break;
17810 case IntToBlockPointer:
17811 DiagKind = diag::err_int_to_block_pointer;
17812 isInvalid = true;
17813 break;
17814 case IncompatibleBlockPointer:
17815 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17816 isInvalid = true;
17817 break;
17818 case IncompatibleObjCQualifiedId: {
17819 if (SrcType->isObjCQualifiedIdType()) {
17820 const ObjCObjectPointerType *srcOPT =
17821 SrcType->castAs<ObjCObjectPointerType>();
17822 for (auto *srcProto : srcOPT->quals()) {
17823 PDecl = srcProto;
17824 break;
17825 }
17826 if (const ObjCInterfaceType *IFaceT =
17827 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17828 IFace = IFaceT->getDecl();
17829 }
17830 else if (DstType->isObjCQualifiedIdType()) {
17831 const ObjCObjectPointerType *dstOPT =
17832 DstType->castAs<ObjCObjectPointerType>();
17833 for (auto *dstProto : dstOPT->quals()) {
17834 PDecl = dstProto;
17835 break;
17836 }
17837 if (const ObjCInterfaceType *IFaceT =
17838 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17839 IFace = IFaceT->getDecl();
17840 }
17841 if (getLangOpts().CPlusPlus) {
17842 DiagKind = diag::err_incompatible_qualified_id;
17843 isInvalid = true;
17844 } else {
17845 DiagKind = diag::warn_incompatible_qualified_id;
17846 }
17847 break;
17848 }
17849 case IncompatibleVectors:
17850 if (getLangOpts().CPlusPlus) {
17851 DiagKind = diag::err_incompatible_vectors;
17852 isInvalid = true;
17853 } else {
17854 DiagKind = diag::warn_incompatible_vectors;
17855 }
17856 break;
17857 case IncompatibleObjCWeakRef:
17858 DiagKind = diag::err_arc_weak_unavailable_assign;
17859 isInvalid = true;
17860 break;
17861 case Incompatible:
17862 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17863 if (Complained)
17864 *Complained = true;
17865 return true;
17866 }
17867
17868 DiagKind = diag::err_typecheck_convert_incompatible;
17869 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17870 MayHaveConvFixit = true;
17871 isInvalid = true;
17872 MayHaveFunctionDiff = true;
17873 break;
17874 }
17875
17876 QualType FirstType, SecondType;
17877 switch (Action) {
17878 case AA_Assigning:
17879 case AA_Initializing:
17880 // The destination type comes first.
17881 FirstType = DstType;
17882 SecondType = SrcType;
17883 break;
17884
17885 case AA_Returning:
17886 case AA_Passing:
17887 case AA_Passing_CFAudited:
17888 case AA_Converting:
17889 case AA_Sending:
17890 case AA_Casting:
17891 // The source type comes first.
17892 FirstType = SrcType;
17893 SecondType = DstType;
17894 break;
17895 }
17896
17897 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17898 AssignmentAction ActionForDiag = Action;
17899 if (Action == AA_Passing_CFAudited)
17900 ActionForDiag = AA_Passing;
17901
17902 FDiag << FirstType << SecondType << ActionForDiag
17903 << SrcExpr->getSourceRange();
17904
17905 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17906 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17907 auto isPlainChar = [](const clang::Type *Type) {
17908 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17909 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17910 };
17911 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17912 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17913 }
17914
17915 // If we can fix the conversion, suggest the FixIts.
17916 if (!ConvHints.isNull()) {
17917 for (FixItHint &H : ConvHints.Hints)
17918 FDiag << H;
17919 }
17920
17921 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17922
17923 if (MayHaveFunctionDiff)
17924 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17925
17926 Diag(Loc, PD: FDiag);
17927 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17928 DiagKind == diag::err_incompatible_qualified_id) &&
17929 PDecl && IFace && !IFace->hasDefinition())
17930 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17931 << IFace << PDecl;
17932
17933 if (SecondType == Context.OverloadTy)
17934 NoteAllOverloadCandidates(OverloadExpr::find(E: SrcExpr).Expression,
17935 FirstType, /*TakingAddress=*/true);
17936
17937 if (CheckInferredResultType)
17938 EmitRelatedResultTypeNote(E: SrcExpr);
17939
17940 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17941 EmitRelatedResultTypeNoteForReturn(destType: DstType);
17942
17943 if (Complained)
17944 *Complained = true;
17945 return isInvalid;
17946}
17947
17948ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17949 llvm::APSInt *Result,
17950 AllowFoldKind CanFold) {
17951 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17952 public:
17953 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17954 QualType T) override {
17955 return S.Diag(Loc, diag::err_ice_not_integral)
17956 << T << S.LangOpts.CPlusPlus;
17957 }
17958 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17959 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17960 }
17961 } Diagnoser;
17962
17963 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17964}
17965
17966ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17967 llvm::APSInt *Result,
17968 unsigned DiagID,
17969 AllowFoldKind CanFold) {
17970 class IDDiagnoser : public VerifyICEDiagnoser {
17971 unsigned DiagID;
17972
17973 public:
17974 IDDiagnoser(unsigned DiagID)
17975 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17976
17977 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17978 return S.Diag(Loc, DiagID);
17979 }
17980 } Diagnoser(DiagID);
17981
17982 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17983}
17984
17985Sema::SemaDiagnosticBuilder
17986Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17987 QualType T) {
17988 return diagnoseNotICE(S, Loc);
17989}
17990
17991Sema::SemaDiagnosticBuilder
17992Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17993 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17994}
17995
17996ExprResult
17997Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17998 VerifyICEDiagnoser &Diagnoser,
17999 AllowFoldKind CanFold) {
18000 SourceLocation DiagLoc = E->getBeginLoc();
18001
18002 if (getLangOpts().CPlusPlus11) {
18003 // C++11 [expr.const]p5:
18004 // If an expression of literal class type is used in a context where an
18005 // integral constant expression is required, then that class type shall
18006 // have a single non-explicit conversion function to an integral or
18007 // unscoped enumeration type
18008 ExprResult Converted;
18009 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18010 VerifyICEDiagnoser &BaseDiagnoser;
18011 public:
18012 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18013 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18014 BaseDiagnoser.Suppress, true),
18015 BaseDiagnoser(BaseDiagnoser) {}
18016
18017 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18018 QualType T) override {
18019 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18020 }
18021
18022 SemaDiagnosticBuilder diagnoseIncomplete(
18023 Sema &S, SourceLocation Loc, QualType T) override {
18024 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18025 }
18026
18027 SemaDiagnosticBuilder diagnoseExplicitConv(
18028 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18029 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18030 }
18031
18032 SemaDiagnosticBuilder noteExplicitConv(
18033 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18034 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18035 << ConvTy->isEnumeralType() << ConvTy;
18036 }
18037
18038 SemaDiagnosticBuilder diagnoseAmbiguous(
18039 Sema &S, SourceLocation Loc, QualType T) override {
18040 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18041 }
18042
18043 SemaDiagnosticBuilder noteAmbiguous(
18044 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18045 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18046 << ConvTy->isEnumeralType() << ConvTy;
18047 }
18048
18049 SemaDiagnosticBuilder diagnoseConversion(
18050 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18051 llvm_unreachable("conversion functions are permitted");
18052 }
18053 } ConvertDiagnoser(Diagnoser);
18054
18055 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18056 Converter&: ConvertDiagnoser);
18057 if (Converted.isInvalid())
18058 return Converted;
18059 E = Converted.get();
18060 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18061 return ExprError();
18062 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18063 // An ICE must be of integral or unscoped enumeration type.
18064 if (!Diagnoser.Suppress)
18065 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18066 << E->getSourceRange();
18067 return ExprError();
18068 }
18069
18070 ExprResult RValueExpr = DefaultLvalueConversion(E);
18071 if (RValueExpr.isInvalid())
18072 return ExprError();
18073
18074 E = RValueExpr.get();
18075
18076 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18077 // in the non-ICE case.
18078 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18079 if (Result)
18080 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context);
18081 if (!isa<ConstantExpr>(Val: E))
18082 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18083 : ConstantExpr::Create(Context, E);
18084 return E;
18085 }
18086
18087 Expr::EvalResult EvalResult;
18088 SmallVector<PartialDiagnosticAt, 8> Notes;
18089 EvalResult.Diag = &Notes;
18090
18091 // Try to evaluate the expression, and produce diagnostics explaining why it's
18092 // not a constant expression as a side-effect.
18093 bool Folded =
18094 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18095 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
18096
18097 if (!isa<ConstantExpr>(Val: E))
18098 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18099
18100 // In C++11, we can rely on diagnostics being produced for any expression
18101 // which is not a constant expression. If no diagnostics were produced, then
18102 // this is a constant expression.
18103 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18104 if (Result)
18105 *Result = EvalResult.Val.getInt();
18106 return E;
18107 }
18108
18109 // If our only note is the usual "invalid subexpression" note, just point
18110 // the caret at its location rather than producing an essentially
18111 // redundant note.
18112 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18113 diag::note_invalid_subexpr_in_const_expr) {
18114 DiagLoc = Notes[0].first;
18115 Notes.clear();
18116 }
18117
18118 if (!Folded || !CanFold) {
18119 if (!Diagnoser.Suppress) {
18120 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18121 for (const PartialDiagnosticAt &Note : Notes)
18122 Diag(Loc: Note.first, PD: Note.second);
18123 }
18124
18125 return ExprError();
18126 }
18127
18128 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18129 for (const PartialDiagnosticAt &Note : Notes)
18130 Diag(Loc: Note.first, PD: Note.second);
18131
18132 if (Result)
18133 *Result = EvalResult.Val.getInt();
18134 return E;
18135}
18136
18137namespace {
18138 // Handle the case where we conclude a expression which we speculatively
18139 // considered to be unevaluated is actually evaluated.
18140 class TransformToPE : public TreeTransform<TransformToPE> {
18141 typedef TreeTransform<TransformToPE> BaseTransform;
18142
18143 public:
18144 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18145
18146 // Make sure we redo semantic analysis
18147 bool AlwaysRebuild() { return true; }
18148 bool ReplacingOriginal() { return true; }
18149
18150 // We need to special-case DeclRefExprs referring to FieldDecls which
18151 // are not part of a member pointer formation; normal TreeTransforming
18152 // doesn't catch this case because of the way we represent them in the AST.
18153 // FIXME: This is a bit ugly; is it really the best way to handle this
18154 // case?
18155 //
18156 // Error on DeclRefExprs referring to FieldDecls.
18157 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18158 if (isa<FieldDecl>(E->getDecl()) &&
18159 !SemaRef.isUnevaluatedContext())
18160 return SemaRef.Diag(E->getLocation(),
18161 diag::err_invalid_non_static_member_use)
18162 << E->getDecl() << E->getSourceRange();
18163
18164 return BaseTransform::TransformDeclRefExpr(E);
18165 }
18166
18167 // Exception: filter out member pointer formation
18168 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18169 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18170 return E;
18171
18172 return BaseTransform::TransformUnaryOperator(E);
18173 }
18174
18175 // The body of a lambda-expression is in a separate expression evaluation
18176 // context so never needs to be transformed.
18177 // FIXME: Ideally we wouldn't transform the closure type either, and would
18178 // just recreate the capture expressions and lambda expression.
18179 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18180 return SkipLambdaBody(E, Body);
18181 }
18182 };
18183}
18184
18185ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18186 assert(isUnevaluatedContext() &&
18187 "Should only transform unevaluated expressions");
18188 ExprEvalContexts.back().Context =
18189 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18190 if (isUnevaluatedContext())
18191 return E;
18192 return TransformToPE(*this).TransformExpr(E);
18193}
18194
18195TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18196 assert(isUnevaluatedContext() &&
18197 "Should only transform unevaluated expressions");
18198 ExprEvalContexts.back().Context =
18199 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
18200 if (isUnevaluatedContext())
18201 return TInfo;
18202 return TransformToPE(*this).TransformType(TInfo);
18203}
18204
18205void
18206Sema::PushExpressionEvaluationContext(
18207 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18208 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18209 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18210 Args&: LambdaContextDecl, Args&: ExprContext);
18211
18212 // Discarded statements and immediate contexts nested in other
18213 // discarded statements or immediate context are themselves
18214 // a discarded statement or an immediate context, respectively.
18215 ExprEvalContexts.back().InDiscardedStatement =
18216 ExprEvalContexts[ExprEvalContexts.size() - 2]
18217 .isDiscardedStatementContext();
18218
18219 // C++23 [expr.const]/p15
18220 // An expression or conversion is in an immediate function context if [...]
18221 // it is a subexpression of a manifestly constant-evaluated expression or
18222 // conversion.
18223 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
18224 ExprEvalContexts.back().InImmediateFunctionContext =
18225 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18226
18227 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18228 Prev.InImmediateEscalatingFunctionContext;
18229
18230 Cleanup.reset();
18231 if (!MaybeODRUseExprs.empty())
18232 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18233}
18234
18235void
18236Sema::PushExpressionEvaluationContext(
18237 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18238 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18239 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18240 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18241}
18242
18243namespace {
18244
18245const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18246 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18247 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18248 if (E->getOpcode() == UO_Deref)
18249 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18250 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18251 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18252 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18253 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18254 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18255 QualType Inner;
18256 QualType Ty = E->getType();
18257 if (const auto *Ptr = Ty->getAs<PointerType>())
18258 Inner = Ptr->getPointeeType();
18259 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18260 Inner = Arr->getElementType();
18261 else
18262 return nullptr;
18263
18264 if (Inner->hasAttr(attr::NoDeref))
18265 return E;
18266 }
18267 return nullptr;
18268}
18269
18270} // namespace
18271
18272void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18273 for (const Expr *E : Rec.PossibleDerefs) {
18274 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18275 if (DeclRef) {
18276 const ValueDecl *Decl = DeclRef->getDecl();
18277 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18278 << Decl->getName() << E->getSourceRange();
18279 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18280 } else {
18281 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18282 << E->getSourceRange();
18283 }
18284 }
18285 Rec.PossibleDerefs.clear();
18286}
18287
18288/// Check whether E, which is either a discarded-value expression or an
18289/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18290/// and if so, remove it from the list of volatile-qualified assignments that
18291/// we are going to warn are deprecated.
18292void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18293 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18294 return;
18295
18296 // Note: ignoring parens here is not justified by the standard rules, but
18297 // ignoring parentheses seems like a more reasonable approach, and this only
18298 // drives a deprecation warning so doesn't affect conformance.
18299 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18300 if (BO->getOpcode() == BO_Assign) {
18301 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18302 llvm::erase(C&: LHSs, V: BO->getLHS());
18303 }
18304 }
18305}
18306
18307void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18308 assert(!FunctionScopes.empty() && "Expected a function scope");
18309 assert(getLangOpts().CPlusPlus20 &&
18310 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18311 "Cannot mark an immediate escalating expression outside of an "
18312 "immediate escalating context");
18313 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18314 Call && Call->getCallee()) {
18315 if (auto *DeclRef =
18316 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18317 DeclRef->setIsImmediateEscalating(true);
18318 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18319 Ctr->setIsImmediateEscalating(true);
18320 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18321 DeclRef->setIsImmediateEscalating(true);
18322 } else {
18323 assert(false && "expected an immediately escalating expression");
18324 }
18325 getCurFunction()->FoundImmediateEscalatingExpression = true;
18326}
18327
18328ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18329 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18330 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18331 isCheckingDefaultArgumentOrInitializer() ||
18332 RebuildingImmediateInvocation || isImmediateFunctionContext())
18333 return E;
18334
18335 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18336 /// It's OK if this fails; we'll also remove this in
18337 /// HandleImmediateInvocations, but catching it here allows us to avoid
18338 /// walking the AST looking for it in simple cases.
18339 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18340 if (auto *DeclRef =
18341 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18342 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18343
18344 // C++23 [expr.const]/p16
18345 // An expression or conversion is immediate-escalating if it is not initially
18346 // in an immediate function context and it is [...] an immediate invocation
18347 // that is not a constant expression and is not a subexpression of an
18348 // immediate invocation.
18349 APValue Cached;
18350 auto CheckConstantExpressionAndKeepResult = [&]() {
18351 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18352 Expr::EvalResult Eval;
18353 Eval.Diag = &Notes;
18354 bool Res = E.get()->EvaluateAsConstantExpr(
18355 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18356 if (Res && Notes.empty()) {
18357 Cached = std::move(Eval.Val);
18358 return true;
18359 }
18360 return false;
18361 };
18362
18363 if (!E.get()->isValueDependent() &&
18364 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18365 !CheckConstantExpressionAndKeepResult()) {
18366 MarkExpressionAsImmediateEscalating(E: E.get());
18367 return E;
18368 }
18369
18370 if (Cleanup.exprNeedsCleanups()) {
18371 // Since an immediate invocation is a full expression itself - it requires
18372 // an additional ExprWithCleanups node, but it can participate to a bigger
18373 // full expression which actually requires cleanups to be run after so
18374 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18375 // may discard cleanups for outer expression too early.
18376
18377 // Note that ExprWithCleanups created here must always have empty cleanup
18378 // objects:
18379 // - compound literals do not create cleanup objects in C++ and immediate
18380 // invocations are C++-only.
18381 // - blocks are not allowed inside constant expressions and compiler will
18382 // issue an error if they appear there.
18383 //
18384 // Hence, in correct code any cleanup objects created inside current
18385 // evaluation context must be outside the immediate invocation.
18386 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18387 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18388 }
18389
18390 ConstantExpr *Res = ConstantExpr::Create(
18391 Context: getASTContext(), E: E.get(),
18392 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18393 Context: getASTContext()),
18394 /*IsImmediateInvocation*/ true);
18395 if (Cached.hasValue())
18396 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18397 /// Value-dependent constant expressions should not be immediately
18398 /// evaluated until they are instantiated.
18399 if (!Res->isValueDependent())
18400 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18401 return Res;
18402}
18403
18404static void EvaluateAndDiagnoseImmediateInvocation(
18405 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18406 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18407 Expr::EvalResult Eval;
18408 Eval.Diag = &Notes;
18409 ConstantExpr *CE = Candidate.getPointer();
18410 bool Result = CE->EvaluateAsConstantExpr(
18411 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18412 if (!Result || !Notes.empty()) {
18413 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18414 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18415 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18416 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18417 FunctionDecl *FD = nullptr;
18418 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18419 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18420 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18421 FD = Call->getConstructor();
18422 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18423 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18424
18425 assert(FD && FD->isImmediateFunction() &&
18426 "could not find an immediate function in this expression");
18427 if (FD->isInvalidDecl())
18428 return;
18429 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18430 << FD << FD->isConsteval();
18431 if (auto Context =
18432 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18433 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18434 << Context->Decl;
18435 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18436 }
18437 if (!FD->isConsteval())
18438 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18439 for (auto &Note : Notes)
18440 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18441 return;
18442 }
18443 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18444}
18445
18446static void RemoveNestedImmediateInvocation(
18447 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18448 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18449 struct ComplexRemove : TreeTransform<ComplexRemove> {
18450 using Base = TreeTransform<ComplexRemove>;
18451 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18452 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18453 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18454 CurrentII;
18455 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18456 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18457 SmallVector<Sema::ImmediateInvocationCandidate,
18458 4>::reverse_iterator Current)
18459 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18460 void RemoveImmediateInvocation(ConstantExpr* E) {
18461 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18462 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18463 return Elem.getPointer() == E;
18464 });
18465 // It is possible that some subexpression of the current immediate
18466 // invocation was handled from another expression evaluation context. Do
18467 // not handle the current immediate invocation if some of its
18468 // subexpressions failed before.
18469 if (It == IISet.rend()) {
18470 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18471 CurrentII->setInt(1);
18472 } else {
18473 It->setInt(1); // Mark as deleted
18474 }
18475 }
18476 ExprResult TransformConstantExpr(ConstantExpr *E) {
18477 if (!E->isImmediateInvocation())
18478 return Base::TransformConstantExpr(E);
18479 RemoveImmediateInvocation(E);
18480 return Base::TransformExpr(E->getSubExpr());
18481 }
18482 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18483 /// we need to remove its DeclRefExpr from the DRSet.
18484 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18485 DRSet.erase(Ptr: cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18486 return Base::TransformCXXOperatorCallExpr(E);
18487 }
18488 /// Base::TransformUserDefinedLiteral doesn't preserve the
18489 /// UserDefinedLiteral node.
18490 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18491 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18492 /// here.
18493 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18494 if (!Init)
18495 return Init;
18496 /// ConstantExpr are the first layer of implicit node to be removed so if
18497 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18498 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
18499 if (CE->isImmediateInvocation())
18500 RemoveImmediateInvocation(E: CE);
18501 return Base::TransformInitializer(Init, NotCopyInit);
18502 }
18503 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18504 DRSet.erase(Ptr: E);
18505 return E;
18506 }
18507 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18508 // Do not rebuild lambdas to avoid creating a new type.
18509 // Lambdas have already been processed inside their eval context.
18510 return E;
18511 }
18512 bool AlwaysRebuild() { return false; }
18513 bool ReplacingOriginal() { return true; }
18514 bool AllowSkippingCXXConstructExpr() {
18515 bool Res = AllowSkippingFirstCXXConstructExpr;
18516 AllowSkippingFirstCXXConstructExpr = true;
18517 return Res;
18518 }
18519 bool AllowSkippingFirstCXXConstructExpr = true;
18520 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18521 Rec.ImmediateInvocationCandidates, It);
18522
18523 /// CXXConstructExpr with a single argument are getting skipped by
18524 /// TreeTransform in some situtation because they could be implicit. This
18525 /// can only occur for the top-level CXXConstructExpr because it is used
18526 /// nowhere in the expression being transformed therefore will not be rebuilt.
18527 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18528 /// skipping the first CXXConstructExpr.
18529 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18530 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18531
18532 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18533 // The result may not be usable in case of previous compilation errors.
18534 // In this case evaluation of the expression may result in crash so just
18535 // don't do anything further with the result.
18536 if (Res.isUsable()) {
18537 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18538 It->getPointer()->setSubExpr(Res.get());
18539 }
18540}
18541
18542static void
18543HandleImmediateInvocations(Sema &SemaRef,
18544 Sema::ExpressionEvaluationContextRecord &Rec) {
18545 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18546 Rec.ReferenceToConsteval.size() == 0) ||
18547 SemaRef.RebuildingImmediateInvocation)
18548 return;
18549
18550 /// When we have more than 1 ImmediateInvocationCandidates or previously
18551 /// failed immediate invocations, we need to check for nested
18552 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18553 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18554 /// invocation.
18555 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18556 !SemaRef.FailedImmediateInvocations.empty()) {
18557
18558 /// Prevent sema calls during the tree transform from adding pointers that
18559 /// are already in the sets.
18560 llvm::SaveAndRestore DisableIITracking(
18561 SemaRef.RebuildingImmediateInvocation, true);
18562
18563 /// Prevent diagnostic during tree transfrom as they are duplicates
18564 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18565
18566 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18567 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18568 if (!It->getInt())
18569 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18570 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18571 Rec.ReferenceToConsteval.size()) {
18572 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18573 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18574 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18575 bool VisitDeclRefExpr(DeclRefExpr *E) {
18576 DRSet.erase(Ptr: E);
18577 return DRSet.size();
18578 }
18579 } Visitor(Rec.ReferenceToConsteval);
18580 Visitor.TraverseStmt(
18581 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18582 }
18583 for (auto CE : Rec.ImmediateInvocationCandidates)
18584 if (!CE.getInt())
18585 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18586 for (auto *DR : Rec.ReferenceToConsteval) {
18587 // If the expression is immediate escalating, it is not an error;
18588 // The outer context itself becomes immediate and further errors,
18589 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18590 if (DR->isImmediateEscalating())
18591 continue;
18592 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18593 const NamedDecl *ND = FD;
18594 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18595 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18596 ND = MD->getParent();
18597
18598 // C++23 [expr.const]/p16
18599 // An expression or conversion is immediate-escalating if it is not
18600 // initially in an immediate function context and it is [...] a
18601 // potentially-evaluated id-expression that denotes an immediate function
18602 // that is not a subexpression of an immediate invocation.
18603 bool ImmediateEscalating = false;
18604 bool IsPotentiallyEvaluated =
18605 Rec.Context ==
18606 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18607 Rec.Context ==
18608 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18609 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18610 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18611
18612 if (!Rec.InImmediateEscalatingFunctionContext ||
18613 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18614 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18615 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18616 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18617 if (auto Context =
18618 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18619 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18620 << Context->Decl;
18621 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18622 }
18623 if (FD->isImmediateEscalating() && !FD->isConsteval())
18624 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18625
18626 } else {
18627 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18628 }
18629 }
18630}
18631
18632void Sema::PopExpressionEvaluationContext() {
18633 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18634 unsigned NumTypos = Rec.NumTypos;
18635
18636 if (!Rec.Lambdas.empty()) {
18637 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18638 if (!getLangOpts().CPlusPlus20 &&
18639 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18640 Rec.isUnevaluated() ||
18641 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18642 unsigned D;
18643 if (Rec.isUnevaluated()) {
18644 // C++11 [expr.prim.lambda]p2:
18645 // A lambda-expression shall not appear in an unevaluated operand
18646 // (Clause 5).
18647 D = diag::err_lambda_unevaluated_operand;
18648 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18649 // C++1y [expr.const]p2:
18650 // A conditional-expression e is a core constant expression unless the
18651 // evaluation of e, following the rules of the abstract machine, would
18652 // evaluate [...] a lambda-expression.
18653 D = diag::err_lambda_in_constant_expression;
18654 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18655 // C++17 [expr.prim.lamda]p2:
18656 // A lambda-expression shall not appear [...] in a template-argument.
18657 D = diag::err_lambda_in_invalid_context;
18658 } else
18659 llvm_unreachable("Couldn't infer lambda error message.");
18660
18661 for (const auto *L : Rec.Lambdas)
18662 Diag(Loc: L->getBeginLoc(), DiagID: D);
18663 }
18664 }
18665
18666 // Append the collected materialized temporaries into previous context before
18667 // exit if the previous also is a lifetime extending context.
18668 auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
18669 if (getLangOpts().CPlusPlus23 && isInLifetimeExtendingContext() &&
18670 PrevRecord.InLifetimeExtendingContext && !ExprEvalContexts.empty()) {
18671 auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
18672 PrevRecord.ForRangeLifetimeExtendTemps.append(
18673 RHS: Rec.ForRangeLifetimeExtendTemps);
18674 }
18675
18676 WarnOnPendingNoDerefs(Rec);
18677 HandleImmediateInvocations(SemaRef&: *this, Rec);
18678
18679 // Warn on any volatile-qualified simple-assignments that are not discarded-
18680 // value expressions nor unevaluated operands (those cases get removed from
18681 // this list by CheckUnusedVolatileAssignment).
18682 for (auto *BO : Rec.VolatileAssignmentLHSs)
18683 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18684 << BO->getType();
18685
18686 // When are coming out of an unevaluated context, clear out any
18687 // temporaries that we may have created as part of the evaluation of
18688 // the expression in that context: they aren't relevant because they
18689 // will never be constructed.
18690 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18691 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18692 CE: ExprCleanupObjects.end());
18693 Cleanup = Rec.ParentCleanup;
18694 CleanupVarDeclMarking();
18695 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18696 // Otherwise, merge the contexts together.
18697 } else {
18698 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18699 MaybeODRUseExprs.insert(Start: Rec.SavedMaybeODRUseExprs.begin(),
18700 End: Rec.SavedMaybeODRUseExprs.end());
18701 }
18702
18703 // Pop the current expression evaluation context off the stack.
18704 ExprEvalContexts.pop_back();
18705
18706 // The global expression evaluation context record is never popped.
18707 ExprEvalContexts.back().NumTypos += NumTypos;
18708}
18709
18710void Sema::DiscardCleanupsInEvaluationContext() {
18711 ExprCleanupObjects.erase(
18712 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18713 CE: ExprCleanupObjects.end());
18714 Cleanup.reset();
18715 MaybeODRUseExprs.clear();
18716}
18717
18718ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18719 ExprResult Result = CheckPlaceholderExpr(E);
18720 if (Result.isInvalid())
18721 return ExprError();
18722 E = Result.get();
18723 if (!E->getType()->isVariablyModifiedType())
18724 return E;
18725 return TransformToPotentiallyEvaluated(E);
18726}
18727
18728/// Are we in a context that is potentially constant evaluated per C++20
18729/// [expr.const]p12?
18730static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18731 /// C++2a [expr.const]p12:
18732 // An expression or conversion is potentially constant evaluated if it is
18733 switch (SemaRef.ExprEvalContexts.back().Context) {
18734 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18735 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18736
18737 // -- a manifestly constant-evaluated expression,
18738 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18739 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18740 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18741 // -- a potentially-evaluated expression,
18742 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18743 // -- an immediate subexpression of a braced-init-list,
18744
18745 // -- [FIXME] an expression of the form & cast-expression that occurs
18746 // within a templated entity
18747 // -- a subexpression of one of the above that is not a subexpression of
18748 // a nested unevaluated operand.
18749 return true;
18750
18751 case Sema::ExpressionEvaluationContext::Unevaluated:
18752 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18753 // Expressions in this context are never evaluated.
18754 return false;
18755 }
18756 llvm_unreachable("Invalid context");
18757}
18758
18759/// Return true if this function has a calling convention that requires mangling
18760/// in the size of the parameter pack.
18761static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18762 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18763 // we don't need parameter type sizes.
18764 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18765 if (!TT.isOSWindows() || !TT.isX86())
18766 return false;
18767
18768 // If this is C++ and this isn't an extern "C" function, parameters do not
18769 // need to be complete. In this case, C++ mangling will apply, which doesn't
18770 // use the size of the parameters.
18771 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18772 return false;
18773
18774 // Stdcall, fastcall, and vectorcall need this special treatment.
18775 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18776 switch (CC) {
18777 case CC_X86StdCall:
18778 case CC_X86FastCall:
18779 case CC_X86VectorCall:
18780 return true;
18781 default:
18782 break;
18783 }
18784 return false;
18785}
18786
18787/// Require that all of the parameter types of function be complete. Normally,
18788/// parameter types are only required to be complete when a function is called
18789/// or defined, but to mangle functions with certain calling conventions, the
18790/// mangler needs to know the size of the parameter list. In this situation,
18791/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18792/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18793/// result in a linker error. Clang doesn't implement this behavior, and instead
18794/// attempts to error at compile time.
18795static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18796 SourceLocation Loc) {
18797 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18798 FunctionDecl *FD;
18799 ParmVarDecl *Param;
18800
18801 public:
18802 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18803 : FD(FD), Param(Param) {}
18804
18805 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18806 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18807 StringRef CCName;
18808 switch (CC) {
18809 case CC_X86StdCall:
18810 CCName = "stdcall";
18811 break;
18812 case CC_X86FastCall:
18813 CCName = "fastcall";
18814 break;
18815 case CC_X86VectorCall:
18816 CCName = "vectorcall";
18817 break;
18818 default:
18819 llvm_unreachable("CC does not need mangling");
18820 }
18821
18822 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18823 << Param->getDeclName() << FD->getDeclName() << CCName;
18824 }
18825 };
18826
18827 for (ParmVarDecl *Param : FD->parameters()) {
18828 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18829 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18830 }
18831}
18832
18833namespace {
18834enum class OdrUseContext {
18835 /// Declarations in this context are not odr-used.
18836 None,
18837 /// Declarations in this context are formally odr-used, but this is a
18838 /// dependent context.
18839 Dependent,
18840 /// Declarations in this context are odr-used but not actually used (yet).
18841 FormallyOdrUsed,
18842 /// Declarations in this context are used.
18843 Used
18844};
18845}
18846
18847/// Are we within a context in which references to resolved functions or to
18848/// variables result in odr-use?
18849static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18850 OdrUseContext Result;
18851
18852 switch (SemaRef.ExprEvalContexts.back().Context) {
18853 case Sema::ExpressionEvaluationContext::Unevaluated:
18854 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18855 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18856 return OdrUseContext::None;
18857
18858 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18859 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18860 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18861 Result = OdrUseContext::Used;
18862 break;
18863
18864 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18865 Result = OdrUseContext::FormallyOdrUsed;
18866 break;
18867
18868 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18869 // A default argument formally results in odr-use, but doesn't actually
18870 // result in a use in any real sense until it itself is used.
18871 Result = OdrUseContext::FormallyOdrUsed;
18872 break;
18873 }
18874
18875 if (SemaRef.CurContext->isDependentContext())
18876 return OdrUseContext::Dependent;
18877
18878 return Result;
18879}
18880
18881static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18882 if (!Func->isConstexpr())
18883 return false;
18884
18885 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18886 return true;
18887 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18888 return CCD && CCD->getInheritedConstructor();
18889}
18890
18891/// Mark a function referenced, and check whether it is odr-used
18892/// (C++ [basic.def.odr]p2, C99 6.9p3)
18893void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18894 bool MightBeOdrUse) {
18895 assert(Func && "No function?");
18896
18897 Func->setReferenced();
18898
18899 // Recursive functions aren't really used until they're used from some other
18900 // context.
18901 bool IsRecursiveCall = CurContext == Func;
18902
18903 // C++11 [basic.def.odr]p3:
18904 // A function whose name appears as a potentially-evaluated expression is
18905 // odr-used if it is the unique lookup result or the selected member of a
18906 // set of overloaded functions [...].
18907 //
18908 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18909 // can just check that here.
18910 OdrUseContext OdrUse =
18911 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18912 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18913 OdrUse = OdrUseContext::FormallyOdrUsed;
18914
18915 // Trivial default constructors and destructors are never actually used.
18916 // FIXME: What about other special members?
18917 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18918 OdrUse == OdrUseContext::Used) {
18919 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18920 if (Constructor->isDefaultConstructor())
18921 OdrUse = OdrUseContext::FormallyOdrUsed;
18922 if (isa<CXXDestructorDecl>(Val: Func))
18923 OdrUse = OdrUseContext::FormallyOdrUsed;
18924 }
18925
18926 // C++20 [expr.const]p12:
18927 // A function [...] is needed for constant evaluation if it is [...] a
18928 // constexpr function that is named by an expression that is potentially
18929 // constant evaluated
18930 bool NeededForConstantEvaluation =
18931 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18932 isImplicitlyDefinableConstexprFunction(Func);
18933
18934 // Determine whether we require a function definition to exist, per
18935 // C++11 [temp.inst]p3:
18936 // Unless a function template specialization has been explicitly
18937 // instantiated or explicitly specialized, the function template
18938 // specialization is implicitly instantiated when the specialization is
18939 // referenced in a context that requires a function definition to exist.
18940 // C++20 [temp.inst]p7:
18941 // The existence of a definition of a [...] function is considered to
18942 // affect the semantics of the program if the [...] function is needed for
18943 // constant evaluation by an expression
18944 // C++20 [basic.def.odr]p10:
18945 // Every program shall contain exactly one definition of every non-inline
18946 // function or variable that is odr-used in that program outside of a
18947 // discarded statement
18948 // C++20 [special]p1:
18949 // The implementation will implicitly define [defaulted special members]
18950 // if they are odr-used or needed for constant evaluation.
18951 //
18952 // Note that we skip the implicit instantiation of templates that are only
18953 // used in unused default arguments or by recursive calls to themselves.
18954 // This is formally non-conforming, but seems reasonable in practice.
18955 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18956 NeededForConstantEvaluation);
18957
18958 // C++14 [temp.expl.spec]p6:
18959 // If a template [...] is explicitly specialized then that specialization
18960 // shall be declared before the first use of that specialization that would
18961 // cause an implicit instantiation to take place, in every translation unit
18962 // in which such a use occurs
18963 if (NeedDefinition &&
18964 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18965 Func->getMemberSpecializationInfo()))
18966 checkSpecializationReachability(Loc, Func);
18967
18968 if (getLangOpts().CUDA)
18969 CheckCUDACall(Loc, Callee: Func);
18970
18971 // If we need a definition, try to create one.
18972 if (NeedDefinition && !Func->getBody()) {
18973 runWithSufficientStackSpace(Loc, Fn: [&] {
18974 if (CXXConstructorDecl *Constructor =
18975 dyn_cast<CXXConstructorDecl>(Val: Func)) {
18976 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18977 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18978 if (Constructor->isDefaultConstructor()) {
18979 if (Constructor->isTrivial() &&
18980 !Constructor->hasAttr<DLLExportAttr>())
18981 return;
18982 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
18983 } else if (Constructor->isCopyConstructor()) {
18984 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18985 } else if (Constructor->isMoveConstructor()) {
18986 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18987 }
18988 } else if (Constructor->getInheritedConstructor()) {
18989 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18990 }
18991 } else if (CXXDestructorDecl *Destructor =
18992 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18993 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18994 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18995 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18996 return;
18997 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18998 }
18999 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19000 MarkVTableUsed(Loc, Class: Destructor->getParent());
19001 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19002 if (MethodDecl->isOverloadedOperator() &&
19003 MethodDecl->getOverloadedOperator() == OO_Equal) {
19004 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19005 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19006 if (MethodDecl->isCopyAssignmentOperator())
19007 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19008 else if (MethodDecl->isMoveAssignmentOperator())
19009 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19010 }
19011 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19012 MethodDecl->getParent()->isLambda()) {
19013 CXXConversionDecl *Conversion =
19014 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19015 if (Conversion->isLambdaToBlockPointerConversion())
19016 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19017 else
19018 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19019 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19020 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19021 }
19022
19023 if (Func->isDefaulted() && !Func->isDeleted()) {
19024 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
19025 if (DCK != DefaultedComparisonKind::None)
19026 DefineDefaultedComparison(Loc, FD: Func, DCK);
19027 }
19028
19029 // Implicit instantiation of function templates and member functions of
19030 // class templates.
19031 if (Func->isImplicitlyInstantiable()) {
19032 TemplateSpecializationKind TSK =
19033 Func->getTemplateSpecializationKindForInstantiation();
19034 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19035 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19036 if (FirstInstantiation) {
19037 PointOfInstantiation = Loc;
19038 if (auto *MSI = Func->getMemberSpecializationInfo())
19039 MSI->setPointOfInstantiation(Loc);
19040 // FIXME: Notify listener.
19041 else
19042 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19043 } else if (TSK != TSK_ImplicitInstantiation) {
19044 // Use the point of use as the point of instantiation, instead of the
19045 // point of explicit instantiation (which we track as the actual point
19046 // of instantiation). This gives better backtraces in diagnostics.
19047 PointOfInstantiation = Loc;
19048 }
19049
19050 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19051 Func->isConstexpr()) {
19052 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19053 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19054 CodeSynthesisContexts.size())
19055 PendingLocalImplicitInstantiations.push_back(
19056 std::make_pair(x&: Func, y&: PointOfInstantiation));
19057 else if (Func->isConstexpr())
19058 // Do not defer instantiations of constexpr functions, to avoid the
19059 // expression evaluator needing to call back into Sema if it sees a
19060 // call to such a function.
19061 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19062 else {
19063 Func->setInstantiationIsPending(true);
19064 PendingInstantiations.push_back(
19065 std::make_pair(x&: Func, y&: PointOfInstantiation));
19066 // Notify the consumer that a function was implicitly instantiated.
19067 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19068 }
19069 }
19070 } else {
19071 // Walk redefinitions, as some of them may be instantiable.
19072 for (auto *i : Func->redecls()) {
19073 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19074 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19075 }
19076 }
19077 });
19078 }
19079
19080 // If a constructor was defined in the context of a default parameter
19081 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19082 // context), its initializers may not be referenced yet.
19083 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19084 EnterExpressionEvaluationContext EvalContext(
19085 *this,
19086 Constructor->isImmediateFunction()
19087 ? ExpressionEvaluationContext::ImmediateFunctionContext
19088 : ExpressionEvaluationContext::PotentiallyEvaluated,
19089 Constructor);
19090 for (CXXCtorInitializer *Init : Constructor->inits()) {
19091 if (Init->isInClassMemberInitializer())
19092 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19093 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19094 });
19095 }
19096 }
19097
19098 // C++14 [except.spec]p17:
19099 // An exception-specification is considered to be needed when:
19100 // - the function is odr-used or, if it appears in an unevaluated operand,
19101 // would be odr-used if the expression were potentially-evaluated;
19102 //
19103 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19104 // function is a pure virtual function we're calling, and in that case the
19105 // function was selected by overload resolution and we need to resolve its
19106 // exception specification for a different reason.
19107 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19108 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19109 ResolveExceptionSpec(Loc, FPT);
19110
19111 // A callee could be called by a host function then by a device function.
19112 // If we only try recording once, we will miss recording the use on device
19113 // side. Therefore keep trying until it is recorded.
19114 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19115 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19116 CUDARecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19117
19118 // If this is the first "real" use, act on that.
19119 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19120 // Keep track of used but undefined functions.
19121 if (!Func->isDefined()) {
19122 if (mightHaveNonExternalLinkage(Func))
19123 UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19124 else if (Func->getMostRecentDecl()->isInlined() &&
19125 !LangOpts.GNUInline &&
19126 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19127 UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19128 else if (isExternalWithNoLinkageType(Func))
19129 UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19130 }
19131
19132 // Some x86 Windows calling conventions mangle the size of the parameter
19133 // pack into the name. Computing the size of the parameters requires the
19134 // parameter types to be complete. Check that now.
19135 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19136 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19137
19138 // In the MS C++ ABI, the compiler emits destructor variants where they are
19139 // used. If the destructor is used here but defined elsewhere, mark the
19140 // virtual base destructors referenced. If those virtual base destructors
19141 // are inline, this will ensure they are defined when emitting the complete
19142 // destructor variant. This checking may be redundant if the destructor is
19143 // provided later in this TU.
19144 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19145 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19146 CXXRecordDecl *Parent = Dtor->getParent();
19147 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19148 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19149 }
19150 }
19151
19152 Func->markUsed(Context);
19153 }
19154}
19155
19156/// Directly mark a variable odr-used. Given a choice, prefer to use
19157/// MarkVariableReferenced since it does additional checks and then
19158/// calls MarkVarDeclODRUsed.
19159/// If the variable must be captured:
19160/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19161/// - else capture it in the DeclContext that maps to the
19162/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19163static void
19164MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19165 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19166 // Keep track of used but undefined variables.
19167 // FIXME: We shouldn't suppress this warning for static data members.
19168 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19169 assert(Var && "expected a capturable variable");
19170
19171 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19172 (!Var->isExternallyVisible() || Var->isInline() ||
19173 SemaRef.isExternalWithNoLinkageType(Var)) &&
19174 !(Var->isStaticDataMember() && Var->hasInit())) {
19175 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19176 if (old.isInvalid())
19177 old = Loc;
19178 }
19179 QualType CaptureType, DeclRefType;
19180 if (SemaRef.LangOpts.OpenMP)
19181 SemaRef.tryCaptureOpenMPLambdas(V);
19182 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: Sema::TryCapture_Implicit,
19183 /*EllipsisLoc*/ SourceLocation(),
19184 /*BuildAndDiagnose*/ true, CaptureType,
19185 DeclRefType, FunctionScopeIndexToStopAt);
19186
19187 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19188 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19189 auto VarTarget = SemaRef.IdentifyCUDATarget(D: Var);
19190 auto UserTarget = SemaRef.IdentifyCUDATarget(D: FD);
19191 if (VarTarget == Sema::CVT_Host &&
19192 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
19193 UserTarget == Sema::CFT_Global)) {
19194 // Diagnose ODR-use of host global variables in device functions.
19195 // Reference of device global variables in host functions is allowed
19196 // through shadow variables therefore it is not diagnosed.
19197 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19198 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19199 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19200 SemaRef.targetDiag(Var->getLocation(),
19201 Var->getType().isConstQualified()
19202 ? diag::note_cuda_const_var_unpromoted
19203 : diag::note_cuda_host_var);
19204 }
19205 } else if (VarTarget == Sema::CVT_Device &&
19206 !Var->hasAttr<CUDASharedAttr>() &&
19207 (UserTarget == Sema::CFT_Host ||
19208 UserTarget == Sema::CFT_HostDevice)) {
19209 // Record a CUDA/HIP device side variable if it is ODR-used
19210 // by host code. This is done conservatively, when the variable is
19211 // referenced in any of the following contexts:
19212 // - a non-function context
19213 // - a host function
19214 // - a host device function
19215 // This makes the ODR-use of the device side variable by host code to
19216 // be visible in the device compilation for the compiler to be able to
19217 // emit template variables instantiated by host code only and to
19218 // externalize the static device side variable ODR-used by host code.
19219 if (!Var->hasExternalStorage())
19220 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var);
19221 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
19222 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
19223 }
19224 }
19225
19226 V->markUsed(SemaRef.Context);
19227}
19228
19229void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19230 SourceLocation Loc,
19231 unsigned CapturingScopeIndex) {
19232 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19233}
19234
19235void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
19236 ValueDecl *var) {
19237 DeclContext *VarDC = var->getDeclContext();
19238
19239 // If the parameter still belongs to the translation unit, then
19240 // we're actually just using one parameter in the declaration of
19241 // the next.
19242 if (isa<ParmVarDecl>(Val: var) &&
19243 isa<TranslationUnitDecl>(Val: VarDC))
19244 return;
19245
19246 // For C code, don't diagnose about capture if we're not actually in code
19247 // right now; it's impossible to write a non-constant expression outside of
19248 // function context, so we'll get other (more useful) diagnostics later.
19249 //
19250 // For C++, things get a bit more nasty... it would be nice to suppress this
19251 // diagnostic for certain cases like using a local variable in an array bound
19252 // for a member of a local class, but the correct predicate is not obvious.
19253 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19254 return;
19255
19256 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19257 unsigned ContextKind = 3; // unknown
19258 if (isa<CXXMethodDecl>(Val: VarDC) &&
19259 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19260 ContextKind = 2;
19261 } else if (isa<FunctionDecl>(Val: VarDC)) {
19262 ContextKind = 0;
19263 } else if (isa<BlockDecl>(Val: VarDC)) {
19264 ContextKind = 1;
19265 }
19266
19267 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19268 << var << ValueKind << ContextKind << VarDC;
19269 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19270 << var;
19271
19272 // FIXME: Add additional diagnostic info about class etc. which prevents
19273 // capture.
19274}
19275
19276static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19277 ValueDecl *Var,
19278 bool &SubCapturesAreNested,
19279 QualType &CaptureType,
19280 QualType &DeclRefType) {
19281 // Check whether we've already captured it.
19282 if (CSI->CaptureMap.count(Val: Var)) {
19283 // If we found a capture, any subcaptures are nested.
19284 SubCapturesAreNested = true;
19285
19286 // Retrieve the capture type for this variable.
19287 CaptureType = CSI->getCapture(Var).getCaptureType();
19288
19289 // Compute the type of an expression that refers to this variable.
19290 DeclRefType = CaptureType.getNonReferenceType();
19291
19292 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19293 // are mutable in the sense that user can change their value - they are
19294 // private instances of the captured declarations.
19295 const Capture &Cap = CSI->getCapture(Var);
19296 if (Cap.isCopyCapture() &&
19297 !(isa<LambdaScopeInfo>(Val: CSI) &&
19298 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19299 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19300 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19301 DeclRefType.addConst();
19302 return true;
19303 }
19304 return false;
19305}
19306
19307// Only block literals, captured statements, and lambda expressions can
19308// capture; other scopes don't work.
19309static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19310 ValueDecl *Var,
19311 SourceLocation Loc,
19312 const bool Diagnose,
19313 Sema &S) {
19314 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19315 return getLambdaAwareParentOfDeclContext(DC);
19316
19317 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19318 if (Underlying) {
19319 if (Underlying->hasLocalStorage() && Diagnose)
19320 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19321 }
19322 return nullptr;
19323}
19324
19325// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19326// certain types of variables (unnamed, variably modified types etc.)
19327// so check for eligibility.
19328static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19329 SourceLocation Loc, const bool Diagnose,
19330 Sema &S) {
19331
19332 assert((isa<VarDecl, BindingDecl>(Var)) &&
19333 "Only variables and structured bindings can be captured");
19334
19335 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19336 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19337
19338 // Lambdas are not allowed to capture unnamed variables
19339 // (e.g. anonymous unions).
19340 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19341 // assuming that's the intent.
19342 if (IsLambda && !Var->getDeclName()) {
19343 if (Diagnose) {
19344 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19345 S.Diag(Var->getLocation(), diag::note_declared_at);
19346 }
19347 return false;
19348 }
19349
19350 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19351 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19352 if (Diagnose) {
19353 S.Diag(Loc, diag::err_ref_vm_type);
19354 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19355 }
19356 return false;
19357 }
19358 // Prohibit structs with flexible array members too.
19359 // We cannot capture what is in the tail end of the struct.
19360 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
19361 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
19362 if (Diagnose) {
19363 if (IsBlock)
19364 S.Diag(Loc, diag::err_ref_flexarray_type);
19365 else
19366 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19367 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19368 }
19369 return false;
19370 }
19371 }
19372 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19373 // Lambdas and captured statements are not allowed to capture __block
19374 // variables; they don't support the expected semantics.
19375 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19376 if (Diagnose) {
19377 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19378 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19379 }
19380 return false;
19381 }
19382 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19383 if (S.getLangOpts().OpenCL && IsBlock &&
19384 Var->getType()->isBlockPointerType()) {
19385 if (Diagnose)
19386 S.Diag(Loc, diag::err_opencl_block_ref_block);
19387 return false;
19388 }
19389
19390 if (isa<BindingDecl>(Val: Var)) {
19391 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19392 if (Diagnose)
19393 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19394 return false;
19395 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19396 S.Diag(Loc, S.LangOpts.CPlusPlus20
19397 ? diag::warn_cxx17_compat_capture_binding
19398 : diag::ext_capture_binding)
19399 << Var;
19400 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19401 }
19402 }
19403
19404 return true;
19405}
19406
19407// Returns true if the capture by block was successful.
19408static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19409 SourceLocation Loc, const bool BuildAndDiagnose,
19410 QualType &CaptureType, QualType &DeclRefType,
19411 const bool Nested, Sema &S, bool Invalid) {
19412 bool ByRef = false;
19413
19414 // Blocks are not allowed to capture arrays, excepting OpenCL.
19415 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19416 // (decayed to pointers).
19417 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19418 if (BuildAndDiagnose) {
19419 S.Diag(Loc, diag::err_ref_array_type);
19420 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19421 Invalid = true;
19422 } else {
19423 return false;
19424 }
19425 }
19426
19427 // Forbid the block-capture of autoreleasing variables.
19428 if (!Invalid &&
19429 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19430 if (BuildAndDiagnose) {
19431 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19432 << /*block*/ 0;
19433 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19434 Invalid = true;
19435 } else {
19436 return false;
19437 }
19438 }
19439
19440 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19441 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19442 QualType PointeeTy = PT->getPointeeType();
19443
19444 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19445 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19446 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19447 if (BuildAndDiagnose) {
19448 SourceLocation VarLoc = Var->getLocation();
19449 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19450 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19451 }
19452 }
19453 }
19454
19455 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19456 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19457 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(D: Var))) {
19458 // Block capture by reference does not change the capture or
19459 // declaration reference types.
19460 ByRef = true;
19461 } else {
19462 // Block capture by copy introduces 'const'.
19463 CaptureType = CaptureType.getNonReferenceType().withConst();
19464 DeclRefType = CaptureType;
19465 }
19466
19467 // Actually capture the variable.
19468 if (BuildAndDiagnose)
19469 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19470 CaptureType, Invalid);
19471
19472 return !Invalid;
19473}
19474
19475/// Capture the given variable in the captured region.
19476static bool captureInCapturedRegion(
19477 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19478 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19479 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
19480 bool IsTopScope, Sema &S, bool Invalid) {
19481 // By default, capture variables by reference.
19482 bool ByRef = true;
19483 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19484 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19485 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19486 // Using an LValue reference type is consistent with Lambdas (see below).
19487 if (S.isOpenMPCapturedDecl(D: Var)) {
19488 bool HasConst = DeclRefType.isConstQualified();
19489 DeclRefType = DeclRefType.getUnqualifiedType();
19490 // Don't lose diagnostics about assignments to const.
19491 if (HasConst)
19492 DeclRefType.addConst();
19493 }
19494 // Do not capture firstprivates in tasks.
19495 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
19496 OMPC_unknown)
19497 return true;
19498 ByRef = S.isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19499 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19500 }
19501
19502 if (ByRef)
19503 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19504 else
19505 CaptureType = DeclRefType;
19506
19507 // Actually capture the variable.
19508 if (BuildAndDiagnose)
19509 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19510 Loc, SourceLocation(), CaptureType, Invalid);
19511
19512 return !Invalid;
19513}
19514
19515/// Capture the given variable in the lambda.
19516static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19517 SourceLocation Loc, const bool BuildAndDiagnose,
19518 QualType &CaptureType, QualType &DeclRefType,
19519 const bool RefersToCapturedVariable,
19520 const Sema::TryCaptureKind Kind,
19521 SourceLocation EllipsisLoc, const bool IsTopScope,
19522 Sema &S, bool Invalid) {
19523 // Determine whether we are capturing by reference or by value.
19524 bool ByRef = false;
19525 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19526 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19527 } else {
19528 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19529 }
19530
19531 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19532 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19533 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19534 Invalid = true;
19535 }
19536
19537 // Compute the type of the field that will capture this variable.
19538 if (ByRef) {
19539 // C++11 [expr.prim.lambda]p15:
19540 // An entity is captured by reference if it is implicitly or
19541 // explicitly captured but not captured by copy. It is
19542 // unspecified whether additional unnamed non-static data
19543 // members are declared in the closure type for entities
19544 // captured by reference.
19545 //
19546 // FIXME: It is not clear whether we want to build an lvalue reference
19547 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19548 // to do the former, while EDG does the latter. Core issue 1249 will
19549 // clarify, but for now we follow GCC because it's a more permissive and
19550 // easily defensible position.
19551 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19552 } else {
19553 // C++11 [expr.prim.lambda]p14:
19554 // For each entity captured by copy, an unnamed non-static
19555 // data member is declared in the closure type. The
19556 // declaration order of these members is unspecified. The type
19557 // of such a data member is the type of the corresponding
19558 // captured entity if the entity is not a reference to an
19559 // object, or the referenced type otherwise. [Note: If the
19560 // captured entity is a reference to a function, the
19561 // corresponding data member is also a reference to a
19562 // function. - end note ]
19563 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19564 if (!RefType->getPointeeType()->isFunctionType())
19565 CaptureType = RefType->getPointeeType();
19566 }
19567
19568 // Forbid the lambda copy-capture of autoreleasing variables.
19569 if (!Invalid &&
19570 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19571 if (BuildAndDiagnose) {
19572 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19573 S.Diag(Var->getLocation(), diag::note_previous_decl)
19574 << Var->getDeclName();
19575 Invalid = true;
19576 } else {
19577 return false;
19578 }
19579 }
19580
19581 // Make sure that by-copy captures are of a complete and non-abstract type.
19582 if (!Invalid && BuildAndDiagnose) {
19583 if (!CaptureType->isDependentType() &&
19584 S.RequireCompleteSizedType(
19585 Loc, CaptureType,
19586 diag::err_capture_of_incomplete_or_sizeless_type,
19587 Var->getDeclName()))
19588 Invalid = true;
19589 else if (S.RequireNonAbstractType(Loc, CaptureType,
19590 diag::err_capture_of_abstract_type))
19591 Invalid = true;
19592 }
19593 }
19594
19595 // Compute the type of a reference to this captured variable.
19596 if (ByRef)
19597 DeclRefType = CaptureType.getNonReferenceType();
19598 else {
19599 // C++ [expr.prim.lambda]p5:
19600 // The closure type for a lambda-expression has a public inline
19601 // function call operator [...]. This function call operator is
19602 // declared const (9.3.1) if and only if the lambda-expression's
19603 // parameter-declaration-clause is not followed by mutable.
19604 DeclRefType = CaptureType.getNonReferenceType();
19605 bool Const = LSI->lambdaCaptureShouldBeConst();
19606 if (Const && !CaptureType->isReferenceType())
19607 DeclRefType.addConst();
19608 }
19609
19610 // Add the capture.
19611 if (BuildAndDiagnose)
19612 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19613 Loc, EllipsisLoc, CaptureType, Invalid);
19614
19615 return !Invalid;
19616}
19617
19618static bool canCaptureVariableByCopy(ValueDecl *Var,
19619 const ASTContext &Context) {
19620 // Offer a Copy fix even if the type is dependent.
19621 if (Var->getType()->isDependentType())
19622 return true;
19623 QualType T = Var->getType().getNonReferenceType();
19624 if (T.isTriviallyCopyableType(Context))
19625 return true;
19626 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19627
19628 if (!(RD = RD->getDefinition()))
19629 return false;
19630 if (RD->hasSimpleCopyConstructor())
19631 return true;
19632 if (RD->hasUserDeclaredCopyConstructor())
19633 for (CXXConstructorDecl *Ctor : RD->ctors())
19634 if (Ctor->isCopyConstructor())
19635 return !Ctor->isDeleted();
19636 }
19637 return false;
19638}
19639
19640/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19641/// default capture. Fixes may be omitted if they aren't allowed by the
19642/// standard, for example we can't emit a default copy capture fix-it if we
19643/// already explicitly copy capture capture another variable.
19644static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19645 ValueDecl *Var) {
19646 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19647 // Don't offer Capture by copy of default capture by copy fixes if Var is
19648 // known not to be copy constructible.
19649 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19650
19651 SmallString<32> FixBuffer;
19652 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19653 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19654 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19655 if (ShouldOfferCopyFix) {
19656 // Offer fixes to insert an explicit capture for the variable.
19657 // [] -> [VarName]
19658 // [OtherCapture] -> [OtherCapture, VarName]
19659 FixBuffer.assign({Separator, Var->getName()});
19660 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19661 << Var << /*value*/ 0
19662 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19663 }
19664 // As above but capture by reference.
19665 FixBuffer.assign({Separator, "&", Var->getName()});
19666 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19667 << Var << /*reference*/ 1
19668 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19669 }
19670
19671 // Only try to offer default capture if there are no captures excluding this
19672 // and init captures.
19673 // [this]: OK.
19674 // [X = Y]: OK.
19675 // [&A, &B]: Don't offer.
19676 // [A, B]: Don't offer.
19677 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19678 return !C.isThisCapture() && !C.isInitCapture();
19679 }))
19680 return;
19681
19682 // The default capture specifiers, '=' or '&', must appear first in the
19683 // capture body.
19684 SourceLocation DefaultInsertLoc =
19685 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19686
19687 if (ShouldOfferCopyFix) {
19688 bool CanDefaultCopyCapture = true;
19689 // [=, *this] OK since c++17
19690 // [=, this] OK since c++20
19691 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19692 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19693 ? LSI->getCXXThisCapture().isCopyCapture()
19694 : false;
19695 // We can't use default capture by copy if any captures already specified
19696 // capture by copy.
19697 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19698 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19699 })) {
19700 FixBuffer.assign(Refs: {"=", Separator});
19701 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19702 << /*value*/ 0
19703 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19704 }
19705 }
19706
19707 // We can't use default capture by reference if any captures already specified
19708 // capture by reference.
19709 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19710 return !C.isInitCapture() && C.isReferenceCapture() &&
19711 !C.isThisCapture();
19712 })) {
19713 FixBuffer.assign(Refs: {"&", Separator});
19714 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19715 << /*reference*/ 1
19716 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19717 }
19718}
19719
19720bool Sema::tryCaptureVariable(
19721 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19722 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19723 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19724 // An init-capture is notionally from the context surrounding its
19725 // declaration, but its parent DC is the lambda class.
19726 DeclContext *VarDC = Var->getDeclContext();
19727 DeclContext *DC = CurContext;
19728
19729 // tryCaptureVariable is called every time a DeclRef is formed,
19730 // it can therefore have non-negigible impact on performances.
19731 // For local variables and when there is no capturing scope,
19732 // we can bailout early.
19733 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19734 return true;
19735
19736 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19737 if (VD) {
19738 if (VD->isInitCapture())
19739 VarDC = VarDC->getParent();
19740 } else {
19741 VD = Var->getPotentiallyDecomposedVarDecl();
19742 }
19743 assert(VD && "Cannot capture a null variable");
19744
19745 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19746 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19747 // We need to sync up the Declaration Context with the
19748 // FunctionScopeIndexToStopAt
19749 if (FunctionScopeIndexToStopAt) {
19750 unsigned FSIndex = FunctionScopes.size() - 1;
19751 while (FSIndex != MaxFunctionScopesIndex) {
19752 DC = getLambdaAwareParentOfDeclContext(DC);
19753 --FSIndex;
19754 }
19755 }
19756
19757 // Capture global variables if it is required to use private copy of this
19758 // variable.
19759 bool IsGlobal = !VD->hasLocalStorage();
19760 if (IsGlobal &&
19761 !(LangOpts.OpenMP && isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19762 StopAt: MaxFunctionScopesIndex)))
19763 return true;
19764
19765 if (isa<VarDecl>(Val: Var))
19766 Var = cast<VarDecl>(Var->getCanonicalDecl());
19767
19768 // Walk up the stack to determine whether we can capture the variable,
19769 // performing the "simple" checks that don't depend on type. We stop when
19770 // we've either hit the declared scope of the variable or find an existing
19771 // capture of that variable. We start from the innermost capturing-entity
19772 // (the DC) and ensure that all intervening capturing-entities
19773 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19774 // declcontext can either capture the variable or have already captured
19775 // the variable.
19776 CaptureType = Var->getType();
19777 DeclRefType = CaptureType.getNonReferenceType();
19778 bool Nested = false;
19779 bool Explicit = (Kind != TryCapture_Implicit);
19780 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19781 do {
19782
19783 LambdaScopeInfo *LSI = nullptr;
19784 if (!FunctionScopes.empty())
19785 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19786 Val: FunctionScopes[FunctionScopesIndex]);
19787
19788 bool IsInScopeDeclarationContext =
19789 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19790
19791 if (LSI && !LSI->AfterParameterList) {
19792 // This allows capturing parameters from a default value which does not
19793 // seems correct
19794 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19795 return true;
19796 }
19797 // If the variable is declared in the current context, there is no need to
19798 // capture it.
19799 if (IsInScopeDeclarationContext &&
19800 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19801 return true;
19802
19803 // Only block literals, captured statements, and lambda expressions can
19804 // capture; other scopes don't work.
19805 DeclContext *ParentDC =
19806 !IsInScopeDeclarationContext
19807 ? DC->getParent()
19808 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19809 Diagnose: BuildAndDiagnose, S&: *this);
19810 // We need to check for the parent *first* because, if we *have*
19811 // private-captured a global variable, we need to recursively capture it in
19812 // intermediate blocks, lambdas, etc.
19813 if (!ParentDC) {
19814 if (IsGlobal) {
19815 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19816 break;
19817 }
19818 return true;
19819 }
19820
19821 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19822 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19823
19824 // Check whether we've already captured it.
19825 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19826 DeclRefType)) {
19827 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19828 break;
19829 }
19830
19831 // When evaluating some attributes (like enable_if) we might refer to a
19832 // function parameter appertaining to the same declaration as that
19833 // attribute.
19834 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19835 Parm && Parm->getDeclContext() == DC)
19836 return true;
19837
19838 // If we are instantiating a generic lambda call operator body,
19839 // we do not want to capture new variables. What was captured
19840 // during either a lambdas transformation or initial parsing
19841 // should be used.
19842 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19843 if (BuildAndDiagnose) {
19844 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19845 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19846 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19847 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19848 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19849 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19850 } else
19851 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19852 }
19853 return true;
19854 }
19855
19856 // Try to capture variable-length arrays types.
19857 if (Var->getType()->isVariablyModifiedType()) {
19858 // We're going to walk down into the type and look for VLA
19859 // expressions.
19860 QualType QTy = Var->getType();
19861 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19862 QTy = PVD->getOriginalType();
19863 captureVariablyModifiedType(Context, T: QTy, CSI);
19864 }
19865
19866 if (getLangOpts().OpenMP) {
19867 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19868 // OpenMP private variables should not be captured in outer scope, so
19869 // just break here. Similarly, global variables that are captured in a
19870 // target region should not be captured outside the scope of the region.
19871 if (RSI->CapRegionKind == CR_OpenMP) {
19872 // FIXME: We should support capturing structured bindings in OpenMP.
19873 if (isa<BindingDecl>(Val: Var)) {
19874 if (BuildAndDiagnose) {
19875 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19876 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19877 }
19878 return true;
19879 }
19880 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19881 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19882 // If the variable is private (i.e. not captured) and has variably
19883 // modified type, we still need to capture the type for correct
19884 // codegen in all regions, associated with the construct. Currently,
19885 // it is captured in the innermost captured region only.
19886 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19887 Var->getType()->isVariablyModifiedType()) {
19888 QualType QTy = Var->getType();
19889 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19890 QTy = PVD->getOriginalType();
19891 for (int I = 1, E = getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19892 I < E; ++I) {
19893 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19894 Val: FunctionScopes[FunctionScopesIndex - I]);
19895 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19896 "Wrong number of captured regions associated with the "
19897 "OpenMP construct.");
19898 captureVariablyModifiedType(Context, QTy, OuterRSI);
19899 }
19900 }
19901 bool IsTargetCap =
19902 IsOpenMPPrivateDecl != OMPC_private &&
19903 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19904 RSI->OpenMPCaptureLevel);
19905 // Do not capture global if it is not privatized in outer regions.
19906 bool IsGlobalCap =
19907 IsGlobal && isOpenMPGlobalCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19908 CaptureLevel: RSI->OpenMPCaptureLevel);
19909
19910 // When we detect target captures we are looking from inside the
19911 // target region, therefore we need to propagate the capture from the
19912 // enclosing region. Therefore, the capture is not initially nested.
19913 if (IsTargetCap)
19914 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, Level: RSI->OpenMPLevel);
19915
19916 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19917 (IsGlobal && !IsGlobalCap)) {
19918 Nested = !IsTargetCap;
19919 bool HasConst = DeclRefType.isConstQualified();
19920 DeclRefType = DeclRefType.getUnqualifiedType();
19921 // Don't lose diagnostics about assignments to const.
19922 if (HasConst)
19923 DeclRefType.addConst();
19924 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
19925 break;
19926 }
19927 }
19928 }
19929 }
19930 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19931 // No capture-default, and this is not an explicit capture
19932 // so cannot capture this variable.
19933 if (BuildAndDiagnose) {
19934 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19935 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19936 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
19937 if (LSI->Lambda) {
19938 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19939 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19940 }
19941 // FIXME: If we error out because an outer lambda can not implicitly
19942 // capture a variable that an inner lambda explicitly captures, we
19943 // should have the inner lambda do the explicit capture - because
19944 // it makes for cleaner diagnostics later. This would purely be done
19945 // so that the diagnostic does not misleadingly claim that a variable
19946 // can not be captured by a lambda implicitly even though it is captured
19947 // explicitly. Suggestion:
19948 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19949 // at the function head
19950 // - cache the StartingDeclContext - this must be a lambda
19951 // - captureInLambda in the innermost lambda the variable.
19952 }
19953 return true;
19954 }
19955 Explicit = false;
19956 FunctionScopesIndex--;
19957 if (IsInScopeDeclarationContext)
19958 DC = ParentDC;
19959 } while (!VarDC->Equals(DC));
19960
19961 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19962 // computing the type of the capture at each step, checking type-specific
19963 // requirements, and adding captures if requested.
19964 // If the variable had already been captured previously, we start capturing
19965 // at the lambda nested within that one.
19966 bool Invalid = false;
19967 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19968 ++I) {
19969 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
19970
19971 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19972 // certain types of variables (unnamed, variably modified types etc.)
19973 // so check for eligibility.
19974 if (!Invalid)
19975 Invalid =
19976 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
19977
19978 // After encountering an error, if we're actually supposed to capture, keep
19979 // capturing in nested contexts to suppress any follow-on diagnostics.
19980 if (Invalid && !BuildAndDiagnose)
19981 return true;
19982
19983 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
19984 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19985 DeclRefType, Nested, S&: *this, Invalid);
19986 Nested = true;
19987 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19988 Invalid = !captureInCapturedRegion(
19989 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
19990 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19991 Nested = true;
19992 } else {
19993 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19994 Invalid =
19995 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19996 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
19997 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19998 Nested = true;
19999 }
20000
20001 if (Invalid && !BuildAndDiagnose)
20002 return true;
20003 }
20004 return Invalid;
20005}
20006
20007bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20008 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20009 QualType CaptureType;
20010 QualType DeclRefType;
20011 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20012 /*BuildAndDiagnose=*/true, CaptureType,
20013 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20014}
20015
20016bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20017 QualType CaptureType;
20018 QualType DeclRefType;
20019 return !tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(),
20020 /*BuildAndDiagnose=*/false, CaptureType,
20021 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20022}
20023
20024QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20025 QualType CaptureType;
20026 QualType DeclRefType;
20027
20028 // Determine whether we can capture this variable.
20029 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(),
20030 /*BuildAndDiagnose=*/false, CaptureType,
20031 DeclRefType, FunctionScopeIndexToStopAt: nullptr))
20032 return QualType();
20033
20034 return DeclRefType;
20035}
20036
20037namespace {
20038// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20039// The produced TemplateArgumentListInfo* points to data stored within this
20040// object, so should only be used in contexts where the pointer will not be
20041// used after the CopiedTemplateArgs object is destroyed.
20042class CopiedTemplateArgs {
20043 bool HasArgs;
20044 TemplateArgumentListInfo TemplateArgStorage;
20045public:
20046 template<typename RefExpr>
20047 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20048 if (HasArgs)
20049 E->copyTemplateArgumentsInto(TemplateArgStorage);
20050 }
20051 operator TemplateArgumentListInfo*()
20052#ifdef __has_cpp_attribute
20053#if __has_cpp_attribute(clang::lifetimebound)
20054 [[clang::lifetimebound]]
20055#endif
20056#endif
20057 {
20058 return HasArgs ? &TemplateArgStorage : nullptr;
20059 }
20060};
20061}
20062
20063/// Walk the set of potential results of an expression and mark them all as
20064/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20065///
20066/// \return A new expression if we found any potential results, ExprEmpty() if
20067/// not, and ExprError() if we diagnosed an error.
20068static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20069 NonOdrUseReason NOUR) {
20070 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20071 // an object that satisfies the requirements for appearing in a
20072 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20073 // is immediately applied." This function handles the lvalue-to-rvalue
20074 // conversion part.
20075 //
20076 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20077 // transform it into the relevant kind of non-odr-use node and rebuild the
20078 // tree of nodes leading to it.
20079 //
20080 // This is a mini-TreeTransform that only transforms a restricted subset of
20081 // nodes (and only certain operands of them).
20082
20083 // Rebuild a subexpression.
20084 auto Rebuild = [&](Expr *Sub) {
20085 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20086 };
20087
20088 // Check whether a potential result satisfies the requirements of NOUR.
20089 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20090 // Any entity other than a VarDecl is always odr-used whenever it's named
20091 // in a potentially-evaluated expression.
20092 auto *VD = dyn_cast<VarDecl>(Val: D);
20093 if (!VD)
20094 return true;
20095
20096 // C++2a [basic.def.odr]p4:
20097 // A variable x whose name appears as a potentially-evalauted expression
20098 // e is odr-used by e unless
20099 // -- x is a reference that is usable in constant expressions, or
20100 // -- x is a variable of non-reference type that is usable in constant
20101 // expressions and has no mutable subobjects, and e is an element of
20102 // the set of potential results of an expression of
20103 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20104 // conversion is applied, or
20105 // -- x is a variable of non-reference type, and e is an element of the
20106 // set of potential results of a discarded-value expression to which
20107 // the lvalue-to-rvalue conversion is not applied
20108 //
20109 // We check the first bullet and the "potentially-evaluated" condition in
20110 // BuildDeclRefExpr. We check the type requirements in the second bullet
20111 // in CheckLValueToRValueConversionOperand below.
20112 switch (NOUR) {
20113 case NOUR_None:
20114 case NOUR_Unevaluated:
20115 llvm_unreachable("unexpected non-odr-use-reason");
20116
20117 case NOUR_Constant:
20118 // Constant references were handled when they were built.
20119 if (VD->getType()->isReferenceType())
20120 return true;
20121 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20122 if (RD->hasMutableFields())
20123 return true;
20124 if (!VD->isUsableInConstantExpressions(C: S.Context))
20125 return true;
20126 break;
20127
20128 case NOUR_Discarded:
20129 if (VD->getType()->isReferenceType())
20130 return true;
20131 break;
20132 }
20133 return false;
20134 };
20135
20136 // Mark that this expression does not constitute an odr-use.
20137 auto MarkNotOdrUsed = [&] {
20138 S.MaybeODRUseExprs.remove(X: E);
20139 if (LambdaScopeInfo *LSI = S.getCurLambda())
20140 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20141 };
20142
20143 // C++2a [basic.def.odr]p2:
20144 // The set of potential results of an expression e is defined as follows:
20145 switch (E->getStmtClass()) {
20146 // -- If e is an id-expression, ...
20147 case Expr::DeclRefExprClass: {
20148 auto *DRE = cast<DeclRefExpr>(Val: E);
20149 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20150 break;
20151
20152 // Rebuild as a non-odr-use DeclRefExpr.
20153 MarkNotOdrUsed();
20154 return DeclRefExpr::Create(
20155 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20156 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20157 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20158 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20159 }
20160
20161 case Expr::FunctionParmPackExprClass: {
20162 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20163 // If any of the declarations in the pack is odr-used, then the expression
20164 // as a whole constitutes an odr-use.
20165 for (VarDecl *D : *FPPE)
20166 if (IsPotentialResultOdrUsed(D))
20167 return ExprEmpty();
20168
20169 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20170 // nothing cares about whether we marked this as an odr-use, but it might
20171 // be useful for non-compiler tools.
20172 MarkNotOdrUsed();
20173 break;
20174 }
20175
20176 // -- If e is a subscripting operation with an array operand...
20177 case Expr::ArraySubscriptExprClass: {
20178 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20179 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20180 if (!OldBase->getType()->isArrayType())
20181 break;
20182 ExprResult Base = Rebuild(OldBase);
20183 if (!Base.isUsable())
20184 return Base;
20185 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20186 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20187 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20188 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20189 rbLoc: ASE->getRBracketLoc());
20190 }
20191
20192 case Expr::MemberExprClass: {
20193 auto *ME = cast<MemberExpr>(Val: E);
20194 // -- If e is a class member access expression [...] naming a non-static
20195 // data member...
20196 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20197 ExprResult Base = Rebuild(ME->getBase());
20198 if (!Base.isUsable())
20199 return Base;
20200 return MemberExpr::Create(
20201 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20202 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20203 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20204 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20205 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20206 }
20207
20208 if (ME->getMemberDecl()->isCXXInstanceMember())
20209 break;
20210
20211 // -- If e is a class member access expression naming a static data member,
20212 // ...
20213 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20214 break;
20215
20216 // Rebuild as a non-odr-use MemberExpr.
20217 MarkNotOdrUsed();
20218 return MemberExpr::Create(
20219 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20220 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20221 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20222 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20223 }
20224
20225 case Expr::BinaryOperatorClass: {
20226 auto *BO = cast<BinaryOperator>(Val: E);
20227 Expr *LHS = BO->getLHS();
20228 Expr *RHS = BO->getRHS();
20229 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20230 if (BO->getOpcode() == BO_PtrMemD) {
20231 ExprResult Sub = Rebuild(LHS);
20232 if (!Sub.isUsable())
20233 return Sub;
20234 LHS = Sub.get();
20235 // -- If e is a comma expression, ...
20236 } else if (BO->getOpcode() == BO_Comma) {
20237 ExprResult Sub = Rebuild(RHS);
20238 if (!Sub.isUsable())
20239 return Sub;
20240 RHS = Sub.get();
20241 } else {
20242 break;
20243 }
20244 return S.BuildBinOp(S: nullptr, OpLoc: BO->getOperatorLoc(), Opc: BO->getOpcode(),
20245 LHSExpr: LHS, RHSExpr: RHS);
20246 }
20247
20248 // -- If e has the form (e1)...
20249 case Expr::ParenExprClass: {
20250 auto *PE = cast<ParenExpr>(Val: E);
20251 ExprResult Sub = Rebuild(PE->getSubExpr());
20252 if (!Sub.isUsable())
20253 return Sub;
20254 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20255 }
20256
20257 // -- If e is a glvalue conditional expression, ...
20258 // We don't apply this to a binary conditional operator. FIXME: Should we?
20259 case Expr::ConditionalOperatorClass: {
20260 auto *CO = cast<ConditionalOperator>(Val: E);
20261 ExprResult LHS = Rebuild(CO->getLHS());
20262 if (LHS.isInvalid())
20263 return ExprError();
20264 ExprResult RHS = Rebuild(CO->getRHS());
20265 if (RHS.isInvalid())
20266 return ExprError();
20267 if (!LHS.isUsable() && !RHS.isUsable())
20268 return ExprEmpty();
20269 if (!LHS.isUsable())
20270 LHS = CO->getLHS();
20271 if (!RHS.isUsable())
20272 RHS = CO->getRHS();
20273 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20274 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20275 }
20276
20277 // [Clang extension]
20278 // -- If e has the form __extension__ e1...
20279 case Expr::UnaryOperatorClass: {
20280 auto *UO = cast<UnaryOperator>(Val: E);
20281 if (UO->getOpcode() != UO_Extension)
20282 break;
20283 ExprResult Sub = Rebuild(UO->getSubExpr());
20284 if (!Sub.isUsable())
20285 return Sub;
20286 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20287 Input: Sub.get());
20288 }
20289
20290 // [Clang extension]
20291 // -- If e has the form _Generic(...), the set of potential results is the
20292 // union of the sets of potential results of the associated expressions.
20293 case Expr::GenericSelectionExprClass: {
20294 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20295
20296 SmallVector<Expr *, 4> AssocExprs;
20297 bool AnyChanged = false;
20298 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20299 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20300 if (AssocExpr.isInvalid())
20301 return ExprError();
20302 if (AssocExpr.isUsable()) {
20303 AssocExprs.push_back(Elt: AssocExpr.get());
20304 AnyChanged = true;
20305 } else {
20306 AssocExprs.push_back(Elt: OrigAssocExpr);
20307 }
20308 }
20309
20310 void *ExOrTy = nullptr;
20311 bool IsExpr = GSE->isExprPredicate();
20312 if (IsExpr)
20313 ExOrTy = GSE->getControllingExpr();
20314 else
20315 ExOrTy = GSE->getControllingType();
20316 return AnyChanged ? S.CreateGenericSelectionExpr(
20317 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20318 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20319 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20320 : ExprEmpty();
20321 }
20322
20323 // [Clang extension]
20324 // -- If e has the form __builtin_choose_expr(...), the set of potential
20325 // results is the union of the sets of potential results of the
20326 // second and third subexpressions.
20327 case Expr::ChooseExprClass: {
20328 auto *CE = cast<ChooseExpr>(Val: E);
20329
20330 ExprResult LHS = Rebuild(CE->getLHS());
20331 if (LHS.isInvalid())
20332 return ExprError();
20333
20334 ExprResult RHS = Rebuild(CE->getLHS());
20335 if (RHS.isInvalid())
20336 return ExprError();
20337
20338 if (!LHS.get() && !RHS.get())
20339 return ExprEmpty();
20340 if (!LHS.isUsable())
20341 LHS = CE->getLHS();
20342 if (!RHS.isUsable())
20343 RHS = CE->getRHS();
20344
20345 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20346 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20347 }
20348
20349 // Step through non-syntactic nodes.
20350 case Expr::ConstantExprClass: {
20351 auto *CE = cast<ConstantExpr>(Val: E);
20352 ExprResult Sub = Rebuild(CE->getSubExpr());
20353 if (!Sub.isUsable())
20354 return Sub;
20355 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20356 }
20357
20358 // We could mostly rely on the recursive rebuilding to rebuild implicit
20359 // casts, but not at the top level, so rebuild them here.
20360 case Expr::ImplicitCastExprClass: {
20361 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20362 // Only step through the narrow set of cast kinds we expect to encounter.
20363 // Anything else suggests we've left the region in which potential results
20364 // can be found.
20365 switch (ICE->getCastKind()) {
20366 case CK_NoOp:
20367 case CK_DerivedToBase:
20368 case CK_UncheckedDerivedToBase: {
20369 ExprResult Sub = Rebuild(ICE->getSubExpr());
20370 if (!Sub.isUsable())
20371 return Sub;
20372 CXXCastPath Path(ICE->path());
20373 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20374 VK: ICE->getValueKind(), BasePath: &Path);
20375 }
20376
20377 default:
20378 break;
20379 }
20380 break;
20381 }
20382
20383 default:
20384 break;
20385 }
20386
20387 // Can't traverse through this node. Nothing to do.
20388 return ExprEmpty();
20389}
20390
20391ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20392 // Check whether the operand is or contains an object of non-trivial C union
20393 // type.
20394 if (E->getType().isVolatileQualified() &&
20395 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20396 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20397 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20398 UseContext: Sema::NTCUC_LValueToRValueVolatile,
20399 NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
20400
20401 // C++2a [basic.def.odr]p4:
20402 // [...] an expression of non-volatile-qualified non-class type to which
20403 // the lvalue-to-rvalue conversion is applied [...]
20404 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
20405 return E;
20406
20407 ExprResult Result =
20408 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20409 if (Result.isInvalid())
20410 return ExprError();
20411 return Result.get() ? Result : E;
20412}
20413
20414ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20415 Res = CorrectDelayedTyposInExpr(ER: Res);
20416
20417 if (!Res.isUsable())
20418 return Res;
20419
20420 // If a constant-expression is a reference to a variable where we delay
20421 // deciding whether it is an odr-use, just assume we will apply the
20422 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20423 // (a non-type template argument), we have special handling anyway.
20424 return CheckLValueToRValueConversionOperand(E: Res.get());
20425}
20426
20427void Sema::CleanupVarDeclMarking() {
20428 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20429 // call.
20430 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20431 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20432
20433 for (Expr *E : LocalMaybeODRUseExprs) {
20434 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20435 MarkVarDeclODRUsed(cast<VarDecl>(Val: DRE->getDecl()),
20436 DRE->getLocation(), *this);
20437 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20438 MarkVarDeclODRUsed(cast<VarDecl>(Val: ME->getMemberDecl()), ME->getMemberLoc(),
20439 *this);
20440 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20441 for (VarDecl *VD : *FP)
20442 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20443 } else {
20444 llvm_unreachable("Unexpected expression");
20445 }
20446 }
20447
20448 assert(MaybeODRUseExprs.empty() &&
20449 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20450}
20451
20452static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20453 ValueDecl *Var, Expr *E) {
20454 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20455 if (!VD)
20456 return;
20457
20458 const bool RefersToEnclosingScope =
20459 (SemaRef.CurContext != VD->getDeclContext() &&
20460 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20461 if (RefersToEnclosingScope) {
20462 LambdaScopeInfo *const LSI =
20463 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20464 if (LSI && (!LSI->CallOperator ||
20465 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20466 // If a variable could potentially be odr-used, defer marking it so
20467 // until we finish analyzing the full expression for any
20468 // lvalue-to-rvalue
20469 // or discarded value conversions that would obviate odr-use.
20470 // Add it to the list of potential captures that will be analyzed
20471 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20472 // unless the variable is a reference that was initialized by a constant
20473 // expression (this will never need to be captured or odr-used).
20474 //
20475 // FIXME: We can simplify this a lot after implementing P0588R1.
20476 assert(E && "Capture variable should be used in an expression.");
20477 if (!Var->getType()->isReferenceType() ||
20478 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20479 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20480 }
20481 }
20482}
20483
20484static void DoMarkVarDeclReferenced(
20485 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20486 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20487 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20488 isa<FunctionParmPackExpr>(E)) &&
20489 "Invalid Expr argument to DoMarkVarDeclReferenced");
20490 Var->setReferenced();
20491
20492 if (Var->isInvalidDecl())
20493 return;
20494
20495 auto *MSI = Var->getMemberSpecializationInfo();
20496 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20497 : Var->getTemplateSpecializationKind();
20498
20499 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20500 bool UsableInConstantExpr =
20501 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20502
20503 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20504 RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++;
20505 }
20506
20507 // C++20 [expr.const]p12:
20508 // A variable [...] is needed for constant evaluation if it is [...] a
20509 // variable whose name appears as a potentially constant evaluated
20510 // expression that is either a contexpr variable or is of non-volatile
20511 // const-qualified integral type or of reference type
20512 bool NeededForConstantEvaluation =
20513 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20514
20515 bool NeedDefinition =
20516 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20517
20518 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20519 "Can't instantiate a partial template specialization.");
20520
20521 // If this might be a member specialization of a static data member, check
20522 // the specialization is visible. We already did the checks for variable
20523 // template specializations when we created them.
20524 if (NeedDefinition && TSK != TSK_Undeclared &&
20525 !isa<VarTemplateSpecializationDecl>(Val: Var))
20526 SemaRef.checkSpecializationVisibility(Loc, Var);
20527
20528 // Perform implicit instantiation of static data members, static data member
20529 // templates of class templates, and variable template specializations. Delay
20530 // instantiations of variable templates, except for those that could be used
20531 // in a constant expression.
20532 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20533 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20534 // instantiation declaration if a variable is usable in a constant
20535 // expression (among other cases).
20536 bool TryInstantiating =
20537 TSK == TSK_ImplicitInstantiation ||
20538 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20539
20540 if (TryInstantiating) {
20541 SourceLocation PointOfInstantiation =
20542 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20543 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20544 if (FirstInstantiation) {
20545 PointOfInstantiation = Loc;
20546 if (MSI)
20547 MSI->setPointOfInstantiation(PointOfInstantiation);
20548 // FIXME: Notify listener.
20549 else
20550 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20551 }
20552
20553 if (UsableInConstantExpr) {
20554 // Do not defer instantiations of variables that could be used in a
20555 // constant expression.
20556 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20557 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20558 });
20559
20560 // Re-set the member to trigger a recomputation of the dependence bits
20561 // for the expression.
20562 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20563 DRE->setDecl(DRE->getDecl());
20564 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20565 ME->setMemberDecl(ME->getMemberDecl());
20566 } else if (FirstInstantiation) {
20567 SemaRef.PendingInstantiations
20568 .push_back(std::make_pair(x&: Var, y&: PointOfInstantiation));
20569 } else {
20570 bool Inserted = false;
20571 for (auto &I : SemaRef.SavedPendingInstantiations) {
20572 auto Iter = llvm::find_if(
20573 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20574 return P.first == Var;
20575 });
20576 if (Iter != I.end()) {
20577 SemaRef.PendingInstantiations.push_back(x: *Iter);
20578 I.erase(position: Iter);
20579 Inserted = true;
20580 break;
20581 }
20582 }
20583
20584 // FIXME: For a specialization of a variable template, we don't
20585 // distinguish between "declaration and type implicitly instantiated"
20586 // and "implicit instantiation of definition requested", so we have
20587 // no direct way to avoid enqueueing the pending instantiation
20588 // multiple times.
20589 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20590 SemaRef.PendingInstantiations
20591 .push_back(std::make_pair(x&: Var, y&: PointOfInstantiation));
20592 }
20593 }
20594 }
20595
20596 // C++2a [basic.def.odr]p4:
20597 // A variable x whose name appears as a potentially-evaluated expression e
20598 // is odr-used by e unless
20599 // -- x is a reference that is usable in constant expressions
20600 // -- x is a variable of non-reference type that is usable in constant
20601 // expressions and has no mutable subobjects [FIXME], and e is an
20602 // element of the set of potential results of an expression of
20603 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20604 // conversion is applied
20605 // -- x is a variable of non-reference type, and e is an element of the set
20606 // of potential results of a discarded-value expression to which the
20607 // lvalue-to-rvalue conversion is not applied [FIXME]
20608 //
20609 // We check the first part of the second bullet here, and
20610 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20611 // FIXME: To get the third bullet right, we need to delay this even for
20612 // variables that are not usable in constant expressions.
20613
20614 // If we already know this isn't an odr-use, there's nothing more to do.
20615 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20616 if (DRE->isNonOdrUse())
20617 return;
20618 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20619 if (ME->isNonOdrUse())
20620 return;
20621
20622 switch (OdrUse) {
20623 case OdrUseContext::None:
20624 // In some cases, a variable may not have been marked unevaluated, if it
20625 // appears in a defaukt initializer.
20626 assert((!E || isa<FunctionParmPackExpr>(E) ||
20627 SemaRef.isUnevaluatedContext()) &&
20628 "missing non-odr-use marking for unevaluated decl ref");
20629 break;
20630
20631 case OdrUseContext::FormallyOdrUsed:
20632 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20633 // behavior.
20634 break;
20635
20636 case OdrUseContext::Used:
20637 // If we might later find that this expression isn't actually an odr-use,
20638 // delay the marking.
20639 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20640 SemaRef.MaybeODRUseExprs.insert(X: E);
20641 else
20642 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20643 break;
20644
20645 case OdrUseContext::Dependent:
20646 // If this is a dependent context, we don't need to mark variables as
20647 // odr-used, but we may still need to track them for lambda capture.
20648 // FIXME: Do we also need to do this inside dependent typeid expressions
20649 // (which are modeled as unevaluated at this point)?
20650 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20651 break;
20652 }
20653}
20654
20655static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20656 BindingDecl *BD, Expr *E) {
20657 BD->setReferenced();
20658
20659 if (BD->isInvalidDecl())
20660 return;
20661
20662 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20663 if (OdrUse == OdrUseContext::Used) {
20664 QualType CaptureType, DeclRefType;
20665 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20666 /*EllipsisLoc*/ SourceLocation(),
20667 /*BuildAndDiagnose*/ true, CaptureType,
20668 DeclRefType,
20669 /*FunctionScopeIndexToStopAt*/ nullptr);
20670 } else if (OdrUse == OdrUseContext::Dependent) {
20671 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20672 }
20673}
20674
20675/// Mark a variable referenced, and check whether it is odr-used
20676/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20677/// used directly for normal expressions referring to VarDecl.
20678void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20679 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20680}
20681
20682// C++ [temp.dep.expr]p3:
20683// An id-expression is type-dependent if it contains:
20684// - an identifier associated by name lookup with an entity captured by copy
20685// in a lambda-expression that has an explicit object parameter whose type
20686// is dependent ([dcl.fct]),
20687static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20688 Sema &SemaRef, ValueDecl *D, Expr *E) {
20689 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20690 if (!ID || ID->isTypeDependent())
20691 return;
20692
20693 auto IsDependent = [&]() {
20694 const LambdaScopeInfo *LSI = SemaRef.getCurLambda();
20695 if (!LSI)
20696 return false;
20697 if (!LSI->ExplicitObjectParameter ||
20698 !LSI->ExplicitObjectParameter->getType()->isDependentType())
20699 return false;
20700 if (!LSI->CaptureMap.count(Val: D))
20701 return false;
20702 const Capture &Cap = LSI->getCapture(D);
20703 return !Cap.isCopyCapture();
20704 }();
20705
20706 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20707 Set: IsDependent, Context: SemaRef.getASTContext());
20708}
20709
20710static void
20711MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20712 bool MightBeOdrUse,
20713 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20714 if (SemaRef.isInOpenMPDeclareTargetContext())
20715 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20716
20717 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20718 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20719 if (SemaRef.getLangOpts().CPlusPlus)
20720 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20721 Var, E);
20722 return;
20723 }
20724
20725 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20726 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20727 if (SemaRef.getLangOpts().CPlusPlus)
20728 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20729 Decl, E);
20730 return;
20731 }
20732 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20733
20734 // If this is a call to a method via a cast, also mark the method in the
20735 // derived class used in case codegen can devirtualize the call.
20736 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20737 if (!ME)
20738 return;
20739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20740 if (!MD)
20741 return;
20742 // Only attempt to devirtualize if this is truly a virtual call.
20743 bool IsVirtualCall = MD->isVirtual() &&
20744 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20745 if (!IsVirtualCall)
20746 return;
20747
20748 // If it's possible to devirtualize the call, mark the called function
20749 // referenced.
20750 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20751 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20752 if (DM)
20753 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20754}
20755
20756/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20757///
20758/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20759/// handled with care if the DeclRefExpr is not newly-created.
20760void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20761 // TODO: update this with DR# once a defect report is filed.
20762 // C++11 defect. The address of a pure member should not be an ODR use, even
20763 // if it's a qualified reference.
20764 bool OdrUse = true;
20765 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20766 if (Method->isVirtual() &&
20767 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20768 OdrUse = false;
20769
20770 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20771 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20772 !isImmediateFunctionContext() &&
20773 !isCheckingDefaultArgumentOrInitializer() &&
20774 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20775 !FD->isDependentContext())
20776 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20777 }
20778 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20779 RefsMinusAssignments);
20780}
20781
20782/// Perform reference-marking and odr-use handling for a MemberExpr.
20783void Sema::MarkMemberReferenced(MemberExpr *E) {
20784 // C++11 [basic.def.odr]p2:
20785 // A non-overloaded function whose name appears as a potentially-evaluated
20786 // expression or a member of a set of candidate functions, if selected by
20787 // overload resolution when referred to from a potentially-evaluated
20788 // expression, is odr-used, unless it is a pure virtual function and its
20789 // name is not explicitly qualified.
20790 bool MightBeOdrUse = true;
20791 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20793 if (Method->isPureVirtual())
20794 MightBeOdrUse = false;
20795 }
20796 SourceLocation Loc =
20797 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20798 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20799 RefsMinusAssignments);
20800}
20801
20802/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20803void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20804 for (VarDecl *VD : *E)
20805 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20806 RefsMinusAssignments);
20807}
20808
20809/// Perform marking for a reference to an arbitrary declaration. It
20810/// marks the declaration referenced, and performs odr-use checking for
20811/// functions and variables. This method should not be used when building a
20812/// normal expression which refers to a variable.
20813void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20814 bool MightBeOdrUse) {
20815 if (MightBeOdrUse) {
20816 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20817 MarkVariableReferenced(Loc, Var: VD);
20818 return;
20819 }
20820 }
20821 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20822 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20823 return;
20824 }
20825 D->setReferenced();
20826}
20827
20828namespace {
20829 // Mark all of the declarations used by a type as referenced.
20830 // FIXME: Not fully implemented yet! We need to have a better understanding
20831 // of when we're entering a context we should not recurse into.
20832 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20833 // TreeTransforms rebuilding the type in a new context. Rather than
20834 // duplicating the TreeTransform logic, we should consider reusing it here.
20835 // Currently that causes problems when rebuilding LambdaExprs.
20836 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20837 Sema &S;
20838 SourceLocation Loc;
20839
20840 public:
20841 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20842
20843 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20844
20845 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20846 };
20847}
20848
20849bool MarkReferencedDecls::TraverseTemplateArgument(
20850 const TemplateArgument &Arg) {
20851 {
20852 // A non-type template argument is a constant-evaluated context.
20853 EnterExpressionEvaluationContext Evaluated(
20854 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20855 if (Arg.getKind() == TemplateArgument::Declaration) {
20856 if (Decl *D = Arg.getAsDecl())
20857 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20858 } else if (Arg.getKind() == TemplateArgument::Expression) {
20859 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20860 }
20861 }
20862
20863 return Inherited::TraverseTemplateArgument(Arg);
20864}
20865
20866void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20867 MarkReferencedDecls Marker(*this, Loc);
20868 Marker.TraverseType(T);
20869}
20870
20871namespace {
20872/// Helper class that marks all of the declarations referenced by
20873/// potentially-evaluated subexpressions as "referenced".
20874class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20875public:
20876 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20877 bool SkipLocalVariables;
20878 ArrayRef<const Expr *> StopAt;
20879
20880 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20881 ArrayRef<const Expr *> StopAt)
20882 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20883
20884 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20885 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20886 }
20887
20888 void Visit(Expr *E) {
20889 if (llvm::is_contained(Range&: StopAt, Element: E))
20890 return;
20891 Inherited::Visit(E);
20892 }
20893
20894 void VisitConstantExpr(ConstantExpr *E) {
20895 // Don't mark declarations within a ConstantExpression, as this expression
20896 // will be evaluated and folded to a value.
20897 }
20898
20899 void VisitDeclRefExpr(DeclRefExpr *E) {
20900 // If we were asked not to visit local variables, don't.
20901 if (SkipLocalVariables) {
20902 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
20903 if (VD->hasLocalStorage())
20904 return;
20905 }
20906
20907 // FIXME: This can trigger the instantiation of the initializer of a
20908 // variable, which can cause the expression to become value-dependent
20909 // or error-dependent. Do we need to propagate the new dependence bits?
20910 S.MarkDeclRefReferenced(E);
20911 }
20912
20913 void VisitMemberExpr(MemberExpr *E) {
20914 S.MarkMemberReferenced(E);
20915 Visit(E: E->getBase());
20916 }
20917};
20918} // namespace
20919
20920/// Mark any declarations that appear within this expression or any
20921/// potentially-evaluated subexpressions as "referenced".
20922///
20923/// \param SkipLocalVariables If true, don't mark local variables as
20924/// 'referenced'.
20925/// \param StopAt Subexpressions that we shouldn't recurse into.
20926void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20927 bool SkipLocalVariables,
20928 ArrayRef<const Expr*> StopAt) {
20929 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20930}
20931
20932/// Emit a diagnostic when statements are reachable.
20933/// FIXME: check for reachability even in expressions for which we don't build a
20934/// CFG (eg, in the initializer of a global or in a constant expression).
20935/// For example,
20936/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20937bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20938 const PartialDiagnostic &PD) {
20939 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20940 if (!FunctionScopes.empty())
20941 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20942 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20943 return true;
20944 }
20945
20946 // The initializer of a constexpr variable or of the first declaration of a
20947 // static data member is not syntactically a constant evaluated constant,
20948 // but nonetheless is always required to be a constant expression, so we
20949 // can skip diagnosing.
20950 // FIXME: Using the mangling context here is a hack.
20951 if (auto *VD = dyn_cast_or_null<VarDecl>(
20952 Val: ExprEvalContexts.back().ManglingContextDecl)) {
20953 if (VD->isConstexpr() ||
20954 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20955 return false;
20956 // FIXME: For any other kind of variable, we should build a CFG for its
20957 // initializer and check whether the context in question is reachable.
20958 }
20959
20960 Diag(Loc, PD);
20961 return true;
20962}
20963
20964/// Emit a diagnostic that describes an effect on the run-time behavior
20965/// of the program being compiled.
20966///
20967/// This routine emits the given diagnostic when the code currently being
20968/// type-checked is "potentially evaluated", meaning that there is a
20969/// possibility that the code will actually be executable. Code in sizeof()
20970/// expressions, code used only during overload resolution, etc., are not
20971/// potentially evaluated. This routine will suppress such diagnostics or,
20972/// in the absolutely nutty case of potentially potentially evaluated
20973/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20974/// later.
20975///
20976/// This routine should be used for all diagnostics that describe the run-time
20977/// behavior of a program, such as passing a non-POD value through an ellipsis.
20978/// Failure to do so will likely result in spurious diagnostics or failures
20979/// during overload resolution or within sizeof/alignof/typeof/typeid.
20980bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20981 const PartialDiagnostic &PD) {
20982
20983 if (ExprEvalContexts.back().isDiscardedStatementContext())
20984 return false;
20985
20986 switch (ExprEvalContexts.back().Context) {
20987 case ExpressionEvaluationContext::Unevaluated:
20988 case ExpressionEvaluationContext::UnevaluatedList:
20989 case ExpressionEvaluationContext::UnevaluatedAbstract:
20990 case ExpressionEvaluationContext::DiscardedStatement:
20991 // The argument will never be evaluated, so don't complain.
20992 break;
20993
20994 case ExpressionEvaluationContext::ConstantEvaluated:
20995 case ExpressionEvaluationContext::ImmediateFunctionContext:
20996 // Relevant diagnostics should be produced by constant evaluation.
20997 break;
20998
20999 case ExpressionEvaluationContext::PotentiallyEvaluated:
21000 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21001 return DiagIfReachable(Loc, Stmts, PD);
21002 }
21003
21004 return false;
21005}
21006
21007bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21008 const PartialDiagnostic &PD) {
21009 return DiagRuntimeBehavior(
21010 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
21011}
21012
21013bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21014 CallExpr *CE, FunctionDecl *FD) {
21015 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21016 return false;
21017
21018 // If we're inside a decltype's expression, don't check for a valid return
21019 // type or construct temporaries until we know whether this is the last call.
21020 if (ExprEvalContexts.back().ExprContext ==
21021 ExpressionEvaluationContextRecord::EK_Decltype) {
21022 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21023 return false;
21024 }
21025
21026 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21027 FunctionDecl *FD;
21028 CallExpr *CE;
21029
21030 public:
21031 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21032 : FD(FD), CE(CE) { }
21033
21034 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21035 if (!FD) {
21036 S.Diag(Loc, diag::err_call_incomplete_return)
21037 << T << CE->getSourceRange();
21038 return;
21039 }
21040
21041 S.Diag(Loc, diag::err_call_function_incomplete_return)
21042 << CE->getSourceRange() << FD << T;
21043 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21044 << FD->getDeclName();
21045 }
21046 } Diagnoser(FD, CE);
21047
21048 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21049 return true;
21050
21051 return false;
21052}
21053
21054// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21055// will prevent this condition from triggering, which is what we want.
21056void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21057 SourceLocation Loc;
21058
21059 unsigned diagnostic = diag::warn_condition_is_assignment;
21060 bool IsOrAssign = false;
21061
21062 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21063 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21064 return;
21065
21066 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21067
21068 // Greylist some idioms by putting them into a warning subcategory.
21069 if (ObjCMessageExpr *ME
21070 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21071 Selector Sel = ME->getSelector();
21072
21073 // self = [<foo> init...]
21074 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21075 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21076
21077 // <foo> = [<bar> nextObject]
21078 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21079 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21080 }
21081
21082 Loc = Op->getOperatorLoc();
21083 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21084 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21085 return;
21086
21087 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21088 Loc = Op->getOperatorLoc();
21089 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21090 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21091 else {
21092 // Not an assignment.
21093 return;
21094 }
21095
21096 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21097
21098 SourceLocation Open = E->getBeginLoc();
21099 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21100 Diag(Loc, diag::note_condition_assign_silence)
21101 << FixItHint::CreateInsertion(Open, "(")
21102 << FixItHint::CreateInsertion(Close, ")");
21103
21104 if (IsOrAssign)
21105 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21106 << FixItHint::CreateReplacement(Loc, "!=");
21107 else
21108 Diag(Loc, diag::note_condition_assign_to_comparison)
21109 << FixItHint::CreateReplacement(Loc, "==");
21110}
21111
21112/// Redundant parentheses over an equality comparison can indicate
21113/// that the user intended an assignment used as condition.
21114void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21115 // Don't warn if the parens came from a macro.
21116 SourceLocation parenLoc = ParenE->getBeginLoc();
21117 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21118 return;
21119 // Don't warn for dependent expressions.
21120 if (ParenE->isTypeDependent())
21121 return;
21122
21123 Expr *E = ParenE->IgnoreParens();
21124
21125 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21126 if (opE->getOpcode() == BO_EQ &&
21127 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21128 == Expr::MLV_Valid) {
21129 SourceLocation Loc = opE->getOperatorLoc();
21130
21131 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21132 SourceRange ParenERange = ParenE->getSourceRange();
21133 Diag(Loc, diag::note_equality_comparison_silence)
21134 << FixItHint::CreateRemoval(ParenERange.getBegin())
21135 << FixItHint::CreateRemoval(ParenERange.getEnd());
21136 Diag(Loc, diag::note_equality_comparison_to_assign)
21137 << FixItHint::CreateReplacement(Loc, "=");
21138 }
21139}
21140
21141ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21142 bool IsConstexpr) {
21143 DiagnoseAssignmentAsCondition(E);
21144 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21145 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21146
21147 ExprResult result = CheckPlaceholderExpr(E);
21148 if (result.isInvalid()) return ExprError();
21149 E = result.get();
21150
21151 if (!E->isTypeDependent()) {
21152 if (getLangOpts().CPlusPlus)
21153 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21154
21155 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21156 if (ERes.isInvalid())
21157 return ExprError();
21158 E = ERes.get();
21159
21160 QualType T = E->getType();
21161 if (!T->isScalarType()) { // C99 6.8.4.1p1
21162 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21163 << T << E->getSourceRange();
21164 return ExprError();
21165 }
21166 CheckBoolLikeConversion(E, CC: Loc);
21167 }
21168
21169 return E;
21170}
21171
21172Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21173 Expr *SubExpr, ConditionKind CK,
21174 bool MissingOK) {
21175 // MissingOK indicates whether having no condition expression is valid
21176 // (for loop) or invalid (e.g. while loop).
21177 if (!SubExpr)
21178 return MissingOK ? ConditionResult() : ConditionError();
21179
21180 ExprResult Cond;
21181 switch (CK) {
21182 case ConditionKind::Boolean:
21183 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21184 break;
21185
21186 case ConditionKind::ConstexprIf:
21187 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21188 break;
21189
21190 case ConditionKind::Switch:
21191 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21192 break;
21193 }
21194 if (Cond.isInvalid()) {
21195 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21196 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21197 if (!Cond.get())
21198 return ConditionError();
21199 }
21200 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
21201 FullExprArg FullExpr = MakeFullExpr(Arg: Cond.get(), CC: Loc);
21202 if (!FullExpr.get())
21203 return ConditionError();
21204
21205 return ConditionResult(*this, nullptr, FullExpr,
21206 CK == ConditionKind::ConstexprIf);
21207}
21208
21209namespace {
21210 /// A visitor for rebuilding a call to an __unknown_any expression
21211 /// to have an appropriate type.
21212 struct RebuildUnknownAnyFunction
21213 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21214
21215 Sema &S;
21216
21217 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21218
21219 ExprResult VisitStmt(Stmt *S) {
21220 llvm_unreachable("unexpected statement!");
21221 }
21222
21223 ExprResult VisitExpr(Expr *E) {
21224 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21225 << E->getSourceRange();
21226 return ExprError();
21227 }
21228
21229 /// Rebuild an expression which simply semantically wraps another
21230 /// expression which it shares the type and value kind of.
21231 template <class T> ExprResult rebuildSugarExpr(T *E) {
21232 ExprResult SubResult = Visit(E->getSubExpr());
21233 if (SubResult.isInvalid()) return ExprError();
21234
21235 Expr *SubExpr = SubResult.get();
21236 E->setSubExpr(SubExpr);
21237 E->setType(SubExpr->getType());
21238 E->setValueKind(SubExpr->getValueKind());
21239 assert(E->getObjectKind() == OK_Ordinary);
21240 return E;
21241 }
21242
21243 ExprResult VisitParenExpr(ParenExpr *E) {
21244 return rebuildSugarExpr(E);
21245 }
21246
21247 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21248 return rebuildSugarExpr(E);
21249 }
21250
21251 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21252 ExprResult SubResult = Visit(E->getSubExpr());
21253 if (SubResult.isInvalid()) return ExprError();
21254
21255 Expr *SubExpr = SubResult.get();
21256 E->setSubExpr(SubExpr);
21257 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21258 assert(E->isPRValue());
21259 assert(E->getObjectKind() == OK_Ordinary);
21260 return E;
21261 }
21262
21263 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21264 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21265
21266 E->setType(VD->getType());
21267
21268 assert(E->isPRValue());
21269 if (S.getLangOpts().CPlusPlus &&
21270 !(isa<CXXMethodDecl>(Val: VD) &&
21271 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21272 E->setValueKind(VK_LValue);
21273
21274 return E;
21275 }
21276
21277 ExprResult VisitMemberExpr(MemberExpr *E) {
21278 return resolveDecl(E, E->getMemberDecl());
21279 }
21280
21281 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21282 return resolveDecl(E, E->getDecl());
21283 }
21284 };
21285}
21286
21287/// Given a function expression of unknown-any type, try to rebuild it
21288/// to have a function type.
21289static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21290 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21291 if (Result.isInvalid()) return ExprError();
21292 return S.DefaultFunctionArrayConversion(E: Result.get());
21293}
21294
21295namespace {
21296 /// A visitor for rebuilding an expression of type __unknown_anytype
21297 /// into one which resolves the type directly on the referring
21298 /// expression. Strict preservation of the original source
21299 /// structure is not a goal.
21300 struct RebuildUnknownAnyExpr
21301 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21302
21303 Sema &S;
21304
21305 /// The current destination type.
21306 QualType DestType;
21307
21308 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21309 : S(S), DestType(CastType) {}
21310
21311 ExprResult VisitStmt(Stmt *S) {
21312 llvm_unreachable("unexpected statement!");
21313 }
21314
21315 ExprResult VisitExpr(Expr *E) {
21316 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21317 << E->getSourceRange();
21318 return ExprError();
21319 }
21320
21321 ExprResult VisitCallExpr(CallExpr *E);
21322 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21323
21324 /// Rebuild an expression which simply semantically wraps another
21325 /// expression which it shares the type and value kind of.
21326 template <class T> ExprResult rebuildSugarExpr(T *E) {
21327 ExprResult SubResult = Visit(E->getSubExpr());
21328 if (SubResult.isInvalid()) return ExprError();
21329 Expr *SubExpr = SubResult.get();
21330 E->setSubExpr(SubExpr);
21331 E->setType(SubExpr->getType());
21332 E->setValueKind(SubExpr->getValueKind());
21333 assert(E->getObjectKind() == OK_Ordinary);
21334 return E;
21335 }
21336
21337 ExprResult VisitParenExpr(ParenExpr *E) {
21338 return rebuildSugarExpr(E);
21339 }
21340
21341 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21342 return rebuildSugarExpr(E);
21343 }
21344
21345 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21346 const PointerType *Ptr = DestType->getAs<PointerType>();
21347 if (!Ptr) {
21348 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21349 << E->getSourceRange();
21350 return ExprError();
21351 }
21352
21353 if (isa<CallExpr>(Val: E->getSubExpr())) {
21354 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21355 << E->getSourceRange();
21356 return ExprError();
21357 }
21358
21359 assert(E->isPRValue());
21360 assert(E->getObjectKind() == OK_Ordinary);
21361 E->setType(DestType);
21362
21363 // Build the sub-expression as if it were an object of the pointee type.
21364 DestType = Ptr->getPointeeType();
21365 ExprResult SubResult = Visit(E->getSubExpr());
21366 if (SubResult.isInvalid()) return ExprError();
21367 E->setSubExpr(SubResult.get());
21368 return E;
21369 }
21370
21371 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21372
21373 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21374
21375 ExprResult VisitMemberExpr(MemberExpr *E) {
21376 return resolveDecl(E, E->getMemberDecl());
21377 }
21378
21379 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21380 return resolveDecl(E, E->getDecl());
21381 }
21382 };
21383}
21384
21385/// Rebuilds a call expression which yielded __unknown_anytype.
21386ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21387 Expr *CalleeExpr = E->getCallee();
21388
21389 enum FnKind {
21390 FK_MemberFunction,
21391 FK_FunctionPointer,
21392 FK_BlockPointer
21393 };
21394
21395 FnKind Kind;
21396 QualType CalleeType = CalleeExpr->getType();
21397 if (CalleeType == S.Context.BoundMemberTy) {
21398 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21399 Kind = FK_MemberFunction;
21400 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21401 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21402 CalleeType = Ptr->getPointeeType();
21403 Kind = FK_FunctionPointer;
21404 } else {
21405 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21406 Kind = FK_BlockPointer;
21407 }
21408 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21409
21410 // Verify that this is a legal result type of a function.
21411 if (DestType->isArrayType() || DestType->isFunctionType()) {
21412 unsigned diagID = diag::err_func_returning_array_function;
21413 if (Kind == FK_BlockPointer)
21414 diagID = diag::err_block_returning_array_function;
21415
21416 S.Diag(E->getExprLoc(), diagID)
21417 << DestType->isFunctionType() << DestType;
21418 return ExprError();
21419 }
21420
21421 // Otherwise, go ahead and set DestType as the call's result.
21422 E->setType(DestType.getNonLValueExprType(S.Context));
21423 E->setValueKind(Expr::getValueKindForType(DestType));
21424 assert(E->getObjectKind() == OK_Ordinary);
21425
21426 // Rebuild the function type, replacing the result type with DestType.
21427 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21428 if (Proto) {
21429 // __unknown_anytype(...) is a special case used by the debugger when
21430 // it has no idea what a function's signature is.
21431 //
21432 // We want to build this call essentially under the K&R
21433 // unprototyped rules, but making a FunctionNoProtoType in C++
21434 // would foul up all sorts of assumptions. However, we cannot
21435 // simply pass all arguments as variadic arguments, nor can we
21436 // portably just call the function under a non-variadic type; see
21437 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21438 // However, it turns out that in practice it is generally safe to
21439 // call a function declared as "A foo(B,C,D);" under the prototype
21440 // "A foo(B,C,D,...);". The only known exception is with the
21441 // Windows ABI, where any variadic function is implicitly cdecl
21442 // regardless of its normal CC. Therefore we change the parameter
21443 // types to match the types of the arguments.
21444 //
21445 // This is a hack, but it is far superior to moving the
21446 // corresponding target-specific code from IR-gen to Sema/AST.
21447
21448 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21449 SmallVector<QualType, 8> ArgTypes;
21450 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21451 ArgTypes.reserve(N: E->getNumArgs());
21452 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21453 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21454 }
21455 ParamTypes = ArgTypes;
21456 }
21457 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21458 Proto->getExtProtoInfo());
21459 } else {
21460 DestType = S.Context.getFunctionNoProtoType(DestType,
21461 FnType->getExtInfo());
21462 }
21463
21464 // Rebuild the appropriate pointer-to-function type.
21465 switch (Kind) {
21466 case FK_MemberFunction:
21467 // Nothing to do.
21468 break;
21469
21470 case FK_FunctionPointer:
21471 DestType = S.Context.getPointerType(DestType);
21472 break;
21473
21474 case FK_BlockPointer:
21475 DestType = S.Context.getBlockPointerType(DestType);
21476 break;
21477 }
21478
21479 // Finally, we can recurse.
21480 ExprResult CalleeResult = Visit(CalleeExpr);
21481 if (!CalleeResult.isUsable()) return ExprError();
21482 E->setCallee(CalleeResult.get());
21483
21484 // Bind a temporary if necessary.
21485 return S.MaybeBindToTemporary(E);
21486}
21487
21488ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21489 // Verify that this is a legal result type of a call.
21490 if (DestType->isArrayType() || DestType->isFunctionType()) {
21491 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21492 << DestType->isFunctionType() << DestType;
21493 return ExprError();
21494 }
21495
21496 // Rewrite the method result type if available.
21497 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21498 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21499 Method->setReturnType(DestType);
21500 }
21501
21502 // Change the type of the message.
21503 E->setType(DestType.getNonReferenceType());
21504 E->setValueKind(Expr::getValueKindForType(DestType));
21505
21506 return S.MaybeBindToTemporary(E);
21507}
21508
21509ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21510 // The only case we should ever see here is a function-to-pointer decay.
21511 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21512 assert(E->isPRValue());
21513 assert(E->getObjectKind() == OK_Ordinary);
21514
21515 E->setType(DestType);
21516
21517 // Rebuild the sub-expression as the pointee (function) type.
21518 DestType = DestType->castAs<PointerType>()->getPointeeType();
21519
21520 ExprResult Result = Visit(E->getSubExpr());
21521 if (!Result.isUsable()) return ExprError();
21522
21523 E->setSubExpr(Result.get());
21524 return E;
21525 } else if (E->getCastKind() == CK_LValueToRValue) {
21526 assert(E->isPRValue());
21527 assert(E->getObjectKind() == OK_Ordinary);
21528
21529 assert(isa<BlockPointerType>(E->getType()));
21530
21531 E->setType(DestType);
21532
21533 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21534 DestType = S.Context.getLValueReferenceType(DestType);
21535
21536 ExprResult Result = Visit(E->getSubExpr());
21537 if (!Result.isUsable()) return ExprError();
21538
21539 E->setSubExpr(Result.get());
21540 return E;
21541 } else {
21542 llvm_unreachable("Unhandled cast type!");
21543 }
21544}
21545
21546ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21547 ExprValueKind ValueKind = VK_LValue;
21548 QualType Type = DestType;
21549
21550 // We know how to make this work for certain kinds of decls:
21551
21552 // - functions
21553 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21554 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21555 DestType = Ptr->getPointeeType();
21556 ExprResult Result = resolveDecl(E, VD);
21557 if (Result.isInvalid()) return ExprError();
21558 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21559 VK: VK_PRValue);
21560 }
21561
21562 if (!Type->isFunctionType()) {
21563 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21564 << VD << E->getSourceRange();
21565 return ExprError();
21566 }
21567 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21568 // We must match the FunctionDecl's type to the hack introduced in
21569 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21570 // type. See the lengthy commentary in that routine.
21571 QualType FDT = FD->getType();
21572 const FunctionType *FnType = FDT->castAs<FunctionType>();
21573 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21574 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21575 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21576 SourceLocation Loc = FD->getLocation();
21577 FunctionDecl *NewFD = FunctionDecl::Create(
21578 S.Context, FD->getDeclContext(), Loc, Loc,
21579 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21580 SC_None, S.getCurFPFeatures().isFPConstrained(),
21581 false /*isInlineSpecified*/, FD->hasPrototype(),
21582 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21583
21584 if (FD->getQualifier())
21585 NewFD->setQualifierInfo(FD->getQualifierLoc());
21586
21587 SmallVector<ParmVarDecl*, 16> Params;
21588 for (const auto &AI : FT->param_types()) {
21589 ParmVarDecl *Param =
21590 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21591 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21592 Params.push_back(Elt: Param);
21593 }
21594 NewFD->setParams(Params);
21595 DRE->setDecl(NewFD);
21596 VD = DRE->getDecl();
21597 }
21598 }
21599
21600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21601 if (MD->isInstance()) {
21602 ValueKind = VK_PRValue;
21603 Type = S.Context.BoundMemberTy;
21604 }
21605
21606 // Function references aren't l-values in C.
21607 if (!S.getLangOpts().CPlusPlus)
21608 ValueKind = VK_PRValue;
21609
21610 // - variables
21611 } else if (isa<VarDecl>(Val: VD)) {
21612 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21613 Type = RefTy->getPointeeType();
21614 } else if (Type->isFunctionType()) {
21615 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21616 << VD << E->getSourceRange();
21617 return ExprError();
21618 }
21619
21620 // - nothing else
21621 } else {
21622 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21623 << VD << E->getSourceRange();
21624 return ExprError();
21625 }
21626
21627 // Modifying the declaration like this is friendly to IR-gen but
21628 // also really dangerous.
21629 VD->setType(DestType);
21630 E->setType(Type);
21631 E->setValueKind(ValueKind);
21632 return E;
21633}
21634
21635/// Check a cast of an unknown-any type. We intentionally only
21636/// trigger this for C-style casts.
21637ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21638 Expr *CastExpr, CastKind &CastKind,
21639 ExprValueKind &VK, CXXCastPath &Path) {
21640 // The type we're casting to must be either void or complete.
21641 if (!CastType->isVoidType() &&
21642 RequireCompleteType(TypeRange.getBegin(), CastType,
21643 diag::err_typecheck_cast_to_incomplete))
21644 return ExprError();
21645
21646 // Rewrite the casted expression from scratch.
21647 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21648 if (!result.isUsable()) return ExprError();
21649
21650 CastExpr = result.get();
21651 VK = CastExpr->getValueKind();
21652 CastKind = CK_NoOp;
21653
21654 return CastExpr;
21655}
21656
21657ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21658 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21659}
21660
21661ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21662 Expr *arg, QualType &paramType) {
21663 // If the syntactic form of the argument is not an explicit cast of
21664 // any sort, just do default argument promotion.
21665 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21666 if (!castArg) {
21667 ExprResult result = DefaultArgumentPromotion(E: arg);
21668 if (result.isInvalid()) return ExprError();
21669 paramType = result.get()->getType();
21670 return result;
21671 }
21672
21673 // Otherwise, use the type that was written in the explicit cast.
21674 assert(!arg->hasPlaceholderType());
21675 paramType = castArg->getTypeAsWritten();
21676
21677 // Copy-initialize a parameter of that type.
21678 InitializedEntity entity =
21679 InitializedEntity::InitializeParameter(Context, Type: paramType,
21680 /*consumed*/ Consumed: false);
21681 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21682}
21683
21684static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21685 Expr *orig = E;
21686 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21687 while (true) {
21688 E = E->IgnoreParenImpCasts();
21689 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21690 E = call->getCallee();
21691 diagID = diag::err_uncasted_call_of_unknown_any;
21692 } else {
21693 break;
21694 }
21695 }
21696
21697 SourceLocation loc;
21698 NamedDecl *d;
21699 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21700 loc = ref->getLocation();
21701 d = ref->getDecl();
21702 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21703 loc = mem->getMemberLoc();
21704 d = mem->getMemberDecl();
21705 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21706 diagID = diag::err_uncasted_call_of_unknown_any;
21707 loc = msg->getSelectorStartLoc();
21708 d = msg->getMethodDecl();
21709 if (!d) {
21710 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21711 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21712 << orig->getSourceRange();
21713 return ExprError();
21714 }
21715 } else {
21716 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21717 << E->getSourceRange();
21718 return ExprError();
21719 }
21720
21721 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21722
21723 // Never recoverable.
21724 return ExprError();
21725}
21726
21727/// Check for operands with placeholder types and complain if found.
21728/// Returns ExprError() if there was an error and no recovery was possible.
21729ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21730 if (!Context.isDependenceAllowed()) {
21731 // C cannot handle TypoExpr nodes on either side of a binop because it
21732 // doesn't handle dependent types properly, so make sure any TypoExprs have
21733 // been dealt with before checking the operands.
21734 ExprResult Result = CorrectDelayedTyposInExpr(E);
21735 if (!Result.isUsable()) return ExprError();
21736 E = Result.get();
21737 }
21738
21739 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21740 if (!placeholderType) return E;
21741
21742 switch (placeholderType->getKind()) {
21743
21744 // Overloaded expressions.
21745 case BuiltinType::Overload: {
21746 // Try to resolve a single function template specialization.
21747 // This is obligatory.
21748 ExprResult Result = E;
21749 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21750 return Result;
21751
21752 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21753 // leaves Result unchanged on failure.
21754 Result = E;
21755 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21756 return Result;
21757
21758 // If that failed, try to recover with a call.
21759 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21760 /*complain*/ true);
21761 return Result;
21762 }
21763
21764 // Bound member functions.
21765 case BuiltinType::BoundMember: {
21766 ExprResult result = E;
21767 const Expr *BME = E->IgnoreParens();
21768 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21769 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21770 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21771 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21772 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21773 if (ME->getMemberNameInfo().getName().getNameKind() ==
21774 DeclarationName::CXXDestructorName)
21775 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21776 }
21777 tryToRecoverWithCall(E&: result, PD,
21778 /*complain*/ ForceComplain: true);
21779 return result;
21780 }
21781
21782 // ARC unbridged casts.
21783 case BuiltinType::ARCUnbridgedCast: {
21784 Expr *realCast = stripARCUnbridgedCast(e: E);
21785 diagnoseARCUnbridgedCast(e: realCast);
21786 return realCast;
21787 }
21788
21789 // Expressions of unknown type.
21790 case BuiltinType::UnknownAny:
21791 return diagnoseUnknownAnyExpr(S&: *this, E);
21792
21793 // Pseudo-objects.
21794 case BuiltinType::PseudoObject:
21795 return checkPseudoObjectRValue(E);
21796
21797 case BuiltinType::BuiltinFn: {
21798 // Accept __noop without parens by implicitly converting it to a call expr.
21799 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21800 if (DRE) {
21801 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21802 unsigned BuiltinID = FD->getBuiltinID();
21803 if (BuiltinID == Builtin::BI__noop) {
21804 E = ImpCastExprToType(E, Type: Context.getPointerType(FD->getType()),
21805 CK: CK_BuiltinFnToFnPtr)
21806 .get();
21807 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21808 VK: VK_PRValue, RParenLoc: SourceLocation(),
21809 FPFeatures: FPOptionsOverride());
21810 }
21811
21812 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21813 // Any use of these other than a direct call is ill-formed as of C++20,
21814 // because they are not addressable functions. In earlier language
21815 // modes, warn and force an instantiation of the real body.
21816 Diag(E->getBeginLoc(),
21817 getLangOpts().CPlusPlus20
21818 ? diag::err_use_of_unaddressable_function
21819 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21820 if (FD->isImplicitlyInstantiable()) {
21821 // Require a definition here because a normal attempt at
21822 // instantiation for a builtin will be ignored, and we won't try
21823 // again later. We assume that the definition of the template
21824 // precedes this use.
21825 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21826 /*Recursive=*/false,
21827 /*DefinitionRequired=*/true,
21828 /*AtEndOfTU=*/false);
21829 }
21830 // Produce a properly-typed reference to the function.
21831 CXXScopeSpec SS;
21832 SS.Adopt(Other: DRE->getQualifierLoc());
21833 TemplateArgumentListInfo TemplateArgs;
21834 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
21835 return BuildDeclRefExpr(
21836 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21837 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21838 DRE->getTemplateKeywordLoc(),
21839 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21840 }
21841 }
21842
21843 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21844 return ExprError();
21845 }
21846
21847 case BuiltinType::IncompleteMatrixIdx:
21848 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21849 ->getRowIdx()
21850 ->getBeginLoc(),
21851 diag::err_matrix_incomplete_index);
21852 return ExprError();
21853
21854 // Expressions of unknown type.
21855 case BuiltinType::OMPArraySection:
21856 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21857 return ExprError();
21858
21859 // Expressions of unknown type.
21860 case BuiltinType::OMPArrayShaping:
21861 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21862
21863 case BuiltinType::OMPIterator:
21864 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21865
21866 // Everything else should be impossible.
21867#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21868 case BuiltinType::Id:
21869#include "clang/Basic/OpenCLImageTypes.def"
21870#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21871 case BuiltinType::Id:
21872#include "clang/Basic/OpenCLExtensionTypes.def"
21873#define SVE_TYPE(Name, Id, SingletonId) \
21874 case BuiltinType::Id:
21875#include "clang/Basic/AArch64SVEACLETypes.def"
21876#define PPC_VECTOR_TYPE(Name, Id, Size) \
21877 case BuiltinType::Id:
21878#include "clang/Basic/PPCTypes.def"
21879#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21880#include "clang/Basic/RISCVVTypes.def"
21881#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21882#include "clang/Basic/WebAssemblyReferenceTypes.def"
21883#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21884#define PLACEHOLDER_TYPE(Id, SingletonId)
21885#include "clang/AST/BuiltinTypes.def"
21886 break;
21887 }
21888
21889 llvm_unreachable("invalid placeholder type!");
21890}
21891
21892bool Sema::CheckCaseExpression(Expr *E) {
21893 if (E->isTypeDependent())
21894 return true;
21895 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
21896 return E->getType()->isIntegralOrEnumerationType();
21897 return false;
21898}
21899
21900/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21901ExprResult
21902Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21903 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21904 "Unknown Objective-C Boolean value!");
21905 QualType BoolT = Context.ObjCBuiltinBoolTy;
21906 if (!Context.getBOOLDecl()) {
21907 LookupResult Result(*this, &Context.Idents.get(Name: "BOOL"), OpLoc,
21908 Sema::LookupOrdinaryName);
21909 if (LookupName(R&: Result, S: getCurScope()) && Result.isSingleResult()) {
21910 NamedDecl *ND = Result.getFoundDecl();
21911 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(Val: ND))
21912 Context.setBOOLDecl(TD);
21913 }
21914 }
21915 if (Context.getBOOLDecl())
21916 BoolT = Context.getBOOLType();
21917 return new (Context)
21918 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21919}
21920
21921ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21922 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21923 SourceLocation RParen) {
21924 auto FindSpecVersion =
21925 [&](StringRef Platform) -> std::optional<VersionTuple> {
21926 auto Spec = llvm::find_if(Range&: AvailSpecs, P: [&](const AvailabilitySpec &Spec) {
21927 return Spec.getPlatform() == Platform;
21928 });
21929 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21930 // for "maccatalyst" if "maccatalyst" is not specified.
21931 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21932 Spec = llvm::find_if(Range&: AvailSpecs, P: [&](const AvailabilitySpec &Spec) {
21933 return Spec.getPlatform() == "ios";
21934 });
21935 }
21936 if (Spec == AvailSpecs.end())
21937 return std::nullopt;
21938 return Spec->getVersion();
21939 };
21940
21941 VersionTuple Version;
21942 if (auto MaybeVersion =
21943 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21944 Version = *MaybeVersion;
21945
21946 // The use of `@available` in the enclosing context should be analyzed to
21947 // warn when it's used inappropriately (i.e. not if(@available)).
21948 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21949 Context->HasPotentialAvailabilityViolations = true;
21950
21951 return new (Context)
21952 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21953}
21954
21955ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21956 ArrayRef<Expr *> SubExprs, QualType T) {
21957 if (!Context.getLangOpts().RecoveryAST)
21958 return ExprError();
21959
21960 if (isSFINAEContext())
21961 return ExprError();
21962
21963 if (T.isNull() || T->isUndeducedType() ||
21964 !Context.getLangOpts().RecoveryASTType)
21965 // We don't know the concrete type, fallback to dependent type.
21966 T = Context.DependentTy;
21967
21968 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
21969}
21970

source code of clang/lib/Sema/SemaExpr.cpp