1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DynamicRecursiveASTVisitor.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtVisitor.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Basic/BuiltinTraits.h"
37#include "clang/Basic/Builtins.h"
38#include "clang/Basic/DiagnosticSema.h"
39#include "clang/Basic/PartialDiagnostic.h"
40#include "clang/Basic/SourceManager.h"
41#include "clang/Basic/Specifiers.h"
42#include "clang/Basic/TargetInfo.h"
43#include "clang/Lex/LiteralSupport.h"
44#include "clang/Lex/Preprocessor.h"
45#include "clang/Sema/AnalysisBasedWarnings.h"
46#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/DelayedDiagnostic.h"
48#include "clang/Sema/Designator.h"
49#include "clang/Sema/EnterExpressionEvaluationContext.h"
50#include "clang/Sema/Initialization.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
53#include "clang/Sema/ParsedTemplate.h"
54#include "clang/Sema/Scope.h"
55#include "clang/Sema/ScopeInfo.h"
56#include "clang/Sema/SemaAMDGPU.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
59#include "clang/Sema/SemaFixItUtils.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/SemaOpenCL.h"
63#include "clang/Sema/SemaOpenMP.h"
64#include "clang/Sema/SemaPseudoObject.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/IR/DerivedTypes.h"
69#include "llvm/Support/ConvertUTF.h"
70#include "llvm/Support/SaveAndRestore.h"
71#include "llvm/Support/TimeProfiler.h"
72#include "llvm/Support/TypeSize.h"
73#include <limits>
74#include <optional>
75
76using namespace clang;
77using namespace sema;
78
79bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
80 // See if this is an auto-typed variable whose initializer we are parsing.
81 if (ParsingInitForAutoVars.count(Ptr: D))
82 return false;
83
84 // See if this is a deleted function.
85 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
86 if (FD->isDeleted())
87 return false;
88
89 // If the function has a deduced return type, and we can't deduce it,
90 // then we can't use it either.
91 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
92 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
93 return false;
94
95 // See if this is an aligned allocation/deallocation function that is
96 // unavailable.
97 if (TreatUnavailableAsInvalid &&
98 isUnavailableAlignedAllocationFunction(FD: *FD))
99 return false;
100 }
101
102 // See if this function is unavailable.
103 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
104 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
105 return false;
106
107 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
108 return false;
109
110 return true;
111}
112
113static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
114 // Warn if this is used but marked unused.
115 if (const auto *A = D->getAttr<UnusedAttr>()) {
116 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
117 // should diagnose them.
118 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
119 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
120 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
121 if (DC && !DC->hasAttr<UnusedAttr>())
122 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
123 }
124 }
125}
126
127void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
128 assert(Decl && Decl->isDeleted());
129
130 if (Decl->isDefaulted()) {
131 // If the method was explicitly defaulted, point at that declaration.
132 if (!Decl->isImplicit())
133 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
134
135 // Try to diagnose why this special member function was implicitly
136 // deleted. This might fail, if that reason no longer applies.
137 DiagnoseDeletedDefaultedFunction(FD: Decl);
138 return;
139 }
140
141 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
142 if (Ctor && Ctor->isInheritingConstructor())
143 return NoteDeletedInheritingConstructor(CD: Ctor);
144
145 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
146 << Decl << 1;
147}
148
149/// Determine whether a FunctionDecl was ever declared with an
150/// explicit storage class.
151static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
152 for (auto *I : D->redecls()) {
153 if (I->getStorageClass() != SC_None)
154 return true;
155 }
156 return false;
157}
158
159/// Check whether we're in an extern inline function and referring to a
160/// variable or function with internal linkage (C11 6.7.4p3).
161///
162/// This is only a warning because we used to silently accept this code, but
163/// in many cases it will not behave correctly. This is not enabled in C++ mode
164/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
165/// and so while there may still be user mistakes, most of the time we can't
166/// prove that there are errors.
167static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
168 const NamedDecl *D,
169 SourceLocation Loc) {
170 // This is disabled under C++; there are too many ways for this to fire in
171 // contexts where the warning is a false positive, or where it is technically
172 // correct but benign.
173 //
174 // WG14 N3622 which removed the constraint entirely in C2y. It is left
175 // enabled in earlier language modes because this is a constraint in those
176 // language modes. But in C2y mode, we still want to issue the "incompatible
177 // with previous standards" diagnostic, too.
178 if (S.getLangOpts().CPlusPlus)
179 return;
180
181 // Check if this is an inlined function or method.
182 FunctionDecl *Current = S.getCurFunctionDecl();
183 if (!Current)
184 return;
185 if (!Current->isInlined())
186 return;
187 if (!Current->isExternallyVisible())
188 return;
189
190 // Check if the decl has internal linkage.
191 if (D->getFormalLinkage() != Linkage::Internal)
192 return;
193
194 // Downgrade from ExtWarn to Extension if
195 // (1) the supposedly external inline function is in the main file,
196 // and probably won't be included anywhere else.
197 // (2) the thing we're referencing is a pure function.
198 // (3) the thing we're referencing is another inline function.
199 // This last can give us false negatives, but it's better than warning on
200 // wrappers for simple C library functions.
201 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
202 unsigned DiagID;
203 if (S.getLangOpts().C2y)
204 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
205 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
206 S.getSourceManager().isInMainFile(Loc))
207 DiagID = diag::ext_internal_in_extern_inline_quiet;
208 else
209 DiagID = diag::ext_internal_in_extern_inline;
210
211 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
212 S.MaybeSuggestAddingStaticToDecl(D: Current);
213 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
214 << D;
215}
216
217void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
218 const FunctionDecl *First = Cur->getFirstDecl();
219
220 // Suggest "static" on the function, if possible.
221 if (!hasAnyExplicitStorageClass(D: First)) {
222 SourceLocation DeclBegin = First->getSourceRange().getBegin();
223 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
224 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
225 }
226}
227
228bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
229 const ObjCInterfaceDecl *UnknownObjCClass,
230 bool ObjCPropertyAccess,
231 bool AvoidPartialAvailabilityChecks,
232 ObjCInterfaceDecl *ClassReceiver,
233 bool SkipTrailingRequiresClause) {
234 SourceLocation Loc = Locs.front();
235 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
236 // If there were any diagnostics suppressed by template argument deduction,
237 // emit them now.
238 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
239 if (Pos != SuppressedDiagnostics.end()) {
240 for (const auto &[DiagLoc, PD] : Pos->second) {
241 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
242 PD.Emit(DB: Builder);
243 }
244 // Clear out the list of suppressed diagnostics, so that we don't emit
245 // them again for this specialization. However, we don't obsolete this
246 // entry from the table, because we want to avoid ever emitting these
247 // diagnostics again.
248 Pos->second.clear();
249 }
250
251 // C++ [basic.start.main]p3:
252 // The function 'main' shall not be used within a program.
253 if (cast<FunctionDecl>(Val: D)->isMain())
254 Diag(Loc, DiagID: diag::ext_main_used);
255
256 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
257 }
258
259 // See if this is an auto-typed variable whose initializer we are parsing.
260 if (ParsingInitForAutoVars.count(Ptr: D)) {
261 if (isa<BindingDecl>(Val: D)) {
262 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
263 << D->getDeclName();
264 } else {
265 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << diag::ParsingInitFor::Var << D->getDeclName()
267 << cast<VarDecl>(Val: D)->getType();
268 }
269 return true;
270 }
271
272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
273 // See if this is a deleted function.
274 if (FD->isDeleted()) {
275 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
276 if (Ctor && Ctor->isInheritingConstructor())
277 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
278 << Ctor->getParent()
279 << Ctor->getInheritedConstructor().getConstructor()->getParent();
280 else {
281 StringLiteral *Msg = FD->getDeletedMessage();
282 Diag(Loc, DiagID: diag::err_deleted_function_use)
283 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
284 }
285 NoteDeletedFunction(Decl: FD);
286 return true;
287 }
288
289 // [expr.prim.id]p4
290 // A program that refers explicitly or implicitly to a function with a
291 // trailing requires-clause whose constraint-expression is not satisfied,
292 // other than to declare it, is ill-formed. [...]
293 //
294 // See if this is a function with constraints that need to be satisfied.
295 // Check this before deducing the return type, as it might instantiate the
296 // definition.
297 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
298 ConstraintSatisfaction Satisfaction;
299 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
300 /*ForOverloadResolution*/ true))
301 // A diagnostic will have already been generated (non-constant
302 // constraint expression, for example)
303 return true;
304 if (!Satisfaction.IsSatisfied) {
305 Diag(Loc,
306 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
307 << D;
308 DiagnoseUnsatisfiedConstraint(Satisfaction);
309 return true;
310 }
311 }
312
313 // If the function has a deduced return type, and we can't deduce it,
314 // then we can't use it either.
315 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
316 DeduceReturnType(FD, Loc))
317 return true;
318
319 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
320 return true;
321
322 }
323
324 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
325 Concept && CheckConceptUseInDefinition(Concept, Loc))
326 return true;
327
328 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
329 // Lambdas are only default-constructible or assignable in C++2a onwards.
330 if (MD->getParent()->isLambda() &&
331 ((isa<CXXConstructorDecl>(Val: MD) &&
332 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
333 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
334 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
335 << !isa<CXXConstructorDecl>(Val: MD);
336 }
337 }
338
339 auto getReferencedObjCProp = [](const NamedDecl *D) ->
340 const ObjCPropertyDecl * {
341 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
342 return MD->findPropertyDecl();
343 return nullptr;
344 };
345 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
346 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
347 return true;
348 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
349 return true;
350 }
351
352 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
353 // Only the variables omp_in and omp_out are allowed in the combiner.
354 // Only the variables omp_priv and omp_orig are allowed in the
355 // initializer-clause.
356 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
357 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
358 isa<VarDecl>(Val: D)) {
359 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
360 << getCurFunction()->HasOMPDeclareReductionCombiner;
361 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
366 // List-items in map clauses on this construct may only refer to the declared
367 // variable var and entities that could be referenced by a procedure defined
368 // at the same location.
369 // [OpenMP 5.2] Also allow iterator declared variables.
370 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
371 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
372 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
373 << OpenMP().getOpenMPDeclareMapperVarName();
374 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
375 return true;
376 }
377
378 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
379 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
380 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
381 return true;
382 }
383
384 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
385 AvoidPartialAvailabilityChecks, ClassReceiver);
386
387 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
388
389 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
390
391 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
392 if (getLangOpts().getFPEvalMethod() !=
393 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
394 PP.getLastFPEvalPragmaLocation().isValid() &&
395 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
396 Diag(Loc: D->getLocation(),
397 DiagID: diag::err_type_available_only_in_default_eval_method)
398 << D->getName();
399 }
400
401 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
402 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
403
404 if (LangOpts.SYCLIsDevice ||
405 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
406 if (!Context.getTargetInfo().isTLSSupported())
407 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
408 if (VD->getTLSKind() != VarDecl::TLS_None)
409 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
410 }
411
412 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
413 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
414
415 return false;
416}
417
418void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
419 ArrayRef<Expr *> Args) {
420 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
421 if (!Attr)
422 return;
423
424 // The number of formal parameters of the declaration.
425 unsigned NumFormalParams;
426
427 // The kind of declaration. This is also an index into a %select in
428 // the diagnostic.
429 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
430
431 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
432 NumFormalParams = MD->param_size();
433 CalleeKind = CK_Method;
434 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
435 NumFormalParams = FD->param_size();
436 CalleeKind = CK_Function;
437 if (FD->hasCXXExplicitFunctionObjectParameter())
438 NumFormalParams++;
439 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
440 QualType Ty = VD->getType();
441 const FunctionType *Fn = nullptr;
442 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
443 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
444 if (!Fn)
445 return;
446 CalleeKind = CK_Function;
447 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
448 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
449 CalleeKind = CK_Block;
450 } else {
451 return;
452 }
453
454 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
455 NumFormalParams = proto->getNumParams();
456 else
457 NumFormalParams = 0;
458 } else {
459 return;
460 }
461
462 // "NullPos" is the number of formal parameters at the end which
463 // effectively count as part of the variadic arguments. This is
464 // useful if you would prefer to not have *any* formal parameters,
465 // but the language forces you to have at least one.
466 unsigned NullPos = Attr->getNullPos();
467 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
468 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
469
470 // The number of arguments which should follow the sentinel.
471 unsigned NumArgsAfterSentinel = Attr->getSentinel();
472
473 // If there aren't enough arguments for all the formal parameters,
474 // the sentinel, and the args after the sentinel, complain.
475 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
476 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
477 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
478 return;
479 }
480
481 // Otherwise, find the sentinel expression.
482 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
483 if (!SentinelExpr)
484 return;
485 if (SentinelExpr->isValueDependent())
486 return;
487 if (Context.isSentinelNullExpr(E: SentinelExpr))
488 return;
489
490 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
491 // or 'NULL' if those are actually defined in the context. Only use
492 // 'nil' for ObjC methods, where it's much more likely that the
493 // variadic arguments form a list of object pointers.
494 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
495 std::string NullValue;
496 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
497 NullValue = "nil";
498 else if (getLangOpts().CPlusPlus11)
499 NullValue = "nullptr";
500 else if (PP.isMacroDefined(Id: "NULL"))
501 NullValue = "NULL";
502 else
503 NullValue = "(void*) 0";
504
505 if (MissingNilLoc.isInvalid())
506 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
507 else
508 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
509 << int(CalleeKind)
510 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
511 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
512 << int(CalleeKind) << Attr->getRange();
513}
514
515SourceRange Sema::getExprRange(Expr *E) const {
516 return E ? E->getSourceRange() : SourceRange();
517}
518
519//===----------------------------------------------------------------------===//
520// Standard Promotions and Conversions
521//===----------------------------------------------------------------------===//
522
523/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
524ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
525 // Handle any placeholder expressions which made it here.
526 if (E->hasPlaceholderType()) {
527 ExprResult result = CheckPlaceholderExpr(E);
528 if (result.isInvalid()) return ExprError();
529 E = result.get();
530 }
531
532 QualType Ty = E->getType();
533 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
534
535 if (Ty->isFunctionType()) {
536 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
537 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
538 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
539 return ExprError();
540
541 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
542 CK: CK_FunctionToPointerDecay).get();
543 } else if (Ty->isArrayType()) {
544 // In C90 mode, arrays only promote to pointers if the array expression is
545 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
546 // type 'array of type' is converted to an expression that has type 'pointer
547 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
548 // that has type 'array of type' ...". The relevant change is "an lvalue"
549 // (C90) to "an expression" (C99).
550 //
551 // C++ 4.2p1:
552 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
553 // T" can be converted to an rvalue of type "pointer to T".
554 //
555 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
556 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
557 CK: CK_ArrayToPointerDecay);
558 if (Res.isInvalid())
559 return ExprError();
560 E = Res.get();
561 }
562 }
563 return E;
564}
565
566static void CheckForNullPointerDereference(Sema &S, Expr *E) {
567 // Check to see if we are dereferencing a null pointer. If so,
568 // and if not volatile-qualified, this is undefined behavior that the
569 // optimizer will delete, so warn about it. People sometimes try to use this
570 // to get a deterministic trap and are surprised by clang's behavior. This
571 // only handles the pattern "*null", which is a very syntactic check.
572 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
573 if (UO && UO->getOpcode() == UO_Deref &&
574 UO->getSubExpr()->getType()->isPointerType()) {
575 const LangAS AS =
576 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
577 if ((!isTargetAddressSpace(AS) ||
578 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
579 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
580 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
581 !UO->getType().isVolatileQualified()) {
582 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
583 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
584 << UO->getSubExpr()->getSourceRange());
585 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
586 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
587 }
588 }
589}
590
591static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
592 SourceLocation AssignLoc,
593 const Expr* RHS) {
594 const ObjCIvarDecl *IV = OIRE->getDecl();
595 if (!IV)
596 return;
597
598 DeclarationName MemberName = IV->getDeclName();
599 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
600 if (!Member || !Member->isStr(Str: "isa"))
601 return;
602
603 const Expr *Base = OIRE->getBase();
604 QualType BaseType = Base->getType();
605 if (OIRE->isArrow())
606 BaseType = BaseType->getPointeeType();
607 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
608 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
609 ObjCInterfaceDecl *ClassDeclared = nullptr;
610 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
611 if (!ClassDeclared->getSuperClass()
612 && (*ClassDeclared->ivar_begin()) == IV) {
613 if (RHS) {
614 NamedDecl *ObjectSetClass =
615 S.LookupSingleName(S: S.TUScope,
616 Name: &S.Context.Idents.get(Name: "object_setClass"),
617 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
618 if (ObjectSetClass) {
619 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
620 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
621 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
622 Code: "object_setClass(")
623 << FixItHint::CreateReplacement(
624 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
625 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
626 }
627 else
628 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
629 } else {
630 NamedDecl *ObjectGetClass =
631 S.LookupSingleName(S: S.TUScope,
632 Name: &S.Context.Idents.get(Name: "object_getClass"),
633 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
634 if (ObjectGetClass)
635 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
636 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
637 Code: "object_getClass(")
638 << FixItHint::CreateReplacement(
639 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
640 else
641 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
642 }
643 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
644 }
645 }
646}
647
648ExprResult Sema::DefaultLvalueConversion(Expr *E) {
649 // Handle any placeholder expressions which made it here.
650 if (E->hasPlaceholderType()) {
651 ExprResult result = CheckPlaceholderExpr(E);
652 if (result.isInvalid()) return ExprError();
653 E = result.get();
654 }
655
656 // C++ [conv.lval]p1:
657 // A glvalue of a non-function, non-array type T can be
658 // converted to a prvalue.
659 if (!E->isGLValue()) return E;
660
661 QualType T = E->getType();
662 assert(!T.isNull() && "r-value conversion on typeless expression?");
663
664 // lvalue-to-rvalue conversion cannot be applied to types that decay to
665 // pointers (i.e. function or array types).
666 if (T->canDecayToPointerType())
667 return E;
668
669 // We don't want to throw lvalue-to-rvalue casts on top of
670 // expressions of certain types in C++.
671 // In HLSL LvaluetoRvalue conversion is allowed on records.
672 if (getLangOpts().CPlusPlus) {
673 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
674 (T->isDependentType() && !T->isAnyPointerType() &&
675 !T->isMemberPointerType()))
676 return E;
677 }
678
679 // The C standard is actually really unclear on this point, and
680 // DR106 tells us what the result should be but not why. It's
681 // generally best to say that void types just doesn't undergo
682 // lvalue-to-rvalue at all. Note that expressions of unqualified
683 // 'void' type are never l-values, but qualified void can be.
684 if (T->isVoidType())
685 return E;
686
687 // OpenCL usually rejects direct accesses to values of 'half' type.
688 if (getLangOpts().OpenCL &&
689 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
690 T->isHalfType()) {
691 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
692 << 0 << T;
693 return ExprError();
694 }
695
696 CheckForNullPointerDereference(S&: *this, E);
697 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
698 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
699 Name: &Context.Idents.get(Name: "object_getClass"),
700 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
701 if (ObjectGetClass)
702 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
703 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
704 << FixItHint::CreateReplacement(
705 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
706 else
707 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
708 }
709 else if (const ObjCIvarRefExpr *OIRE =
710 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
711 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
712
713 // C++ [conv.lval]p1:
714 // [...] If T is a non-class type, the type of the prvalue is the
715 // cv-unqualified version of T. Otherwise, the type of the
716 // rvalue is T.
717 //
718 // C99 6.3.2.1p2:
719 // If the lvalue has qualified type, the value has the unqualified
720 // version of the type of the lvalue; otherwise, the value has the
721 // type of the lvalue.
722 if (T.hasQualifiers())
723 T = T.getUnqualifiedType();
724
725 if (getLangOpts().HLSL)
726 if (const auto *MT = T->getAs<ConstantMatrixType>(); MT && MT->getLayout())
727 T = Context.getCanonicalType(T);
728
729 // Under the MS ABI, lock down the inheritance model now.
730 if (T->isMemberPointerType() &&
731 Context.getTargetInfo().getCXXABI().isMicrosoft())
732 (void)isCompleteType(Loc: E->getExprLoc(), T);
733
734 ExprResult Res = CheckLValueToRValueConversionOperand(E);
735 if (Res.isInvalid())
736 return Res;
737 E = Res.get();
738
739 // Loading a __weak object implicitly retains the value, so we need a cleanup to
740 // balance that.
741 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
742 Cleanup.setExprNeedsCleanups(true);
743
744 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
745 Cleanup.setExprNeedsCleanups(true);
746
747 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
748 return ExprError();
749
750 // C++ [conv.lval]p3:
751 // If T is cv std::nullptr_t, the result is a null pointer constant.
752 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
753 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
754 FPO: CurFPFeatureOverrides());
755
756 // C11 6.3.2.1p2:
757 // ... if the lvalue has atomic type, the value has the non-atomic version
758 // of the type of the lvalue ...
759 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
760 T = Atomic->getValueType().getUnqualifiedType();
761 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
762 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
763 }
764
765 return Res;
766}
767
768ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
769 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
770 if (Res.isInvalid())
771 return ExprError();
772 Res = DefaultLvalueConversion(E: Res.get());
773 if (Res.isInvalid())
774 return ExprError();
775 return Res;
776}
777
778ExprResult Sema::CallExprUnaryConversions(Expr *E) {
779 QualType Ty = E->getType();
780 ExprResult Res = E;
781 // Only do implicit cast for a function type, but not for a pointer
782 // to function type.
783 if (Ty->isFunctionType()) {
784 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
785 CK: CK_FunctionToPointerDecay);
786 if (Res.isInvalid())
787 return ExprError();
788 }
789 Res = DefaultLvalueConversion(E: Res.get());
790 if (Res.isInvalid())
791 return ExprError();
792 return Res.get();
793}
794
795/// UsualUnaryFPConversions - Promotes floating-point types according to the
796/// current language semantics.
797ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
800
801 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
802 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
803 (getLangOpts().getFPEvalMethod() !=
804 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
805 PP.getLastFPEvalPragmaLocation().isValid())) {
806 switch (EvalMethod) {
807 default:
808 llvm_unreachable("Unrecognized float evaluation method");
809 break;
810 case LangOptions::FEM_UnsetOnCommandLine:
811 llvm_unreachable("Float evaluation method should be set by now");
812 break;
813 case LangOptions::FEM_Double:
814 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
815 // Widen the expression to double.
816 return Ty->isComplexType()
817 ? ImpCastExprToType(E,
818 Type: Context.getComplexType(T: Context.DoubleTy),
819 CK: CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
821 break;
822 case LangOptions::FEM_Extended:
823 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
824 // Widen the expression to long double.
825 return Ty->isComplexType()
826 ? ImpCastExprToType(
827 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
828 CK: CK_FloatingComplexCast)
829 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
830 CK: CK_FloatingCast);
831 break;
832 }
833 }
834
835 // Half FP have to be promoted to float unless it is natively supported
836 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
837 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
838
839 return E;
840}
841
842/// UsualUnaryConversions - Performs various conversions that are common to most
843/// operators (C99 6.3). The conversions of array and function types are
844/// sometimes suppressed. For example, the array->pointer conversion doesn't
845/// apply if the array is an argument to the sizeof or address (&) operators.
846/// In these instances, this routine should *not* be called.
847ExprResult Sema::UsualUnaryConversions(Expr *E) {
848 // First, convert to an r-value.
849 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
850 if (Res.isInvalid())
851 return ExprError();
852
853 // Promote floating-point types.
854 Res = UsualUnaryFPConversions(E: Res.get());
855 if (Res.isInvalid())
856 return ExprError();
857 E = Res.get();
858
859 QualType Ty = E->getType();
860 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
861
862 // Try to perform integral promotions if the object has a theoretically
863 // promotable type.
864 if (Ty->isIntegralOrUnscopedEnumerationType()) {
865 // C99 6.3.1.1p2:
866 //
867 // The following may be used in an expression wherever an int or
868 // unsigned int may be used:
869 // - an object or expression with an integer type whose integer
870 // conversion rank is less than or equal to the rank of int
871 // and unsigned int.
872 // - A bit-field of type _Bool, int, signed int, or unsigned int.
873 //
874 // If an int can represent all values of the original type, the
875 // value is converted to an int; otherwise, it is converted to an
876 // unsigned int. These are called the integer promotions. All
877 // other types are unchanged by the integer promotions.
878
879 QualType PTy = Context.isPromotableBitField(E);
880 if (!PTy.isNull()) {
881 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
882 return E;
883 }
884 if (Context.isPromotableIntegerType(T: Ty)) {
885 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
886 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
887 return E;
888 }
889 }
890 return E;
891}
892
893/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
894/// do not have a prototype. Arguments that have type float or __fp16
895/// are promoted to double. All other argument types are converted by
896/// UsualUnaryConversions().
897ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
898 QualType Ty = E->getType();
899 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
900
901 ExprResult Res = UsualUnaryConversions(E);
902 if (Res.isInvalid())
903 return ExprError();
904 E = Res.get();
905
906 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
907 // promote to double.
908 // Note that default argument promotion applies only to float (and
909 // half/fp16); it does not apply to _Float16.
910 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
911 if (BTy && (BTy->getKind() == BuiltinType::Half ||
912 BTy->getKind() == BuiltinType::Float)) {
913 if (getLangOpts().OpenCL &&
914 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
915 if (BTy->getKind() == BuiltinType::Half) {
916 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
917 }
918 } else {
919 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
920 }
921 }
922 if (BTy &&
923 getLangOpts().getExtendIntArgs() ==
924 LangOptions::ExtendArgsKind::ExtendTo64 &&
925 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
926 Context.getTypeSizeInChars(T: BTy) <
927 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
928 E = (Ty->isUnsignedIntegerType())
929 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
930 .get()
931 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
932 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
933 "Unexpected typesize for LongLongTy");
934 }
935
936 // C++ performs lvalue-to-rvalue conversion as a default argument
937 // promotion, even on class types, but note:
938 // C++11 [conv.lval]p2:
939 // When an lvalue-to-rvalue conversion occurs in an unevaluated
940 // operand or a subexpression thereof the value contained in the
941 // referenced object is not accessed. Otherwise, if the glvalue
942 // has a class type, the conversion copy-initializes a temporary
943 // of type T from the glvalue and the result of the conversion
944 // is a prvalue for the temporary.
945 // FIXME: add some way to gate this entire thing for correctness in
946 // potentially potentially evaluated contexts.
947 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
948 ExprResult Temp = PerformCopyInitialization(
949 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
950 EqualLoc: E->getExprLoc(), Init: E);
951 if (Temp.isInvalid())
952 return ExprError();
953 E = Temp.get();
954 }
955
956 // C++ [expr.call]p7, per CWG722:
957 // An argument that has (possibly cv-qualified) type std::nullptr_t is
958 // converted to void* ([conv.ptr]).
959 // (This does not apply to C23 nullptr)
960 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
961 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
962
963 return E;
964}
965
966VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
967 if (Ty->isIncompleteType()) {
968 // C++11 [expr.call]p7:
969 // After these conversions, if the argument does not have arithmetic,
970 // enumeration, pointer, pointer to member, or class type, the program
971 // is ill-formed.
972 //
973 // Since we've already performed null pointer conversion, array-to-pointer
974 // decay and function-to-pointer decay, the only such type in C++ is cv
975 // void. This also handles initializer lists as variadic arguments.
976 if (Ty->isVoidType())
977 return VarArgKind::Invalid;
978
979 if (Ty->isObjCObjectType())
980 return VarArgKind::Invalid;
981 return VarArgKind::Valid;
982 }
983
984 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
985 return VarArgKind::Invalid;
986
987 if (Context.getTargetInfo().getTriple().isWasm() &&
988 Ty.isWebAssemblyReferenceType()) {
989 return VarArgKind::Invalid;
990 }
991
992 if (Ty.isCXX98PODType(Context))
993 return VarArgKind::Valid;
994
995 // C++11 [expr.call]p7:
996 // Passing a potentially-evaluated argument of class type (Clause 9)
997 // having a non-trivial copy constructor, a non-trivial move constructor,
998 // or a non-trivial destructor, with no corresponding parameter,
999 // is conditionally-supported with implementation-defined semantics.
1000 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1001 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
1002 if (!Record->hasNonTrivialCopyConstructor() &&
1003 !Record->hasNonTrivialMoveConstructor() &&
1004 !Record->hasNonTrivialDestructor())
1005 return VarArgKind::ValidInCXX11;
1006
1007 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1008 return VarArgKind::Valid;
1009
1010 if (Ty->isObjCObjectType())
1011 return VarArgKind::Invalid;
1012
1013 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1014 return VarArgKind::Valid;
1015
1016 if (getLangOpts().MSVCCompat)
1017 return VarArgKind::MSVCUndefined;
1018
1019 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1020 return VarArgKind::Valid;
1021
1022 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1023 // permitted to reject them. We should consider doing so.
1024 return VarArgKind::Undefined;
1025}
1026
1027void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1028 // Don't allow one to pass an Objective-C interface to a vararg.
1029 const QualType &Ty = E->getType();
1030 VarArgKind VAK = isValidVarArgType(Ty);
1031
1032 // Complain about passing non-POD types through varargs.
1033 switch (VAK) {
1034 case VarArgKind::ValidInCXX11:
1035 DiagRuntimeBehavior(
1036 Loc: E->getBeginLoc(), Statement: nullptr,
1037 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1038 [[fallthrough]];
1039 case VarArgKind::Valid:
1040 if (Ty->isRecordType()) {
1041 // This is unlikely to be what the user intended. If the class has a
1042 // 'c_str' member function, the user probably meant to call that.
1043 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1044 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1045 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1046 }
1047 break;
1048
1049 case VarArgKind::Undefined:
1050 case VarArgKind::MSVCUndefined:
1051 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1052 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1053 << getLangOpts().CPlusPlus11 << Ty << CT);
1054 break;
1055
1056 case VarArgKind::Invalid:
1057 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1058 Diag(Loc: E->getBeginLoc(),
1059 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1060 << Ty << CT;
1061 else if (Ty->isObjCObjectType())
1062 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1063 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1064 << Ty << CT);
1065 else
1066 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1067 << isa<InitListExpr>(Val: E) << Ty << CT;
1068 break;
1069 }
1070}
1071
1072ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1073 FunctionDecl *FDecl) {
1074 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1075 // Strip the unbridged-cast placeholder expression off, if applicable.
1076 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1077 (CT == VariadicCallType::Method ||
1078 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1079 E = ObjC().stripARCUnbridgedCast(e: E);
1080
1081 // Otherwise, do normal placeholder checking.
1082 } else {
1083 ExprResult ExprRes = CheckPlaceholderExpr(E);
1084 if (ExprRes.isInvalid())
1085 return ExprError();
1086 E = ExprRes.get();
1087 }
1088 }
1089
1090 ExprResult ExprRes = DefaultArgumentPromotion(E);
1091 if (ExprRes.isInvalid())
1092 return ExprError();
1093
1094 // Copy blocks to the heap.
1095 if (ExprRes.get()->getType()->isBlockPointerType())
1096 maybeExtendBlockObject(E&: ExprRes);
1097
1098 E = ExprRes.get();
1099
1100 // Diagnostics regarding non-POD argument types are
1101 // emitted along with format string checking in Sema::CheckFunctionCall().
1102 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1103 // Turn this into a trap.
1104 CXXScopeSpec SS;
1105 SourceLocation TemplateKWLoc;
1106 UnqualifiedId Name;
1107 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1108 IdLoc: E->getBeginLoc());
1109 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1110 /*HasTrailingLParen=*/true,
1111 /*IsAddressOfOperand=*/false);
1112 if (TrapFn.isInvalid())
1113 return ExprError();
1114
1115 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1116 RParenLoc: E->getEndLoc());
1117 if (Call.isInvalid())
1118 return ExprError();
1119
1120 ExprResult Comma =
1121 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1122 if (Comma.isInvalid())
1123 return ExprError();
1124 return Comma.get();
1125 }
1126
1127 if (!getLangOpts().CPlusPlus &&
1128 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1129 DiagID: diag::err_call_incomplete_argument))
1130 return ExprError();
1131
1132 return E;
1133}
1134
1135/// Convert complex integers to complex floats and real integers to
1136/// real floats as required for complex arithmetic. Helper function of
1137/// UsualArithmeticConversions()
1138///
1139/// \return false if the integer expression is an integer type and is
1140/// successfully converted to the (complex) float type.
1141static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1142 ExprResult &ComplexExpr,
1143 QualType IntTy,
1144 QualType ComplexTy,
1145 bool SkipCast) {
1146 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1147 if (SkipCast) return false;
1148 if (IntTy->isIntegerType()) {
1149 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1150 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1151 } else {
1152 assert(IntTy->isComplexIntegerType());
1153 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1154 CK: CK_IntegralComplexToFloatingComplex);
1155 }
1156 return false;
1157}
1158
1159// This handles complex/complex, complex/float, or float/complex.
1160// When both operands are complex, the shorter operand is converted to the
1161// type of the longer, and that is the type of the result. This corresponds
1162// to what is done when combining two real floating-point operands.
1163// The fun begins when size promotion occur across type domains.
1164// From H&S 6.3.4: When one operand is complex and the other is a real
1165// floating-point type, the less precise type is converted, within it's
1166// real or complex domain, to the precision of the other type. For example,
1167// when combining a "long double" with a "double _Complex", the
1168// "double _Complex" is promoted to "long double _Complex".
1169static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1170 QualType ShorterType,
1171 QualType LongerType,
1172 bool PromotePrecision) {
1173 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1174 QualType Result =
1175 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1176
1177 if (PromotePrecision) {
1178 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1179 Shorter =
1180 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1181 } else {
1182 if (LongerIsComplex)
1183 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1184 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1185 }
1186 }
1187 return Result;
1188}
1189
1190/// Handle arithmetic conversion with complex types. Helper function of
1191/// UsualArithmeticConversions()
1192static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 // Handle (complex) integer types.
1196 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1197 /*SkipCast=*/false))
1198 return LHSType;
1199 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1200 /*SkipCast=*/IsCompAssign))
1201 return RHSType;
1202
1203 // Compute the rank of the two types, regardless of whether they are complex.
1204 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1205 if (Order < 0)
1206 // Promote the precision of the LHS if not an assignment.
1207 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1208 /*PromotePrecision=*/!IsCompAssign);
1209 // Promote the precision of the RHS unless it is already the same as the LHS.
1210 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1211 /*PromotePrecision=*/Order > 0);
1212}
1213
1214/// Handle arithmetic conversion from integer to float. Helper function
1215/// of UsualArithmeticConversions()
1216static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1217 ExprResult &IntExpr,
1218 QualType FloatTy, QualType IntTy,
1219 bool ConvertFloat, bool ConvertInt) {
1220 if (IntTy->isIntegerType()) {
1221 if (ConvertInt)
1222 // Convert intExpr to the lhs floating point type.
1223 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1224 CK: CK_IntegralToFloating);
1225 return FloatTy;
1226 }
1227
1228 // Convert both sides to the appropriate complex float.
1229 assert(IntTy->isComplexIntegerType());
1230 QualType result = S.Context.getComplexType(T: FloatTy);
1231
1232 // _Complex int -> _Complex float
1233 if (ConvertInt)
1234 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1235 CK: CK_IntegralComplexToFloatingComplex);
1236
1237 // float -> _Complex float
1238 if (ConvertFloat)
1239 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1240 CK: CK_FloatingRealToComplex);
1241
1242 return result;
1243}
1244
1245/// Handle arithmethic conversion with floating point types. Helper
1246/// function of UsualArithmeticConversions()
1247static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1248 ExprResult &RHS, QualType LHSType,
1249 QualType RHSType, bool IsCompAssign) {
1250 bool LHSFloat = LHSType->isRealFloatingType();
1251 bool RHSFloat = RHSType->isRealFloatingType();
1252
1253 // N1169 4.1.4: If one of the operands has a floating type and the other
1254 // operand has a fixed-point type, the fixed-point operand
1255 // is converted to the floating type [...]
1256 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1257 if (LHSFloat)
1258 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1259 else if (!IsCompAssign)
1260 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1261 return LHSFloat ? LHSType : RHSType;
1262 }
1263
1264 // If we have two real floating types, convert the smaller operand
1265 // to the bigger result.
1266 if (LHSFloat && RHSFloat) {
1267 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1268 if (order > 0) {
1269 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1270 return LHSType;
1271 }
1272
1273 assert(order < 0 && "illegal float comparison");
1274 if (!IsCompAssign)
1275 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1276 return RHSType;
1277 }
1278
1279 if (LHSFloat) {
1280 // Half FP has to be promoted to float unless it is natively supported
1281 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1282 LHSType = S.Context.FloatTy;
1283
1284 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1285 /*ConvertFloat=*/!IsCompAssign,
1286 /*ConvertInt=*/ true);
1287 }
1288 assert(RHSFloat);
1289 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1290 /*ConvertFloat=*/ true,
1291 /*ConvertInt=*/!IsCompAssign);
1292}
1293
1294/// Diagnose attempts to convert between __float128, __ibm128 and
1295/// long double if there is no support for such conversion.
1296/// Helper function of UsualArithmeticConversions().
1297static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1298 QualType RHSType) {
1299 // No issue if either is not a floating point type.
1300 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1301 return false;
1302
1303 // No issue if both have the same 128-bit float semantics.
1304 auto *LHSComplex = LHSType->getAs<ComplexType>();
1305 auto *RHSComplex = RHSType->getAs<ComplexType>();
1306
1307 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1308 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1309
1310 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1311 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1312
1313 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1314 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1315 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1316 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1317 return false;
1318
1319 return true;
1320}
1321
1322typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1323
1324namespace {
1325/// These helper callbacks are placed in an anonymous namespace to
1326/// permit their use as function template parameters.
1327ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1328 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1329}
1330
1331ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1332 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1333 CK: CK_IntegralComplexCast);
1334}
1335}
1336
1337/// Handle integer arithmetic conversions. Helper function of
1338/// UsualArithmeticConversions()
1339template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1340static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1341 ExprResult &RHS, QualType LHSType,
1342 QualType RHSType, bool IsCompAssign) {
1343 // The rules for this case are in C99 6.3.1.8
1344 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1345 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1346 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1347 if (LHSSigned == RHSSigned) {
1348 // Same signedness; use the higher-ranked type
1349 if (order >= 0) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (order != (LHSSigned ? 1 : -1)) {
1356 // The unsigned type has greater than or equal rank to the
1357 // signed type, so use the unsigned type
1358 if (RHSSigned) {
1359 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1360 return LHSType;
1361 } else if (!IsCompAssign)
1362 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1363 return RHSType;
1364 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1365 // The two types are different widths; if we are here, that
1366 // means the signed type is larger than the unsigned type, so
1367 // use the signed type.
1368 if (LHSSigned) {
1369 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1370 return LHSType;
1371 } else if (!IsCompAssign)
1372 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1373 return RHSType;
1374 } else {
1375 // The signed type is higher-ranked than the unsigned type,
1376 // but isn't actually any bigger (like unsigned int and long
1377 // on most 32-bit systems). Use the unsigned type corresponding
1378 // to the signed type.
1379 QualType result =
1380 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1381 RHS = (*doRHSCast)(S, RHS.get(), result);
1382 if (!IsCompAssign)
1383 LHS = (*doLHSCast)(S, LHS.get(), result);
1384 return result;
1385 }
1386}
1387
1388/// Handle conversions with GCC complex int extension. Helper function
1389/// of UsualArithmeticConversions()
1390static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1391 ExprResult &RHS, QualType LHSType,
1392 QualType RHSType,
1393 bool IsCompAssign) {
1394 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1395 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1396
1397 if (LHSComplexInt && RHSComplexInt) {
1398 QualType LHSEltType = LHSComplexInt->getElementType();
1399 QualType RHSEltType = RHSComplexInt->getElementType();
1400 QualType ScalarType =
1401 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1402 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1403
1404 return S.Context.getComplexType(T: ScalarType);
1405 }
1406
1407 if (LHSComplexInt) {
1408 QualType LHSEltType = LHSComplexInt->getElementType();
1409 QualType ScalarType =
1410 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1411 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1412 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1413 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1414 CK: CK_IntegralRealToComplex);
1415
1416 return ComplexType;
1417 }
1418
1419 assert(RHSComplexInt);
1420
1421 QualType RHSEltType = RHSComplexInt->getElementType();
1422 QualType ScalarType =
1423 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1424 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1425 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1426
1427 if (!IsCompAssign)
1428 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1429 CK: CK_IntegralRealToComplex);
1430 return ComplexType;
1431}
1432
1433static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1434 ExprResult &RHS,
1435 QualType LHSType,
1436 QualType RHSType,
1437 bool IsCompAssign) {
1438
1439 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1440 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1441
1442 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1443 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1444
1445 bool LHSHasTrap =
1446 LhsOBT && LhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1448 bool RHSHasTrap =
1449 RhsOBT && RhsOBT->getBehaviorKind() ==
1450 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1451 bool LHSHasWrap =
1452 LhsOBT && LhsOBT->getBehaviorKind() ==
1453 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1454 bool RHSHasWrap =
1455 RhsOBT && RhsOBT->getBehaviorKind() ==
1456 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1459 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1460
1461 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1462 if (LHSHasTrap || RHSHasTrap)
1463 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1464 else if (LHSHasWrap || RHSHasWrap)
1465 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1466
1467 QualType LHSConvType = LHSUnderlyingType;
1468 QualType RHSConvType = RHSUnderlyingType;
1469 if (DominantBehavior) {
1470 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1471 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1472 Wrapped: LHSUnderlyingType);
1473 else
1474 LHSConvType = LHSType;
1475
1476 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1477 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1478 Wrapped: RHSUnderlyingType);
1479 else
1480 RHSConvType = RHSType;
1481 }
1482
1483 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1484 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1485}
1486
1487/// Return the rank of a given fixed point or integer type. The value itself
1488/// doesn't matter, but the values must be increasing with proper increasing
1489/// rank as described in N1169 4.1.1.
1490static unsigned GetFixedPointRank(QualType Ty) {
1491 const auto *BTy = Ty->getAs<BuiltinType>();
1492 assert(BTy && "Expected a builtin type.");
1493
1494 switch (BTy->getKind()) {
1495 case BuiltinType::ShortFract:
1496 case BuiltinType::UShortFract:
1497 case BuiltinType::SatShortFract:
1498 case BuiltinType::SatUShortFract:
1499 return 1;
1500 case BuiltinType::Fract:
1501 case BuiltinType::UFract:
1502 case BuiltinType::SatFract:
1503 case BuiltinType::SatUFract:
1504 return 2;
1505 case BuiltinType::LongFract:
1506 case BuiltinType::ULongFract:
1507 case BuiltinType::SatLongFract:
1508 case BuiltinType::SatULongFract:
1509 return 3;
1510 case BuiltinType::ShortAccum:
1511 case BuiltinType::UShortAccum:
1512 case BuiltinType::SatShortAccum:
1513 case BuiltinType::SatUShortAccum:
1514 return 4;
1515 case BuiltinType::Accum:
1516 case BuiltinType::UAccum:
1517 case BuiltinType::SatAccum:
1518 case BuiltinType::SatUAccum:
1519 return 5;
1520 case BuiltinType::LongAccum:
1521 case BuiltinType::ULongAccum:
1522 case BuiltinType::SatLongAccum:
1523 case BuiltinType::SatULongAccum:
1524 return 6;
1525 default:
1526 if (BTy->isInteger())
1527 return 0;
1528 llvm_unreachable("Unexpected fixed point or integer type");
1529 }
1530}
1531
1532/// handleFixedPointConversion - Fixed point operations between fixed
1533/// point types and integers or other fixed point types do not fall under
1534/// usual arithmetic conversion since these conversions could result in loss
1535/// of precsision (N1169 4.1.4). These operations should be calculated with
1536/// the full precision of their result type (N1169 4.1.6.2.1).
1537static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1538 QualType RHSTy) {
1539 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1540 "Expected at least one of the operands to be a fixed point type");
1541 assert((LHSTy->isFixedPointOrIntegerType() ||
1542 RHSTy->isFixedPointOrIntegerType()) &&
1543 "Special fixed point arithmetic operation conversions are only "
1544 "applied to ints or other fixed point types");
1545
1546 // If one operand has signed fixed-point type and the other operand has
1547 // unsigned fixed-point type, then the unsigned fixed-point operand is
1548 // converted to its corresponding signed fixed-point type and the resulting
1549 // type is the type of the converted operand.
1550 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1551 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1552 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1553 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1554
1555 // The result type is the type with the highest rank, whereby a fixed-point
1556 // conversion rank is always greater than an integer conversion rank; if the
1557 // type of either of the operands is a saturating fixedpoint type, the result
1558 // type shall be the saturating fixed-point type corresponding to the type
1559 // with the highest rank; the resulting value is converted (taking into
1560 // account rounding and overflow) to the precision of the resulting type.
1561 // Same ranks between signed and unsigned types are resolved earlier, so both
1562 // types are either signed or both unsigned at this point.
1563 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1564 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1565
1566 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1567
1568 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1569 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1570
1571 return ResultTy;
1572}
1573
1574/// Check that the usual arithmetic conversions can be performed on this pair of
1575/// expressions that might be of enumeration type.
1576void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1577 SourceLocation Loc,
1578 ArithConvKind ACK) {
1579 // C++2a [expr.arith.conv]p1:
1580 // If one operand is of enumeration type and the other operand is of a
1581 // different enumeration type or a floating-point type, this behavior is
1582 // deprecated ([depr.arith.conv.enum]).
1583 //
1584 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1585 // Eventually we will presumably reject these cases (in C++23 onwards?).
1586 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1587 R = RHS->getEnumCoercedType(Ctx: Context);
1588 bool LEnum = L->isUnscopedEnumerationType(),
1589 REnum = R->isUnscopedEnumerationType();
1590 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1591 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1592 (REnum && L->isFloatingType())) {
1593 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1594 : getLangOpts().CPlusPlus20
1595 ? diag::warn_arith_conv_enum_float_cxx20
1596 : diag::warn_arith_conv_enum_float)
1597 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1598 << L << R;
1599 } else if (!IsCompAssign && LEnum && REnum &&
1600 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1601 unsigned DiagID;
1602 // In C++ 26, usual arithmetic conversions between 2 different enum types
1603 // are ill-formed.
1604 if (getLangOpts().CPlusPlus26)
1605 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1606 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1607 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1608 // If either enumeration type is unnamed, it's less likely that the
1609 // user cares about this, but this situation is still deprecated in
1610 // C++2a. Use a different warning group.
1611 DiagID = getLangOpts().CPlusPlus20
1612 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1613 : diag::warn_arith_conv_mixed_anon_enum_types;
1614 } else if (ACK == ArithConvKind::Conditional) {
1615 // Conditional expressions are separated out because they have
1616 // historically had a different warning flag.
1617 DiagID = getLangOpts().CPlusPlus20
1618 ? diag::warn_conditional_mixed_enum_types_cxx20
1619 : diag::warn_conditional_mixed_enum_types;
1620 } else if (ACK == ArithConvKind::Comparison) {
1621 // Comparison expressions are separated out because they have
1622 // historically had a different warning flag.
1623 DiagID = getLangOpts().CPlusPlus20
1624 ? diag::warn_comparison_mixed_enum_types_cxx20
1625 : diag::warn_comparison_mixed_enum_types;
1626 } else {
1627 DiagID = getLangOpts().CPlusPlus20
1628 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1629 : diag::warn_arith_conv_mixed_enum_types;
1630 }
1631 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1632 << (int)ACK << L << R;
1633 }
1634}
1635
1636static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1637 Expr *RHS, SourceLocation Loc,
1638 ArithConvKind ACK) {
1639 QualType LHSType = LHS->getType().getUnqualifiedType();
1640 QualType RHSType = RHS->getType().getUnqualifiedType();
1641
1642 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1643 !RHSType->isUnicodeCharacterType())
1644 return;
1645
1646 if (ACK == ArithConvKind::Comparison) {
1647 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1648 return;
1649
1650 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1651 if (T->isChar8Type())
1652 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1653 if (T->isChar16Type())
1654 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1655 assert(T->isChar32Type());
1656 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1657 };
1658
1659 Expr::EvalResult LHSRes, RHSRes;
1660 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1661 AllowSideEffects: Expr::SE_AllowSideEffects,
1662 InConstantContext: SemaRef.isConstantEvaluatedContext());
1663 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1664 AllowSideEffects: Expr::SE_AllowSideEffects,
1665 InConstantContext: SemaRef.isConstantEvaluatedContext());
1666
1667 // Don't warn if the one known value is a representable
1668 // in the type of both expressions.
1669 if (LHSSuccess != RHSuccess) {
1670 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1671 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1672 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1673 return;
1674 }
1675
1676 if (!LHSSuccess || !RHSuccess) {
1677 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1678 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1679 << RHSType;
1680 return;
1681 }
1682
1683 llvm::APSInt LHSValue(32);
1684 LHSValue = LHSRes.Val.getInt();
1685 llvm::APSInt RHSValue(32);
1686 RHSValue = RHSRes.Val.getInt();
1687
1688 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1689 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1690 if (LHSSafe && RHSSafe)
1691 return;
1692
1693 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1694 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1695 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1696 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1697 return;
1698 }
1699
1700 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1701 return;
1702
1703 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1704 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1705 << RHSType;
1706}
1707
1708/// UsualArithmeticConversions - Performs various conversions that are common to
1709/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1710/// routine returns the first non-arithmetic type found. The client is
1711/// responsible for emitting appropriate error diagnostics.
1712QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1713 SourceLocation Loc,
1714 ArithConvKind ACK) {
1715
1716 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1717
1718 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1719
1720 if (ACK != ArithConvKind::CompAssign) {
1721 LHS = UsualUnaryConversions(E: LHS.get());
1722 if (LHS.isInvalid())
1723 return QualType();
1724 }
1725
1726 RHS = UsualUnaryConversions(E: RHS.get());
1727 if (RHS.isInvalid())
1728 return QualType();
1729
1730 // For conversion purposes, we ignore any qualifiers.
1731 // For example, "const float" and "float" are equivalent.
1732 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1733 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1734
1735 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1736 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1737 LHSType = AtomicLHS->getValueType();
1738
1739 // If both types are identical, no conversion is needed.
1740 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1741 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1742
1743 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1744 // The caller can deal with this (e.g. pointer + int).
1745 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1746 return QualType();
1747
1748 // Apply unary and bitfield promotions to the LHS's type.
1749 QualType LHSUnpromotedType = LHSType;
1750 if (Context.isPromotableIntegerType(T: LHSType))
1751 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1752 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1753 if (!LHSBitfieldPromoteTy.isNull())
1754 LHSType = LHSBitfieldPromoteTy;
1755 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1756 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1757
1758 // If both types are identical, no conversion is needed.
1759 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1760 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1761
1762 // At this point, we have two different arithmetic types.
1763
1764 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1765 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1766 return QualType();
1767
1768 // Diagnose attempts to convert between __ibm128, __float128 and long double
1769 // where such conversions currently can't be handled.
1770 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1771 return QualType();
1772
1773 // Handle complex types first (C99 6.3.1.8p1).
1774 if (LHSType->isComplexType() || RHSType->isComplexType())
1775 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1776 IsCompAssign: ACK == ArithConvKind::CompAssign);
1777
1778 // Now handle "real" floating types (i.e. float, double, long double).
1779 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1780 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1781 IsCompAssign: ACK == ArithConvKind::CompAssign);
1782
1783 // Handle GCC complex int extension.
1784 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1785 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1786 IsCompAssign: ACK == ArithConvKind::CompAssign);
1787
1788 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1789 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1790
1791 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1792 return handleOverflowBehaviorTypeConversion(
1793 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1794
1795 // Finally, we have two differing integer types.
1796 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1797 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1798}
1799
1800//===----------------------------------------------------------------------===//
1801// Semantic Analysis for various Expression Types
1802//===----------------------------------------------------------------------===//
1803
1804
1805ExprResult Sema::ActOnGenericSelectionExpr(
1806 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1807 bool PredicateIsExpr, void *ControllingExprOrType,
1808 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1809 unsigned NumAssocs = ArgTypes.size();
1810 assert(NumAssocs == ArgExprs.size());
1811
1812 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1813 for (unsigned i = 0; i < NumAssocs; ++i) {
1814 if (ArgTypes[i])
1815 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1816 else
1817 Types[i] = nullptr;
1818 }
1819
1820 // If we have a controlling type, we need to convert it from a parsed type
1821 // into a semantic type and then pass that along.
1822 if (!PredicateIsExpr) {
1823 TypeSourceInfo *ControllingType;
1824 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1825 TInfo: &ControllingType);
1826 assert(ControllingType && "couldn't get the type out of the parser");
1827 ControllingExprOrType = ControllingType;
1828 }
1829
1830 ExprResult ER = CreateGenericSelectionExpr(
1831 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1832 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1833 delete [] Types;
1834 return ER;
1835}
1836
1837// Helper function to determine type compatibility for C _Generic expressions.
1838// Multiple compatible types within the same _Generic expression is ambiguous
1839// and not valid.
1840static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1841 QualType U) {
1842 // Try to handle special types like OverflowBehaviorTypes
1843 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1844 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1845
1846 if (TOBT || UOBT) {
1847 if (TOBT && UOBT) {
1848 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1849 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1850 T2: UOBT->getUnderlyingType());
1851 return false;
1852 }
1853 return false;
1854 }
1855
1856 // We're dealing with types that don't require special handling.
1857 return Ctx.typesAreCompatible(T1: T, T2: U);
1858}
1859
1860ExprResult Sema::CreateGenericSelectionExpr(
1861 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1862 bool PredicateIsExpr, void *ControllingExprOrType,
1863 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1864 unsigned NumAssocs = Types.size();
1865 assert(NumAssocs == Exprs.size());
1866 assert(ControllingExprOrType &&
1867 "Must have either a controlling expression or a controlling type");
1868
1869 Expr *ControllingExpr = nullptr;
1870 TypeSourceInfo *ControllingType = nullptr;
1871 if (PredicateIsExpr) {
1872 // Decay and strip qualifiers for the controlling expression type, and
1873 // handle placeholder type replacement. See committee discussion from WG14
1874 // DR423.
1875 EnterExpressionEvaluationContext Unevaluated(
1876 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1877 ExprResult R = DefaultFunctionArrayLvalueConversion(
1878 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1879 if (R.isInvalid())
1880 return ExprError();
1881 ControllingExpr = R.get();
1882 } else {
1883 // The extension form uses the type directly rather than converting it.
1884 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1885 if (!ControllingType)
1886 return ExprError();
1887 }
1888
1889 bool TypeErrorFound = false,
1890 IsResultDependent = ControllingExpr
1891 ? ControllingExpr->isTypeDependent()
1892 : ControllingType->getType()->isDependentType(),
1893 ContainsUnexpandedParameterPack =
1894 ControllingExpr
1895 ? ControllingExpr->containsUnexpandedParameterPack()
1896 : ControllingType->getType()->containsUnexpandedParameterPack();
1897
1898 // The controlling expression is an unevaluated operand, so side effects are
1899 // likely unintended.
1900 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1901 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1902 Diag(Loc: ControllingExpr->getExprLoc(),
1903 DiagID: diag::warn_side_effects_unevaluated_context);
1904
1905 for (unsigned i = 0; i < NumAssocs; ++i) {
1906 if (Exprs[i]->containsUnexpandedParameterPack())
1907 ContainsUnexpandedParameterPack = true;
1908
1909 if (Types[i]) {
1910 if (Types[i]->getType()->containsUnexpandedParameterPack())
1911 ContainsUnexpandedParameterPack = true;
1912
1913 if (Types[i]->getType()->isDependentType()) {
1914 IsResultDependent = true;
1915 } else {
1916 // We relax the restriction on use of incomplete types and non-object
1917 // types with the type-based extension of _Generic. Allowing incomplete
1918 // objects means those can be used as "tags" for a type-safe way to map
1919 // to a value. Similarly, matching on function types rather than
1920 // function pointer types can be useful. However, the restriction on VM
1921 // types makes sense to retain as there are open questions about how
1922 // the selection can be made at compile time.
1923 //
1924 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1925 // complete object type other than a variably modified type."
1926 // C2y removed the requirement that an expression form must
1927 // use a complete type, though it's still as-if the type has undergone
1928 // lvalue conversion. We support this as an extension in C23 and
1929 // earlier because GCC does so.
1930 unsigned D = 0;
1931 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1932 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1933 : diag::compat_pre_c2y_assoc_type_incomplete;
1934 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1935 D = diag::err_assoc_type_nonobject;
1936 else if (Types[i]->getType()->isVariablyModifiedType())
1937 D = diag::err_assoc_type_variably_modified;
1938 else if (ControllingExpr) {
1939 // Because the controlling expression undergoes lvalue conversion,
1940 // array conversion, and function conversion, an association which is
1941 // of array type, function type, or is qualified can never be
1942 // reached. We will warn about this so users are less surprised by
1943 // the unreachable association. However, we don't have to handle
1944 // function types; that's not an object type, so it's handled above.
1945 //
1946 // The logic is somewhat different for C++ because C++ has different
1947 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1948 // If T is a non-class type, the type of the prvalue is the cv-
1949 // unqualified version of T. Otherwise, the type of the prvalue is T.
1950 // The result of these rules is that all qualified types in an
1951 // association in C are unreachable, and in C++, only qualified non-
1952 // class types are unreachable.
1953 //
1954 // NB: this does not apply when the first operand is a type rather
1955 // than an expression, because the type form does not undergo
1956 // conversion.
1957 unsigned Reason = 0;
1958 QualType QT = Types[i]->getType();
1959 if (QT->isArrayType())
1960 Reason = 1;
1961 else if (QT.hasQualifiers() &&
1962 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1963 Reason = 2;
1964
1965 if (Reason)
1966 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1967 DiagID: diag::warn_unreachable_association)
1968 << QT << (Reason - 1);
1969 }
1970
1971 if (D != 0) {
1972 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1973 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1974 if (getDiagnostics().getDiagnosticLevel(
1975 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1976 DiagnosticsEngine::Error)
1977 TypeErrorFound = true;
1978 }
1979
1980 // C11 6.5.1.1p2 "No two generic associations in the same generic
1981 // selection shall specify compatible types."
1982 for (unsigned j = i+1; j < NumAssocs; ++j)
1983 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1984 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1985 U: Types[j]->getType())) {
1986 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1987 DiagID: diag::err_assoc_compatible_types)
1988 << Types[j]->getTypeLoc().getSourceRange()
1989 << Types[j]->getType()
1990 << Types[i]->getType();
1991 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1992 DiagID: diag::note_compat_assoc)
1993 << Types[i]->getTypeLoc().getSourceRange()
1994 << Types[i]->getType();
1995 TypeErrorFound = true;
1996 }
1997 }
1998 }
1999 }
2000 if (TypeErrorFound)
2001 return ExprError();
2002
2003 // If we determined that the generic selection is result-dependent, don't
2004 // try to compute the result expression.
2005 if (IsResultDependent) {
2006 if (ControllingExpr)
2007 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2008 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2009 ContainsUnexpandedParameterPack);
2010 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2011 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2012 ContainsUnexpandedParameterPack);
2013 }
2014
2015 SmallVector<unsigned, 1> CompatIndices;
2016 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2017 // Look at the canonical type of the controlling expression in case it was a
2018 // deduced type like __auto_type. However, when issuing diagnostics, use the
2019 // type the user wrote in source rather than the canonical one.
2020 for (unsigned i = 0; i < NumAssocs; ++i) {
2021 if (!Types[i])
2022 DefaultIndex = i;
2023 else {
2024 bool Compatible;
2025 QualType ControllingQT =
2026 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2027 : ControllingType->getType().getCanonicalType();
2028 QualType AssocQT = Types[i]->getType();
2029
2030 Compatible =
2031 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2032
2033 if (Compatible)
2034 CompatIndices.push_back(Elt: i);
2035 }
2036 }
2037
2038 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2039 TypeSourceInfo *ControllingType) {
2040 // We strip parens here because the controlling expression is typically
2041 // parenthesized in macro definitions.
2042 if (ControllingExpr)
2043 ControllingExpr = ControllingExpr->IgnoreParens();
2044
2045 SourceRange SR = ControllingExpr
2046 ? ControllingExpr->getSourceRange()
2047 : ControllingType->getTypeLoc().getSourceRange();
2048 QualType QT = ControllingExpr ? ControllingExpr->getType()
2049 : ControllingType->getType();
2050
2051 return std::make_pair(x&: SR, y&: QT);
2052 };
2053
2054 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2055 // type compatible with at most one of the types named in its generic
2056 // association list."
2057 if (CompatIndices.size() > 1) {
2058 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2059 SourceRange SR = P.first;
2060 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2061 << SR << P.second << (unsigned)CompatIndices.size();
2062 for (unsigned I : CompatIndices) {
2063 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2064 DiagID: diag::note_compat_assoc)
2065 << Types[I]->getTypeLoc().getSourceRange()
2066 << Types[I]->getType();
2067 }
2068 return ExprError();
2069 }
2070
2071 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2072 // its controlling expression shall have type compatible with exactly one of
2073 // the types named in its generic association list."
2074 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2075 CompatIndices.size() == 0) {
2076 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2077 SourceRange SR = P.first;
2078 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2079 return ExprError();
2080 }
2081
2082 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2083 // type name that is compatible with the type of the controlling expression,
2084 // then the result expression of the generic selection is the expression
2085 // in that generic association. Otherwise, the result expression of the
2086 // generic selection is the expression in the default generic association."
2087 unsigned ResultIndex =
2088 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2089
2090 if (ControllingExpr) {
2091 return GenericSelectionExpr::Create(
2092 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2093 ContainsUnexpandedParameterPack, ResultIndex);
2094 }
2095 return GenericSelectionExpr::Create(
2096 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2097 ContainsUnexpandedParameterPack, ResultIndex);
2098}
2099
2100static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2101 switch (Kind) {
2102 default:
2103 llvm_unreachable("unexpected TokenKind");
2104 case tok::kw___func__:
2105 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2106 case tok::kw___FUNCTION__:
2107 return PredefinedIdentKind::Function;
2108 case tok::kw___FUNCDNAME__:
2109 return PredefinedIdentKind::FuncDName; // [MS]
2110 case tok::kw___FUNCSIG__:
2111 return PredefinedIdentKind::FuncSig; // [MS]
2112 case tok::kw_L__FUNCTION__:
2113 return PredefinedIdentKind::LFunction; // [MS]
2114 case tok::kw_L__FUNCSIG__:
2115 return PredefinedIdentKind::LFuncSig; // [MS]
2116 case tok::kw___PRETTY_FUNCTION__:
2117 return PredefinedIdentKind::PrettyFunction; // [GNU]
2118 }
2119}
2120
2121/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2122/// to determine the value of a PredefinedExpr. This can be either a
2123/// block, lambda, captured statement, function, otherwise a nullptr.
2124static Decl *getPredefinedExprDecl(Sema &S, DeclContext *DC) {
2125 auto LSI = S.FunctionScopes.rbegin();
2126
2127 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2128 if (isLambdaCallOperator(DC)) {
2129 auto E = S.FunctionScopes.rend();
2130 while (LSI != E && !isa<LambdaScopeInfo>(Val: *LSI))
2131 ++LSI;
2132 assert(LSI != E && "Should be in a lambda scope info");
2133 if (dyn_cast<LambdaScopeInfo>(Val: *LSI)->BeforeCompoundStatement)
2134 DC = DC->getParent();
2135 ++LSI;
2136 }
2137 };
2138
2139 tryAdjustLambdaContext(DC);
2140 while (DC &&
2141 !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) {
2142 DC = DC->getParent();
2143 tryAdjustLambdaContext(DC);
2144 }
2145
2146 return cast_or_null<Decl>(Val: DC);
2147}
2148
2149/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2150/// location of the token and the offset of the ud-suffix within it.
2151static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2152 unsigned Offset) {
2153 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2154 LangOpts: S.getLangOpts());
2155}
2156
2157/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2158/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2159static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2160 IdentifierInfo *UDSuffix,
2161 SourceLocation UDSuffixLoc,
2162 ArrayRef<Expr*> Args,
2163 SourceLocation LitEndLoc) {
2164 assert(Args.size() <= 2 && "too many arguments for literal operator");
2165
2166 QualType ArgTy[2];
2167 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2168 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2169 if (ArgTy[ArgIdx]->isArrayType())
2170 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2171 }
2172
2173 DeclarationName OpName =
2174 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2175 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2176 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2177
2178 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2179 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2180 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2181 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2182 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2183 return ExprError();
2184
2185 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2186}
2187
2188ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2189 // StringToks needs backing storage as it doesn't hold array elements itself
2190 std::vector<Token> ExpandedToks;
2191 if (getLangOpts().MicrosoftExt)
2192 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2193
2194 StringLiteralParser Literal(StringToks, PP,
2195 StringLiteralEvalMethod::Unevaluated);
2196 if (Literal.hadError)
2197 return ExprError();
2198
2199 SmallVector<SourceLocation, 4> StringTokLocs;
2200 for (const Token &Tok : StringToks)
2201 StringTokLocs.push_back(Elt: Tok.getLocation());
2202
2203 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2204 Kind: StringLiteralKind::Unevaluated,
2205 Pascal: false, Ty: {}, Locs: StringTokLocs);
2206
2207 if (!Literal.getUDSuffix().empty()) {
2208 SourceLocation UDSuffixLoc =
2209 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2210 Offset: Literal.getUDSuffixOffset());
2211 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2212 }
2213
2214 return Lit;
2215}
2216
2217std::vector<Token>
2218Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2219 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2220 // local macros that expand to string literals that may be concatenated.
2221 // These macros are expanded here (in Sema), because StringLiteralParser
2222 // (in Lex) doesn't know the enclosing function (because it hasn't been
2223 // parsed yet).
2224 assert(getLangOpts().MicrosoftExt);
2225
2226 // Note: Although function local macros are defined only inside functions,
2227 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2228 // expansion of macros into empty string literals without additional checks.
2229 Decl *CurrentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
2230 if (!CurrentDecl)
2231 CurrentDecl = Context.getTranslationUnitDecl();
2232
2233 std::vector<Token> ExpandedToks;
2234 ExpandedToks.reserve(n: Toks.size());
2235 for (const Token &Tok : Toks) {
2236 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2237 assert(tok::isStringLiteral(Tok.getKind()));
2238 ExpandedToks.emplace_back(args: Tok);
2239 continue;
2240 }
2241 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2242 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2243 // Stringify predefined expression
2244 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2245 << Tok.getKind();
2246 SmallString<64> Str;
2247 llvm::raw_svector_ostream OS(Str);
2248 Token &Exp = ExpandedToks.emplace_back();
2249 Exp.startToken();
2250 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2251 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2252 OS << 'L';
2253 Exp.setKind(tok::wide_string_literal);
2254 } else {
2255 Exp.setKind(tok::string_literal);
2256 }
2257 OS << '"'
2258 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2259 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2260 << '"';
2261 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2262 }
2263 return ExpandedToks;
2264}
2265
2266ExprResult
2267Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2268 assert(!StringToks.empty() && "Must have at least one string!");
2269
2270 // StringToks needs backing storage as it doesn't hold array elements itself
2271 std::vector<Token> ExpandedToks;
2272 if (getLangOpts().MicrosoftExt)
2273 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2274
2275 StringLiteralParser Literal(
2276 StringToks, PP, StringLiteralEvalMethod::Evaluated, CA_ToLiteralEncoding);
2277 if (Literal.hadError)
2278 return ExprError();
2279
2280 SmallVector<SourceLocation, 4> StringTokLocs;
2281 for (const Token &Tok : StringToks)
2282 StringTokLocs.push_back(Elt: Tok.getLocation());
2283
2284 QualType CharTy = Context.CharTy;
2285 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2286 if (Literal.isWide()) {
2287 CharTy = Context.getWideCharType();
2288 Kind = StringLiteralKind::Wide;
2289 } else if (Literal.isUTF8()) {
2290 if (getLangOpts().Char8)
2291 CharTy = Context.Char8Ty;
2292 else if (getLangOpts().C23)
2293 CharTy = Context.UnsignedCharTy;
2294 Kind = StringLiteralKind::UTF8;
2295 } else if (Literal.isUTF16()) {
2296 CharTy = Context.Char16Ty;
2297 Kind = StringLiteralKind::UTF16;
2298 } else if (Literal.isUTF32()) {
2299 CharTy = Context.Char32Ty;
2300 Kind = StringLiteralKind::UTF32;
2301 } else if (Literal.isPascal()) {
2302 CharTy = Context.UnsignedCharTy;
2303 }
2304
2305 // Warn on u8 string literals before C++20 and C23, whose type
2306 // was an array of char before but becomes an array of char8_t.
2307 // In C++20, it cannot be used where a pointer to char is expected.
2308 // In C23, it might have an unexpected value if char was signed.
2309 if (Kind == StringLiteralKind::UTF8 &&
2310 (getLangOpts().CPlusPlus
2311 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2312 : !getLangOpts().C23)) {
2313 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2314 ? diag::warn_cxx20_compat_utf8_string
2315 : diag::warn_c23_compat_utf8_string);
2316
2317 // Create removals for all 'u8' prefixes in the string literal(s). This
2318 // ensures C++20/C23 compatibility (but may change the program behavior when
2319 // built by non-Clang compilers for which the execution character set is
2320 // not always UTF-8).
2321 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2322 SourceLocation RemovalDiagLoc;
2323 for (const Token &Tok : StringToks) {
2324 if (Tok.getKind() == tok::utf8_string_literal) {
2325 if (RemovalDiagLoc.isInvalid())
2326 RemovalDiagLoc = Tok.getLocation();
2327 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2328 B: Tok.getLocation(),
2329 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2330 SM: getSourceManager(), LangOpts: getLangOpts())));
2331 }
2332 }
2333 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2334 }
2335
2336 QualType StrTy =
2337 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2338
2339 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2340 StringLiteral *Lit = StringLiteral::Create(
2341 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2342 if (Literal.getUDSuffix().empty())
2343 return Lit;
2344
2345 // We're building a user-defined literal.
2346 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2347 SourceLocation UDSuffixLoc =
2348 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2349 Offset: Literal.getUDSuffixOffset());
2350
2351 // Make sure we're allowed user-defined literals here.
2352 if (!UDLScope)
2353 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2354
2355 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2356 // operator "" X (str, len)
2357 QualType SizeType = Context.getSizeType();
2358
2359 DeclarationName OpName =
2360 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2361 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2362 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2363
2364 QualType ArgTy[] = {
2365 Context.getArrayDecayedType(T: StrTy), SizeType
2366 };
2367
2368 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2369 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2370 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2371 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2372 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2373
2374 case LOLR_Cooked: {
2375 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2376 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2377 l: StringTokLocs[0]);
2378 Expr *Args[] = { Lit, LenArg };
2379
2380 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2381 }
2382
2383 case LOLR_Template: {
2384 TemplateArgumentListInfo ExplicitArgs;
2385 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2386 TemplateArgumentLocInfo ArgInfo(Lit);
2387 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2388 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2389 ExplicitTemplateArgs: &ExplicitArgs);
2390 }
2391
2392 case LOLR_StringTemplatePack: {
2393 TemplateArgumentListInfo ExplicitArgs;
2394
2395 unsigned CharBits = Context.getIntWidth(T: CharTy);
2396 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2397 llvm::APSInt Value(CharBits, CharIsUnsigned);
2398
2399 TemplateArgument TypeArg(CharTy);
2400 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2401 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2402
2403 SourceLocation Loc = StringTokLocs.back();
2404 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2405 Value = Lit->getCodeUnit(I);
2406 TemplateArgument Arg(Context, Value, CharTy);
2407 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2408 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2409 }
2410 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2411 }
2412 case LOLR_Raw:
2413 case LOLR_ErrorNoDiagnostic:
2414 llvm_unreachable("unexpected literal operator lookup result");
2415 case LOLR_Error:
2416 return ExprError();
2417 }
2418 llvm_unreachable("unexpected literal operator lookup result");
2419}
2420
2421DeclRefExpr *
2422Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2423 SourceLocation Loc,
2424 const CXXScopeSpec *SS) {
2425 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2426 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2427}
2428
2429DeclRefExpr *
2430Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2431 const DeclarationNameInfo &NameInfo,
2432 const CXXScopeSpec *SS, NamedDecl *FoundD,
2433 SourceLocation TemplateKWLoc,
2434 const TemplateArgumentListInfo *TemplateArgs) {
2435 NestedNameSpecifierLoc NNS =
2436 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2437 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2438 TemplateArgs);
2439}
2440
2441// CUDA/HIP: Check whether a captured reference variable is referencing a
2442// host variable in a device or host device lambda.
2443static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2444 VarDecl *VD) {
2445 if (!S.getLangOpts().CUDA || !VD->hasInit())
2446 return false;
2447 assert(VD->getType()->isReferenceType());
2448
2449 // Check whether the reference variable is referencing a host variable.
2450 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2451 if (!DRE)
2452 return false;
2453 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2454 if (!Referee || !Referee->hasGlobalStorage() ||
2455 Referee->hasAttr<CUDADeviceAttr>())
2456 return false;
2457
2458 // Check whether the current function is a device or host device lambda.
2459 // Check whether the reference variable is a capture by getDeclContext()
2460 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2461 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2462 if (MD && MD->getParent()->isLambda() &&
2463 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2464 VD->getDeclContext() != MD)
2465 return true;
2466
2467 return false;
2468}
2469
2470NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2471 // A declaration named in an unevaluated operand never constitutes an odr-use.
2472 if (isUnevaluatedContext())
2473 return NOUR_Unevaluated;
2474
2475 // C++2a [basic.def.odr]p4:
2476 // A variable x whose name appears as a potentially-evaluated expression e
2477 // is odr-used by e unless [...] x is a reference that is usable in
2478 // constant expressions.
2479 // CUDA/HIP:
2480 // If a reference variable referencing a host variable is captured in a
2481 // device or host device lambda, the value of the referee must be copied
2482 // to the capture and the reference variable must be treated as odr-use
2483 // since the value of the referee is not known at compile time and must
2484 // be loaded from the captured.
2485 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2486 if (VD->getType()->isReferenceType() &&
2487 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2488 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2489 VD->isUsableInConstantExpressions(C: Context))
2490 return NOUR_Constant;
2491 }
2492
2493 // All remaining non-variable cases constitute an odr-use. For variables, we
2494 // need to wait and see how the expression is used.
2495 return NOUR_None;
2496}
2497
2498DeclRefExpr *
2499Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2500 const DeclarationNameInfo &NameInfo,
2501 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2502 SourceLocation TemplateKWLoc,
2503 const TemplateArgumentListInfo *TemplateArgs) {
2504 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2505 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2506
2507 DeclRefExpr *E = DeclRefExpr::Create(
2508 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2509 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2510 MarkDeclRefReferenced(E);
2511
2512 // C++ [except.spec]p17:
2513 // An exception-specification is considered to be needed when:
2514 // - in an expression, the function is the unique lookup result or
2515 // the selected member of a set of overloaded functions.
2516 //
2517 // We delay doing this until after we've built the function reference and
2518 // marked it as used so that:
2519 // a) if the function is defaulted, we get errors from defining it before /
2520 // instead of errors from computing its exception specification, and
2521 // b) if the function is a defaulted comparison, we can use the body we
2522 // build when defining it as input to the exception specification
2523 // computation rather than computing a new body.
2524 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2525 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2526 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2527 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2528 }
2529 }
2530
2531 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2532 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2533 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2534 getCurFunction()->recordUseOfWeak(E);
2535
2536 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2537 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2538 FD = IFD->getAnonField();
2539 if (FD) {
2540 UnusedPrivateFields.remove(X: FD);
2541 // Just in case we're building an illegal pointer-to-member.
2542 if (FD->isBitField())
2543 E->setObjectKind(OK_BitField);
2544 }
2545
2546 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2547 // designates a bit-field.
2548 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2549 if (const auto *BE = BD->getBinding())
2550 E->setObjectKind(BE->getObjectKind());
2551
2552 return E;
2553}
2554
2555// Diagnose when a macro cannot be expanded because it's a function-like macro
2556// being used as a function-like macro. Returns true if a diagnostic is emitted.
2557static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name,
2558 SourceLocation TypoLoc) {
2559
2560 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2561 if (II->hasMacroDefinition()) {
2562 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2563 if (MI && MI->isFunctionLike()) {
2564 // If the identifier is immediately followed by '(', the user did
2565 // attempt to invoke it as a function-like macro; the failure is
2566 // for some other reason (e.g. wrong argument count), which the
2567 // preprocessor already diagnosed separately. Don't suggest adding
2568 // parens in that case, since they're already there.
2569 SourceManager &SM = SemaRef.getSourceManager();
2570 const LangOptions &LangOpts = SemaRef.getLangOpts();
2571 std::optional<Token> NextTok =
2572 Lexer::findNextToken(Loc: TypoLoc, SM, LangOpts);
2573 if (NextTok && NextTok->is(K: tok::l_paren))
2574 return false;
2575 SemaRef.Diag(Loc: TypoLoc,
2576 DiagID: diag::err_undeclared_var_use_suggest_func_like_macro)
2577 << II->getName();
2578 SemaRef.Diag(Loc: MI->getDefinitionLoc(),
2579 DiagID: diag::note_function_like_macro_requires_parens)
2580 << II->getName();
2581 return true;
2582 }
2583 }
2584 }
2585 return false;
2586}
2587
2588void
2589Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2590 TemplateArgumentListInfo &Buffer,
2591 DeclarationNameInfo &NameInfo,
2592 const TemplateArgumentListInfo *&TemplateArgs) {
2593 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2594 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2595 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2596
2597 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2598 Id.TemplateId->NumArgs);
2599 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2600
2601 TemplateName TName = Id.TemplateId->Template.get();
2602 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2603 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2604 TemplateArgs = &Buffer;
2605 } else {
2606 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2607 TemplateArgs = nullptr;
2608 }
2609}
2610
2611bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2612 // During a default argument instantiation the CurContext points
2613 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2614 // function parameter list, hence add an explicit check.
2615 bool isDefaultArgument =
2616 !CodeSynthesisContexts.empty() &&
2617 CodeSynthesisContexts.back().Kind ==
2618 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2619 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2620 bool isInstance = CurMethod && CurMethod->isInstance() &&
2621 R.getNamingClass() == CurMethod->getParent() &&
2622 !isDefaultArgument;
2623
2624 // There are two ways we can find a class-scope declaration during template
2625 // instantiation that we did not find in the template definition: if it is a
2626 // member of a dependent base class, or if it is declared after the point of
2627 // use in the same class. Distinguish these by comparing the class in which
2628 // the member was found to the naming class of the lookup.
2629 unsigned DiagID = diag::err_found_in_dependent_base;
2630 unsigned NoteID = diag::note_member_declared_at;
2631 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2632 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2633 : diag::err_found_later_in_class;
2634 } else if (getLangOpts().MSVCCompat) {
2635 DiagID = diag::ext_found_in_dependent_base;
2636 NoteID = diag::note_dependent_member_use;
2637 }
2638
2639 if (isInstance) {
2640 // Give a code modification hint to insert 'this->'.
2641 Diag(Loc: R.getNameLoc(), DiagID)
2642 << R.getLookupName()
2643 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2644 CheckCXXThisCapture(Loc: R.getNameLoc());
2645 } else {
2646 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2647 // they're not shadowed).
2648 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2649 }
2650
2651 for (const NamedDecl *D : R)
2652 Diag(Loc: D->getLocation(), DiagID: NoteID);
2653
2654 // Return true if we are inside a default argument instantiation
2655 // and the found name refers to an instance member function, otherwise
2656 // the caller will try to create an implicit member call and this is wrong
2657 // for default arguments.
2658 //
2659 // FIXME: Is this special case necessary? We could allow the caller to
2660 // diagnose this.
2661 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2662 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2663 return true;
2664 }
2665
2666 // Tell the callee to try to recover.
2667 return false;
2668}
2669
2670bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2671 CorrectionCandidateCallback &CCC,
2672 TemplateArgumentListInfo *ExplicitTemplateArgs,
2673 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2674 DeclarationName Name = R.getLookupName();
2675 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2676
2677 unsigned diagnostic = diag::err_undeclared_var_use;
2678 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2679 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2680 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2681 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2682 diagnostic = diag::err_undeclared_use;
2683 diagnostic_suggest = diag::err_undeclared_use_suggest;
2684 }
2685
2686 // If the original lookup was an unqualified lookup, fake an
2687 // unqualified lookup. This is useful when (for example) the
2688 // original lookup would not have found something because it was a
2689 // dependent name.
2690 DeclContext *DC =
2691 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2692 while (DC) {
2693 if (isa<CXXRecordDecl>(Val: DC)) {
2694 if (ExplicitTemplateArgs) {
2695 if (LookupTemplateName(
2696 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2697 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2698 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2699 return true;
2700 } else {
2701 LookupQualifiedName(R, LookupCtx: DC);
2702 }
2703
2704 if (!R.empty()) {
2705 // Don't give errors about ambiguities in this lookup.
2706 R.suppressDiagnostics();
2707
2708 // If there's a best viable function among the results, only mention
2709 // that one in the notes.
2710 OverloadCandidateSet Candidates(R.getNameLoc(),
2711 OverloadCandidateSet::CSK_Normal);
2712 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2713 OverloadCandidateSet::iterator Best;
2714 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2715 OR_Success) {
2716 R.clear();
2717 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2718 R.resolveKind();
2719 }
2720
2721 return DiagnoseDependentMemberLookup(R);
2722 }
2723
2724 R.clear();
2725 }
2726
2727 DC = DC->getLookupParent();
2728 }
2729
2730 // We didn't find anything, so try to correct for a typo.
2731 TypoCorrection Corrected;
2732 if (S && (Corrected =
2733 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2734 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2735 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2736 bool DroppedSpecifier =
2737 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2738 R.setLookupName(Corrected.getCorrection());
2739
2740 bool AcceptableWithRecovery = false;
2741 bool AcceptableWithoutRecovery = false;
2742 NamedDecl *ND = Corrected.getFoundDecl();
2743 if (ND) {
2744 if (Corrected.isOverloaded()) {
2745 OverloadCandidateSet OCS(R.getNameLoc(),
2746 OverloadCandidateSet::CSK_Normal);
2747 OverloadCandidateSet::iterator Best;
2748 for (NamedDecl *CD : Corrected) {
2749 if (FunctionTemplateDecl *FTD =
2750 dyn_cast<FunctionTemplateDecl>(Val: CD))
2751 AddTemplateOverloadCandidate(
2752 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2753 Args, CandidateSet&: OCS);
2754 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2755 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2756 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2757 Args, CandidateSet&: OCS);
2758 }
2759 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2760 case OR_Success:
2761 ND = Best->FoundDecl;
2762 Corrected.setCorrectionDecl(ND);
2763 break;
2764 default:
2765 // FIXME: Arbitrarily pick the first declaration for the note.
2766 Corrected.setCorrectionDecl(ND);
2767 break;
2768 }
2769 }
2770 R.addDecl(D: ND);
2771 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2772 CXXRecordDecl *Record =
2773 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2774 if (!Record)
2775 Record = cast<CXXRecordDecl>(
2776 Val: ND->getDeclContext()->getRedeclContext());
2777 R.setNamingClass(Record);
2778 }
2779
2780 auto *UnderlyingND = ND->getUnderlyingDecl();
2781 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2782 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2783 // FIXME: If we ended up with a typo for a type name or
2784 // Objective-C class name, we're in trouble because the parser
2785 // is in the wrong place to recover. Suggest the typo
2786 // correction, but don't make it a fix-it since we're not going
2787 // to recover well anyway.
2788 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2789 getAsTypeTemplateDecl(D: UnderlyingND) ||
2790 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2791 } else {
2792 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2793 // because we aren't able to recover.
2794 AcceptableWithoutRecovery = true;
2795 }
2796
2797 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2798 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2799 ? diag::note_implicit_param_decl
2800 : diag::note_previous_decl;
2801 if (SS.isEmpty())
2802 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2803 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2804 else
2805 diagnoseTypo(Correction: Corrected,
2806 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2807 << Name << computeDeclContext(SS, EnteringContext: false)
2808 << DroppedSpecifier << NameRange,
2809 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2810
2811 if (Corrected.WillReplaceSpecifier()) {
2812 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2813 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2814 SS.MakeTrivial(Context, Qualifier: NNS,
2815 R: NNS ? NameRange.getBegin() : SourceRange());
2816 }
2817
2818 // Tell the callee whether to try to recover.
2819 return !AcceptableWithRecovery;
2820 }
2821 }
2822 R.clear();
2823
2824 if (diagnoseFunctionLikeMacro(SemaRef, Name, TypoLoc: R.getNameLoc()))
2825 return true;
2826
2827 // Emit a special diagnostic for failed member lookups.
2828 // FIXME: computing the declaration context might fail here (?)
2829 if (!SS.isEmpty()) {
2830 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2831 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2832 return true;
2833 }
2834
2835 // Give up, we can't recover.
2836 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2837 return true;
2838}
2839
2840/// In Microsoft mode, if we are inside a template class whose parent class has
2841/// dependent base classes, and we can't resolve an unqualified identifier, then
2842/// assume the identifier is a member of a dependent base class. We can only
2843/// recover successfully in static methods, instance methods, and other contexts
2844/// where 'this' is available. This doesn't precisely match MSVC's
2845/// instantiation model, but it's close enough.
2846static Expr *
2847recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2848 DeclarationNameInfo &NameInfo,
2849 SourceLocation TemplateKWLoc,
2850 const TemplateArgumentListInfo *TemplateArgs) {
2851 // Only try to recover from lookup into dependent bases in static methods or
2852 // contexts where 'this' is available.
2853 QualType ThisType = S.getCurrentThisType();
2854 const CXXRecordDecl *RD = nullptr;
2855 if (!ThisType.isNull())
2856 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2857 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2858 RD = MD->getParent();
2859 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2860 return nullptr;
2861
2862 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2863 // is available, suggest inserting 'this->' as a fixit.
2864 SourceLocation Loc = NameInfo.getLoc();
2865 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2866 DB << NameInfo.getName() << RD;
2867
2868 if (!ThisType.isNull()) {
2869 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2870 return CXXDependentScopeMemberExpr::Create(
2871 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2872 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2873 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2874 }
2875
2876 // Synthesize a fake NNS that points to the derived class. This will
2877 // perform name lookup during template instantiation.
2878 CXXScopeSpec SS;
2879 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2880 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2881 return DependentScopeDeclRefExpr::Create(
2882 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2883 TemplateArgs);
2884}
2885
2886ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2887 SourceLocation TemplateKWLoc,
2888 UnqualifiedId &Id, bool HasTrailingLParen,
2889 bool IsAddressOfOperand,
2890 CorrectionCandidateCallback *CCC,
2891 bool IsInlineAsmIdentifier) {
2892 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2893 "cannot be direct & operand and have a trailing lparen");
2894 if (SS.isInvalid())
2895 return ExprError();
2896
2897 TemplateArgumentListInfo TemplateArgsBuffer;
2898
2899 // Decompose the UnqualifiedId into the following data.
2900 DeclarationNameInfo NameInfo;
2901 const TemplateArgumentListInfo *TemplateArgs;
2902 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2903
2904 DeclarationName Name = NameInfo.getName();
2905 IdentifierInfo *II = Name.getAsIdentifierInfo();
2906 SourceLocation NameLoc = NameInfo.getLoc();
2907
2908 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId &&
2909 Id.TemplateId->Template)
2910 if (TemplateName TN = Id.TemplateId->Template.get();
2911 TN.getAsPackIndexingTemplate())
2912 return CheckVarOrConceptTemplateTemplateId(NameInfo, Template: TN, TemplateArgs);
2913
2914 if (II && II->isEditorPlaceholder()) {
2915 // FIXME: When typed placeholders are supported we can create a typed
2916 // placeholder expression node.
2917 return ExprError();
2918 }
2919
2920 // This specially handles arguments of attributes appertains to a type of C
2921 // struct field such that the name lookup within a struct finds the member
2922 // name, which is not the case for other contexts in C.
2923 // A late-parsed attribute on a function pointer field has the pointee's
2924 // parameters in the struct's scope too; as when the attribute was written, a
2925 // parameter shadows a field of the same name.
2926 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope() &&
2927 llvm::none_of(Range: S->decls(), P: [&](Decl *D) {
2928 return isa<ParmVarDecl>(Val: D) &&
2929 cast<ParmVarDecl>(Val: D)->getDeclName() == NameInfo.getName();
2930 })) {
2931 // See if this is reference to a field of struct.
2932 LookupResult R(*this, NameInfo, LookupMemberName);
2933 // LookupName handles a name lookup from within anonymous struct.
2934 if (LookupName(R, S)) {
2935 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2936 QualType type = VD->getType().getNonReferenceType();
2937 // This will eventually be translated into MemberExpr upon
2938 // the use of instantiated struct fields.
2939 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2940 }
2941 }
2942 }
2943
2944 // Perform the required lookup.
2945 LookupResult R(*this, NameInfo,
2946 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2947 ? LookupObjCImplicitSelfParam
2948 : LookupOrdinaryName);
2949 if (TemplateKWLoc.isValid() || TemplateArgs) {
2950 // Lookup the template name again to correctly establish the context in
2951 // which it was found. This is really unfortunate as we already did the
2952 // lookup to determine that it was a template name in the first place. If
2953 // this becomes a performance hit, we can work harder to preserve those
2954 // results until we get here but it's likely not worth it.
2955 AssumedTemplateKind AssumedTemplate;
2956 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2957 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2958 ATK: &AssumedTemplate))
2959 return ExprError();
2960
2961 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2962 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2963 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2964 } else {
2965 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2966 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2967 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2968
2969 // If the result might be in a dependent base class, this is a dependent
2970 // id-expression.
2971 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2972 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2973 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2974
2975 // If this reference is in an Objective-C method, then we need to do
2976 // some special Objective-C lookup, too.
2977 if (IvarLookupFollowUp) {
2978 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2979 if (E.isInvalid())
2980 return ExprError();
2981
2982 if (Expr *Ex = E.getAs<Expr>())
2983 return Ex;
2984 }
2985 }
2986
2987 if (R.isAmbiguous())
2988 return ExprError();
2989
2990 // This could be an implicitly declared function reference if the language
2991 // mode allows it as a feature.
2992 if (R.empty() && HasTrailingLParen && II &&
2993 getLangOpts().implicitFunctionsAllowed()) {
2994 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2995 if (D) R.addDecl(D);
2996 }
2997
2998 // Determine whether this name might be a candidate for
2999 // argument-dependent lookup.
3000 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
3001
3002 if (R.empty() && !ADL) {
3003 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
3004 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
3005 TemplateKWLoc, TemplateArgs))
3006 return E;
3007 }
3008
3009 // Don't diagnose an empty lookup for inline assembly.
3010 if (IsInlineAsmIdentifier)
3011 return ExprError();
3012
3013 // If this name wasn't predeclared and if this is not a function
3014 // call, diagnose the problem.
3015 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3016 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3017 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3018 "Typo correction callback misconfigured");
3019 if (CCC) {
3020 // Make sure the callback knows what the typo being diagnosed is.
3021 CCC->setTypoName(II);
3022 if (SS.isValid())
3023 CCC->setTypoNNS(SS.getScopeRep());
3024 }
3025 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3026 // a template name, but we happen to have always already looked up the name
3027 // before we get here if it must be a template name.
3028 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
3029 Args: {}, LookupCtx: nullptr))
3030 return ExprError();
3031
3032 assert(!R.empty() &&
3033 "DiagnoseEmptyLookup returned false but added no results");
3034
3035 // If we found an Objective-C instance variable, let
3036 // LookupInObjCMethod build the appropriate expression to
3037 // reference the ivar.
3038 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3039 R.clear();
3040 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
3041 // In a hopelessly buggy code, Objective-C instance variable
3042 // lookup fails and no expression will be built to reference it.
3043 if (!E.isInvalid() && !E.get())
3044 return ExprError();
3045 return E;
3046 }
3047 }
3048
3049 // This is guaranteed from this point on.
3050 assert(!R.empty() || ADL);
3051
3052 // Check whether this might be a C++ implicit instance member access.
3053 // C++ [class.mfct.non-static]p3:
3054 // When an id-expression that is not part of a class member access
3055 // syntax and not used to form a pointer to member is used in the
3056 // body of a non-static member function of class X, if name lookup
3057 // resolves the name in the id-expression to a non-static non-type
3058 // member of some class C, the id-expression is transformed into a
3059 // class member access expression using (*this) as the
3060 // postfix-expression to the left of the . operator.
3061 //
3062 // But we don't actually need to do this for '&' operands if R
3063 // resolved to a function or overloaded function set, because the
3064 // expression is ill-formed if it actually works out to be a
3065 // non-static member function:
3066 //
3067 // C++ [expr.ref]p4:
3068 // Otherwise, if E1.E2 refers to a non-static member function. . .
3069 // [t]he expression can be used only as the left-hand operand of a
3070 // member function call.
3071 //
3072 // There are other safeguards against such uses, but it's important
3073 // to get this right here so that we don't end up making a
3074 // spuriously dependent expression if we're inside a dependent
3075 // instance method.
3076 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3077 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3078 S);
3079
3080 if (TemplateArgs || TemplateKWLoc.isValid()) {
3081
3082 // In C++1y, if this is a variable template id, then check it
3083 // in BuildTemplateIdExpr().
3084 // The single lookup result must be a variable template declaration.
3085 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3086 (Id.TemplateId->Kind == TNK_Var_template ||
3087 Id.TemplateId->Kind == TNK_Concept_template)) {
3088 assert(R.getAsSingle<TemplateDecl>() &&
3089 "There should only be one declaration found.");
3090 }
3091
3092 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3093 }
3094
3095 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3096}
3097
3098ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3099 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3100 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3101 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3102 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3103
3104 if (R.isAmbiguous())
3105 return ExprError();
3106
3107 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3108 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3109 NameInfo, /*TemplateArgs=*/nullptr);
3110
3111 if (R.empty()) {
3112 // Don't diagnose problems with invalid record decl, the secondary no_member
3113 // diagnostic during template instantiation is likely bogus, e.g. if a class
3114 // is invalid because it's derived from an invalid base class, then missing
3115 // members were likely supposed to be inherited.
3116 DeclContext *DC = computeDeclContext(SS);
3117 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3118 if (CD->isInvalidDecl() || CD->isBeingDefined())
3119 return ExprError();
3120 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3121 << NameInfo.getName() << DC << SS.getRange();
3122 return ExprError();
3123 }
3124
3125 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3126 QualType ET;
3127 TypeLocBuilder TLB;
3128 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3129 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3130 Qualifier: SS.getScopeRep(), TD: TagD,
3131 /*OwnsTag=*/false);
3132 auto TL = TLB.push<TagTypeLoc>(T: ET);
3133 TL.setElaboratedKeywordLoc(SourceLocation());
3134 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3135 TL.setNameLoc(NameInfo.getLoc());
3136 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3137 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3138 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3139 TLB.push<TypedefTypeLoc>(T: ET).set(
3140 /*ElaboratedKeywordLoc=*/SourceLocation(),
3141 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3142 } else {
3143 // FIXME: What else can appear here?
3144 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3145 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3146 assert(SS.isEmpty());
3147 }
3148
3149 // Diagnose a missing typename if this resolved unambiguously to a type in
3150 // a dependent context. If we can recover with a type, downgrade this to
3151 // a warning in Microsoft compatibility mode.
3152 unsigned DiagID = diag::err_typename_missing;
3153 if (RecoveryTSI && getLangOpts().MSVCCompat)
3154 DiagID = diag::ext_typename_missing;
3155 SourceLocation Loc = SS.getBeginLoc();
3156 auto D = Diag(Loc, DiagID);
3157 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3158
3159 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3160 // context.
3161 if (!RecoveryTSI)
3162 return ExprError();
3163
3164 // Only issue the fixit if we're prepared to recover.
3165 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3166
3167 // Recover by pretending this was an elaborated type.
3168 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3169
3170 return ExprEmpty();
3171 }
3172
3173 // If necessary, build an implicit class member access.
3174 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3175 return BuildPossibleImplicitMemberExpr(SS,
3176 /*TemplateKWLoc=*/SourceLocation(),
3177 R, /*TemplateArgs=*/nullptr,
3178 /*S=*/nullptr);
3179
3180 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3181}
3182
3183ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3184 NestedNameSpecifier Qualifier,
3185 NamedDecl *FoundDecl,
3186 NamedDecl *Member) {
3187 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3188 if (!RD)
3189 return From;
3190
3191 QualType DestRecordType;
3192 QualType DestType;
3193 QualType FromRecordType;
3194 QualType FromType = From->getType();
3195 bool PointerConversions = false;
3196 if (isa<FieldDecl>(Val: Member)) {
3197 DestRecordType = Context.getCanonicalTagType(TD: RD);
3198 auto FromPtrType = FromType->getAs<PointerType>();
3199 DestRecordType = Context.getAddrSpaceQualType(
3200 T: DestRecordType, AddressSpace: FromPtrType
3201 ? FromType->getPointeeType().getAddressSpace()
3202 : FromType.getAddressSpace());
3203
3204 if (FromPtrType) {
3205 DestType = Context.getPointerType(T: DestRecordType);
3206 FromRecordType = FromPtrType->getPointeeType();
3207 PointerConversions = true;
3208 } else {
3209 DestType = DestRecordType;
3210 FromRecordType = FromType;
3211 }
3212 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3213 if (!Method->isImplicitObjectMemberFunction())
3214 return From;
3215
3216 DestType = Method->getThisType().getNonReferenceType();
3217 DestRecordType = Method->getFunctionObjectParameterType();
3218
3219 if (FromType->getAs<PointerType>()) {
3220 FromRecordType = FromType->getPointeeType();
3221 PointerConversions = true;
3222 } else {
3223 FromRecordType = FromType;
3224 DestType = DestRecordType;
3225 }
3226
3227 LangAS FromAS = FromRecordType.getAddressSpace();
3228 LangAS DestAS = DestRecordType.getAddressSpace();
3229 if (FromAS != DestAS) {
3230 QualType FromRecordTypeWithoutAS =
3231 Context.removeAddrSpaceQualType(T: FromRecordType);
3232 QualType FromTypeWithDestAS =
3233 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3234 if (PointerConversions)
3235 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3236 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3237 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3238 .get();
3239 }
3240 } else {
3241 // No conversion necessary.
3242 return From;
3243 }
3244
3245 if (DestType->isDependentType() || FromType->isDependentType())
3246 return From;
3247
3248 // If the unqualified types are the same, no conversion is necessary.
3249 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3250 return From;
3251
3252 SourceRange FromRange = From->getSourceRange();
3253 SourceLocation FromLoc = FromRange.getBegin();
3254
3255 ExprValueKind VK = From->getValueKind();
3256
3257 // C++ [class.member.lookup]p8:
3258 // [...] Ambiguities can often be resolved by qualifying a name with its
3259 // class name.
3260 //
3261 // If the member was a qualified name and the qualified referred to a
3262 // specific base subobject type, we'll cast to that intermediate type
3263 // first and then to the object in which the member is declared. That allows
3264 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3265 //
3266 // class Base { public: int x; };
3267 // class Derived1 : public Base { };
3268 // class Derived2 : public Base { };
3269 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3270 //
3271 // void VeryDerived::f() {
3272 // x = 17; // error: ambiguous base subobjects
3273 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3274 // }
3275 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3276 QualType QType = QualType(Qualifier.getAsType(), 0);
3277 assert(QType->isRecordType() && "lookup done with non-record type");
3278
3279 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3280
3281 // In C++98, the qualifier type doesn't actually have to be a base
3282 // type of the object type, in which case we just ignore it.
3283 // Otherwise build the appropriate casts.
3284 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3285 CXXCastPath BasePath;
3286 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3287 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3288 return ExprError();
3289
3290 if (PointerConversions)
3291 QType = Context.getPointerType(T: QType);
3292 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3293 VK, BasePath: &BasePath).get();
3294
3295 FromType = QType;
3296 FromRecordType = QRecordType;
3297
3298 // If the qualifier type was the same as the destination type,
3299 // we're done.
3300 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3301 return From;
3302 }
3303 }
3304
3305 CXXCastPath BasePath;
3306 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3307 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3308 /*IgnoreAccess=*/true))
3309 return ExprError();
3310
3311 // Propagate qualifiers to base subobjects as per:
3312 // C++ [basic.type.qualifier]p1.2:
3313 // A volatile object is [...] a subobject of a volatile object.
3314 Qualifiers FromTypeQuals = FromType.getQualifiers();
3315 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3316 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3317
3318 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3319 BasePath: &BasePath);
3320}
3321
3322bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3323 const LookupResult &R,
3324 bool HasTrailingLParen) {
3325 // Only when used directly as the postfix-expression of a call.
3326 if (!HasTrailingLParen)
3327 return false;
3328
3329 // Never if a scope specifier was provided.
3330 if (SS.isNotEmpty())
3331 return false;
3332
3333 // Only in C++ or ObjC++.
3334 if (!getLangOpts().CPlusPlus)
3335 return false;
3336
3337 // Turn off ADL when we find certain kinds of declarations during
3338 // normal lookup:
3339 for (const NamedDecl *D : R) {
3340 // C++0x [basic.lookup.argdep]p3:
3341 // -- a declaration of a class member
3342 // Since using decls preserve this property, we check this on the
3343 // original decl.
3344 if (D->isCXXClassMember())
3345 return false;
3346
3347 // C++0x [basic.lookup.argdep]p3:
3348 // -- a block-scope function declaration that is not a
3349 // using-declaration
3350 // NOTE: we also trigger this for function templates (in fact, we
3351 // don't check the decl type at all, since all other decl types
3352 // turn off ADL anyway).
3353 if (isa<UsingShadowDecl>(Val: D))
3354 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3355 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3356 return false;
3357
3358 // C++0x [basic.lookup.argdep]p3:
3359 // -- a declaration that is neither a function or a function
3360 // template
3361 // And also for builtin functions.
3362 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3363 // But also builtin functions.
3364 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3365 return false;
3366 } else if (!isa<FunctionTemplateDecl>(Val: D))
3367 return false;
3368 }
3369
3370 return true;
3371}
3372
3373
3374/// Diagnoses obvious problems with the use of the given declaration
3375/// as an expression. This is only actually called for lookups that
3376/// were not overloaded, and it doesn't promise that the declaration
3377/// will in fact be used.
3378static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3379 bool AcceptInvalid) {
3380 if (D->isInvalidDecl() && !AcceptInvalid)
3381 return true;
3382
3383 if (isa<TypedefNameDecl>(Val: D)) {
3384 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3385 return true;
3386 }
3387
3388 if (isa<ObjCInterfaceDecl>(Val: D)) {
3389 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3390 return true;
3391 }
3392
3393 if (isa<NamespaceDecl>(Val: D)) {
3394 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3395 return true;
3396 }
3397
3398 return false;
3399}
3400
3401// Certain multiversion types should be treated as overloaded even when there is
3402// only one result.
3403static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3404 assert(R.isSingleResult() && "Expected only a single result");
3405 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3406 return FD &&
3407 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3408}
3409
3410ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3411 LookupResult &R, bool NeedsADL,
3412 bool AcceptInvalidDecl) {
3413 // If this is a single, fully-resolved result and we don't need ADL,
3414 // just build an ordinary singleton decl ref.
3415 if (!NeedsADL && R.isSingleResult() &&
3416 !R.getAsSingle<FunctionTemplateDecl>() &&
3417 !ShouldLookupResultBeMultiVersionOverload(R))
3418 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3419 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3420 AcceptInvalidDecl);
3421
3422 // We only need to check the declaration if there's exactly one
3423 // result, because in the overloaded case the results can only be
3424 // functions and function templates.
3425 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3426 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3427 AcceptInvalid: AcceptInvalidDecl))
3428 return ExprError();
3429
3430 // Otherwise, just build an unresolved lookup expression. Suppress
3431 // any lookup-related diagnostics; we'll hash these out later, when
3432 // we've picked a target.
3433 R.suppressDiagnostics();
3434
3435 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3436 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3437 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3438 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3439
3440 return ULE;
3441}
3442
3443ExprResult Sema::BuildDeclarationNameExpr(
3444 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3445 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3446 bool AcceptInvalidDecl) {
3447 assert(D && "Cannot refer to a NULL declaration");
3448 assert(!isa<FunctionTemplateDecl>(D) &&
3449 "Cannot refer unambiguously to a function template");
3450
3451 SourceLocation Loc = NameInfo.getLoc();
3452 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3453 // Recovery from invalid cases (e.g. D is an invalid Decl).
3454 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3455 // diagnostics, as invalid decls use int as a fallback type.
3456 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3457 }
3458
3459 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3460 // Specifically diagnose references to class templates that are missing
3461 // a template argument list.
3462 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3463 return ExprError();
3464 }
3465
3466 // Make sure that we're referring to a value.
3467 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3468 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3469 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3470 return ExprError();
3471 }
3472
3473 // Check whether this declaration can be used. Note that we suppress
3474 // this check when we're going to perform argument-dependent lookup
3475 // on this function name, because this might not be the function
3476 // that overload resolution actually selects.
3477 if (DiagnoseUseOfDecl(D, Locs: Loc))
3478 return ExprError();
3479
3480 auto *VD = cast<ValueDecl>(Val: D);
3481
3482 // Only create DeclRefExpr's for valid Decl's.
3483 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3484 return ExprError();
3485
3486 // Handle members of anonymous structs and unions. If we got here,
3487 // and the reference is to a class member indirect field, then this
3488 // must be the subject of a pointer-to-member expression.
3489 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3490 IndirectField && !IndirectField->isCXXClassMember())
3491 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3492 indirectField: IndirectField);
3493
3494 QualType type = VD->getType();
3495 if (type.isNull())
3496 return ExprError();
3497 ExprValueKind valueKind = VK_PRValue;
3498
3499 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3500 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3501 // is expanded by some outer '...' in the context of the use.
3502 type = type.getNonPackExpansionType();
3503
3504 switch (D->getKind()) {
3505 // Ignore all the non-ValueDecl kinds.
3506#define ABSTRACT_DECL(kind)
3507#define VALUE(type, base)
3508#define DECL(type, base) case Decl::type:
3509#include "clang/AST/DeclNodes.inc"
3510 llvm_unreachable("invalid value decl kind");
3511
3512 // These shouldn't make it here.
3513 case Decl::ObjCAtDefsField:
3514 llvm_unreachable("forming non-member reference to ivar?");
3515
3516 // Enum constants are always r-values and never references.
3517 // Unresolved using declarations are dependent.
3518 case Decl::EnumConstant:
3519 case Decl::UnresolvedUsingValue:
3520 case Decl::OMPDeclareReduction:
3521 case Decl::OMPDeclareMapper:
3522 valueKind = VK_PRValue;
3523 break;
3524
3525 // Fields and indirect fields that got here must be for
3526 // pointer-to-member expressions; we just call them l-values for
3527 // internal consistency, because this subexpression doesn't really
3528 // exist in the high-level semantics.
3529 case Decl::Field:
3530 case Decl::IndirectField:
3531 case Decl::ObjCIvar:
3532 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3533 "building reference to field in C?");
3534
3535 // These can't have reference type in well-formed programs, but
3536 // for internal consistency we do this anyway.
3537 type = type.getNonReferenceType();
3538 valueKind = VK_LValue;
3539 break;
3540
3541 // Non-type template parameters are either l-values or r-values
3542 // depending on the type.
3543 case Decl::NonTypeTemplateParm: {
3544 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3545 type = reftype->getPointeeType();
3546 valueKind = VK_LValue; // even if the parameter is an r-value reference
3547 break;
3548 }
3549
3550 // [expr.prim.id.unqual]p2:
3551 // If the entity is a template parameter object for a template
3552 // parameter of type T, the type of the expression is const T.
3553 // [...] The expression is an lvalue if the entity is a [...] template
3554 // parameter object.
3555 if (type->isRecordType()) {
3556 type = type.getUnqualifiedType().withConst();
3557 valueKind = VK_LValue;
3558 break;
3559 }
3560
3561 // For non-references, we need to strip qualifiers just in case
3562 // the template parameter was declared as 'const int' or whatever.
3563 valueKind = VK_PRValue;
3564 type = type.getUnqualifiedType();
3565 break;
3566 }
3567
3568 case Decl::Var:
3569 case Decl::VarTemplateSpecialization:
3570 case Decl::VarTemplatePartialSpecialization:
3571 case Decl::Decomposition:
3572 case Decl::Binding:
3573 case Decl::OMPCapturedExpr:
3574 // In C, "extern void blah;" is valid and is an r-value.
3575 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3576 type->isVoidType()) {
3577 valueKind = VK_PRValue;
3578 break;
3579 }
3580 [[fallthrough]];
3581
3582 case Decl::ImplicitParam:
3583 case Decl::ParmVar: {
3584 // These are always l-values.
3585 valueKind = VK_LValue;
3586 type = type.getNonReferenceType();
3587
3588 // FIXME: Does the addition of const really only apply in
3589 // potentially-evaluated contexts? Since the variable isn't actually
3590 // captured in an unevaluated context, it seems that the answer is no.
3591 if (!isUnevaluatedContext()) {
3592 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3593 if (!CapturedType.isNull())
3594 type = CapturedType;
3595 }
3596 break;
3597 }
3598
3599 case Decl::Function: {
3600 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3601 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3602 type = Context.BuiltinFnTy;
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606 }
3607
3608 const FunctionType *fty = type->castAs<FunctionType>();
3609
3610 // If we're referring to a function with an __unknown_anytype
3611 // result type, make the entire expression __unknown_anytype.
3612 if (fty->getReturnType() == Context.UnknownAnyTy) {
3613 type = Context.UnknownAnyTy;
3614 valueKind = VK_PRValue;
3615 break;
3616 }
3617
3618 // Functions are l-values in C++.
3619 if (getLangOpts().CPlusPlus) {
3620 valueKind = VK_LValue;
3621 break;
3622 }
3623
3624 // C99 DR 316 says that, if a function type comes from a
3625 // function definition (without a prototype), that type is only
3626 // used for checking compatibility. Therefore, when referencing
3627 // the function, we pretend that we don't have the full function
3628 // type.
3629 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3630 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3631 Info: fty->getExtInfo());
3632
3633 // Functions are r-values in C.
3634 valueKind = VK_PRValue;
3635 break;
3636 }
3637
3638 case Decl::CXXDeductionGuide:
3639 llvm_unreachable("building reference to deduction guide");
3640
3641 case Decl::MSProperty:
3642 case Decl::MSGuid:
3643 case Decl::TemplateParamObject:
3644 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3645 // capture in OpenMP, or duplicated between host and device?
3646 valueKind = VK_LValue;
3647 break;
3648
3649 case Decl::UnnamedGlobalConstant:
3650 valueKind = VK_LValue;
3651 break;
3652
3653 case Decl::CXXMethod:
3654 // If we're referring to a method with an __unknown_anytype
3655 // result type, make the entire expression __unknown_anytype.
3656 // This should only be possible with a type written directly.
3657 if (const FunctionProtoType *proto =
3658 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3659 if (proto->getReturnType() == Context.UnknownAnyTy) {
3660 type = Context.UnknownAnyTy;
3661 valueKind = VK_PRValue;
3662 break;
3663 }
3664
3665 // C++ methods are l-values if static, r-values if non-static.
3666 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3667 valueKind = VK_LValue;
3668 break;
3669 }
3670 [[fallthrough]];
3671
3672 case Decl::CXXConversion:
3673 case Decl::CXXDestructor:
3674 case Decl::CXXConstructor:
3675 valueKind = VK_PRValue;
3676 break;
3677 }
3678
3679 auto *E =
3680 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3681 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3682 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3683 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3684 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3685 // diagnostics).
3686 if (VD->isInvalidDecl() && E)
3687 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3688 return E;
3689}
3690
3691static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3692 SmallString<32> &Target) {
3693 Target.resize(N: CharByteWidth * (Source.size() + 1));
3694 char *ResultPtr = &Target[0];
3695 const llvm::UTF8 *ErrorPtr;
3696 bool success =
3697 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3698 (void)success;
3699 assert(success);
3700 Target.resize(N: ResultPtr - &Target[0]);
3701}
3702
3703ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3704 PredefinedIdentKind IK) {
3705 Decl *currentDecl = getPredefinedExprDecl(S&: *this, DC: CurContext);
3706 if (!currentDecl) {
3707 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3708 currentDecl = Context.getTranslationUnitDecl();
3709 }
3710
3711 QualType ResTy;
3712 StringLiteral *SL = nullptr;
3713 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3714 ResTy = Context.DependentTy;
3715 else {
3716 // Pre-defined identifiers are of type char[x], where x is the length of
3717 // the string.
3718 bool ForceElaboratedPrinting =
3719 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3720 auto Str =
3721 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3722 unsigned Length = Str.length();
3723
3724 llvm::APInt LengthI(32, Length + 1);
3725 if (IK == PredefinedIdentKind::LFunction ||
3726 IK == PredefinedIdentKind::LFuncSig) {
3727 ResTy =
3728 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3729 SmallString<32> RawChars;
3730 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3731 Source: Str, Target&: RawChars);
3732 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3733 ASM: ArraySizeModifier::Normal,
3734 /*IndexTypeQuals*/ 0);
3735 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3736 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3737 } else {
3738 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3739 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3740 ASM: ArraySizeModifier::Normal,
3741 /*IndexTypeQuals*/ 0);
3742 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3743 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3744 }
3745 }
3746
3747 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3748 SL);
3749}
3750
3751ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3752 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3753}
3754
3755ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3756 SmallString<16> CharBuffer;
3757 bool Invalid = false;
3758 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3759 if (Invalid)
3760 return ExprError();
3761
3762 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3763 PP, Tok.getKind());
3764 if (Literal.hadError())
3765 return ExprError();
3766
3767 QualType Ty;
3768 if (Literal.isWide())
3769 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3770 else if (Literal.isUTF8() && getLangOpts().C23)
3771 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3772 else if (Literal.isUTF8() && getLangOpts().Char8)
3773 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3774 else if (Literal.isUTF16())
3775 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3776 else if (Literal.isUTF32())
3777 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3778 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3779 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3780 else
3781 Ty = Context.CharTy; // 'x' -> char in C++;
3782 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3783
3784 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3785 if (Literal.isWide())
3786 Kind = CharacterLiteralKind::Wide;
3787 else if (Literal.isUTF16())
3788 Kind = CharacterLiteralKind::UTF16;
3789 else if (Literal.isUTF32())
3790 Kind = CharacterLiteralKind::UTF32;
3791 else if (Literal.isUTF8())
3792 Kind = CharacterLiteralKind::UTF8;
3793
3794 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3795 Tok.getLocation());
3796
3797 if (Literal.getUDSuffix().empty())
3798 return Lit;
3799
3800 // We're building a user-defined literal.
3801 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3802 SourceLocation UDSuffixLoc =
3803 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3804
3805 // Make sure we're allowed user-defined literals here.
3806 if (!UDLScope)
3807 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3808
3809 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3810 // operator "" X (ch)
3811 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3812 Args: Lit, LitEndLoc: Tok.getLocation());
3813}
3814
3815ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3816 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3817 return IntegerLiteral::Create(C: Context,
3818 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3819 type: Context.IntTy, l: Loc);
3820}
3821
3822ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3823 ExprResult Inner;
3824 if (getLangOpts().CPlusPlus) {
3825 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3826 } else {
3827 // C doesn't actually have a way to represent literal values of type
3828 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3829 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3830 Inner =
3831 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3832 }
3833 return Inner;
3834}
3835
3836static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3837 QualType Ty, SourceLocation Loc) {
3838 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3839
3840 using llvm::APFloat;
3841 APFloat Val(Format);
3842
3843 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3844 if (RM == llvm::RoundingMode::Dynamic)
3845 RM = llvm::RoundingMode::NearestTiesToEven;
3846 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3847
3848 // Overflow is always an error, but underflow is only an error if
3849 // we underflowed to zero (APFloat reports denormals as underflow).
3850 if ((result & APFloat::opOverflow) ||
3851 ((result & APFloat::opUnderflow) && Val.isZero())) {
3852 unsigned diagnostic;
3853 SmallString<20> buffer;
3854 if (result & APFloat::opOverflow) {
3855 diagnostic = diag::warn_float_overflow;
3856 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3857 } else {
3858 diagnostic = diag::warn_float_underflow;
3859 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3860 }
3861
3862 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3863 }
3864
3865 bool isExact = (result == APFloat::opOK);
3866 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3867}
3868
3869bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3870 assert(E && "Invalid expression");
3871
3872 if (E->isValueDependent())
3873 return false;
3874
3875 QualType QT = E->getType();
3876 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3877 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3878 return true;
3879 }
3880
3881 llvm::APSInt ValueAPS;
3882 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3883
3884 if (R.isInvalid())
3885 return true;
3886
3887 // GCC allows the value of unroll count to be 0.
3888 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3889 // "The values of 0 and 1 block any unrolling of the loop."
3890 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3891 // '#pragma unroll' cases.
3892 bool ValueIsPositive =
3893 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3894 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3895 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3896 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3897 return true;
3898 }
3899
3900 return false;
3901}
3902
3903ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3904 // Fast path for a single digit (which is quite common). A single digit
3905 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3906 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3907 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3908 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3909 }
3910
3911 SmallString<128> SpellingBuffer;
3912 // NumericLiteralParser wants to overread by one character. Add padding to
3913 // the buffer in case the token is copied to the buffer. If getSpelling()
3914 // returns a StringRef to the memory buffer, it should have a null char at
3915 // the EOF, so it is also safe.
3916 SpellingBuffer.resize(N: Tok.getLength() + 1);
3917
3918 // Get the spelling of the token, which eliminates trigraphs, etc.
3919 bool Invalid = false;
3920 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3921 if (Invalid)
3922 return ExprError();
3923
3924 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3925 PP.getSourceManager(), PP.getLangOpts(),
3926 PP.getTargetInfo(), PP.getDiagnostics());
3927 if (Literal.hadError)
3928 return ExprError();
3929
3930 if (Literal.hasUDSuffix()) {
3931 // We're building a user-defined literal.
3932 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3933 SourceLocation UDSuffixLoc =
3934 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3935
3936 // Make sure we're allowed user-defined literals here.
3937 if (!UDLScope)
3938 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3939
3940 QualType CookedTy;
3941 if (Literal.isFloatingLiteral()) {
3942 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3943 // long double, the literal is treated as a call of the form
3944 // operator "" X (f L)
3945 CookedTy = Context.LongDoubleTy;
3946 } else {
3947 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3948 // unsigned long long, the literal is treated as a call of the form
3949 // operator "" X (n ULL)
3950 CookedTy = Context.UnsignedLongLongTy;
3951 }
3952
3953 DeclarationName OpName =
3954 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3955 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3956 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3957
3958 SourceLocation TokLoc = Tok.getLocation();
3959
3960 // Perform literal operator lookup to determine if we're building a raw
3961 // literal or a cooked one.
3962 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3963 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3964 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3965 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3966 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3967 case LOLR_ErrorNoDiagnostic:
3968 // Lookup failure for imaginary constants isn't fatal, there's still the
3969 // GNU extension producing _Complex types.
3970 break;
3971 case LOLR_Error:
3972 return ExprError();
3973 case LOLR_Cooked: {
3974 Expr *Lit;
3975 if (Literal.isFloatingLiteral()) {
3976 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3977 } else {
3978 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3979 if (Literal.GetIntegerValue(Val&: ResultVal))
3980 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3981 << /* Unsigned */ 1;
3982 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3983 l: Tok.getLocation());
3984 }
3985 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3986 }
3987
3988 case LOLR_Raw: {
3989 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3990 // literal is treated as a call of the form
3991 // operator "" X ("n")
3992 unsigned Length = Literal.getUDSuffixOffset();
3993 QualType StrTy = Context.getConstantArrayType(
3994 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3995 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3996 Expr *Lit =
3997 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3998 Kind: StringLiteralKind::Ordinary,
3999 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
4000 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
4001 }
4002
4003 case LOLR_Template: {
4004 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4005 // template), L is treated as a call fo the form
4006 // operator "" X <'c1', 'c2', ... 'ck'>()
4007 // where n is the source character sequence c1 c2 ... ck.
4008 TemplateArgumentListInfo ExplicitArgs;
4009 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
4010 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4011 llvm::APSInt Value(CharBits, CharIsUnsigned);
4012 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4013 Value = TokSpelling[I];
4014 TemplateArgument Arg(Context, Value, Context.CharTy);
4015 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
4016 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4017 }
4018 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
4019 }
4020 case LOLR_StringTemplatePack:
4021 llvm_unreachable("unexpected literal operator lookup result");
4022 }
4023 }
4024
4025 Expr *Res;
4026
4027 if (Literal.isFixedPointLiteral()) {
4028 QualType Ty;
4029
4030 if (Literal.isAccum) {
4031 if (Literal.isHalf) {
4032 Ty = Context.ShortAccumTy;
4033 } else if (Literal.isLong) {
4034 Ty = Context.LongAccumTy;
4035 } else {
4036 Ty = Context.AccumTy;
4037 }
4038 } else if (Literal.isFract) {
4039 if (Literal.isHalf) {
4040 Ty = Context.ShortFractTy;
4041 } else if (Literal.isLong) {
4042 Ty = Context.LongFractTy;
4043 } else {
4044 Ty = Context.FractTy;
4045 }
4046 }
4047
4048 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
4049
4050 bool isSigned = !Literal.isUnsigned;
4051 unsigned scale = Context.getFixedPointScale(Ty);
4052 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4053
4054 llvm::APInt Val(bit_width, 0, isSigned);
4055 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
4056 bool ValIsZero = Val.isZero() && !Overflowed;
4057
4058 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4059 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4060 // Clause 6.4.4 - The value of a constant shall be in the range of
4061 // representable values for its type, with exception for constants of a
4062 // fract type with a value of exactly 1; such a constant shall denote
4063 // the maximal value for the type.
4064 --Val;
4065 else if (Val.ugt(RHS: MaxVal) || Overflowed)
4066 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
4067
4068 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4069 l: Tok.getLocation(), Scale: scale);
4070 } else if (Literal.isFloatingLiteral()) {
4071 QualType Ty;
4072 if (Literal.isHalf){
4073 if (getLangOpts().HLSL ||
4074 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
4075 Ty = Context.HalfTy;
4076 else {
4077 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4078 return ExprError();
4079 }
4080 } else if (Literal.isFloat)
4081 Ty = Context.FloatTy;
4082 else if (Literal.isLong)
4083 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4084 else if (Literal.isFloat16)
4085 Ty = Context.Float16Ty;
4086 else if (Literal.isFloat128)
4087 Ty = Context.Float128Ty;
4088 else if (getLangOpts().HLSL)
4089 Ty = Context.FloatTy;
4090 else
4091 Ty = Context.DoubleTy;
4092
4093 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4094
4095 if (Ty == Context.DoubleTy) {
4096 if (getLangOpts().SinglePrecisionConstants) {
4097 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4098 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4099 }
4100 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4101 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4102 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4103 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4104 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4105 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4106 }
4107 }
4108 } else if (!Literal.isIntegerLiteral()) {
4109 return ExprError();
4110 } else {
4111 QualType Ty;
4112
4113 // 'z/uz' literals are a C++23 feature.
4114 if (Literal.isSizeT) {
4115 if (getLangOpts().CPlusPlus)
4116 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::size_t_suffix);
4117 else
4118 Diag(Loc: Tok.getLocation(), DiagID: diag::err_cxx23_size_t_suffix);
4119 }
4120
4121 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4122 // but we do not currently support the suffix in C++ mode because it's not
4123 // entirely clear whether WG21 will prefer this suffix to return a library
4124 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4125 // literals are a C++ extension.
4126 if (Literal.isBitInt)
4127 PP.Diag(Loc: Tok.getLocation(),
4128 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4129 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4130 : diag::ext_c23_bitint_suffix);
4131
4132 // Get the value in the widest-possible width. What is "widest" depends on
4133 // whether the literal is a bit-precise integer or not. For a bit-precise
4134 // integer type, try to scan the source to determine how many bits are
4135 // needed to represent the value. This may seem a bit expensive, but trying
4136 // to get the integer value from an overly-wide APInt is *extremely*
4137 // expensive, so the naive approach of assuming
4138 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4139 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4140 if (Literal.isBitInt)
4141 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4142 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4143 if (Literal.MicrosoftInteger) {
4144 if (Literal.MicrosoftInteger == 128 &&
4145 !Context.getTargetInfo().hasInt128Type())
4146 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4147 << Literal.isUnsigned;
4148 BitsNeeded = std::max<unsigned>(a: BitsNeeded, b: Literal.MicrosoftInteger);
4149 }
4150
4151 llvm::APInt ResultVal(BitsNeeded, 0);
4152
4153 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4154 // If this value didn't fit into uintmax_t, error and force to ull.
4155 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4156 << /* Unsigned */ 1;
4157 Ty = Context.UnsignedLongLongTy;
4158 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4159 "long long is not intmax_t?");
4160 } else {
4161 // If this value fits into a ULL, try to figure out what else it fits into
4162 // according to the rules of C99 6.4.4.1p5.
4163
4164 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4165 // be an unsigned int.
4166 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4167
4168 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4169 // suffix for portability of code with C++, but both `l` and `ll` are
4170 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4171 // same.
4172 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4173 Literal.isLong = true;
4174 Literal.isLongLong = false;
4175 }
4176
4177 // Check from smallest to largest, picking the smallest type we can.
4178 unsigned Width = 0;
4179
4180 // Microsoft specific integer suffixes are explicitly sized.
4181 if (Literal.MicrosoftInteger) {
4182 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4183 Width = 8;
4184 Ty = Context.CharTy;
4185 } else {
4186 Width = Literal.MicrosoftInteger;
4187 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4188 /*Signed=*/!Literal.isUnsigned);
4189 }
4190 // To maintain consistency with MSVC, we chose to truncate directly
4191 // without issuing any warnings.
4192 ResultVal = ResultVal.zextOrTrunc(width: Width);
4193 }
4194
4195 // Bit-precise integer literals are automagically-sized based on the
4196 // width required by the literal.
4197 if (Literal.isBitInt) {
4198 // The signed version has one more bit for the sign value. There are no
4199 // zero-width bit-precise integers, even if the literal value is 0.
4200 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4201 (Literal.isUnsigned ? 0u : 1u);
4202
4203 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4204 // and reset the type to the largest supported width.
4205 unsigned int MaxBitIntWidth =
4206 Context.getTargetInfo().getMaxBitIntWidth();
4207 if (Width > MaxBitIntWidth) {
4208 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4209 << Literal.isUnsigned;
4210 Width = MaxBitIntWidth;
4211 }
4212
4213 // Reset the result value to the smaller APInt and select the correct
4214 // type to be used. Note, we zext even for signed values because the
4215 // literal itself is always an unsigned value (a preceeding - is a
4216 // unary operator, not part of the literal).
4217 ResultVal = ResultVal.zextOrTrunc(width: Width);
4218 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4219 }
4220
4221 // Check C++23 size_t literals.
4222 if (Literal.isSizeT) {
4223 assert(!Literal.MicrosoftInteger &&
4224 "size_t literals can't be Microsoft literals");
4225 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4226 T: Context.getTargetInfo().getSizeType());
4227
4228 // Does it fit in size_t?
4229 if (ResultVal.isIntN(N: SizeTSize)) {
4230 // Does it fit in ssize_t?
4231 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4232 Ty = Context.getSignedSizeType();
4233 else if (AllowUnsigned)
4234 Ty = Context.getSizeType();
4235 Width = SizeTSize;
4236 }
4237 }
4238
4239 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4240 !Literal.isSizeT) {
4241 // Are int/unsigned possibilities?
4242 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4243
4244 // Does it fit in a unsigned int?
4245 if (ResultVal.isIntN(N: IntSize)) {
4246 // Does it fit in a signed int?
4247 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4248 Ty = Context.IntTy;
4249 else if (AllowUnsigned)
4250 Ty = Context.UnsignedIntTy;
4251 Width = IntSize;
4252 }
4253 }
4254
4255 // Are long/unsigned long possibilities?
4256 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4257 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4258
4259 // Does it fit in a unsigned long?
4260 if (ResultVal.isIntN(N: LongSize)) {
4261 // Does it fit in a signed long?
4262 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4263 Ty = Context.LongTy;
4264 else if (AllowUnsigned)
4265 Ty = Context.UnsignedLongTy;
4266 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4267 // is compatible.
4268 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4269 const unsigned LongLongSize =
4270 Context.getTargetInfo().getLongLongWidth();
4271 Diag(Loc: Tok.getLocation(),
4272 DiagID: getLangOpts().CPlusPlus
4273 ? Literal.isLong
4274 ? diag::warn_old_implicitly_unsigned_long_cxx
4275 : /*C++98 UB*/ diag::
4276 ext_old_implicitly_unsigned_long_cxx
4277 : diag::warn_old_implicitly_unsigned_long)
4278 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4279 : /*will be ill-formed*/ 1);
4280 Ty = Context.UnsignedLongTy;
4281 }
4282 Width = LongSize;
4283 }
4284 }
4285
4286 // Check long long if needed.
4287 if (Ty.isNull() && !Literal.isSizeT) {
4288 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4289
4290 // Does it fit in a unsigned long long?
4291 if (ResultVal.isIntN(N: LongLongSize)) {
4292 // Does it fit in a signed long long?
4293 // To be compatible with MSVC, hex integer literals ending with the
4294 // LL or i64 suffix are always signed in Microsoft mode.
4295 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4296 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4297 Ty = Context.LongLongTy;
4298 else if (AllowUnsigned)
4299 Ty = Context.UnsignedLongLongTy;
4300 Width = LongLongSize;
4301
4302 // 'long long' is a C99 or C++11 feature, whether the literal
4303 // explicitly specified 'long long' or we needed the extra width.
4304 if (getLangOpts().CPlusPlus)
4305 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4306 ? diag::warn_cxx98_compat_longlong
4307 : diag::ext_cxx11_longlong);
4308 else if (!getLangOpts().C99)
4309 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4310 }
4311 }
4312
4313 // If we still couldn't decide a type, we either have 'size_t' literal
4314 // that is out of range, or a decimal literal that does not fit in a
4315 // signed long long and has no U suffix.
4316 if (Ty.isNull()) {
4317 if (Literal.isSizeT)
4318 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4319 << Literal.isUnsigned;
4320 else
4321 Diag(Loc: Tok.getLocation(),
4322 DiagID: diag::ext_integer_literal_too_large_for_signed);
4323 Ty = Context.UnsignedLongLongTy;
4324 Width = Context.getTargetInfo().getLongLongWidth();
4325 }
4326
4327 if (ResultVal.getBitWidth() != Width)
4328 ResultVal = ResultVal.trunc(width: Width);
4329 }
4330 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4331 }
4332
4333 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4334 if (Literal.isImaginary) {
4335 Res = new (Context) ImaginaryLiteral(Res,
4336 Context.getComplexType(T: Res->getType()));
4337
4338 // In C++, this is a GNU extension. In C, it's a C2y extension.
4339 if (getLangOpts().CPlusPlus)
4340 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_gnu_imaginary_constant);
4341 else
4342 DiagCompat(Loc: Tok.getLocation(), CompatDiagId: diag_compat::imaginary_constant);
4343 }
4344 return Res;
4345}
4346
4347ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4348 assert(E && "ActOnParenExpr() missing expr");
4349 QualType ExprTy = E->getType();
4350 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4351 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4352 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4353 return new (Context) ParenExpr(L, R, E);
4354}
4355
4356static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4357 SourceLocation Loc,
4358 SourceRange ArgRange) {
4359 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4360 // scalar or vector data type argument..."
4361 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4362 // type (C99 6.2.5p18) or void.
4363 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4364 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4365 << T << ArgRange;
4366 return true;
4367 }
4368
4369 assert((T->isVoidType() || !T->isIncompleteType()) &&
4370 "Scalar types should always be complete");
4371 return false;
4372}
4373
4374static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4375 SourceLocation Loc,
4376 SourceRange ArgRange) {
4377 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4378 if (!T->isVectorType() && !T->isSizelessVectorType())
4379 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4380 << ""
4381 << "__builtin_vectorelements" << T << ArgRange;
4382
4383 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4384 if (T->isSVESizelessBuiltinType()) {
4385 llvm::StringMap<bool> CallerFeatureMap;
4386 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4387 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4388 }
4389 }
4390
4391 return false;
4392}
4393
4394static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4395 SourceLocation Loc,
4396 SourceRange ArgRange) {
4397 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4398 return true;
4399
4400 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4401 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4402 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4403 return true;
4404 }
4405
4406 return false;
4407}
4408
4409static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4410 SourceLocation Loc,
4411 SourceRange ArgRange,
4412 UnaryExprOrTypeTrait TraitKind) {
4413 // Invalid types must be hard errors for SFINAE in C++.
4414 if (S.LangOpts.CPlusPlus)
4415 return true;
4416
4417 // C99 6.5.3.4p1:
4418 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4419 TraitKind == UETT_PreferredAlignOf) {
4420
4421 // sizeof(function)/alignof(function) is allowed as an extension.
4422 if (T->isFunctionType()) {
4423 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4424 << getTraitSpelling(T: TraitKind) << ArgRange;
4425 return false;
4426 }
4427
4428 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4429 // this is an error (OpenCL v1.1 s6.3.k)
4430 if (T->isVoidType()) {
4431 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4432 : diag::ext_sizeof_alignof_void_type;
4433 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4434 return false;
4435 }
4436 }
4437 return true;
4438}
4439
4440static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4441 SourceLocation Loc,
4442 SourceRange ArgRange,
4443 UnaryExprOrTypeTrait TraitKind) {
4444 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4445 // runtime doesn't allow it.
4446 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4447 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4448 << T << (TraitKind == UETT_SizeOf)
4449 << ArgRange;
4450 return true;
4451 }
4452
4453 return false;
4454}
4455
4456/// Check whether E is a pointer from a decayed array type (the decayed
4457/// pointer type is equal to T) and emit a warning if it is.
4458static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4459 const Expr *E) {
4460 // Don't warn if the operation changed the type.
4461 if (T != E->getType())
4462 return;
4463
4464 // Now look for array decays.
4465 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4466 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4467 return;
4468
4469 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4470 << ICE->getType()
4471 << ICE->getSubExpr()->getType();
4472}
4473
4474bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4475 UnaryExprOrTypeTrait ExprKind) {
4476 QualType ExprTy = E->getType();
4477 assert(!ExprTy->isReferenceType());
4478
4479 bool IsUnevaluatedOperand =
4480 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4481 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4482 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4483 if (IsUnevaluatedOperand) {
4484 ExprResult Result = CheckUnevaluatedOperand(E);
4485 if (Result.isInvalid())
4486 return true;
4487 E = Result.get();
4488 }
4489
4490 // The operand for sizeof and alignof is in an unevaluated expression context,
4491 // so side effects could result in unintended consequences.
4492 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4493 // used to build SFINAE gadgets.
4494 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4495 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4496 !E->isInstantiationDependent() &&
4497 !E->getType()->isVariableArrayType() &&
4498 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4499 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4500
4501 if (ExprKind == UETT_VecStep)
4502 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4503 ArgRange: E->getSourceRange());
4504
4505 if (ExprKind == UETT_VectorElements)
4506 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4507 ArgRange: E->getSourceRange());
4508
4509 // Explicitly list some types as extensions.
4510 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4511 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4512 return false;
4513
4514 // WebAssembly tables are always illegal operands to unary expressions and
4515 // type traits.
4516 if (Context.getTargetInfo().getTriple().isWasm() &&
4517 E->getType()->isWebAssemblyTableType()) {
4518 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4519 << getTraitSpelling(T: ExprKind);
4520 return true;
4521 }
4522
4523 // 'alignof' applied to an expression only requires the base element type of
4524 // the expression to be complete. 'sizeof' requires the expression's type to
4525 // be complete (and will attempt to complete it if it's an array of unknown
4526 // bound).
4527 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4528 if (RequireCompleteSizedType(
4529 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4530 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4531 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4532 return true;
4533 } else {
4534 if (RequireCompleteSizedExprType(
4535 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4536 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4537 return true;
4538 }
4539
4540 // Completing the expression's type may have changed it.
4541 ExprTy = E->getType();
4542 assert(!ExprTy->isReferenceType());
4543
4544 if (ExprTy->isFunctionType()) {
4545 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4546 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4547 return true;
4548 }
4549
4550 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4551 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4552 return true;
4553
4554 if (ExprKind == UETT_CountOf) {
4555 // The type has to be an array type. We already checked for incomplete
4556 // types above.
4557 QualType ExprType = E->IgnoreParens()->getType();
4558 if (!ExprType->isArrayType()) {
4559 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4560 return true;
4561 }
4562 // FIXME: warn on _Countof on an array parameter. Not warning on it
4563 // currently because there are papers in WG14 about array types which do
4564 // not decay that could impact this behavior, so we want to see if anything
4565 // changes here before coming up with a warning group for _Countof-related
4566 // diagnostics.
4567 }
4568
4569 if (ExprKind == UETT_SizeOf) {
4570 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4571 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4572 QualType OType = PVD->getOriginalType();
4573 QualType Type = PVD->getType();
4574 if (Type->isPointerType() && OType->isArrayType()) {
4575 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4576 << Type << OType;
4577 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4578 }
4579 }
4580 }
4581
4582 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4583 // decays into a pointer and returns an unintended result. This is most
4584 // likely a typo for "sizeof(array) op x".
4585 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4586 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4587 E: BO->getLHS());
4588 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4589 E: BO->getRHS());
4590 }
4591 }
4592
4593 return false;
4594}
4595
4596static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4597 // Cannot know anything else if the expression is dependent.
4598 if (E->isTypeDependent())
4599 return false;
4600
4601 if (E->getObjectKind() == OK_BitField) {
4602 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4603 << 1 << E->getSourceRange();
4604 return true;
4605 }
4606
4607 ValueDecl *D = nullptr;
4608 Expr *Inner = E->IgnoreParens();
4609 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4610 D = DRE->getDecl();
4611 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4612 D = ME->getMemberDecl();
4613 }
4614
4615 // If it's a field, require the containing struct to have a
4616 // complete definition so that we can compute the layout.
4617 //
4618 // This can happen in C++11 onwards, either by naming the member
4619 // in a way that is not transformed into a member access expression
4620 // (in an unevaluated operand, for instance), or by naming the member
4621 // in a trailing-return-type.
4622 //
4623 // For the record, since __alignof__ on expressions is a GCC
4624 // extension, GCC seems to permit this but always gives the
4625 // nonsensical answer 0.
4626 //
4627 // We don't really need the layout here --- we could instead just
4628 // directly check for all the appropriate alignment-lowing
4629 // attributes --- but that would require duplicating a lot of
4630 // logic that just isn't worth duplicating for such a marginal
4631 // use-case.
4632 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4633 // Fast path this check, since we at least know the record has a
4634 // definition if we can find a member of it.
4635 if (!FD->getParent()->isCompleteDefinition()) {
4636 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4637 << E->getSourceRange();
4638 return true;
4639 }
4640
4641 // Otherwise, if it's a field, and the field doesn't have
4642 // reference type, then it must have a complete type (or be a
4643 // flexible array member, which we explicitly want to
4644 // white-list anyway), which makes the following checks trivial.
4645 if (!FD->getType()->isReferenceType())
4646 return false;
4647 }
4648
4649 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4650}
4651
4652bool Sema::CheckVecStepExpr(Expr *E) {
4653 E = E->IgnoreParens();
4654
4655 // Cannot know anything else if the expression is dependent.
4656 if (E->isTypeDependent())
4657 return false;
4658
4659 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4660}
4661
4662static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4663 CapturingScopeInfo *CSI) {
4664 assert(T->isVariablyModifiedType());
4665 assert(CSI != nullptr);
4666
4667 // We're going to walk down into the type and look for VLA expressions.
4668 do {
4669 const Type *Ty = T.getTypePtr();
4670 switch (Ty->getTypeClass()) {
4671#define TYPE(Class, Base)
4672#define ABSTRACT_TYPE(Class, Base)
4673#define NON_CANONICAL_TYPE(Class, Base)
4674#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4675#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4676#include "clang/AST/TypeNodes.inc"
4677 T = QualType();
4678 break;
4679 // These types are never variably-modified.
4680 case Type::Builtin:
4681 case Type::Complex:
4682 case Type::Vector:
4683 case Type::ExtVector:
4684 case Type::ConstantMatrix:
4685 case Type::Record:
4686 case Type::Enum:
4687 case Type::TemplateSpecialization:
4688 case Type::ObjCObject:
4689 case Type::ObjCInterface:
4690 case Type::ObjCObjectPointer:
4691 case Type::ObjCTypeParam:
4692 case Type::Pipe:
4693 case Type::BitInt:
4694 case Type::HLSLInlineSpirv:
4695 llvm_unreachable("type class is never variably-modified!");
4696 case Type::Adjusted:
4697 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4698 break;
4699 case Type::Decayed:
4700 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4701 break;
4702 case Type::ArrayParameter:
4703 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4704 break;
4705 case Type::Pointer:
4706 T = cast<PointerType>(Val: Ty)->getPointeeType();
4707 break;
4708 case Type::BlockPointer:
4709 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4710 break;
4711 case Type::LValueReference:
4712 case Type::RValueReference:
4713 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4714 break;
4715 case Type::MemberPointer:
4716 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4717 break;
4718 case Type::ConstantArray:
4719 case Type::IncompleteArray:
4720 // Losing element qualification here is fine.
4721 T = cast<ArrayType>(Val: Ty)->getElementType();
4722 break;
4723 case Type::VariableArray: {
4724 // Losing element qualification here is fine.
4725 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4726
4727 // Unknown size indication requires no size computation.
4728 // Otherwise, evaluate and record it.
4729 auto Size = VAT->getSizeExpr();
4730 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4731 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4732 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4733
4734 T = VAT->getElementType();
4735 break;
4736 }
4737 case Type::FunctionProto:
4738 case Type::FunctionNoProto:
4739 T = cast<FunctionType>(Val: Ty)->getReturnType();
4740 break;
4741 case Type::Paren:
4742 case Type::TypeOf:
4743 case Type::UnaryTransform:
4744 case Type::Attributed:
4745 case Type::BTFTagAttributed:
4746 case Type::OverflowBehavior:
4747 case Type::HLSLAttributedResource:
4748 case Type::SubstTemplateTypeParm:
4749 case Type::MacroQualified:
4750 case Type::CountAttributed:
4751 case Type::LateParsedAttr:
4752 // Keep walking after single level desugaring.
4753 T = T.getSingleStepDesugaredType(Context);
4754 break;
4755 case Type::Typedef:
4756 T = cast<TypedefType>(Val: Ty)->desugar();
4757 break;
4758 case Type::Decltype:
4759 T = cast<DecltypeType>(Val: Ty)->desugar();
4760 break;
4761 case Type::PackIndexing:
4762 T = cast<PackIndexingType>(Val: Ty)->desugar();
4763 break;
4764 case Type::Using:
4765 T = cast<UsingType>(Val: Ty)->desugar();
4766 break;
4767 case Type::Auto:
4768 case Type::DeducedTemplateSpecialization:
4769 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4770 break;
4771 case Type::TypeOfExpr:
4772 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4773 break;
4774 case Type::Atomic:
4775 T = cast<AtomicType>(Val: Ty)->getValueType();
4776 break;
4777 case Type::PredefinedSugar:
4778 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4779 break;
4780 }
4781 } while (!T.isNull() && T->isVariablyModifiedType());
4782}
4783
4784bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4785 SourceLocation OpLoc,
4786 SourceRange ExprRange,
4787 UnaryExprOrTypeTrait ExprKind,
4788 StringRef KWName) {
4789 if (ExprType->isDependentType())
4790 return false;
4791
4792 // These builtins evaluate with the operand type as written; a reference is
4793 // not looked through.
4794 if (ExprKind == UETT_VectorElements)
4795 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4796 ArgRange: ExprRange);
4797 if (ExprKind == UETT_VecStep)
4798 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4799 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4800 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4801 ArgRange: ExprRange);
4802
4803 // C++ [expr.sizeof]p2:
4804 // When applied to a reference or a reference type, the result
4805 // is the size of the referenced type.
4806 // C++11 [expr.alignof]p3:
4807 // When alignof is applied to a reference type, the result
4808 // shall be the alignment of the referenced type.
4809 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4810 ExprType = Ref->getPointeeType();
4811
4812 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4813 // When alignof or _Alignof is applied to an array type, the result
4814 // is the alignment of the element type.
4815 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4816 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4817 // If the trait is 'alignof' in C before C2y, the ability to apply the
4818 // trait to an incomplete array is an extension.
4819 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4820 ExprType->isIncompleteArrayType())
4821 DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::alignof_incomplete_array);
4822 ExprType = Context.getBaseElementType(QT: ExprType);
4823 }
4824
4825 // Explicitly list some types as extensions.
4826 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4827 TraitKind: ExprKind))
4828 return false;
4829
4830 if (RequireCompleteSizedType(
4831 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4832 Args: KWName, Args: ExprRange))
4833 return true;
4834
4835 if (ExprType->isFunctionType()) {
4836 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4837 return true;
4838 }
4839
4840 if (ExprKind == UETT_CountOf) {
4841 // The type has to be an array type. We already checked for incomplete
4842 // types above.
4843 if (!ExprType->isArrayType()) {
4844 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4845 return true;
4846 }
4847 }
4848
4849 // WebAssembly tables are always illegal operands to unary expressions and
4850 // type traits.
4851 if (Context.getTargetInfo().getTriple().isWasm() &&
4852 ExprType->isWebAssemblyTableType()) {
4853 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4854 << getTraitSpelling(T: ExprKind);
4855 return true;
4856 }
4857
4858 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4859 TraitKind: ExprKind))
4860 return true;
4861
4862 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4863 if (auto *TT = ExprType->getAs<TypedefType>()) {
4864 for (auto I = FunctionScopes.rbegin(),
4865 E = std::prev(x: FunctionScopes.rend());
4866 I != E; ++I) {
4867 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4868 if (CSI == nullptr)
4869 break;
4870 DeclContext *DC = nullptr;
4871 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4872 DC = LSI->CallOperator;
4873 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4874 DC = CRSI->TheCapturedDecl;
4875 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4876 DC = BSI->TheDecl;
4877 if (DC) {
4878 if (DC->containsDecl(D: TT->getDecl()))
4879 break;
4880 captureVariablyModifiedType(Context, T: ExprType, CSI);
4881 }
4882 }
4883 }
4884 }
4885
4886 return false;
4887}
4888
4889ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4890 SourceLocation OpLoc,
4891 UnaryExprOrTypeTrait ExprKind,
4892 SourceRange R) {
4893 if (!TInfo)
4894 return ExprError();
4895
4896 QualType T = TInfo->getType();
4897
4898 if (!T->isDependentType() &&
4899 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4900 KWName: getTraitSpelling(T: ExprKind)))
4901 return ExprError();
4902
4903 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4904 // properly deal with VLAs in nested calls of sizeof and typeof.
4905 if (currentEvaluationContext().isUnevaluated() &&
4906 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4907 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4908 TInfo->getType()->isVariablyModifiedType())
4909 TInfo = TransformToPotentiallyEvaluated(TInfo);
4910
4911 // It's possible that the transformation above failed.
4912 if (!TInfo)
4913 return ExprError();
4914
4915 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4916 return new (Context) UnaryExprOrTypeTraitExpr(
4917 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4918}
4919
4920ExprResult
4921Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4922 UnaryExprOrTypeTrait ExprKind) {
4923 ExprResult PE = CheckPlaceholderExpr(E);
4924 if (PE.isInvalid())
4925 return ExprError();
4926
4927 E = PE.get();
4928
4929 // Verify that the operand is valid.
4930 bool isInvalid = false;
4931 if (E->isTypeDependent()) {
4932 // Delay type-checking for type-dependent expressions.
4933 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4934 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4935 } else if (ExprKind == UETT_VecStep) {
4936 isInvalid = CheckVecStepExpr(E);
4937 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4938 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4939 isInvalid = true;
4940 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4941 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4942 isInvalid = true;
4943 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4944 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4945 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4946 }
4947
4948 if (isInvalid)
4949 return ExprError();
4950
4951 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4952 E->getType()->isVariableArrayType()) {
4953 PE = TransformToPotentiallyEvaluated(E);
4954 if (PE.isInvalid()) return ExprError();
4955 E = PE.get();
4956 }
4957
4958 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4959 return new (Context) UnaryExprOrTypeTraitExpr(
4960 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4961}
4962
4963ExprResult
4964Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4965 UnaryExprOrTypeTrait ExprKind, bool IsType,
4966 void *TyOrEx, SourceRange ArgRange) {
4967 // If error parsing type, ignore.
4968 if (!TyOrEx) return ExprError();
4969
4970 if (IsType) {
4971 TypeSourceInfo *TInfo;
4972 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4973 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4974 }
4975
4976 Expr *ArgEx = (Expr *)TyOrEx;
4977 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4978 return Result;
4979}
4980
4981bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4982 SourceLocation OpLoc, SourceRange R) {
4983 if (!TInfo)
4984 return true;
4985 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4986 ExprKind: UETT_AlignOf, KWName);
4987}
4988
4989bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4990 SourceLocation OpLoc, SourceRange R) {
4991 TypeSourceInfo *TInfo;
4992 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4993 TInfo: &TInfo);
4994 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4995}
4996
4997static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4998 bool IsReal) {
4999 if (V.get()->isTypeDependent())
5000 return S.Context.DependentTy;
5001
5002 // _Real and _Imag are only l-values for normal l-values.
5003 if (V.get()->getObjectKind() != OK_Ordinary) {
5004 V = S.DefaultLvalueConversion(E: V.get());
5005 if (V.isInvalid())
5006 return QualType();
5007 }
5008
5009 // These operators return the element type of a complex type.
5010 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5011 return CT->getElementType();
5012
5013 // Otherwise they pass through real integer and floating point types here.
5014 if (V.get()->getType()->isArithmeticType())
5015 return V.get()->getType();
5016
5017 // Test for placeholders.
5018 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
5019 if (PR.isInvalid()) return QualType();
5020 if (PR.get() != V.get()) {
5021 V = PR;
5022 return CheckRealImagOperand(S, V, Loc, IsReal);
5023 }
5024
5025 // Reject anything else.
5026 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
5027 << (IsReal ? "__real" : "__imag");
5028 return QualType();
5029}
5030
5031
5032
5033ExprResult
5034Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5035 tok::TokenKind Kind, Expr *Input) {
5036 UnaryOperatorKind Opc;
5037 switch (Kind) {
5038 default: llvm_unreachable("Unknown unary op!");
5039 case tok::plusplus: Opc = UO_PostInc; break;
5040 case tok::minusminus: Opc = UO_PostDec; break;
5041 }
5042
5043 // Since this might is a postfix expression, get rid of ParenListExprs.
5044 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
5045 if (Result.isInvalid()) return ExprError();
5046 Input = Result.get();
5047
5048 return BuildUnaryOp(S, OpLoc, Opc, Input);
5049}
5050
5051/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5052///
5053/// \return true on error
5054static bool checkArithmeticOnObjCPointer(Sema &S,
5055 SourceLocation opLoc,
5056 Expr *op) {
5057 assert(op->getType()->isObjCObjectPointerType());
5058 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5059 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5060 return false;
5061
5062 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
5063 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5064 << op->getSourceRange();
5065 return true;
5066}
5067
5068static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5069 auto *BaseNoParens = Base->IgnoreParens();
5070 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5071 return MSProp->getPropertyDecl()->getType()->isArrayType();
5072 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
5073}
5074
5075// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5076// Typically this is DependentTy, but can sometimes be more precise.
5077//
5078// There are cases when we could determine a non-dependent type:
5079// - LHS and RHS may have non-dependent types despite being type-dependent
5080// (e.g. unbounded array static members of the current instantiation)
5081// - one may be a dependent-sized array with known element type
5082// - one may be a dependent-typed valid index (enum in current instantiation)
5083//
5084// We *always* return a dependent type, in such cases it is DependentTy.
5085// This avoids creating type-dependent expressions with non-dependent types.
5086// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5087static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5088 const ASTContext &Ctx) {
5089 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5090 QualType LTy = LHS->getType(), RTy = RHS->getType();
5091 QualType Result = Ctx.DependentTy;
5092 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5093 if (const PointerType *PT = LTy->getAs<PointerType>())
5094 Result = PT->getPointeeType();
5095 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5096 Result = AT->getElementType();
5097 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5098 if (const PointerType *PT = RTy->getAs<PointerType>())
5099 Result = PT->getPointeeType();
5100 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5101 Result = AT->getElementType();
5102 }
5103 // Ensure we return a dependent type.
5104 return Result->isDependentType() ? Result : Ctx.DependentTy;
5105}
5106
5107ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5108 SourceLocation lbLoc,
5109 MultiExprArg ArgExprs,
5110 SourceLocation rbLoc) {
5111
5112 if (base && !base->getType().isNull() &&
5113 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5114 auto *AS = cast<ArraySectionExpr>(Val: base);
5115 if (AS->isOMPArraySection())
5116 return OpenMP().ActOnOMPArraySectionExpr(
5117 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5118 /*Length*/ nullptr,
5119 /*Stride=*/nullptr, RBLoc: rbLoc);
5120
5121 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5122 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5123 RBLoc: rbLoc);
5124 }
5125
5126 // Since this might be a postfix expression, get rid of ParenListExprs.
5127 if (isa<ParenListExpr>(Val: base)) {
5128 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5129 if (result.isInvalid())
5130 return ExprError();
5131 base = result.get();
5132 }
5133
5134 // Check if base and idx form a MatrixSubscriptExpr.
5135 //
5136 // Helper to check for comma expressions, which are not allowed as indices for
5137 // matrix subscript expressions.
5138 //
5139 // In C++23, we get multiple arguments instead of a comma expression.
5140 auto CheckAndReportCommaError = [&](Expr *E) {
5141 if (ArgExprs.size() > 1 ||
5142 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5143 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5144 << SourceRange(base->getBeginLoc(), rbLoc);
5145 return true;
5146 }
5147 return false;
5148 };
5149 // The matrix subscript operator ([][])is considered a single operator.
5150 // Separating the index expressions by parenthesis is not allowed.
5151 if (base && !base->getType().isNull() &&
5152 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5153 !isa<MatrixSubscriptExpr>(Val: base)) {
5154 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5155 << SourceRange(base->getBeginLoc(), rbLoc);
5156 return ExprError();
5157 }
5158 // If the base is a MatrixSubscriptExpr, try to create a new
5159 // MatrixSubscriptExpr.
5160 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5161 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5162 if (CheckAndReportCommaError(ArgExprs.front()))
5163 return ExprError();
5164
5165 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5166 RowIdx: matSubscriptE->getRowIdx(),
5167 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5168 }
5169 if (base->getType()->isWebAssemblyTableType()) {
5170 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5171 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5172 return ExprError();
5173 }
5174
5175 CheckInvalidBuiltinCountedByRef(E: base,
5176 K: BuiltinCountedByRefKind::ArraySubscript);
5177
5178 // Handle any non-overload placeholder types in the base and index
5179 // expressions. We can't handle overloads here because the other
5180 // operand might be an overloadable type, in which case the overload
5181 // resolution for the operator overload should get the first crack
5182 // at the overload.
5183 bool IsMSPropertySubscript = false;
5184 if (base->getType()->isNonOverloadPlaceholderType()) {
5185 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5186 if (!IsMSPropertySubscript) {
5187 ExprResult result = CheckPlaceholderExpr(E: base);
5188 if (result.isInvalid())
5189 return ExprError();
5190 base = result.get();
5191 }
5192 }
5193
5194 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5195 if (base->getType()->isMatrixType()) {
5196 if (CheckAndReportCommaError(ArgExprs.front()))
5197 return ExprError();
5198
5199 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5200 RBLoc: rbLoc);
5201 }
5202
5203 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5204 Expr *idx = ArgExprs[0];
5205 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5206 (isa<CXXOperatorCallExpr>(Val: idx) &&
5207 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5208 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5209 << SourceRange(base->getBeginLoc(), rbLoc);
5210 }
5211 }
5212
5213 if (ArgExprs.size() == 1 &&
5214 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5215 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5216 if (result.isInvalid())
5217 return ExprError();
5218 ArgExprs[0] = result.get();
5219 } else {
5220 if (CheckArgsForPlaceholders(args: ArgExprs))
5221 return ExprError();
5222 }
5223
5224 // Build an unanalyzed expression if either operand is type-dependent.
5225 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5226 (base->isTypeDependent() ||
5227 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5228 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5229 return new (Context) ArraySubscriptExpr(
5230 base, ArgExprs.front(),
5231 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5232 VK_LValue, OK_Ordinary, rbLoc);
5233 }
5234
5235 // MSDN, property (C++)
5236 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5237 // This attribute can also be used in the declaration of an empty array in a
5238 // class or structure definition. For example:
5239 // __declspec(property(get=GetX, put=PutX)) int x[];
5240 // The above statement indicates that x[] can be used with one or more array
5241 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5242 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5243 if (IsMSPropertySubscript) {
5244 if (ArgExprs.size() > 1) {
5245 Diag(Loc: base->getExprLoc(),
5246 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5247 return ExprError();
5248 }
5249
5250 // Build MS property subscript expression if base is MS property reference
5251 // or MS property subscript.
5252 return new (Context)
5253 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5254 VK_LValue, OK_Ordinary, rbLoc);
5255 }
5256
5257 // Use C++ overloaded-operator rules if either operand has record
5258 // type. The spec says to do this if either type is *overloadable*,
5259 // but enum types can't declare subscript operators or conversion
5260 // operators, so there's nothing interesting for overload resolution
5261 // to do if there aren't any record types involved.
5262 //
5263 // ObjC pointers have their own subscripting logic that is not tied
5264 // to overload resolution and so should not take this path.
5265 //
5266 // Issue a better diagnostic if we tried to pass multiple arguments to
5267 // a builtin subscript operator rather than diagnosing this as a generic
5268 // overload resolution failure.
5269 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5270 !base->getType()->isRecordType() &&
5271 !base->getType()->isObjCObjectPointerType()) {
5272 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5273 << base->getType() << base->getSourceRange();
5274 return ExprError();
5275 }
5276
5277 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5278 ((base->getType()->isRecordType() ||
5279 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5280 ArgExprs[0]->getType()->isRecordType())))) {
5281 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5282 }
5283
5284 ExprResult Res =
5285 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5286
5287 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5288 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5289
5290 return Res;
5291}
5292
5293ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5294 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5295 InitializationKind Kind =
5296 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5297 InitializationSequence InitSeq(*this, Entity, Kind, E);
5298 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5299}
5300
5301ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5302 Expr *RowIdx,
5303 SourceLocation RBLoc) {
5304 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5305 if (BaseR.isInvalid())
5306 return BaseR;
5307 Base = BaseR.get();
5308
5309 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5310 if (RowR.isInvalid())
5311 return RowR;
5312 RowIdx = RowR.get();
5313
5314 // Build an unanalyzed expression if any of the operands is type-dependent.
5315 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5316 return new (Context)
5317 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5318
5319 // Check that IndexExpr is an integer expression. If it is a constant
5320 // expression, check that it is less than Dim (= the number of elements in the
5321 // corresponding dimension).
5322 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5323 bool IsColumnIdx) -> Expr * {
5324 if (!IndexExpr->getType()->isIntegerType() &&
5325 !IndexExpr->isTypeDependent()) {
5326 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5327 << IsColumnIdx;
5328 return nullptr;
5329 }
5330
5331 if (std::optional<llvm::APSInt> Idx =
5332 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5333 if ((*Idx < 0 || *Idx >= Dim)) {
5334 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5335 << IsColumnIdx << Dim;
5336 return nullptr;
5337 }
5338 }
5339
5340 ExprResult ConvExpr = IndexExpr;
5341 assert(!ConvExpr.isInvalid() &&
5342 "should be able to convert any integer type to size type");
5343 return ConvExpr.get();
5344 };
5345
5346 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5347 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5348 if (!RowIdx)
5349 return ExprError();
5350
5351 QualType RowVecQT =
5352 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5353
5354 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5355}
5356
5357ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5358 Expr *ColumnIdx,
5359 SourceLocation RBLoc) {
5360 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5361 if (BaseR.isInvalid())
5362 return BaseR;
5363 Base = BaseR.get();
5364
5365 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5366 if (RowR.isInvalid())
5367 return RowR;
5368 RowIdx = RowR.get();
5369
5370 if (!ColumnIdx)
5371 return new (Context) MatrixSubscriptExpr(
5372 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5373
5374 // Build an unanalyzed expression if any of the operands is type-dependent.
5375 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5376 ColumnIdx->isTypeDependent())
5377 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5378 Context.DependentTy, RBLoc);
5379
5380 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5381 if (ColumnR.isInvalid())
5382 return ColumnR;
5383 ColumnIdx = ColumnR.get();
5384
5385 // Check that IndexExpr is an integer expression. If it is a constant
5386 // expression, check that it is less than Dim (= the number of elements in the
5387 // corresponding dimension).
5388 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5389 bool IsColumnIdx) -> Expr * {
5390 if (!IndexExpr->getType()->isIntegerType() &&
5391 !IndexExpr->isTypeDependent()) {
5392 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5393 << IsColumnIdx;
5394 return nullptr;
5395 }
5396
5397 if (std::optional<llvm::APSInt> Idx =
5398 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5399 if ((*Idx < 0 || *Idx >= Dim)) {
5400 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5401 << IsColumnIdx << Dim;
5402 return nullptr;
5403 }
5404 }
5405
5406 ExprResult ConvExpr = IndexExpr;
5407 assert(!ConvExpr.isInvalid() &&
5408 "should be able to convert any integer type to size type");
5409 return ConvExpr.get();
5410 };
5411
5412 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5413 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5414 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5415 if (!RowIdx || !ColumnIdx)
5416 return ExprError();
5417
5418 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5419 MTy->getElementType(), RBLoc);
5420}
5421
5422void Sema::CheckAddressOfNoDeref(const Expr *E) {
5423 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5424 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5425
5426 // For expressions like `&(*s).b`, the base is recorded and what should be
5427 // checked.
5428 const MemberExpr *Member = nullptr;
5429 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5430 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5431
5432 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5433}
5434
5435void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5436 if (isUnevaluatedContext())
5437 return;
5438
5439 QualType ResultTy = E->getType();
5440 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5441
5442 // Bail if the element is an array since it is not memory access.
5443 if (isa<ArrayType>(Val: ResultTy))
5444 return;
5445
5446 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5447 LastRecord.PossibleDerefs.insert(Ptr: E);
5448 return;
5449 }
5450
5451 // Check if the base type is a pointer to a member access of a struct
5452 // marked with noderef.
5453 const Expr *Base = E->getBase();
5454 QualType BaseTy = Base->getType();
5455 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5456 // Not a pointer access
5457 return;
5458
5459 const MemberExpr *Member = nullptr;
5460 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5461 Member->isArrow())
5462 Base = Member->getBase();
5463
5464 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5465 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5466 LastRecord.PossibleDerefs.insert(Ptr: E);
5467 }
5468}
5469
5470ExprResult
5471Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5472 Expr *Idx, SourceLocation RLoc) {
5473 Expr *LHSExp = Base;
5474 Expr *RHSExp = Idx;
5475
5476 ExprValueKind VK = VK_LValue;
5477 ExprObjectKind OK = OK_Ordinary;
5478
5479 // Per C++ core issue 1213, the result is an xvalue if either operand is
5480 // a non-lvalue array, and an lvalue otherwise.
5481 if (getLangOpts().CPlusPlus11) {
5482 for (auto *Op : {LHSExp, RHSExp}) {
5483 Op = Op->IgnoreImplicit();
5484 if (Op->getType()->isArrayType() && !Op->isLValue())
5485 VK = VK_XValue;
5486 }
5487 }
5488
5489 // Perform default conversions.
5490 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5491 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5492 if (Result.isInvalid())
5493 return ExprError();
5494 LHSExp = Result.get();
5495 }
5496 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5497 if (Result.isInvalid())
5498 return ExprError();
5499 RHSExp = Result.get();
5500
5501 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5502
5503 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5504 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5505 // in the subscript position. As a result, we need to derive the array base
5506 // and index from the expression types.
5507 Expr *BaseExpr, *IndexExpr;
5508 QualType ResultType;
5509 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5510 BaseExpr = LHSExp;
5511 IndexExpr = RHSExp;
5512 ResultType =
5513 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5514 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5515 BaseExpr = LHSExp;
5516 IndexExpr = RHSExp;
5517 ResultType = PTy->getPointeeType();
5518 } else if (const ObjCObjectPointerType *PTy =
5519 LHSTy->getAs<ObjCObjectPointerType>()) {
5520 BaseExpr = LHSExp;
5521 IndexExpr = RHSExp;
5522
5523 // Use custom logic if this should be the pseudo-object subscript
5524 // expression.
5525 if (!LangOpts.isSubscriptPointerArithmetic())
5526 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5527 getterMethod: nullptr, setterMethod: nullptr);
5528
5529 ResultType = PTy->getPointeeType();
5530 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5531 // Handle the uncommon case of "123[Ptr]".
5532 BaseExpr = RHSExp;
5533 IndexExpr = LHSExp;
5534 ResultType = PTy->getPointeeType();
5535 } else if (const ObjCObjectPointerType *PTy =
5536 RHSTy->getAs<ObjCObjectPointerType>()) {
5537 // Handle the uncommon case of "123[Ptr]".
5538 BaseExpr = RHSExp;
5539 IndexExpr = LHSExp;
5540 ResultType = PTy->getPointeeType();
5541 if (!LangOpts.isSubscriptPointerArithmetic()) {
5542 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5543 << ResultType << BaseExpr->getSourceRange();
5544 return ExprError();
5545 }
5546 } else if (LHSTy->isSubscriptableVectorType()) {
5547 if (LHSTy->isBuiltinType() &&
5548 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5549 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5550 if (BTy->isSVEBool())
5551 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5552 << LHSExp->getSourceRange()
5553 << RHSExp->getSourceRange());
5554 ResultType = BTy->getSveEltType(Ctx: Context);
5555 } else {
5556 const VectorType *VTy = LHSTy->getAs<VectorType>();
5557 ResultType = VTy->getElementType();
5558 }
5559 BaseExpr = LHSExp; // vectors: V[123]
5560 IndexExpr = RHSExp;
5561 // We apply C++ DR1213 to vector subscripting too.
5562 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5563 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5564 if (Materialized.isInvalid())
5565 return ExprError();
5566 LHSExp = Materialized.get();
5567 }
5568 VK = LHSExp->getValueKind();
5569 if (VK != VK_PRValue)
5570 OK = OK_VectorComponent;
5571
5572 QualType BaseType = BaseExpr->getType();
5573 Qualifiers BaseQuals = BaseType.getQualifiers();
5574 Qualifiers MemberQuals = ResultType.getQualifiers();
5575 Qualifiers Combined = BaseQuals + MemberQuals;
5576 if (Combined != MemberQuals)
5577 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5578 } else if (LHSTy->isArrayType()) {
5579 // If we see an array that wasn't promoted by
5580 // DefaultFunctionArrayLvalueConversion, it must be an array that
5581 // wasn't promoted because of the C90 rule that doesn't
5582 // allow promoting non-lvalue arrays. Warn, then
5583 // force the promotion here.
5584 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5585 << LHSExp->getSourceRange();
5586 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5587 CK: CK_ArrayToPointerDecay).get();
5588 LHSTy = LHSExp->getType();
5589
5590 BaseExpr = LHSExp;
5591 IndexExpr = RHSExp;
5592 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5593 } else if (RHSTy->isArrayType()) {
5594 // Same as previous, except for 123[f().a] case
5595 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5596 << RHSExp->getSourceRange();
5597 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5598 CK: CK_ArrayToPointerDecay).get();
5599 RHSTy = RHSExp->getType();
5600
5601 BaseExpr = RHSExp;
5602 IndexExpr = LHSExp;
5603 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5604 } else {
5605 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5606 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5607 }
5608 // C99 6.5.2.1p1
5609 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5610 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5611 << IndexExpr->getSourceRange());
5612
5613 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5614 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5615 !IndexExpr->isTypeDependent()) {
5616 std::optional<llvm::APSInt> IntegerContantExpr =
5617 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5618 if (!IntegerContantExpr.has_value() ||
5619 IntegerContantExpr.value().isNegative())
5620 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5621 }
5622
5623 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5624 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5625 // type. Note that Functions are not objects, and that (in C99 parlance)
5626 // incomplete types are not object types.
5627 if (ResultType->isFunctionType()) {
5628 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5629 << ResultType << BaseExpr->getSourceRange();
5630 return ExprError();
5631 }
5632
5633 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5634 // GNU extension: subscripting on pointer to void
5635 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5636 << BaseExpr->getSourceRange();
5637
5638 // C forbids expressions of unqualified void type from being l-values.
5639 // See IsCForbiddenLValueType.
5640 if (!ResultType.hasQualifiers())
5641 VK = VK_PRValue;
5642 } else if (!ResultType->isDependentType() &&
5643 !ResultType.isWebAssemblyReferenceType() &&
5644 RequireCompleteSizedType(
5645 Loc: LLoc, T: ResultType,
5646 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5647 return ExprError();
5648
5649 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5650 !ResultType.isCForbiddenLValueType());
5651
5652 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5653 FunctionScopes.size() > 1) {
5654 if (auto *TT =
5655 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5656 for (auto I = FunctionScopes.rbegin(),
5657 E = std::prev(x: FunctionScopes.rend());
5658 I != E; ++I) {
5659 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5660 if (CSI == nullptr)
5661 break;
5662 DeclContext *DC = nullptr;
5663 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5664 DC = LSI->CallOperator;
5665 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5666 DC = CRSI->TheCapturedDecl;
5667 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5668 DC = BSI->TheDecl;
5669 if (DC) {
5670 if (DC->containsDecl(D: TT->getDecl()))
5671 break;
5672 captureVariablyModifiedType(
5673 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5674 }
5675 }
5676 }
5677 }
5678
5679 return new (Context)
5680 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5681}
5682
5683bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5684 ParmVarDecl *Param, Expr *RewrittenInit,
5685 bool SkipImmediateInvocations) {
5686 if (Param->hasUnparsedDefaultArg()) {
5687 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5688 // If we've already cleared out the location for the default argument,
5689 // that means we're parsing it right now.
5690 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5691 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5692 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5693 Param->setInvalidDecl();
5694 return true;
5695 }
5696
5697 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5698 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5699 Diag(Loc: UnparsedDefaultArgLocs[Param],
5700 DiagID: diag::note_default_argument_declared_here);
5701 return true;
5702 }
5703
5704 if (Param->hasUninstantiatedDefaultArg()) {
5705 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5706 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5707 return true;
5708 }
5709
5710 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5711 assert(Init && "default argument but no initializer?");
5712
5713 // If the default expression creates temporaries, we need to
5714 // push them to the current stack of expression temporaries so they'll
5715 // be properly destroyed.
5716 // FIXME: We should really be rebuilding the default argument with new
5717 // bound temporaries; see the comment in PR5810.
5718 // We don't need to do that with block decls, though, because
5719 // blocks in default argument expression can never capture anything.
5720 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5721 // Set the "needs cleanups" bit regardless of whether there are
5722 // any explicit objects.
5723 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5724 // Append all the objects to the cleanup list. Right now, this
5725 // should always be a no-op, because blocks in default argument
5726 // expressions should never be able to capture anything.
5727 assert(!InitWithCleanup->getNumObjects() &&
5728 "default argument expression has capturing blocks?");
5729 }
5730 // C++ [expr.const]p15.1:
5731 // An expression or conversion is in an immediate function context if it is
5732 // potentially evaluated and [...] its innermost enclosing non-block scope
5733 // is a function parameter scope of an immediate function.
5734 EnterExpressionEvaluationContext EvalContext(
5735 *this,
5736 FD->isImmediateFunction()
5737 ? ExpressionEvaluationContext::ImmediateFunctionContext
5738 : ExpressionEvaluationContext::PotentiallyEvaluated,
5739 Param);
5740 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5741 SkipImmediateInvocations;
5742 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5743 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5744 });
5745 return false;
5746}
5747
5748struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5749 const ASTContext &Context;
5750 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5751 ShouldVisitImplicitCode = true;
5752 }
5753
5754 bool HasImmediateCalls = false;
5755
5756 bool VisitCallExpr(CallExpr *E) override {
5757 if (const FunctionDecl *FD = E->getDirectCallee())
5758 HasImmediateCalls |= FD->isImmediateFunction();
5759 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5760 }
5761
5762 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5763 if (const FunctionDecl *FD = E->getConstructor())
5764 HasImmediateCalls |= FD->isImmediateFunction();
5765 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5766 }
5767
5768 // SourceLocExpr are not immediate invocations
5769 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5770 // need to be rebuilt so that they refer to the correct SourceLocation and
5771 // DeclContext.
5772 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5773 HasImmediateCalls = true;
5774 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5775 }
5776
5777 // A nested lambda might have parameters with immediate invocations
5778 // in their default arguments.
5779 // The compound statement is not visited (as it does not constitute a
5780 // subexpression).
5781 // FIXME: We should consider visiting and transforming captures
5782 // with init expressions.
5783 bool VisitLambdaExpr(LambdaExpr *E) override {
5784 return VisitCXXMethodDecl(D: E->getCallOperator());
5785 }
5786
5787 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5788 return TraverseStmt(S: E->getExpr());
5789 }
5790
5791 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5792 return TraverseStmt(S: E->getExpr());
5793 }
5794};
5795
5796struct EnsureImmediateInvocationInDefaultArgs
5797 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5798 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5799 : TreeTransform(SemaRef) {}
5800
5801 bool AlwaysRebuild() { return true; }
5802
5803 // Lambda can only have immediate invocations in the default
5804 // args of their parameters, which is transformed upon calling the closure.
5805 // The body is not a subexpression, so we have nothing to do.
5806 // FIXME: Immediate calls in capture initializers should be transformed.
5807 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5808 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5809
5810 // Make sure we don't rebuild the this pointer as it would
5811 // cause it to incorrectly point it to the outermost class
5812 // in the case of nested struct initialization.
5813 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5814
5815 // Rewrite to source location to refer to the context in which they are used.
5816 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5817 DeclContext *DC = E->getParentContext();
5818 if (DC == SemaRef.CurContext)
5819 return E;
5820
5821 // FIXME: During instantiation, because the rebuild of defaults arguments
5822 // is not always done in the context of the template instantiator,
5823 // we run the risk of producing a dependent source location
5824 // that would never be rebuilt.
5825 // This usually happens during overload resolution, or in contexts
5826 // where the value of the source location does not matter.
5827 // However, we should find a better way to deal with source location
5828 // of function templates.
5829 if (!SemaRef.CurrentInstantiationScope ||
5830 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5831 DC = SemaRef.CurContext;
5832
5833 return getDerived().RebuildSourceLocExpr(
5834 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5835 }
5836};
5837
5838ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5839 FunctionDecl *FD, ParmVarDecl *Param,
5840 Expr *Init) {
5841 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5842
5843 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5844 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5845 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5846 InitializationContext =
5847 OutermostDeclarationWithDelayedImmediateInvocations();
5848 if (!InitializationContext.has_value())
5849 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5850
5851 if (!Init && !Param->hasUnparsedDefaultArg()) {
5852 // Mark that we are replacing a default argument first.
5853 // If we are instantiating a template we won't have to
5854 // retransform immediate calls.
5855 // C++ [expr.const]p15.1:
5856 // An expression or conversion is in an immediate function context if it
5857 // is potentially evaluated and [...] its innermost enclosing non-block
5858 // scope is a function parameter scope of an immediate function.
5859 EnterExpressionEvaluationContext EvalContext(
5860 *this,
5861 FD->isImmediateFunction()
5862 ? ExpressionEvaluationContext::ImmediateFunctionContext
5863 : ExpressionEvaluationContext::PotentiallyEvaluated,
5864 Param);
5865
5866 if (Param->hasUninstantiatedDefaultArg()) {
5867 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5868 return ExprError();
5869 }
5870 // CWG2631
5871 // An immediate invocation that is not evaluated where it appears is
5872 // evaluated and checked for whether it is a constant expression at the
5873 // point where the enclosing initializer is used in a function call.
5874 ImmediateCallVisitor V(getASTContext());
5875 if (!NestedDefaultChecking)
5876 V.TraverseDecl(D: Param);
5877
5878 // Rewrite the call argument that was created from the corresponding
5879 // parameter's default argument.
5880 if (V.HasImmediateCalls ||
5881 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5882 if (V.HasImmediateCalls)
5883 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5884 CallLoc, Param, CurContext};
5885 // Pass down lifetime extending flag, and collect temporaries in
5886 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5887 currentEvaluationContext().InLifetimeExtendingContext =
5888 parentEvaluationContext().InLifetimeExtendingContext;
5889 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5890 ExprResult Res;
5891 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5892 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5893 /*NotCopy=*/NotCopyInit: false);
5894 });
5895 if (Res.isInvalid())
5896 return ExprError();
5897 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5898 EqualLoc: Res.get()->getBeginLoc());
5899 if (Res.isInvalid())
5900 return ExprError();
5901 Init = Res.get();
5902 }
5903 }
5904
5905 if (CheckCXXDefaultArgExpr(
5906 CallLoc, FD, Param, RewrittenInit: Init,
5907 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5908 return ExprError();
5909
5910 if (getLangOpts().CUDA)
5911 CUDA().checkRTTIInDefaultInit(D: Param, Init: Init ? Init : Param->getDefaultArg(),
5912 UseLoc: CallLoc);
5913
5914 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5915 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5916}
5917
5918static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5919 FieldDecl *Field) {
5920 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5921 return Pattern;
5922 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5923 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5924 DeclContext::lookup_result Lookup =
5925 ClassPattern->lookup(Name: Field->getDeclName());
5926 auto Rng = llvm::make_filter_range(
5927 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5928 if (Rng.empty())
5929 return nullptr;
5930 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5931 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5932 // && "Duplicated instantiation pattern for field decl");
5933 return cast<FieldDecl>(Val: *Rng.begin());
5934}
5935
5936ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
5937 FieldDecl *Field,
5938 const InitializedEntity &Entity,
5939 bool NestedDefaultChecking,
5940 bool NeedRebuild) {
5941 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5942
5943 if (!Field->getInClassInitializer() &&
5944 isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5945 // Maybe we haven't instantiated the in-class initializer. Go check the
5946 // pattern FieldDecl to see if it has one.
5947 FieldDecl *Pattern =
5948 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5949 assert(Pattern && "We must have set the Pattern!");
5950 if (!Pattern->hasInClassInitializer() ||
5951 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5952 TemplateArgs: getTemplateInstantiationArgs(D: Field)))
5953 return ExprError();
5954 }
5955
5956 Expr *InClassInit = Field->getInClassInitializer();
5957 if (!InClassInit) {
5958 // DR1351:
5959 // If the brace-or-equal-initializer of a non-static data member
5960 // invokes a defaulted default constructor of its class or of an
5961 // enclosing class in a potentially evaluated subexpression, the
5962 // program is ill-formed.
5963 //
5964 // This resolution is unworkable: the exception specification of the
5965 // default constructor can be needed in an unevaluated context, in
5966 // particular, in the operand of a noexcept-expression, and we can be
5967 // unable to compute an exception specification for an enclosed class.
5968 //
5969 // Any attempt to resolve the exception specification of a defaulted default
5970 // constructor before the initializer is lexically complete will ultimately
5971 // come here at which point we can diagnose it.
5972 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5973 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5974 << OutermostClass << Field;
5975 Diag(Loc: Field->getEndLoc(),
5976 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5977 // Recover by marking the field invalid, unless we're in a SFINAE context.
5978 if (!isSFINAEContext())
5979 Field->setInvalidDecl();
5980 return ExprError();
5981 }
5982
5983 if (getLangOpts().CUDA)
5984 CUDA().checkRTTIInDefaultInit(D: Field, Init: InClassInit, UseLoc: Loc);
5985
5986 // CWG2631
5987 // An immediate invocation that is not evaluated where it appears is
5988 // evaluated and checked for whether it is a constant expression at the
5989 // point where the enclosing initializer is used in a [...] a constructor
5990 // definition, or an aggregate initialization.
5991 ImmediateCallVisitor V(getASTContext());
5992 if (!NestedDefaultChecking)
5993 V.TraverseDecl(D: Field);
5994
5995 // CWG1815
5996 // Support lifetime extension of temporary created by aggregate
5997 // initialization using a default member initializer. We should rebuild
5998 // the initializer in a lifetime extension context if the initializer
5999 // expression is an ExprWithCleanups. Then make sure the normal lifetime
6000 // extension code recurses into the default initializer and does lifetime
6001 // extension when warranted.
6002 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(Val: InClassInit);
6003 Expr *Init = InClassInit;
6004 if (!InClassInit->containsErrors() &&
6005 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
6006 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6007 CurContext};
6008 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6009 NestedDefaultChecking;
6010 // Pass down lifetime extending flag, and collect temporaries in
6011 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
6012 currentEvaluationContext().InLifetimeExtendingContext =
6013 parentEvaluationContext().InLifetimeExtendingContext;
6014
6015 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6016 ExprResult Res;
6017 runWithSufficientStackSpace(Loc, Fn: [&] {
6018 Res = Immediate.TransformInitializer(Init: InClassInit,
6019 /*CXXDirectInit=*/NotCopyInit: false);
6020 });
6021 if (!Res.isInvalid())
6022 Res = ConvertMemberDefaultInitExpression(FD: Field, Entity, InitExpr: Res.get(), InitLoc: Loc);
6023 if (Res.isInvalid()) {
6024 Field->setInvalidDecl();
6025 return ExprError();
6026 }
6027 Init = Res.get();
6028 }
6029
6030 if (!NestedDefaultChecking)
6031 runWithSufficientStackSpace(Loc, Fn: [&] {
6032 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/false);
6033 });
6034 return Init;
6035}
6036
6037ExprResult Sema::BuildCXXCtorDefaultInitExpr(SourceLocation Loc,
6038 FieldDecl *Field) {
6039 assert(Field->hasInClassInitializer());
6040
6041 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6042
6043 // C++11 [class.base.init]p7:
6044 // The initialization of each base and member constitutes a
6045 // full-expression.
6046 // So this initializer gets an evaluation context of its own, and is finished
6047 // as a full-expression below.
6048 EnterExpressionEvaluationContext EvalContext(
6049 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6050 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6051
6052 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6053 if (!InitContext)
6054 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6055
6056 // [class.temporary]/p7:
6057 // If such a temporary object would otherwise be destroyed at the end of the
6058 // for-range-initializer full-expression, the object persists for the lifetime
6059 // of the reference initialized by the for-range-initializer.
6060 //
6061 // A default member initializer used by a constructor is a separate
6062 // full-expression, we don't need extend temporaries lifetime in this
6063 // situation, the NeedRebuild will always false.
6064 ExprResult Init = BuildCXXDefaultInitInternal(
6065 Loc, Field,
6066 Entity: InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: Field),
6067 NestedDefaultChecking, /*NeedRebuild=*/false);
6068 if (Init.isInvalid())
6069 return ExprError();
6070
6071 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue=*/false);
6072 if (Init.isInvalid()) {
6073 Field->setInvalidDecl();
6074 return ExprError();
6075 }
6076
6077 return CXXDefaultInitExpr::Create(
6078 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6079 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6080}
6081
6082ExprResult
6083Sema::BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
6084 const InitializedEntity &MemberEntity) {
6085 assert(Field->hasInClassInitializer());
6086
6087 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6088
6089 // Unlike a mem-initializer, this initializer is a subexpression of the
6090 // full-expression containing the aggregate initialization. It is evaluated
6091 // exactly as that full-expression is, so inherit the enclosing context kind
6092 // rather than forcing a potentially evaluated one.
6093 EnterExpressionEvaluationContext EvalContext(
6094 *this, currentEvaluationContext().Context, Field);
6095 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6096
6097 auto InitContext = OutermostDeclarationWithDelayedImmediateInvocations();
6098 if (!InitContext)
6099 InitContext.emplace(args&: Loc, args&: Field, args&: CurContext);
6100
6101 // [class.temporary]/p7:
6102 // If such a temporary object would otherwise be destroyed at the end of the
6103 // for-range-initializer full-expression, the object persists for the lifetime
6104 // of the reference initialized by the for-range-initializer.
6105 //
6106 // A default member initializer used by an aggregate initialization belongs to
6107 // the full-expression containing the aggregate initialization. we need extend
6108 // temporaries lifetime in this situation, the NeedRebuild will always true.
6109
6110 // CWG1815: always rebuild, never share the AST built when the field was
6111 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6112 // collected in this context, which is what lets the aggregate initialization
6113 // lifetime-extend them; sharing one AST would also make several uses of the
6114 // same field fight over its extension. A mem-initializer has no such need,
6115 // as its temporaries die at the end of the initializer itself.
6116 ExprResult Init = BuildCXXDefaultInitInternal(
6117 Loc, Field, Entity: MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6118 if (Init.isInvalid())
6119 return ExprError();
6120
6121 // Deliberately not finished as a full-expression: leaving the temporaries it
6122 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6123 // them into the enclosing context, which eventually wraps them all in a
6124 // single ExprWithCleanups. They are then destroyed at the end of the
6125 // containing full-expression, in reverse construction order.
6126
6127 return CXXDefaultInitExpr::Create(
6128 Ctx: Context, Loc: InitContext->Loc, Field, UsedContext: InitContext->Context,
6129 RewrittenInitExpr: Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6130}
6131
6132VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
6133 const FunctionProtoType *Proto,
6134 Expr *Fn) {
6135 if (Proto && Proto->isVariadic()) {
6136 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
6137 return VariadicCallType::Constructor;
6138 else if (Fn && Fn->getType()->isBlockPointerType())
6139 return VariadicCallType::Block;
6140 else if (FDecl) {
6141 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
6142 if (Method->isInstance())
6143 return VariadicCallType::Method;
6144 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6145 return VariadicCallType::Method;
6146 return VariadicCallType::Function;
6147 }
6148 return VariadicCallType::DoesNotApply;
6149}
6150
6151namespace {
6152class FunctionCallCCC final : public FunctionCallFilterCCC {
6153public:
6154 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6155 unsigned NumArgs, MemberExpr *ME)
6156 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6157 FunctionName(FuncName) {}
6158
6159 bool ValidateCandidate(const TypoCorrection &candidate) override {
6160 if (!candidate.getCorrectionSpecifier() ||
6161 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6162 return false;
6163 }
6164
6165 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6166 }
6167
6168 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6169 return std::make_unique<FunctionCallCCC>(args&: *this);
6170 }
6171
6172private:
6173 const IdentifierInfo *const FunctionName;
6174};
6175}
6176
6177static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6178 FunctionDecl *FDecl,
6179 ArrayRef<Expr *> Args) {
6180 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6181 DeclarationName FuncName = FDecl->getDeclName();
6182 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6183
6184 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6185 if (TypoCorrection Corrected = S.CorrectTypo(
6186 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6187 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6188 Mode: CorrectTypoKind::ErrorRecovery)) {
6189 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6190 if (Corrected.isOverloaded()) {
6191 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6192 OverloadCandidateSet::iterator Best;
6193 for (NamedDecl *CD : Corrected) {
6194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6195 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6196 CandidateSet&: OCS);
6197 }
6198 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6199 case OR_Success:
6200 ND = Best->FoundDecl;
6201 Corrected.setCorrectionDecl(ND);
6202 break;
6203 default:
6204 break;
6205 }
6206 }
6207 ND = ND->getUnderlyingDecl();
6208 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6209 return Corrected;
6210 }
6211 }
6212 return TypoCorrection();
6213}
6214
6215// [C++26][[expr.unary.op]/p4
6216// A pointer to member is only formed when an explicit &
6217// is used and its operand is a qualified-id not enclosed in parentheses.
6218static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6219 if (!isa<ParenExpr>(Val: Fn))
6220 return false;
6221
6222 Fn = Fn->IgnoreParens();
6223
6224 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6225 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6226 return false;
6227 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6228 return DRE->hasQualifier();
6229 }
6230 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6231 return bool(OVL->getQualifier());
6232 return false;
6233}
6234
6235bool
6236Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6237 FunctionDecl *FDecl,
6238 const FunctionProtoType *Proto,
6239 ArrayRef<Expr *> Args,
6240 SourceLocation RParenLoc,
6241 bool IsExecConfig) {
6242 // Bail out early if calling a builtin with custom typechecking.
6243 // For HLSL builtin aliases, argument conversion is still needed because
6244 // overload resolution may have selected a conversion sequence (e.g.,
6245 // vector-to-scalar truncation) that must be applied before the custom
6246 // type checker runs.
6247 if (FDecl)
6248 if (unsigned ID = FDecl->getBuiltinID())
6249 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6250 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6251 return false;
6252
6253 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6254 // assignment, to the types of the corresponding parameter, ...
6255
6256 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6257 bool HasExplicitObjectParameter =
6258 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6259 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6260 unsigned NumParams = Proto->getNumParams();
6261 bool Invalid = false;
6262 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6263 unsigned FnKind = Fn->getType()->isBlockPointerType()
6264 ? 1 /* block */
6265 : (IsExecConfig ? 3 /* kernel function (exec config) */
6266 : 0 /* function */);
6267
6268 // If too few arguments are available (and we don't have default
6269 // arguments for the remaining parameters), don't make the call.
6270 if (Args.size() < NumParams) {
6271 if (Args.size() < MinArgs) {
6272 TypoCorrection TC;
6273 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6274 unsigned diag_id =
6275 MinArgs == NumParams && !Proto->isVariadic()
6276 ? diag::err_typecheck_call_too_few_args_suggest
6277 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6278 diagnoseTypo(
6279 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6280 << FnKind << MinArgs - ExplicitObjectParameterOffset
6281 << static_cast<unsigned>(Args.size()) -
6282 ExplicitObjectParameterOffset
6283 << HasExplicitObjectParameter << TC.getCorrectionRange());
6284 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6285 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6286 ->getDeclName())
6287 Diag(Loc: RParenLoc,
6288 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6289 ? diag::err_typecheck_call_too_few_args_one
6290 : diag::err_typecheck_call_too_few_args_at_least_one)
6291 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6292 << HasExplicitObjectParameter << Fn->getSourceRange();
6293 else
6294 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6295 ? diag::err_typecheck_call_too_few_args
6296 : diag::err_typecheck_call_too_few_args_at_least)
6297 << FnKind << MinArgs - ExplicitObjectParameterOffset
6298 << static_cast<unsigned>(Args.size()) -
6299 ExplicitObjectParameterOffset
6300 << HasExplicitObjectParameter << Fn->getSourceRange();
6301
6302 // Emit the location of the prototype.
6303 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6304 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6305 << FDecl << FDecl->getParametersSourceRange();
6306
6307 return true;
6308 }
6309 // We reserve space for the default arguments when we create
6310 // the call expression, before calling ConvertArgumentsForCall.
6311 assert((Call->getNumArgs() == NumParams) &&
6312 "We should have reserved space for the default arguments before!");
6313 }
6314
6315 // If too many are passed and not variadic, error on the extras and drop
6316 // them.
6317 if (Args.size() > NumParams) {
6318 if (!Proto->isVariadic()) {
6319 TypoCorrection TC;
6320 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6321 unsigned diag_id =
6322 MinArgs == NumParams && !Proto->isVariadic()
6323 ? diag::err_typecheck_call_too_many_args_suggest
6324 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6325 diagnoseTypo(
6326 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6327 << FnKind << NumParams - ExplicitObjectParameterOffset
6328 << static_cast<unsigned>(Args.size()) -
6329 ExplicitObjectParameterOffset
6330 << HasExplicitObjectParameter << TC.getCorrectionRange());
6331 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6332 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6333 ->getDeclName())
6334 Diag(Loc: Args[NumParams]->getBeginLoc(),
6335 DiagID: MinArgs == NumParams
6336 ? diag::err_typecheck_call_too_many_args_one
6337 : diag::err_typecheck_call_too_many_args_at_most_one)
6338 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6339 << static_cast<unsigned>(Args.size()) -
6340 ExplicitObjectParameterOffset
6341 << HasExplicitObjectParameter << Fn->getSourceRange()
6342 << SourceRange(Args[NumParams]->getBeginLoc(),
6343 Args.back()->getEndLoc());
6344 else
6345 Diag(Loc: Args[NumParams]->getBeginLoc(),
6346 DiagID: MinArgs == NumParams
6347 ? diag::err_typecheck_call_too_many_args
6348 : diag::err_typecheck_call_too_many_args_at_most)
6349 << FnKind << NumParams - ExplicitObjectParameterOffset
6350 << static_cast<unsigned>(Args.size()) -
6351 ExplicitObjectParameterOffset
6352 << HasExplicitObjectParameter << Fn->getSourceRange()
6353 << SourceRange(Args[NumParams]->getBeginLoc(),
6354 Args.back()->getEndLoc());
6355
6356 // Emit the location of the prototype.
6357 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6358 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6359 << FDecl << FDecl->getParametersSourceRange();
6360
6361 // This deletes the extra arguments.
6362 Call->shrinkNumArgs(NewNumArgs: NumParams);
6363 return true;
6364 }
6365 }
6366 SmallVector<Expr *, 8> AllArgs;
6367 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6368
6369 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6370 AllArgs, CallType);
6371 if (Invalid)
6372 return true;
6373 unsigned TotalNumArgs = AllArgs.size();
6374 for (unsigned i = 0; i < TotalNumArgs; ++i)
6375 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6376
6377 Call->computeDependence();
6378 return false;
6379}
6380
6381bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6382 const FunctionProtoType *Proto,
6383 unsigned FirstParam, ArrayRef<Expr *> Args,
6384 SmallVectorImpl<Expr *> &AllArgs,
6385 VariadicCallType CallType, bool AllowExplicit,
6386 bool IsListInitialization) {
6387 unsigned NumParams = Proto->getNumParams();
6388 bool Invalid = false;
6389 size_t ArgIx = 0;
6390 // Continue to check argument types (even if we have too few/many args).
6391 for (unsigned i = FirstParam; i < NumParams; i++) {
6392 QualType ProtoArgType = Proto->getParamType(i);
6393
6394 Expr *Arg;
6395 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6396 if (ArgIx < Args.size()) {
6397 Arg = Args[ArgIx++];
6398
6399 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6400 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6401 return true;
6402
6403 // Strip the unbridged-cast placeholder expression off, if applicable.
6404 bool CFAudited = false;
6405 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6406 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6407 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6408 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6409 else if (getLangOpts().ObjCAutoRefCount &&
6410 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6411 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6412 CFAudited = true;
6413
6414 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6415 ProtoArgType->isBlockPointerType())
6416 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6417 BE->getBlockDecl()->setDoesNotEscape();
6418 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6419 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6420 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6421 if (ArgExpr.isInvalid())
6422 return true;
6423 Arg = ArgExpr.getAs<Expr>();
6424 }
6425
6426 InitializedEntity Entity =
6427 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6428 Type: ProtoArgType)
6429 : InitializedEntity::InitializeParameter(
6430 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6431
6432 // Remember that parameter belongs to a CF audited API.
6433 if (CFAudited)
6434 Entity.setParameterCFAudited();
6435
6436 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6437 // function boundaries is a common oversight.
6438 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6439 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6440 bool isPedantic =
6441 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6442 Diag(Loc: Arg->getExprLoc(),
6443 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6444 : diag::warn_obt_discarded_at_function_boundary)
6445 << Arg->getType() << ProtoArgType;
6446 }
6447
6448 ExprResult ArgE = PerformCopyInitialization(
6449 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6450 if (ArgE.isInvalid())
6451 return true;
6452
6453 Arg = ArgE.getAs<Expr>();
6454 } else {
6455 assert(Param && "can't use default arguments without a known callee");
6456
6457 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6458 if (ArgExpr.isInvalid())
6459 return true;
6460
6461 Arg = ArgExpr.getAs<Expr>();
6462 }
6463
6464 // Check for array bounds violations for each argument to the call. This
6465 // check only triggers warnings when the argument isn't a more complex Expr
6466 // with its own checking, such as a BinaryOperator.
6467 CheckArrayAccess(E: Arg);
6468
6469 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6470 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6471
6472 AllArgs.push_back(Elt: Arg);
6473 }
6474
6475 // If this is a variadic call, handle args passed through "...".
6476 if (CallType != VariadicCallType::DoesNotApply) {
6477 // Assume that extern "C" functions with variadic arguments that
6478 // return __unknown_anytype aren't *really* variadic.
6479 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6480 FDecl->isExternC()) {
6481 for (Expr *A : Args.slice(N: ArgIx)) {
6482 QualType paramType; // ignored
6483 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6484 Invalid |= arg.isInvalid();
6485 AllArgs.push_back(Elt: arg.get());
6486 }
6487
6488 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6489 } else {
6490 for (Expr *A : Args.slice(N: ArgIx)) {
6491 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6492 Invalid |= Arg.isInvalid();
6493 AllArgs.push_back(Elt: Arg.get());
6494 }
6495 }
6496
6497 // Check for array bounds violations.
6498 for (Expr *A : Args.slice(N: ArgIx))
6499 CheckArrayAccess(E: A);
6500 }
6501 return Invalid;
6502}
6503
6504static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6505 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6506 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6507 TL = DTL.getOriginalLoc();
6508 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6509 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6510 << ATL.getLocalSourceRange();
6511}
6512
6513void
6514Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6515 ParmVarDecl *Param,
6516 const Expr *ArgExpr) {
6517 // Static array parameters are not supported in C++.
6518 if (!Param || getLangOpts().CPlusPlus)
6519 return;
6520
6521 QualType OrigTy = Param->getOriginalType();
6522
6523 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6524 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6525 return;
6526
6527 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6528 NPC: Expr::NPC_NeverValueDependent)) {
6529 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6530 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6531 return;
6532 }
6533
6534 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6535 if (!CAT)
6536 return;
6537
6538 const ConstantArrayType *ArgCAT =
6539 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6540 if (!ArgCAT)
6541 return;
6542
6543 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6544 T2: ArgCAT->getElementType())) {
6545 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6546 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6547 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6548 << (unsigned)CAT->getZExtSize() << 0;
6549 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6550 }
6551 return;
6552 }
6553
6554 std::optional<CharUnits> ArgSize =
6555 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6556 std::optional<CharUnits> ParmSize =
6557 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6558 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6559 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6560 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6561 << (unsigned)ParmSize->getQuantity() << 1;
6562 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6563 }
6564}
6565
6566/// Given a function expression of unknown-any type, try to rebuild it
6567/// to have a function type.
6568static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6569
6570/// Is the given type a placeholder that we need to lower out
6571/// immediately during argument processing?
6572static bool isPlaceholderToRemoveAsArg(QualType type) {
6573 // Placeholders are never sugared.
6574 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6575 if (!placeholder) return false;
6576
6577 switch (placeholder->getKind()) {
6578 // Ignore all the non-placeholder types.
6579#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6580 case BuiltinType::Id:
6581#include "clang/Basic/OpenCLImageTypes.def"
6582#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6583 case BuiltinType::Id:
6584#include "clang/Basic/OpenCLExtensionTypes.def"
6585 // In practice we'll never use this, since all SVE types are sugared
6586 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6587#define SVE_TYPE(Name, Id, SingletonId) \
6588 case BuiltinType::Id:
6589#include "clang/Basic/AArch64ACLETypes.def"
6590#define PPC_VECTOR_TYPE(Name, Id, Size) \
6591 case BuiltinType::Id:
6592#include "clang/Basic/PPCTypes.def"
6593#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6594#include "clang/Basic/RISCVVTypes.def"
6595#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6596#include "clang/Basic/WebAssemblyReferenceTypes.def"
6597#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6598#include "clang/Basic/AMDGPUTypes.def"
6599#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6600#include "clang/Basic/HLSLIntangibleTypes.def"
6601#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6602#include "clang/Basic/HLSLPackedTypes.def"
6603#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6604#include "clang/Basic/SPIRVTypes.def"
6605#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6606#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6607#include "clang/AST/BuiltinTypes.def"
6608 return false;
6609
6610 case BuiltinType::UnresolvedTemplate:
6611 // We cannot lower out overload sets; they might validly be resolved
6612 // by the call machinery.
6613 case BuiltinType::Overload:
6614 return false;
6615
6616 // Unbridged casts in ARC can be handled in some call positions and
6617 // should be left in place.
6618 case BuiltinType::ARCUnbridgedCast:
6619 return false;
6620
6621 // Pseudo-objects should be converted as soon as possible.
6622 case BuiltinType::PseudoObject:
6623 return true;
6624
6625 // The debugger mode could theoretically but currently does not try
6626 // to resolve unknown-typed arguments based on known parameter types.
6627 case BuiltinType::UnknownAny:
6628 return true;
6629
6630 // These are always invalid as call arguments and should be reported.
6631 case BuiltinType::BoundMember:
6632 case BuiltinType::BuiltinFn:
6633 case BuiltinType::IncompleteMatrixIdx:
6634 case BuiltinType::ArraySection:
6635 case BuiltinType::OMPArrayShaping:
6636 case BuiltinType::OMPIterator:
6637 return true;
6638
6639 }
6640 llvm_unreachable("bad builtin type kind");
6641}
6642
6643bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6644 // Apply this processing to all the arguments at once instead of
6645 // dying at the first failure.
6646 bool hasInvalid = false;
6647 for (size_t i = 0, e = args.size(); i != e; i++) {
6648 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6649 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6650 if (result.isInvalid()) hasInvalid = true;
6651 else args[i] = result.get();
6652 }
6653 }
6654 return hasInvalid;
6655}
6656
6657/// If a builtin function has a pointer argument with no explicit address
6658/// space, then it should be able to accept a pointer to any address
6659/// space as input. In order to do this, we need to replace the
6660/// standard builtin declaration with one that uses the same address space
6661/// as the call.
6662///
6663/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6664/// it does not contain any pointer arguments without
6665/// an address space qualifer. Otherwise the rewritten
6666/// FunctionDecl is returned.
6667/// TODO: Handle pointer return types.
6668static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6669 FunctionDecl *FDecl,
6670 MultiExprArg ArgExprs) {
6671
6672 QualType DeclType = FDecl->getType();
6673 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6674
6675 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6676 ArgExprs.size() < FT->getNumParams())
6677 return nullptr;
6678
6679 bool NeedsNewDecl = false;
6680 unsigned i = 0;
6681 SmallVector<QualType, 8> OverloadParams;
6682
6683 {
6684 // The lvalue conversions in this loop are only for type resolution and
6685 // don't actually occur.
6686 EnterExpressionEvaluationContext Unevaluated(
6687 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6688 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6689
6690 for (QualType ParamType : FT->param_types()) {
6691
6692 // Convert array arguments to pointer to simplify type lookup.
6693 ExprResult ArgRes =
6694 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6695 if (ArgRes.isInvalid())
6696 return nullptr;
6697 Expr *Arg = ArgRes.get();
6698 QualType ArgType = Arg->getType();
6699 if (!ParamType->isPointerType() ||
6700 ParamType->getPointeeType().hasAddressSpace() ||
6701 !ArgType->isPointerType() ||
6702 !ArgType->getPointeeType().hasAddressSpace() ||
6703 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6704 OverloadParams.push_back(Elt: ParamType);
6705 continue;
6706 }
6707
6708 QualType PointeeType = ParamType->getPointeeType();
6709 NeedsNewDecl = true;
6710 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6711
6712 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6713 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6714 }
6715 }
6716
6717 if (!NeedsNewDecl)
6718 return nullptr;
6719
6720 FunctionProtoType::ExtProtoInfo EPI;
6721 EPI.Variadic = FT->isVariadic();
6722 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6723 Args: OverloadParams, EPI);
6724 DeclContext *Parent = FDecl->getParent();
6725 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6726 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6727 N: FDecl->getIdentifier(), T: OverloadTy,
6728 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6729 isInlineSpecified: false,
6730 /*hasPrototype=*/hasWrittenPrototype: true);
6731 SmallVector<ParmVarDecl*, 16> Params;
6732 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6733 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6734 QualType ParamType = FT->getParamType(i);
6735 ParmVarDecl *Parm =
6736 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6737 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6738 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6739 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6740 Params.push_back(Elt: Parm);
6741 }
6742 OverloadDecl->setParams(Params);
6743 // We cannot merge host/device attributes of redeclarations. They have to
6744 // be consistent when created.
6745 if (Sema->LangOpts.CUDA) {
6746 if (FDecl->hasAttr<CUDAHostAttr>())
6747 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6748 if (FDecl->hasAttr<CUDADeviceAttr>())
6749 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6750 }
6751 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6752 return OverloadDecl;
6753}
6754
6755static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6756 FunctionDecl *Callee,
6757 MultiExprArg ArgExprs) {
6758 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6759 // similar attributes) really don't like it when functions are called with an
6760 // invalid number of args.
6761 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6762 /*PartialOverloading=*/false) &&
6763 !Callee->isVariadic())
6764 return;
6765 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6766 return;
6767
6768 if (const EnableIfAttr *Attr =
6769 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6770 S.Diag(Loc: Fn->getBeginLoc(),
6771 DiagID: isa<CXXMethodDecl>(Val: Callee)
6772 ? diag::err_ovl_no_viable_member_function_in_call
6773 : diag::err_ovl_no_viable_function_in_call)
6774 << Callee << Callee->getSourceRange();
6775 S.Diag(Loc: Callee->getLocation(),
6776 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6777 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6778 return;
6779 }
6780}
6781
6782static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6783 const UnresolvedMemberExpr *const UME, Sema &S) {
6784
6785 const auto GetFunctionLevelDCIfCXXClass =
6786 [](Sema &S) -> const CXXRecordDecl * {
6787 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6788 if (!DC || !DC->getParent())
6789 return nullptr;
6790
6791 // If the call to some member function was made from within a member
6792 // function body 'M' return return 'M's parent.
6793 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6794 return MD->getParent()->getCanonicalDecl();
6795 // else the call was made from within a default member initializer of a
6796 // class, so return the class.
6797 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6798 return RD->getCanonicalDecl();
6799 return nullptr;
6800 };
6801 // If our DeclContext is neither a member function nor a class (in the
6802 // case of a lambda in a default member initializer), we can't have an
6803 // enclosing 'this'.
6804
6805 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6806 if (!CurParentClass)
6807 return false;
6808
6809 // The naming class for implicit member functions call is the class in which
6810 // name lookup starts.
6811 const CXXRecordDecl *const NamingClass =
6812 UME->getNamingClass()->getCanonicalDecl();
6813 assert(NamingClass && "Must have naming class even for implicit access");
6814
6815 // If the unresolved member functions were found in a 'naming class' that is
6816 // related (either the same or derived from) to the class that contains the
6817 // member function that itself contained the implicit member access.
6818
6819 return CurParentClass == NamingClass ||
6820 CurParentClass->isDerivedFrom(Base: NamingClass);
6821}
6822
6823static void
6824tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6825 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6826
6827 if (!UME)
6828 return;
6829
6830 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6831 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6832 // already been captured, or if this is an implicit member function call (if
6833 // it isn't, an attempt to capture 'this' should already have been made).
6834 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6835 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6836 return;
6837
6838 // Check if the naming class in which the unresolved members were found is
6839 // related (same as or is a base of) to the enclosing class.
6840
6841 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6842 return;
6843
6844
6845 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6846 // If the enclosing function is not dependent, then this lambda is
6847 // capture ready, so if we can capture this, do so.
6848 if (!EnclosingFunctionCtx->isDependentContext()) {
6849 // If the current lambda and all enclosing lambdas can capture 'this' -
6850 // then go ahead and capture 'this' (since our unresolved overload set
6851 // contains at least one non-static member function).
6852 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6853 S.CheckCXXThisCapture(Loc: CallLoc);
6854 } else if (S.CurContext->isDependentContext()) {
6855 // ... since this is an implicit member reference, that might potentially
6856 // involve a 'this' capture, mark 'this' for potential capture in
6857 // enclosing lambdas.
6858 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6859 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6860 }
6861}
6862
6863// Once a call is fully resolved, warn for unqualified calls to specific
6864// C++ standard functions, like move and forward.
6865static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6866 const CallExpr *Call) {
6867 // We are only checking unary move and forward so exit early here.
6868 if (Call->getNumArgs() != 1)
6869 return;
6870
6871 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6872 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6873 return;
6874 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6875 if (!DRE || !DRE->getLocation().isValid())
6876 return;
6877
6878 if (DRE->getQualifier())
6879 return;
6880
6881 const FunctionDecl *FD = Call->getDirectCallee();
6882 if (!FD)
6883 return;
6884
6885 // Only warn for some functions deemed more frequent or problematic.
6886 unsigned BuiltinID = FD->getBuiltinID();
6887 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6888 return;
6889
6890 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6891 << FD->getQualifiedNameAsString()
6892 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6893}
6894
6895ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6896 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6897 Expr *ExecConfig) {
6898 ExprResult Call =
6899 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6900 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6901 if (Call.isInvalid())
6902 return Call;
6903
6904 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6905 // language modes.
6906 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6907 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6908 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6909 << ULE->getName();
6910 }
6911
6912 if (LangOpts.OpenMP)
6913 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6914 ExecConfig);
6915 if (LangOpts.CPlusPlus) {
6916 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6917 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6918
6919 // If we previously found that the id-expression of this call refers to a
6920 // consteval function but the call is dependent, we should not treat is an
6921 // an invalid immediate call.
6922 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6923 DRE && Call.get()->isValueDependent()) {
6924 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6925 }
6926 }
6927 return Call;
6928}
6929
6930// Any type that could be used to form a callable expression
6931static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6932 QualType T = E->getType();
6933 if (T->isDependentType())
6934 return true;
6935
6936 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6937 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6938 T->isFunctionType() || T->isFunctionReferenceType() ||
6939 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6940 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6941 return true;
6942
6943 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6944 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6945}
6946
6947ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6948 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6949 Expr *ExecConfig, bool IsExecConfig,
6950 bool AllowRecovery) {
6951 // Since this might be a postfix expression, get rid of ParenListExprs.
6952 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6953 if (Result.isInvalid()) return ExprError();
6954 Fn = Result.get();
6955
6956 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6957 // later, when we check boolean conditions, for now we merely forward it
6958 // without any additional checking.
6959 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6960 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6961 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6962
6963 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6964 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6965 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6966 return CallExpr::Create(
6967 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6968 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6969 }
6970 }
6971
6972 if (CheckArgsForPlaceholders(args: ArgExprs))
6973 return ExprError();
6974
6975 // The result of __builtin_counted_by_ref cannot be used as a function
6976 // argument. It allows leaking and modification of bounds safety information.
6977 for (const Expr *Arg : ArgExprs)
6978 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6979 K: BuiltinCountedByRefKind::FunctionArg))
6980 return ExprError();
6981
6982 if (getLangOpts().CPlusPlus) {
6983 // If this is a pseudo-destructor expression, build the call immediately.
6984 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6985 if (!ArgExprs.empty()) {
6986 // Pseudo-destructor calls should not have any arguments.
6987 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6988 << FixItHint::CreateRemoval(
6989 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6990 ArgExprs.back()->getEndLoc()));
6991 }
6992
6993 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6994 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6995 }
6996 if (Fn->getType() == Context.PseudoObjectTy) {
6997 ExprResult result = CheckPlaceholderExpr(E: Fn);
6998 if (result.isInvalid()) return ExprError();
6999 Fn = result.get();
7000 }
7001
7002 // Determine whether this is a dependent call inside a C++ template,
7003 // in which case we won't do any semantic analysis now.
7004 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
7005 if (ExecConfig) {
7006 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
7007 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
7008 Ty: Context.DependentTy, VK: VK_PRValue,
7009 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
7010 } else {
7011
7012 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7013 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
7014 CallLoc: Fn->getBeginLoc());
7015
7016 // If the type of the function itself is not dependent
7017 // check that it is a reasonable as a function, as type deduction
7018 // later assume the CallExpr has a sensible TYPE.
7019 if (!MayBeFunctionType(Context, E: Fn))
7020 return ExprError(
7021 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7022 << Fn->getType() << Fn->getSourceRange());
7023
7024 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7025 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7026 }
7027 }
7028
7029 // Determine whether this is a call to an object (C++ [over.call.object]).
7030 if (Fn->getType()->isRecordType())
7031 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
7032 RParenLoc);
7033
7034 if (Fn->getType() == Context.UnknownAnyTy) {
7035 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7036 if (result.isInvalid()) return ExprError();
7037 Fn = result.get();
7038 }
7039
7040 if (Fn->getType() == Context.BoundMemberTy) {
7041 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7042 RParenLoc, ExecConfig, IsExecConfig,
7043 AllowRecovery);
7044 }
7045 }
7046
7047 // Check for overloaded calls. This can happen even in C due to extensions.
7048 if (Fn->getType() == Context.OverloadTy) {
7049 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
7050
7051 // We aren't supposed to apply this logic if there's an '&' involved.
7052 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
7053 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
7054 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7055 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7056 OverloadExpr *ovl = find.Expression;
7057 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
7058 return BuildOverloadedCallExpr(
7059 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
7060 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
7061 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
7062 RParenLoc, ExecConfig, IsExecConfig,
7063 AllowRecovery);
7064 }
7065 }
7066
7067 // If we're directly calling a function, get the appropriate declaration.
7068 if (Fn->getType() == Context.UnknownAnyTy) {
7069 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7070 if (result.isInvalid()) return ExprError();
7071 Fn = result.get();
7072 }
7073
7074 Expr *NakedFn = Fn->IgnoreParens();
7075
7076 bool CallingNDeclIndirectly = false;
7077 NamedDecl *NDecl = nullptr;
7078 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
7079 if (UnOp->getOpcode() == UO_AddrOf) {
7080 CallingNDeclIndirectly = true;
7081 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7082 }
7083 }
7084
7085 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
7086 NDecl = DRE->getDecl();
7087
7088 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
7089 if (FDecl && FDecl->getBuiltinID()) {
7090 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7091 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7092 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
7093 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
7094 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
7095 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7096 }
7097 }
7098
7099 // Rewrite the function decl for this builtin by replacing parameters
7100 // with no explicit address space with the address space of the arguments
7101 // in ArgExprs.
7102 if ((FDecl =
7103 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
7104 NDecl = FDecl;
7105 Fn = DeclRefExpr::Create(
7106 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
7107 NameLoc: DRE->getLocation(), T: Fn->getType() /* BuiltinFnTy */,
7108 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
7109 }
7110 }
7111 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
7112 NDecl = ME->getMemberDecl();
7113
7114 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
7115 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7116 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
7117 return ExprError();
7118
7119 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
7120
7121 // If this expression is a call to a builtin function in HIP compilation,
7122 // allow a pointer-type argument to default address space to be passed as a
7123 // pointer-type parameter to a non-default address space. If Arg is declared
7124 // in the default address space and Param is declared in a non-default
7125 // address space, perform an implicit address space cast to the parameter
7126 // type.
7127 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7128 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7129 ++Idx) {
7130 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
7131 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7132 !ArgExprs[Idx]->getType()->isPointerType())
7133 continue;
7134
7135 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7136 auto ArgTy = ArgExprs[Idx]->getType();
7137 auto ArgPtTy = ArgTy->getPointeeType();
7138 auto ArgAS = ArgPtTy.getAddressSpace();
7139
7140 // Add address space cast if target address spaces are different
7141 bool NeedImplicitASC =
7142 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7143 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7144 // or from specific AS which has target AS matching that of Param.
7145 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
7146 if (!NeedImplicitASC)
7147 continue;
7148
7149 // First, ensure that the Arg is an RValue.
7150 if (ArgExprs[Idx]->isGLValue()) {
7151 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7152 if (Res.isInvalid())
7153 return ExprError();
7154 ArgExprs[Idx] = Res.get();
7155 }
7156
7157 // Construct a new arg type with address space of Param
7158 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7159 ArgPtQuals.setAddressSpace(ParamAS);
7160 auto NewArgPtTy =
7161 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7162 auto NewArgTy =
7163 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7164 Qs: ArgTy.getQualifiers());
7165
7166 // Finally perform an implicit address space cast
7167 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7168 CK: CK_AddressSpaceConversion)
7169 .get();
7170 }
7171 }
7172 }
7173
7174 if (Context.isDependenceAllowed() &&
7175 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7176 assert(!getLangOpts().CPlusPlus);
7177 assert((Fn->containsErrors() ||
7178 llvm::any_of(ArgExprs,
7179 [](clang::Expr *E) { return E->containsErrors(); })) &&
7180 "should only occur in error-recovery path.");
7181 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7182 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7183 }
7184 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7185 Config: ExecConfig, IsExecConfig);
7186}
7187
7188Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7189 MultiExprArg CallArgs) {
7190 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7191 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7192 Sema::LookupOrdinaryName);
7193 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7194
7195 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7196 assert(BuiltInDecl && "failed to find builtin declaration");
7197
7198 ExprResult DeclRef =
7199 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7200 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7201
7202 ExprResult Call =
7203 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7204
7205 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7206 return Call.get();
7207}
7208
7209ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7210 SourceLocation BuiltinLoc,
7211 SourceLocation RParenLoc) {
7212 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7213 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7214}
7215
7216ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7217 SourceLocation BuiltinLoc,
7218 SourceLocation RParenLoc) {
7219 ExprValueKind VK = VK_PRValue;
7220 ExprObjectKind OK = OK_Ordinary;
7221 QualType SrcTy = E->getType();
7222 if (!SrcTy->isDependentType() &&
7223 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7224 return ExprError(
7225 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7226 << DestTy << SrcTy << E->getSourceRange());
7227 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7228}
7229
7230ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7231 SourceLocation BuiltinLoc,
7232 SourceLocation RParenLoc) {
7233 TypeSourceInfo *TInfo;
7234 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7235 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7236}
7237
7238ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7239 SourceLocation LParenLoc,
7240 ArrayRef<Expr *> Args,
7241 SourceLocation RParenLoc, Expr *Config,
7242 bool IsExecConfig, ADLCallKind UsesADL) {
7243 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7244 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7245
7246 auto IsSJLJ = [&] {
7247 switch (BuiltinID) {
7248 case Builtin::BI__builtin_longjmp:
7249 case Builtin::BI__builtin_setjmp:
7250 case Builtin::BI__sigsetjmp:
7251 case Builtin::BI_longjmp:
7252 case Builtin::BI_setjmp:
7253 case Builtin::BIlongjmp:
7254 case Builtin::BIsetjmp:
7255 case Builtin::BIsiglongjmp:
7256 case Builtin::BIsigsetjmp:
7257 return true;
7258 default:
7259 return false;
7260 }
7261 };
7262
7263 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7264 if (!CurrentDefer.empty() && IsSJLJ()) {
7265 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7266 // for more than just blocks (e.g. lambdas, nested classes...).
7267 Scope *DeferParent = CurrentDefer.back().first;
7268 Scope *Block = CurScope->getBlockParent();
7269 if (DeferParent->Contains(rhs: *CurScope) &&
7270 (!Block || !DeferParent->Contains(rhs: *Block)))
7271 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7272 }
7273
7274 // Functions with 'interrupt' attribute cannot be called directly.
7275 if (FDecl) {
7276 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7277 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7278 return ExprError();
7279 }
7280 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7281 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7282 return ExprError();
7283 }
7284 }
7285
7286 // X86 interrupt handlers may only call routines with attribute
7287 // no_caller_saved_registers since there is no efficient way to
7288 // save and restore the non-GPR state.
7289 if (auto *Caller = getCurFunctionDecl()) {
7290 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7291 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7292 const TargetInfo &TI = Context.getTargetInfo();
7293 bool HasNonGPRRegisters =
7294 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7295 if (HasNonGPRRegisters &&
7296 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7297 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7298 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7299 if (FDecl)
7300 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7301 }
7302 }
7303 }
7304
7305 // Extract the return type from the builtin function pointer type.
7306 QualType ResultTy;
7307 if (BuiltinID)
7308 ResultTy = FDecl->getCallResultType();
7309 else
7310 ResultTy = Context.BoolTy;
7311
7312 // Promote the function operand.
7313 // We special-case function promotion here because we only allow promoting
7314 // builtin functions to function pointers in the callee of a call.
7315 ExprResult Result;
7316 if (BuiltinID &&
7317 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7318 // FIXME Several builtins still have setType in
7319 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7320 // Builtins.td to ensure they are correct before removing setType calls.
7321 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7322 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7323 } else
7324 Result = CallExprUnaryConversions(E: Fn);
7325 if (Result.isInvalid())
7326 return ExprError();
7327 Fn = Result.get();
7328
7329 // Check for a valid function type, but only if it is not a builtin which
7330 // requires custom type checking. These will be handled by
7331 // CheckBuiltinFunctionCall below just after creation of the call expression.
7332 const FunctionType *FuncT = nullptr;
7333 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7334 retry:
7335 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7336 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7337 // have type pointer to function".
7338 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7339 if (!FuncT)
7340 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7341 << Fn->getType() << Fn->getSourceRange());
7342 } else if (const BlockPointerType *BPT =
7343 Fn->getType()->getAs<BlockPointerType>()) {
7344 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7345 } else {
7346 // Handle calls to expressions of unknown-any type.
7347 if (Fn->getType() == Context.UnknownAnyTy) {
7348 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7349 if (rewrite.isInvalid())
7350 return ExprError();
7351 Fn = rewrite.get();
7352 goto retry;
7353 }
7354
7355 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7356 << Fn->getType() << Fn->getSourceRange());
7357 }
7358 }
7359
7360 // Get the number of parameters in the function prototype, if any.
7361 // We will allocate space for max(Args.size(), NumParams) arguments
7362 // in the call expression.
7363 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7364 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7365
7366 CallExpr *TheCall;
7367 if (Config) {
7368 assert(UsesADL == ADLCallKind::NotADL &&
7369 "CUDAKernelCallExpr should not use ADL");
7370 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7371 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7372 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7373 } else {
7374 TheCall =
7375 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7376 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7377 }
7378
7379 // Bail out early if calling a builtin with custom type checking.
7380 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7381 // For HLSL builtin aliases, the call was resolved via overload resolution
7382 // which may have selected a conversion sequence (e.g., vector-to-scalar
7383 // truncation). Convert arguments to match the declared prototype before
7384 // the custom type checker runs, otherwise the builtin will operate on
7385 // the unconverted argument types.
7386 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7387 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7388 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7389 IsExecConfig))
7390 return ExprError();
7391 }
7392 }
7393 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7394 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7395 E = CheckForImmediateInvocation(E, Decl: FDecl);
7396 return E;
7397 }
7398
7399 if (getLangOpts().CUDA) {
7400 if (Config) {
7401 // CUDA: Kernel calls must be to global functions
7402 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7403 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7404 << FDecl << Fn->getSourceRange());
7405
7406 // CUDA: Kernel function must have 'void' return type
7407 if (!FuncT->getReturnType()->isVoidType() &&
7408 !FuncT->getReturnType()->getAs<AutoType>() &&
7409 !FuncT->getReturnType()->isInstantiationDependentType())
7410 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7411 << Fn->getType() << Fn->getSourceRange());
7412 } else {
7413 // CUDA: Calls to global functions must be configured
7414 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7415 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7416 << FDecl << Fn->getSourceRange());
7417 }
7418 }
7419
7420 // Check for a valid return type
7421 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7422 FD: FDecl))
7423 return ExprError();
7424
7425 // We know the result type of the call, set it.
7426 TheCall->setType(FuncT->getCallResultType(Context));
7427 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7428
7429 // WebAssembly tables can't be used as arguments.
7430 if (Context.getTargetInfo().getTriple().isWasm()) {
7431 for (const Expr *Arg : Args) {
7432 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7433 return ExprError(Diag(Loc: Arg->getExprLoc(),
7434 DiagID: diag::err_wasm_table_as_function_parameter));
7435 }
7436 }
7437 }
7438
7439 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7440 // replaces sampler DeclRefExprs with their integer initializers.
7441 if (getLangOpts().OpenCL && FDecl) {
7442 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7443 }
7444
7445 if (Proto) {
7446 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7447 IsExecConfig))
7448 return ExprError();
7449 } else {
7450 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7451
7452 if (FDecl) {
7453 // Check if we have too few/too many template arguments, based
7454 // on our knowledge of the function definition.
7455 const FunctionDecl *Def = nullptr;
7456 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7457 Proto = Def->getType()->getAs<FunctionProtoType>();
7458 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7459 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7460 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7461 }
7462
7463 // If the function we're calling isn't a function prototype, but we have
7464 // a function prototype from a prior declaratiom, use that prototype.
7465 if (!FDecl->hasPrototype())
7466 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7467 }
7468
7469 // If we still haven't found a prototype to use but there are arguments to
7470 // the call, diagnose this as calling a function without a prototype.
7471 // However, if we found a function declaration, check to see if
7472 // -Wdeprecated-non-prototype was disabled where the function was declared.
7473 // If so, we will silence the diagnostic here on the assumption that this
7474 // interface is intentional and the user knows what they're doing. We will
7475 // also silence the diagnostic if there is a function declaration but it
7476 // was implicitly defined (the user already gets diagnostics about the
7477 // creation of the implicit function declaration, so the additional warning
7478 // is not helpful).
7479 if (!Proto && !Args.empty() &&
7480 (!FDecl || (!FDecl->isImplicit() &&
7481 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7482 Loc: FDecl->getLocation()))))
7483 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7484 << (FDecl != nullptr) << FDecl;
7485
7486 // Promote the arguments (C99 6.5.2.2p6).
7487 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7488 Expr *Arg = Args[i];
7489
7490 if (Proto && i < Proto->getNumParams()) {
7491 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7492 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7493 ExprResult ArgE =
7494 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7495 if (ArgE.isInvalid())
7496 return true;
7497
7498 Arg = ArgE.getAs<Expr>();
7499
7500 } else {
7501 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7502
7503 if (ArgE.isInvalid())
7504 return true;
7505
7506 Arg = ArgE.getAs<Expr>();
7507 }
7508
7509 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7510 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7511 return ExprError();
7512
7513 TheCall->setArg(Arg: i, ArgExpr: Arg);
7514 }
7515 TheCall->computeDependence();
7516 }
7517
7518 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7519 if (Method->isImplicitObjectMemberFunction())
7520 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7521 << Fn->getSourceRange() << 0);
7522
7523 // Check for sentinels
7524 if (NDecl)
7525 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7526
7527 // Warn for unions passing across security boundary (CMSE).
7528 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7529 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7530 if (const auto *RT =
7531 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7532 if (RT->getDecl()->isOrContainsUnion())
7533 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7534 << 0 << i;
7535 }
7536 }
7537 }
7538
7539 // Do special checking on direct calls to functions.
7540 if (FDecl) {
7541 if (CheckFunctionCall(FDecl, TheCall, Proto))
7542 return ExprError();
7543
7544 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7545 checkFortifiedLibcArgument(FD: FDecl, TheCall);
7546
7547 if (BuiltinID)
7548 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7549 } else if (NDecl) {
7550 if (CheckPointerCall(NDecl, TheCall, Proto))
7551 return ExprError();
7552 } else {
7553 if (CheckOtherCall(TheCall, Proto))
7554 return ExprError();
7555 }
7556
7557 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7558}
7559
7560ExprResult
7561Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7562 SourceLocation RParenLoc, Expr *InitExpr) {
7563 assert(Ty && "ActOnCompoundLiteral(): missing type");
7564 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7565
7566 TypeSourceInfo *TInfo;
7567 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7568 if (!TInfo)
7569 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7570
7571 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7572}
7573
7574ExprResult
7575Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7576 SourceLocation RParenLoc, Expr *LiteralExpr) {
7577 QualType literalType = TInfo->getType();
7578
7579 if (literalType->isArrayType()) {
7580 if (RequireCompleteSizedType(
7581 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7582 DiagID: diag::err_array_incomplete_or_sizeless_type,
7583 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7584 return ExprError();
7585 if (literalType->isVariableArrayType()) {
7586 // C23 6.7.10p4: An entity of variable length array type shall not be
7587 // initialized except by an empty initializer.
7588 //
7589 // The C extension warnings are issued from ParseBraceInitializer() and
7590 // do not need to be issued here. However, we continue to issue an error
7591 // in the case there are initializers or we are compiling C++. We allow
7592 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7593 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7594 // FIXME: should we allow this construct in C++ when it makes sense to do
7595 // so?
7596 //
7597 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7598 // shall specify an object type or an array of unknown size, but not a
7599 // variable length array type. This seems odd, as it allows 'int a[size] =
7600 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7601 // says, this is what's implemented here for C (except for the extension
7602 // that permits constant foldable size arrays)
7603
7604 auto diagID = LangOpts.CPlusPlus
7605 ? diag::err_variable_object_no_init
7606 : diag::err_compound_literal_with_vla_type;
7607 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7608 FailedFoldDiagID: diagID))
7609 return ExprError();
7610 }
7611 } else if (!literalType->isDependentType() &&
7612 RequireCompleteType(Loc: LParenLoc, T: literalType,
7613 DiagID: diag::err_typecheck_decl_incomplete_type,
7614 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7615 return ExprError();
7616
7617 InitializedEntity Entity
7618 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7619 InitializationKind Kind
7620 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7621 TypeRange: SourceRange(LParenLoc, RParenLoc),
7622 /*InitList=*/true);
7623 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7624 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7625 ResultType: &literalType);
7626 if (Result.isInvalid())
7627 return ExprError();
7628 LiteralExpr = Result.get();
7629
7630 // We treat the compound literal as being at file scope if it's not in a
7631 // function or method body, or within the function's prototype scope. This
7632 // means the following compound literal is not at file scope:
7633 // void func(char *para[(int [1]){ 0 }[0]);
7634 const Scope *S = getCurScope();
7635 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7636 !S->isInCFunctionScope() &&
7637 (!S || !S->isFunctionPrototypeScope());
7638
7639 // In C, compound literals are l-values for some reason.
7640 // For GCC compatibility, in C++, file-scope array compound literals with
7641 // constant initializers are also l-values, and compound literals are
7642 // otherwise prvalues.
7643 //
7644 // (GCC also treats C++ list-initialized file-scope array prvalues with
7645 // constant initializers as l-values, but that's non-conforming, so we don't
7646 // follow it there.)
7647 //
7648 // FIXME: It would be better to handle the lvalue cases as materializing and
7649 // lifetime-extending a temporary object, but our materialized temporaries
7650 // representation only supports lifetime extension from a variable, not "out
7651 // of thin air".
7652 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7653 // is bound to the result of applying array-to-pointer decay to the compound
7654 // literal.
7655 // FIXME: GCC supports compound literals of reference type, which should
7656 // obviously have a value kind derived from the kind of reference involved.
7657 ExprValueKind VK =
7658 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7659 ? VK_PRValue
7660 : VK_LValue;
7661
7662 // C99 6.5.2.5
7663 // "If the compound literal occurs outside the body of a function, the
7664 // initializer list shall consist of constant expressions."
7665 if (IsFileScope) {
7666 // An element with an immediate call or source_location is left for the
7667 // use site, and for its rebuild too when the rebuilt default arguments
7668 // could not be given the use-site location.
7669 bool DeferImmediate =
7670 isCheckingDefaultArgumentOrInitializer() ||
7671 (currentEvaluationContext().DelayedDefaultInitializationContext &&
7672 !OutermostDeclarationWithDelayedImmediateInvocations());
7673 // Store the element's value so CodeGen does not re-evaluate it outside a
7674 // constant context.
7675 auto CheckElement = [&](Expr *Init) -> Expr * {
7676 if (Init->isTypeDependent() || Init->isValueDependent())
7677 return ConstantExpr::Create(Context, E: Init);
7678 if (DeferImmediate) {
7679 ImmediateCallVisitor V(Context);
7680 V.TraverseStmt(S: Init);
7681 if (V.HasImmediateCalls)
7682 return ConstantExpr::Create(Context, E: Init);
7683 }
7684 Expr::EvalResult Eval;
7685 if (!Init->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context,
7686 Kind: ConstantExprKind::Initializer)) {
7687 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7688 << Init->getSourceBitField();
7689 return nullptr;
7690 }
7691 // An immediate invocation already is a ConstantExpr.
7692 if (isa<ConstantExpr>(Val: Init))
7693 return Init;
7694 return ConstantExpr::Create(Context, E: Init, Result: Eval.Val);
7695 };
7696 if (auto *ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) {
7697 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7698 Expr *Init = CheckElement(ILE->getInit(Init: i));
7699 if (!Init)
7700 return ExprError();
7701 ILE->setInit(Init: i, expr: Init);
7702 }
7703 } else {
7704 LiteralExpr = CheckElement(LiteralExpr);
7705 if (!LiteralExpr)
7706 return ExprError();
7707 }
7708 }
7709
7710 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7711 LiteralExpr, IsFileScope);
7712 if (!IsFileScope && literalType.getAddressSpace() != LangAS::opencl_private &&
7713 literalType.getAddressSpace() != LangAS::Default) {
7714 // Embedded-C extensions to C99 6.5.2.5:
7715 // "If the compound literal occurs inside the body of a function, the
7716 // type name shall not be qualified by an address-space qualifier."
7717 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7718 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7719 return ExprError();
7720 }
7721
7722 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7723 // Compound literals that have automatic storage duration are destroyed at
7724 // the end of the scope in C; in C++, they're just temporaries.
7725
7726 // Emit diagnostics if it is or contains a C union type that is non-trivial
7727 // to destruct.
7728 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7729 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7730 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7731 NonTrivialKind: NTCUK_Destruct);
7732
7733 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7734 Cleanup.setExprNeedsCleanups(true);
7735 ExprCleanupObjects.push_back(Elt: E);
7736 if (literalType.isDestructedType()) {
7737 getCurFunction()->setHasBranchProtectedScope();
7738 }
7739 }
7740
7741 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7742 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7743 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7744 Loc: E->getInitializer()->getExprLoc());
7745
7746 return MaybeBindToTemporary(E);
7747}
7748
7749ExprResult
7750Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7751 SourceLocation RBraceLoc) {
7752 // Only produce each kind of designated initialization diagnostic once.
7753 SourceLocation FirstDesignator;
7754 bool DiagnosedArrayDesignator = false;
7755 bool DiagnosedNestedDesignator = false;
7756 bool DiagnosedMixedDesignator = false;
7757
7758 // Check that any designated initializers are syntactically valid in the
7759 // current language mode.
7760 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7761 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7762 if (FirstDesignator.isInvalid())
7763 FirstDesignator = DIE->getBeginLoc();
7764
7765 if (!getLangOpts().CPlusPlus)
7766 break;
7767
7768 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7769 DiagnosedNestedDesignator = true;
7770 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7771 << DIE->getDesignatorsSourceRange();
7772 }
7773
7774 for (auto &Desig : DIE->designators()) {
7775 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7776 DiagnosedArrayDesignator = true;
7777 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7778 << Desig.getSourceRange();
7779 }
7780 }
7781
7782 if (!DiagnosedMixedDesignator &&
7783 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7784 DiagnosedMixedDesignator = true;
7785 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7786 << DIE->getSourceRange();
7787 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7788 << InitArgList[0]->getSourceRange();
7789 }
7790 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7791 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7792 DiagnosedMixedDesignator = true;
7793 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7794 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7795 << DIE->getSourceRange();
7796 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7797 << InitArgList[I]->getSourceRange();
7798 }
7799 }
7800
7801 if (FirstDesignator.isValid()) {
7802 // Only diagnose designated initiaization as a C++20 extension if we didn't
7803 // already diagnose use of (non-C++20) C99 designator syntax.
7804 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7805 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7806 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7807 ? diag::warn_cxx17_compat_designated_init
7808 : diag::ext_cxx_designated_init);
7809 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7810 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7811 }
7812 }
7813
7814 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7815}
7816
7817ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7818 MultiExprArg InitArgList,
7819 SourceLocation RBraceLoc, bool IsExplicit) {
7820 // Semantic analysis for initializers is done by ActOnDeclarator() and
7821 // CheckInitializer() - it requires knowledge of the object being initialized.
7822
7823 // Immediately handle non-overload placeholders. Overloads can be
7824 // resolved contextually, but everything else here can't.
7825 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7826 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7827 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7828
7829 // Ignore failures; dropping the entire initializer list because
7830 // of one failure would be terrible for indexing/etc.
7831 if (result.isInvalid()) continue;
7832
7833 InitArgList[I] = result.get();
7834 }
7835 }
7836
7837 InitListExpr *E = new (Context)
7838 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7839 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7840 return E;
7841}
7842
7843void Sema::maybeExtendBlockObject(ExprResult &E) {
7844 assert(E.get()->getType()->isBlockPointerType());
7845 assert(E.get()->isPRValue());
7846
7847 // Only do this in an r-value context.
7848 if (!getLangOpts().ObjCAutoRefCount) return;
7849
7850 E = ImplicitCastExpr::Create(
7851 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7852 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7853 Cleanup.setExprNeedsCleanups(true);
7854}
7855
7856CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7857 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7858 // Also, callers should have filtered out the invalid cases with
7859 // pointers. Everything else should be possible.
7860
7861 QualType SrcTy = Src.get()->getType();
7862 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7863 return CK_NoOp;
7864
7865 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7866 case Type::STK_MemberPointer:
7867 llvm_unreachable("member pointer type in C");
7868
7869 case Type::STK_CPointer:
7870 case Type::STK_BlockPointer:
7871 case Type::STK_ObjCObjectPointer:
7872 switch (DestTy->getScalarTypeKind()) {
7873 case Type::STK_CPointer: {
7874 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7875 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7876 if (SrcAS != DestAS)
7877 return CK_AddressSpaceConversion;
7878 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7879 return CK_NoOp;
7880 return CK_BitCast;
7881 }
7882 case Type::STK_BlockPointer:
7883 return (SrcKind == Type::STK_BlockPointer
7884 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7885 case Type::STK_ObjCObjectPointer:
7886 if (SrcKind == Type::STK_ObjCObjectPointer)
7887 return CK_BitCast;
7888 if (SrcKind == Type::STK_CPointer)
7889 return CK_CPointerToObjCPointerCast;
7890 maybeExtendBlockObject(E&: Src);
7891 return CK_BlockPointerToObjCPointerCast;
7892 case Type::STK_Bool:
7893 return CK_PointerToBoolean;
7894 case Type::STK_Integral:
7895 return CK_PointerToIntegral;
7896 case Type::STK_Floating:
7897 case Type::STK_FloatingComplex:
7898 case Type::STK_IntegralComplex:
7899 case Type::STK_MemberPointer:
7900 case Type::STK_FixedPoint:
7901 llvm_unreachable("illegal cast from pointer");
7902 }
7903 llvm_unreachable("Should have returned before this");
7904
7905 case Type::STK_FixedPoint:
7906 switch (DestTy->getScalarTypeKind()) {
7907 case Type::STK_FixedPoint:
7908 return CK_FixedPointCast;
7909 case Type::STK_Bool:
7910 return CK_FixedPointToBoolean;
7911 case Type::STK_Integral:
7912 return CK_FixedPointToIntegral;
7913 case Type::STK_Floating:
7914 return CK_FixedPointToFloating;
7915 case Type::STK_IntegralComplex:
7916 case Type::STK_FloatingComplex:
7917 Diag(Loc: Src.get()->getExprLoc(),
7918 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7919 << DestTy;
7920 return CK_IntegralCast;
7921 case Type::STK_CPointer:
7922 case Type::STK_ObjCObjectPointer:
7923 case Type::STK_BlockPointer:
7924 case Type::STK_MemberPointer:
7925 llvm_unreachable("illegal cast to pointer type");
7926 }
7927 llvm_unreachable("Should have returned before this");
7928
7929 case Type::STK_Bool: // casting from bool is like casting from an integer
7930 case Type::STK_Integral:
7931 switch (DestTy->getScalarTypeKind()) {
7932 case Type::STK_CPointer:
7933 case Type::STK_ObjCObjectPointer:
7934 case Type::STK_BlockPointer:
7935 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7936 NPC: Expr::NPC_ValueDependentIsNull))
7937 return CK_NullToPointer;
7938 return CK_IntegralToPointer;
7939 case Type::STK_Bool:
7940 return CK_IntegralToBoolean;
7941 case Type::STK_Integral:
7942 return CK_IntegralCast;
7943 case Type::STK_Floating:
7944 return CK_IntegralToFloating;
7945 case Type::STK_IntegralComplex:
7946 Src = ImpCastExprToType(E: Src.get(),
7947 Type: DestTy->castAs<ComplexType>()->getElementType(),
7948 CK: CK_IntegralCast);
7949 return CK_IntegralRealToComplex;
7950 case Type::STK_FloatingComplex:
7951 Src = ImpCastExprToType(E: Src.get(),
7952 Type: DestTy->castAs<ComplexType>()->getElementType(),
7953 CK: CK_IntegralToFloating);
7954 return CK_FloatingRealToComplex;
7955 case Type::STK_MemberPointer:
7956 llvm_unreachable("member pointer type in C");
7957 case Type::STK_FixedPoint:
7958 return CK_IntegralToFixedPoint;
7959 }
7960 llvm_unreachable("Should have returned before this");
7961
7962 case Type::STK_Floating:
7963 switch (DestTy->getScalarTypeKind()) {
7964 case Type::STK_Floating:
7965 return CK_FloatingCast;
7966 case Type::STK_Bool:
7967 return CK_FloatingToBoolean;
7968 case Type::STK_Integral:
7969 return CK_FloatingToIntegral;
7970 case Type::STK_FloatingComplex:
7971 Src = ImpCastExprToType(E: Src.get(),
7972 Type: DestTy->castAs<ComplexType>()->getElementType(),
7973 CK: CK_FloatingCast);
7974 return CK_FloatingRealToComplex;
7975 case Type::STK_IntegralComplex:
7976 Src = ImpCastExprToType(E: Src.get(),
7977 Type: DestTy->castAs<ComplexType>()->getElementType(),
7978 CK: CK_FloatingToIntegral);
7979 return CK_IntegralRealToComplex;
7980 case Type::STK_CPointer:
7981 case Type::STK_ObjCObjectPointer:
7982 case Type::STK_BlockPointer:
7983 llvm_unreachable("valid float->pointer cast?");
7984 case Type::STK_MemberPointer:
7985 llvm_unreachable("member pointer type in C");
7986 case Type::STK_FixedPoint:
7987 return CK_FloatingToFixedPoint;
7988 }
7989 llvm_unreachable("Should have returned before this");
7990
7991 case Type::STK_FloatingComplex:
7992 switch (DestTy->getScalarTypeKind()) {
7993 case Type::STK_FloatingComplex:
7994 return CK_FloatingComplexCast;
7995 case Type::STK_IntegralComplex:
7996 return CK_FloatingComplexToIntegralComplex;
7997 case Type::STK_Floating: {
7998 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7999 if (Context.hasSameType(T1: ET, T2: DestTy))
8000 return CK_FloatingComplexToReal;
8001 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
8002 return CK_FloatingCast;
8003 }
8004 case Type::STK_Bool:
8005 return CK_FloatingComplexToBoolean;
8006 case Type::STK_Integral:
8007 Src = ImpCastExprToType(E: Src.get(),
8008 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8009 CK: CK_FloatingComplexToReal);
8010 return CK_FloatingToIntegral;
8011 case Type::STK_CPointer:
8012 case Type::STK_ObjCObjectPointer:
8013 case Type::STK_BlockPointer:
8014 llvm_unreachable("valid complex float->pointer cast?");
8015 case Type::STK_MemberPointer:
8016 llvm_unreachable("member pointer type in C");
8017 case Type::STK_FixedPoint:
8018 Diag(Loc: Src.get()->getExprLoc(),
8019 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8020 << SrcTy;
8021 return CK_IntegralCast;
8022 }
8023 llvm_unreachable("Should have returned before this");
8024
8025 case Type::STK_IntegralComplex:
8026 switch (DestTy->getScalarTypeKind()) {
8027 case Type::STK_FloatingComplex:
8028 return CK_IntegralComplexToFloatingComplex;
8029 case Type::STK_IntegralComplex:
8030 return CK_IntegralComplexCast;
8031 case Type::STK_Integral: {
8032 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8033 if (Context.hasSameType(T1: ET, T2: DestTy))
8034 return CK_IntegralComplexToReal;
8035 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
8036 return CK_IntegralCast;
8037 }
8038 case Type::STK_Bool:
8039 return CK_IntegralComplexToBoolean;
8040 case Type::STK_Floating:
8041 Src = ImpCastExprToType(E: Src.get(),
8042 Type: SrcTy->castAs<ComplexType>()->getElementType(),
8043 CK: CK_IntegralComplexToReal);
8044 return CK_IntegralToFloating;
8045 case Type::STK_CPointer:
8046 case Type::STK_ObjCObjectPointer:
8047 case Type::STK_BlockPointer:
8048 llvm_unreachable("valid complex int->pointer cast?");
8049 case Type::STK_MemberPointer:
8050 llvm_unreachable("member pointer type in C");
8051 case Type::STK_FixedPoint:
8052 Diag(Loc: Src.get()->getExprLoc(),
8053 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
8054 << SrcTy;
8055 return CK_IntegralCast;
8056 }
8057 llvm_unreachable("Should have returned before this");
8058 }
8059
8060 llvm_unreachable("Unhandled scalar cast");
8061}
8062
8063static bool breakDownVectorType(QualType type, uint64_t &len,
8064 QualType &eltType) {
8065 // Vectors are simple.
8066 if (const VectorType *vecType = type->getAs<VectorType>()) {
8067 len = vecType->getNumElements();
8068 eltType = vecType->getElementType();
8069 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8070 return true;
8071 }
8072
8073 // We allow lax conversion to and from non-vector types, but only if
8074 // they're real types (i.e. non-complex, non-pointer scalar types).
8075 if (!type->isRealType()) return false;
8076
8077 len = 1;
8078 eltType = type;
8079 return true;
8080}
8081
8082bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8083 assert(srcTy->isVectorType() || destTy->isVectorType());
8084
8085 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8086 if (!FirstType->isSVESizelessBuiltinType())
8087 return false;
8088
8089 const auto *VecTy = SecondType->getAs<VectorType>();
8090 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8091 };
8092
8093 return ValidScalableConversion(srcTy, destTy) ||
8094 ValidScalableConversion(destTy, srcTy);
8095}
8096
8097bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8098 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8099 return false;
8100
8101 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8102 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8103
8104 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8105 matSrcType->getNumColumns() == matDestType->getNumColumns();
8106}
8107
8108bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8109 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8110
8111 uint64_t SrcLen, DestLen;
8112 QualType SrcEltTy, DestEltTy;
8113 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
8114 return false;
8115 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
8116 return false;
8117
8118 // x87 long double has padding bits, so it cannot be bitcast to another type.
8119 auto IsX87LongDouble = [&](QualType T) {
8120 return T->isRealFloatingType() && &Context.getFloatTypeSemantics(T) ==
8121 &llvm::APFloat::x87DoubleExtended();
8122 };
8123 if (IsX87LongDouble(SrcEltTy) != IsX87LongDouble(DestEltTy))
8124 return false;
8125
8126 // ASTContext::getTypeSize will return the size rounded up to a
8127 // power of 2, so instead of using that, we need to use the raw
8128 // element size multiplied by the element count.
8129 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
8130 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
8131
8132 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8133}
8134
8135bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8136 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8137 "expected at least one type to be a vector here");
8138
8139 bool IsSrcTyAltivec =
8140 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8141 VectorKind::AltiVecVector) ||
8142 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8143 VectorKind::AltiVecBool) ||
8144 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8145 VectorKind::AltiVecPixel));
8146
8147 bool IsDestTyAltivec = DestTy->isVectorType() &&
8148 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8149 VectorKind::AltiVecVector) ||
8150 (DestTy->castAs<VectorType>()->getVectorKind() ==
8151 VectorKind::AltiVecBool) ||
8152 (DestTy->castAs<VectorType>()->getVectorKind() ==
8153 VectorKind::AltiVecPixel));
8154
8155 return (IsSrcTyAltivec || IsDestTyAltivec);
8156}
8157
8158bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8159 assert(destTy->isVectorType() || srcTy->isVectorType());
8160
8161 // Disallow lax conversions between scalars and ExtVectors (these
8162 // conversions are allowed for other vector types because common headers
8163 // depend on them). Most scalar OP ExtVector cases are handled by the
8164 // splat path anyway, which does what we want (convert, not bitcast).
8165 // What this rules out for ExtVectors is crazy things like char4*float.
8166 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8167 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8168
8169 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
8170}
8171
8172bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8173 assert(destTy->isVectorType() || srcTy->isVectorType());
8174
8175 switch (Context.getLangOpts().getLaxVectorConversions()) {
8176 case LangOptions::LaxVectorConversionKind::None:
8177 return false;
8178
8179 case LangOptions::LaxVectorConversionKind::Integer:
8180 if (!srcTy->isIntegralOrEnumerationType()) {
8181 auto *Vec = srcTy->getAs<VectorType>();
8182 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8183 return false;
8184 }
8185 if (!destTy->isIntegralOrEnumerationType()) {
8186 auto *Vec = destTy->getAs<VectorType>();
8187 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8188 return false;
8189 }
8190 // OK, integer (vector) -> integer (vector) bitcast.
8191 break;
8192
8193 case LangOptions::LaxVectorConversionKind::All:
8194 break;
8195 }
8196
8197 return areLaxCompatibleVectorTypes(srcTy, destTy);
8198}
8199
8200bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8201 CastKind &Kind) {
8202 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8203 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8204 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8205 << DestTy << SrcTy << R;
8206 }
8207 } else if (SrcTy->isMatrixType()) {
8208 return Diag(Loc: R.getBegin(),
8209 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8210 << SrcTy << DestTy << R;
8211 } else if (DestTy->isMatrixType()) {
8212 return Diag(Loc: R.getBegin(),
8213 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8214 << DestTy << SrcTy << R;
8215 }
8216
8217 Kind = CK_MatrixCast;
8218 return false;
8219}
8220
8221bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8222 CastKind &Kind) {
8223 assert(VectorTy->isVectorType() && "Not a vector type!");
8224
8225 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8226 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8227 return Diag(Loc: R.getBegin(),
8228 DiagID: Ty->isVectorType() ?
8229 diag::err_invalid_conversion_between_vectors :
8230 diag::err_invalid_conversion_between_vector_and_integer)
8231 << VectorTy << Ty << R;
8232 } else
8233 return Diag(Loc: R.getBegin(),
8234 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8235 << VectorTy << Ty << R;
8236
8237 Kind = CK_BitCast;
8238 return false;
8239}
8240
8241ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8242 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8243
8244 if (DestElemTy == SplattedExpr->getType())
8245 return SplattedExpr;
8246
8247 assert(DestElemTy->isFloatingType() ||
8248 DestElemTy->isIntegralOrEnumerationType());
8249
8250 CastKind CK;
8251 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8252 // OpenCL requires that we convert `true` boolean expressions to -1, but
8253 // only when splatting vectors.
8254 if (DestElemTy->isFloatingType()) {
8255 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8256 // in two steps: boolean to signed integral, then to floating.
8257 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8258 CK: CK_BooleanToSignedIntegral);
8259 SplattedExpr = CastExprRes.get();
8260 CK = CK_IntegralToFloating;
8261 } else {
8262 CK = CK_BooleanToSignedIntegral;
8263 }
8264 } else {
8265 ExprResult CastExprRes = SplattedExpr;
8266 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8267 if (CastExprRes.isInvalid())
8268 return ExprError();
8269 SplattedExpr = CastExprRes.get();
8270 }
8271 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8272}
8273
8274ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8275 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8276
8277 if (DestElemTy == SplattedExpr->getType())
8278 return SplattedExpr;
8279
8280 assert(DestElemTy->isFloatingType() ||
8281 DestElemTy->isIntegralOrEnumerationType());
8282
8283 ExprResult CastExprRes = SplattedExpr;
8284 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8285 if (CastExprRes.isInvalid())
8286 return ExprError();
8287 SplattedExpr = CastExprRes.get();
8288
8289 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8290}
8291
8292ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8293 Expr *CastExpr, CastKind &Kind) {
8294 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8295
8296 QualType SrcTy = CastExpr->getType();
8297
8298 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8299 // an ExtVectorType.
8300 // In OpenCL, casts between vectors of different types are not allowed.
8301 // (See OpenCL 6.2).
8302 if (SrcTy->isVectorType()) {
8303 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8304 (getLangOpts().OpenCL &&
8305 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8306 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8307 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8308 << DestTy << SrcTy << R;
8309 return ExprError();
8310 }
8311 Kind = CK_BitCast;
8312 return CastExpr;
8313 }
8314
8315 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8316 // conversion will take place first from scalar to elt type, and then
8317 // splat from elt type to vector.
8318 if (SrcTy->isPointerType())
8319 return Diag(Loc: R.getBegin(),
8320 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8321 << DestTy << SrcTy << R;
8322
8323 Kind = CK_VectorSplat;
8324 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8325}
8326
8327/// Check that a call to alloc_size function specifies sufficient space for the
8328/// destination type.
8329static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8330 const Expr *E) {
8331 QualType SourceType = E->getType();
8332 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8333 DestType == SourceType)
8334 return;
8335
8336 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8337 if (!CE)
8338 return;
8339
8340 // Find the total size allocated by the function call.
8341 if (!CE->getCalleeAllocSizeAttr())
8342 return;
8343 std::optional<llvm::APInt> AllocSize =
8344 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8345 // Allocations of size zero are permitted as a special case. They are usually
8346 // done intentionally.
8347 if (!AllocSize || AllocSize->isZero())
8348 return;
8349 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8350
8351 QualType TargetType = DestType->getPointeeType();
8352 // Find the destination size. As a special case function types have size of
8353 // one byte to match the sizeof operator behavior.
8354 auto LhsSize = TargetType->isFunctionType()
8355 ? CharUnits::One()
8356 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8357 if (LhsSize && Size < LhsSize)
8358 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8359 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8360}
8361
8362ExprResult
8363Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8364 Declarator &D, ParsedType &Ty,
8365 SourceLocation RParenLoc, Expr *CastExpr) {
8366 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8367 "ActOnCastExpr(): missing type or expr");
8368
8369 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8370 if (D.isInvalidType())
8371 return ExprError();
8372
8373 if (getLangOpts().CPlusPlus) {
8374 // Check that there are no default arguments (C++ only).
8375 CheckExtraCXXDefaultArguments(D);
8376 }
8377
8378 checkUnusedDeclAttributes(D);
8379
8380 QualType castType = castTInfo->getType();
8381 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8382
8383 bool isVectorLiteral = false;
8384
8385 // Check for an altivec or OpenCL literal,
8386 // i.e. all the elements are integer constants.
8387 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8388 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8389 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8390 && castType->isVectorType() && (PE || PLE)) {
8391 if (PLE && PLE->getNumExprs() == 0) {
8392 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8393 return ExprError();
8394 }
8395 if (PE || PLE->getNumExprs() == 1) {
8396 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8397 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8398 isVectorLiteral = true;
8399 }
8400 else
8401 isVectorLiteral = true;
8402 }
8403
8404 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8405 // then handle it as such.
8406 if (isVectorLiteral)
8407 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8408
8409 // If the Expr being casted is a ParenListExpr, handle it specially.
8410 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8411 // sequence of BinOp comma operators.
8412 if (isa<ParenListExpr>(Val: CastExpr)) {
8413 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8414 if (Result.isInvalid()) return ExprError();
8415 CastExpr = Result.get();
8416 }
8417
8418 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8419 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8420
8421 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8422
8423 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8424
8425 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8426
8427 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8428
8429 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8430}
8431
8432ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8433 SourceLocation RParenLoc, Expr *E,
8434 TypeSourceInfo *TInfo) {
8435 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8436 "Expected paren or paren list expression");
8437
8438 Expr **exprs;
8439 unsigned numExprs;
8440 Expr *subExpr;
8441 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8442 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8443 LiteralLParenLoc = PE->getLParenLoc();
8444 LiteralRParenLoc = PE->getRParenLoc();
8445 exprs = PE->getExprs();
8446 numExprs = PE->getNumExprs();
8447 } else { // isa<ParenExpr> by assertion at function entrance
8448 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8449 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8450 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8451 exprs = &subExpr;
8452 numExprs = 1;
8453 }
8454
8455 QualType Ty = TInfo->getType();
8456 assert(Ty->isVectorType() && "Expected vector type");
8457
8458 SmallVector<Expr *, 8> initExprs;
8459 const VectorType *VTy = Ty->castAs<VectorType>();
8460 unsigned numElems = VTy->getNumElements();
8461
8462 // '(...)' form of vector initialization in AltiVec: the number of
8463 // initializers must be one or must match the size of the vector.
8464 // If a single value is specified in the initializer then it will be
8465 // replicated to all the components of the vector
8466 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8467 SrcTy: VTy->getElementType()))
8468 return ExprError();
8469 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8470 // The number of initializers must be one or must match the size of the
8471 // vector. If a single value is specified in the initializer then it will
8472 // be replicated to all the components of the vector
8473 if (numExprs == 1) {
8474 QualType ElemTy = VTy->getElementType();
8475 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8476 if (Literal.isInvalid())
8477 return ExprError();
8478 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8479 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8480 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8481 }
8482 else if (numExprs < numElems) {
8483 Diag(Loc: E->getExprLoc(),
8484 DiagID: diag::err_incorrect_number_of_vector_initializers);
8485 return ExprError();
8486 }
8487 else
8488 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8489 }
8490 else {
8491 // For OpenCL, when the number of initializers is a single value,
8492 // it will be replicated to all components of the vector.
8493 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8494 numExprs == 1) {
8495 QualType SrcTy = exprs[0]->getType();
8496 if (!SrcTy->isArithmeticType()) {
8497 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8498 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8499 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8500 return ExprError();
8501 }
8502 QualType ElemTy = VTy->getElementType();
8503 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8504 if (Literal.isInvalid())
8505 return ExprError();
8506 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8507 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8508 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8509 }
8510
8511 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8512 }
8513 // FIXME: This means that pretty-printing the final AST will produce curly
8514 // braces instead of the original commas.
8515 InitListExpr *initE =
8516 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8517 LiteralRParenLoc, /*isExplicit=*/false);
8518 initE->setType(Ty);
8519 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8520}
8521
8522ExprResult
8523Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8524 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8525 if (!E)
8526 return OrigExpr;
8527
8528 ExprResult Result(E->getExpr(Init: 0));
8529
8530 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8531 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8532 RHSExpr: E->getExpr(Init: i));
8533
8534 if (Result.isInvalid()) return ExprError();
8535
8536 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8537}
8538
8539ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8540 SourceLocation R,
8541 MultiExprArg Val) {
8542 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8543}
8544
8545ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8546 unsigned NumUserSpecifiedExprs,
8547 SourceLocation InitLoc,
8548 SourceLocation LParenLoc,
8549 SourceLocation RParenLoc) {
8550 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8551 InitLoc, LParenLoc, RParenLoc);
8552}
8553
8554bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8555 SourceLocation QuestionLoc) {
8556 const Expr *NullExpr = LHSExpr;
8557 const Expr *NonPointerExpr = RHSExpr;
8558 Expr::NullPointerConstantKind NullKind =
8559 NullExpr->isNullPointerConstant(Ctx&: Context,
8560 NPC: Expr::NPC_ValueDependentIsNotNull);
8561
8562 if (NullKind == Expr::NPCK_NotNull) {
8563 NullExpr = RHSExpr;
8564 NonPointerExpr = LHSExpr;
8565 NullKind =
8566 NullExpr->isNullPointerConstant(Ctx&: Context,
8567 NPC: Expr::NPC_ValueDependentIsNotNull);
8568 }
8569
8570 if (NullKind == Expr::NPCK_NotNull)
8571 return false;
8572
8573 if (NullKind == Expr::NPCK_ZeroExpression)
8574 return false;
8575
8576 if (NullKind == Expr::NPCK_ZeroLiteral) {
8577 // In this case, check to make sure that we got here from a "NULL"
8578 // string in the source code.
8579 NullExpr = NullExpr->IgnoreParenImpCasts();
8580 SourceLocation loc = NullExpr->getExprLoc();
8581 if (!findMacroSpelling(loc, name: "NULL"))
8582 return false;
8583 }
8584
8585 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8586 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8587 << NonPointerExpr->getType() << DiagType
8588 << NonPointerExpr->getSourceRange();
8589 return true;
8590}
8591
8592/// Return false if the condition expression is valid, true otherwise.
8593static bool checkCondition(Sema &S, const Expr *Cond,
8594 SourceLocation QuestionLoc) {
8595 QualType CondTy = Cond->getType();
8596
8597 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8598 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8599 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8600 << CondTy << Cond->getSourceRange();
8601 return true;
8602 }
8603
8604 // C99 6.5.15p2
8605 if (CondTy->isScalarType()) return false;
8606
8607 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8608 << CondTy << Cond->getSourceRange();
8609 return true;
8610}
8611
8612/// Return false if the NullExpr can be promoted to PointerTy,
8613/// true otherwise.
8614static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8615 QualType PointerTy) {
8616 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8617 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8618 NPC: Expr::NPC_ValueDependentIsNull))
8619 return true;
8620
8621 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8622 return false;
8623}
8624
8625/// Checks compatibility between two pointers and return the resulting
8626/// type.
8627static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8628 ExprResult &RHS,
8629 SourceLocation Loc) {
8630 QualType LHSTy = LHS.get()->getType();
8631 QualType RHSTy = RHS.get()->getType();
8632
8633 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8634 // Two identical pointers types are always compatible.
8635 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8636 }
8637
8638 QualType lhptee, rhptee;
8639
8640 // Get the pointee types.
8641 bool IsBlockPointer = false;
8642 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8643 lhptee = LHSBTy->getPointeeType();
8644 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8645 IsBlockPointer = true;
8646 } else {
8647 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8648 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8649 }
8650
8651 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8652 // differently qualified versions of compatible types, the result type is
8653 // a pointer to an appropriately qualified version of the composite
8654 // type.
8655
8656 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8657 // clause doesn't make sense for our extensions. E.g. address space 2 should
8658 // be incompatible with address space 3: they may live on different devices or
8659 // anything.
8660 Qualifiers lhQual = lhptee.getQualifiers();
8661 Qualifiers rhQual = rhptee.getQualifiers();
8662
8663 LangAS ResultAddrSpace = LangAS::Default;
8664 LangAS LAddrSpace = lhQual.getAddressSpace();
8665 LangAS RAddrSpace = rhQual.getAddressSpace();
8666
8667 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8668 // spaces is disallowed.
8669 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8670 ResultAddrSpace = LAddrSpace;
8671 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8672 ResultAddrSpace = RAddrSpace;
8673 else {
8674 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8675 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8676 << RHS.get()->getSourceRange();
8677 return QualType();
8678 }
8679
8680 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8681 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8682 lhQual.removeCVRQualifiers();
8683 rhQual.removeCVRQualifiers();
8684
8685 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8686 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8687 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8688 << RHS.get()->getSourceRange();
8689 return QualType();
8690 }
8691
8692 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8693 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8694 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8695 // qual types are compatible iff
8696 // * corresponded types are compatible
8697 // * CVR qualifiers are equal
8698 // * address spaces are equal
8699 // Thus for conditional operator we merge CVR and address space unqualified
8700 // pointees and if there is a composite type we return a pointer to it with
8701 // merged qualifiers.
8702 LHSCastKind =
8703 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8704 RHSCastKind =
8705 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8706 lhQual.removeAddressSpace();
8707 rhQual.removeAddressSpace();
8708
8709 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8710 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8711
8712 QualType CompositeTy = S.Context.mergeTypes(
8713 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8714 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8715
8716 if (CompositeTy.isNull()) {
8717 // In this situation, we assume void* type. No especially good
8718 // reason, but this is what gcc does, and we do have to pick
8719 // to get a consistent AST.
8720 QualType incompatTy;
8721 incompatTy = S.Context.getPointerType(
8722 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8723 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8724 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8725
8726 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8727 // for casts between types with incompatible address space qualifiers.
8728 // For the following code the compiler produces casts between global and
8729 // local address spaces of the corresponded innermost pointees:
8730 // local int *global *a;
8731 // global int *global *b;
8732 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8733 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8734 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8735 << RHS.get()->getSourceRange();
8736
8737 return incompatTy;
8738 }
8739
8740 // The pointer types are compatible.
8741 // In case of OpenCL ResultTy should have the address space qualifier
8742 // which is a superset of address spaces of both the 2nd and the 3rd
8743 // operands of the conditional operator.
8744 QualType ResultTy = [&, ResultAddrSpace]() {
8745 if (S.getLangOpts().OpenCL) {
8746 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8747 CompositeQuals.setAddressSpace(ResultAddrSpace);
8748 return S.Context
8749 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8750 .withCVRQualifiers(CVR: MergedCVRQual);
8751 }
8752 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8753 }();
8754 if (IsBlockPointer)
8755 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8756 else
8757 ResultTy = S.Context.getPointerType(T: ResultTy);
8758
8759 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8760 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8761 return ResultTy;
8762}
8763
8764/// Return the resulting type when the operands are both block pointers.
8765static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8766 ExprResult &LHS,
8767 ExprResult &RHS,
8768 SourceLocation Loc) {
8769 QualType LHSTy = LHS.get()->getType();
8770 QualType RHSTy = RHS.get()->getType();
8771
8772 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8773 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8774 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8775 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8776 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8777 return destType;
8778 }
8779 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8780 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8781 << RHS.get()->getSourceRange();
8782 return QualType();
8783 }
8784
8785 // We have 2 block pointer types.
8786 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8787}
8788
8789/// Return the resulting type when the operands are both pointers.
8790static QualType
8791checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8792 ExprResult &RHS,
8793 SourceLocation Loc) {
8794 // get the pointer types
8795 QualType LHSTy = LHS.get()->getType();
8796 QualType RHSTy = RHS.get()->getType();
8797
8798 // get the "pointed to" types
8799 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8800 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8801
8802 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8803 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8804 // Figure out necessary qualifiers (C99 6.5.15p6)
8805 QualType destPointee
8806 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8807 QualType destType = S.Context.getPointerType(T: destPointee);
8808 // Add qualifiers if necessary.
8809 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8810 // Promote to void*.
8811 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8812 return destType;
8813 }
8814 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8815 QualType destPointee
8816 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8817 QualType destType = S.Context.getPointerType(T: destPointee);
8818 // Add qualifiers if necessary.
8819 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8820 // Promote to void*.
8821 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8822 return destType;
8823 }
8824
8825 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8826}
8827
8828/// Return false if the first expression is not an integer and the second
8829/// expression is not a pointer, true otherwise.
8830static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8831 Expr* PointerExpr, SourceLocation Loc,
8832 bool IsIntFirstExpr) {
8833 if (!PointerExpr->getType()->isPointerType() ||
8834 !Int.get()->getType()->isIntegerType())
8835 return false;
8836
8837 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8838 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8839
8840 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8841 << Expr1->getType() << Expr2->getType()
8842 << Expr1->getSourceRange() << Expr2->getSourceRange();
8843 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8844 CK: CK_IntegralToPointer);
8845 return true;
8846}
8847
8848/// Simple conversion between integer and floating point types.
8849///
8850/// Used when handling the OpenCL conditional operator where the
8851/// condition is a vector while the other operands are scalar.
8852///
8853/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8854/// types are either integer or floating type. Between the two
8855/// operands, the type with the higher rank is defined as the "result
8856/// type". The other operand needs to be promoted to the same type. No
8857/// other type promotion is allowed. We cannot use
8858/// UsualArithmeticConversions() for this purpose, since it always
8859/// promotes promotable types.
8860static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8861 ExprResult &RHS,
8862 SourceLocation QuestionLoc) {
8863 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8864 if (LHS.isInvalid())
8865 return QualType();
8866 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8867 if (RHS.isInvalid())
8868 return QualType();
8869
8870 // For conversion purposes, we ignore any qualifiers.
8871 // For example, "const float" and "float" are equivalent.
8872 QualType LHSType =
8873 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8874 QualType RHSType =
8875 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8876
8877 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8878 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8879 << LHSType << LHS.get()->getSourceRange();
8880 return QualType();
8881 }
8882
8883 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8884 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8885 << RHSType << RHS.get()->getSourceRange();
8886 return QualType();
8887 }
8888
8889 // If both types are identical, no conversion is needed.
8890 if (LHSType == RHSType)
8891 return LHSType;
8892
8893 // Now handle "real" floating types (i.e. float, double, long double).
8894 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8895 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8896 /*IsCompAssign = */ false);
8897
8898 // Finally, we have two differing integer types.
8899 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8900 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8901}
8902
8903/// Convert scalar operands to a vector that matches the
8904/// condition in length.
8905///
8906/// Used when handling the OpenCL conditional operator where the
8907/// condition is a vector while the other operands are scalar.
8908///
8909/// We first compute the "result type" for the scalar operands
8910/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8911/// into a vector of that type where the length matches the condition
8912/// vector type. s6.11.6 requires that the element types of the result
8913/// and the condition must have the same number of bits.
8914static QualType
8915OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8916 QualType CondTy, SourceLocation QuestionLoc) {
8917 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8918 if (ResTy.isNull()) return QualType();
8919
8920 const VectorType *CV = CondTy->getAs<VectorType>();
8921 assert(CV);
8922
8923 // Determine the vector result type
8924 unsigned NumElements = CV->getNumElements();
8925 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8926
8927 // Ensure that all types have the same number of bits
8928 if (S.Context.getTypeSize(T: CV->getElementType())
8929 != S.Context.getTypeSize(T: ResTy)) {
8930 // Since VectorTy is created internally, it does not pretty print
8931 // with an OpenCL name. Instead, we just print a description.
8932 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8933 SmallString<64> Str;
8934 llvm::raw_svector_ostream OS(Str);
8935 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8936 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8937 << CondTy << OS.str();
8938 return QualType();
8939 }
8940
8941 // Convert operands to the vector result type
8942 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8943 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8944
8945 return VectorTy;
8946}
8947
8948/// Return false if this is a valid OpenCL condition vector
8949static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8950 SourceLocation QuestionLoc) {
8951 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8952 // integral type.
8953 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8954 assert(CondTy);
8955 QualType EleTy = CondTy->getElementType();
8956 if (EleTy->isIntegerType()) return false;
8957
8958 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8959 << Cond->getType() << Cond->getSourceRange();
8960 return true;
8961}
8962
8963/// Return false if the vector condition type and the vector
8964/// result type are compatible.
8965///
8966/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8967/// number of elements, and their element types have the same number
8968/// of bits.
8969static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8970 SourceLocation QuestionLoc) {
8971 const VectorType *CV = CondTy->getAs<VectorType>();
8972 const VectorType *RV = VecResTy->getAs<VectorType>();
8973 assert(CV && RV);
8974
8975 if (CV->getNumElements() != RV->getNumElements()) {
8976 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8977 << CondTy << VecResTy;
8978 return true;
8979 }
8980
8981 QualType CVE = CV->getElementType();
8982 QualType RVE = RV->getElementType();
8983
8984 // Boolean vectors are permitted outside of OpenCL mode.
8985 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8986 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8987 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8988 << CondTy << VecResTy;
8989 return true;
8990 }
8991
8992 return false;
8993}
8994
8995/// Return the resulting type for the conditional operator in
8996/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8997/// s6.3.i) when the condition is a vector type.
8998static QualType
8999OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9000 ExprResult &LHS, ExprResult &RHS,
9001 SourceLocation QuestionLoc) {
9002 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
9003 if (Cond.isInvalid())
9004 return QualType();
9005 QualType CondTy = Cond.get()->getType();
9006
9007 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
9008 return QualType();
9009
9010 // If either operand is a vector then find the vector type of the
9011 // result as specified in OpenCL v1.1 s6.3.i.
9012 if (LHS.get()->getType()->isVectorType() ||
9013 RHS.get()->getType()->isVectorType()) {
9014 bool IsBoolVecLang =
9015 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9016 QualType VecResTy =
9017 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
9018 /*isCompAssign*/ IsCompAssign: false,
9019 /*AllowBothBool*/ true,
9020 /*AllowBoolConversions*/ AllowBoolConversion: false,
9021 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang);
9022 if (VecResTy.isNull())
9023 return QualType();
9024 // The result type must match the condition type as specified in
9025 // OpenCL v1.1 s6.11.6.
9026 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9027 return QualType();
9028 return VecResTy;
9029 }
9030
9031 // Both operands are scalar.
9032 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9033}
9034
9035/// Return true if the Expr is block type
9036static bool checkBlockType(Sema &S, const Expr *E) {
9037 if (E->getType()->isBlockPointerType()) {
9038 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9039 return true;
9040 }
9041
9042 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
9043 QualType Ty = CE->getCallee()->getType();
9044 if (Ty->isBlockPointerType()) {
9045 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
9046 return true;
9047 }
9048 }
9049 return false;
9050}
9051
9052/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9053/// In that case, LHS = cond.
9054/// C99 6.5.15
9055QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9056 ExprResult &RHS, ExprValueKind &VK,
9057 ExprObjectKind &OK,
9058 SourceLocation QuestionLoc) {
9059
9060 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
9061 if (!LHSResult.isUsable()) return QualType();
9062 LHS = LHSResult;
9063
9064 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
9065 if (!RHSResult.isUsable()) return QualType();
9066 RHS = RHSResult;
9067
9068 // C++ is sufficiently different to merit its own checker.
9069 if (getLangOpts().CPlusPlus)
9070 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
9071
9072 VK = VK_PRValue;
9073 OK = OK_Ordinary;
9074
9075 if (Context.isDependenceAllowed() &&
9076 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9077 RHS.get()->isTypeDependent())) {
9078 assert(!getLangOpts().CPlusPlus);
9079 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9080 RHS.get()->containsErrors()) &&
9081 "should only occur in error-recovery path.");
9082 return Context.DependentTy;
9083 }
9084
9085 // The OpenCL operator with a vector condition is sufficiently
9086 // different to merit its own checker.
9087 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9088 Cond.get()->getType()->isExtVectorType())
9089 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
9090
9091 // First, check the condition.
9092 Cond = UsualUnaryConversions(E: Cond.get());
9093 if (Cond.isInvalid())
9094 return QualType();
9095 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
9096 return QualType();
9097
9098 // Handle vectors.
9099 if (LHS.get()->getType()->isVectorType() ||
9100 RHS.get()->getType()->isVectorType())
9101 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
9102 /*AllowBothBool*/ true,
9103 /*AllowBoolConversions*/ AllowBoolConversion: false,
9104 /*AllowBooleanOperation*/ AllowBoolOperation: false);
9105
9106 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
9107 ACK: ArithConvKind::Conditional);
9108 if (LHS.isInvalid() || RHS.isInvalid())
9109 return QualType();
9110
9111 // WebAssembly tables are not allowed as conditional LHS or RHS.
9112 QualType LHSTy = LHS.get()->getType();
9113 QualType RHSTy = RHS.get()->getType();
9114 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9115 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
9116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9117 return QualType();
9118 }
9119
9120 // Diagnose attempts to convert between __ibm128, __float128 and long double
9121 // where such conversions currently can't be handled.
9122 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
9123 Diag(Loc: QuestionLoc,
9124 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9126 return QualType();
9127 }
9128
9129 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9130 // selection operator (?:).
9131 if (getLangOpts().OpenCL &&
9132 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
9133 return QualType();
9134 }
9135
9136 // If both operands have arithmetic type, do the usual arithmetic conversions
9137 // to find a common type: C99 6.5.15p3,5.
9138 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9139 // Disallow invalid arithmetic conversions, such as those between bit-
9140 // precise integers types of different sizes, or between a bit-precise
9141 // integer and another type.
9142 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9143 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9144 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9145 << RHS.get()->getSourceRange();
9146 return QualType();
9147 }
9148
9149 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
9150 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
9151
9152 return ResTy;
9153 }
9154
9155 // If both operands are the same structure or union type, the result is that
9156 // type.
9157 // FIXME: Type of conditional expression must be complete in C mode.
9158 if (LHSTy->isRecordType() &&
9159 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
9160 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
9161 Y: RHSTy.getUnqualifiedType());
9162
9163 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9164 // The following || allows only one side to be void (a GCC-ism).
9165 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9166 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9167 // UsualArithmeticConversions already handled the case where both sides
9168 // are the same type.
9169 } else if (RHSTy->isVoidType()) {
9170 ResTy = RHSTy;
9171 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9172 << RHS.get()->getSourceRange();
9173 } else {
9174 ResTy = LHSTy;
9175 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
9176 << LHS.get()->getSourceRange();
9177 }
9178 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
9179 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9180 return ResTy;
9181 }
9182
9183 // C23 6.5.15p7:
9184 // ... if both the second and third operands have nullptr_t type, the
9185 // result also has that type.
9186 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9187 return ResTy;
9188
9189 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9190 // the type of the other operand."
9191 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9192 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9193
9194 // All objective-c pointer type analysis is done here.
9195 QualType compositeType =
9196 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9197 if (LHS.isInvalid() || RHS.isInvalid())
9198 return QualType();
9199 if (!compositeType.isNull())
9200 return compositeType;
9201
9202
9203 // Handle block pointer types.
9204 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9205 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9206 Loc: QuestionLoc);
9207
9208 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9209 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9210 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9211 Loc: QuestionLoc);
9212
9213 // GCC compatibility: soften pointer/integer mismatch. Note that
9214 // null pointers have been filtered out by this point.
9215 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9216 /*IsIntFirstExpr=*/true))
9217 return RHSTy;
9218 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9219 /*IsIntFirstExpr=*/false))
9220 return LHSTy;
9221
9222 // Emit a better diagnostic if one of the expressions is a null pointer
9223 // constant and the other is not a pointer type. In this case, the user most
9224 // likely forgot to take the address of the other expression.
9225 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9226 return QualType();
9227
9228 // Finally, if the LHS and RHS types are canonically the same type, we can
9229 // use the common sugared type.
9230 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9231 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9232
9233 // Otherwise, the operands are not compatible.
9234 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9235 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9236 << RHS.get()->getSourceRange();
9237 return QualType();
9238}
9239
9240/// SuggestParentheses - Emit a note with a fixit hint that wraps
9241/// ParenRange in parentheses.
9242static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9243 const PartialDiagnostic &Note,
9244 SourceRange ParenRange) {
9245 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9246 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9247 EndLoc.isValid()) {
9248 Self.Diag(Loc, PD: Note)
9249 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9250 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9251 } else {
9252 // We can't display the parentheses, so just show the bare note.
9253 Self.Diag(Loc, PD: Note) << ParenRange;
9254 }
9255}
9256
9257static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9258 return BinaryOperator::isAdditiveOp(Opc) ||
9259 BinaryOperator::isMultiplicativeOp(Opc) ||
9260 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9261 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9262 // not any of the logical operators. Bitwise-xor is commonly used as a
9263 // logical-xor because there is no logical-xor operator. The logical
9264 // operators, including uses of xor, have a high false positive rate for
9265 // precedence warnings.
9266}
9267
9268/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9269/// expression, either using a built-in or overloaded operator,
9270/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9271/// expression.
9272static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9273 const Expr **RHSExprs) {
9274 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9275 E = E->IgnoreImpCasts();
9276 E = E->IgnoreConversionOperatorSingleStep();
9277 E = E->IgnoreImpCasts();
9278 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9279 E = MTE->getSubExpr();
9280 E = E->IgnoreImpCasts();
9281 }
9282
9283 // Built-in binary operator.
9284 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9285 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9286 *Opcode = OP->getOpcode();
9287 *RHSExprs = OP->getRHS();
9288 return true;
9289 }
9290
9291 // Overloaded operator.
9292 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9293 if (Call->getNumArgs() != 2)
9294 return false;
9295
9296 // Make sure this is really a binary operator that is safe to pass into
9297 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9298 OverloadedOperatorKind OO = Call->getOperator();
9299 if (OO < OO_Plus || OO > OO_Arrow ||
9300 OO == OO_PlusPlus || OO == OO_MinusMinus)
9301 return false;
9302
9303 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9304 if (IsArithmeticOp(Opc: OpKind)) {
9305 *Opcode = OpKind;
9306 *RHSExprs = Call->getArg(Arg: 1);
9307 return true;
9308 }
9309 }
9310
9311 return false;
9312}
9313
9314/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9315/// or is a logical expression such as (x==y) which has int type, but is
9316/// commonly interpreted as boolean.
9317static bool ExprLooksBoolean(const Expr *E) {
9318 E = E->IgnoreParenImpCasts();
9319
9320 if (E->getType()->isBooleanType())
9321 return true;
9322 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9323 return OP->isComparisonOp() || OP->isLogicalOp();
9324 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9325 return OP->getOpcode() == UO_LNot;
9326 if (E->getType()->isPointerType())
9327 return true;
9328 // FIXME: What about overloaded operator calls returning "unspecified boolean
9329 // type"s (commonly pointer-to-members)?
9330
9331 return false;
9332}
9333
9334/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9335/// and binary operator are mixed in a way that suggests the programmer assumed
9336/// the conditional operator has higher precedence, for example:
9337/// "int x = a + someBinaryCondition ? 1 : 2".
9338static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9339 Expr *Condition, const Expr *LHSExpr,
9340 const Expr *RHSExpr) {
9341 BinaryOperatorKind CondOpcode;
9342 const Expr *CondRHS;
9343
9344 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9345 return;
9346 if (!ExprLooksBoolean(E: CondRHS))
9347 return;
9348
9349 // The condition is an arithmetic binary expression, with a right-
9350 // hand side that looks boolean, so warn.
9351
9352 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9353 ? diag::warn_precedence_bitwise_conditional
9354 : diag::warn_precedence_conditional;
9355
9356 Self.Diag(Loc: OpLoc, DiagID)
9357 << Condition->getSourceRange()
9358 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9359
9360 SuggestParentheses(
9361 Self, Loc: OpLoc,
9362 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9363 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9364 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9365
9366 SuggestParentheses(Self, Loc: OpLoc,
9367 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9368 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9369}
9370
9371/// Compute the nullability of a conditional expression.
9372static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9373 QualType LHSTy, QualType RHSTy,
9374 ASTContext &Ctx) {
9375 if (!ResTy->isAnyPointerType())
9376 return ResTy;
9377
9378 auto GetNullability = [](QualType Ty) {
9379 NullabilityKindOrNone Kind = Ty->getNullability();
9380 if (Kind) {
9381 // For our purposes, treat _Nullable_result as _Nullable.
9382 if (*Kind == NullabilityKind::NullableResult)
9383 return NullabilityKind::Nullable;
9384 return *Kind;
9385 }
9386 return NullabilityKind::Unspecified;
9387 };
9388
9389 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9390 NullabilityKind MergedKind;
9391
9392 // Compute nullability of a binary conditional expression.
9393 if (IsBin) {
9394 if (LHSKind == NullabilityKind::NonNull)
9395 MergedKind = NullabilityKind::NonNull;
9396 else
9397 MergedKind = RHSKind;
9398 // Compute nullability of a normal conditional expression.
9399 } else {
9400 if (LHSKind == NullabilityKind::Nullable ||
9401 RHSKind == NullabilityKind::Nullable)
9402 MergedKind = NullabilityKind::Nullable;
9403 else if (LHSKind == NullabilityKind::NonNull)
9404 MergedKind = RHSKind;
9405 else if (RHSKind == NullabilityKind::NonNull)
9406 MergedKind = LHSKind;
9407 else
9408 MergedKind = NullabilityKind::Unspecified;
9409 }
9410
9411 // Return if ResTy already has the correct nullability.
9412 if (GetNullability(ResTy) == MergedKind)
9413 return ResTy;
9414
9415 // Strip all nullability from ResTy.
9416 while (ResTy->getNullability())
9417 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9418
9419 // Create a new AttributedType with the new nullability kind.
9420 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9421}
9422
9423ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9424 SourceLocation ColonLoc,
9425 Expr *CondExpr, Expr *LHSExpr,
9426 Expr *RHSExpr) {
9427 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9428 // was the condition.
9429 OpaqueValueExpr *opaqueValue = nullptr;
9430 Expr *commonExpr = nullptr;
9431 if (!LHSExpr) {
9432 commonExpr = CondExpr;
9433 // Lower out placeholder types first. This is important so that we don't
9434 // try to capture a placeholder. This happens in few cases in C++; such
9435 // as Objective-C++'s dictionary subscripting syntax.
9436 if (commonExpr->hasPlaceholderType()) {
9437 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9438 if (!result.isUsable()) return ExprError();
9439 commonExpr = result.get();
9440 }
9441 // We usually want to apply unary conversions *before* saving, except
9442 // in the special case of a C++ l-value conditional.
9443 if (!(getLangOpts().CPlusPlus
9444 && !commonExpr->isTypeDependent()
9445 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9446 && commonExpr->isGLValue()
9447 && commonExpr->isOrdinaryOrBitFieldObject()
9448 && RHSExpr->isOrdinaryOrBitFieldObject()
9449 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9450 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9451 if (commonRes.isInvalid())
9452 return ExprError();
9453 commonExpr = commonRes.get();
9454 }
9455
9456 // If the common expression is a class or array prvalue, materialize it
9457 // so that we can safely refer to it multiple times.
9458 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9459 commonExpr->getType()->isArrayType())) {
9460 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9461 if (MatExpr.isInvalid())
9462 return ExprError();
9463 commonExpr = MatExpr.get();
9464 }
9465
9466 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9467 commonExpr->getType(),
9468 commonExpr->getValueKind(),
9469 commonExpr->getObjectKind(),
9470 commonExpr);
9471 LHSExpr = CondExpr = opaqueValue;
9472 }
9473
9474 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9475 ExprValueKind VK = VK_PRValue;
9476 ExprObjectKind OK = OK_Ordinary;
9477 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9478 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9479 VK, OK, QuestionLoc);
9480 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9481 RHS.isInvalid())
9482 return ExprError();
9483
9484 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9485 RHSExpr: RHS.get());
9486
9487 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9488
9489 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9490 Ctx&: Context);
9491
9492 if (!commonExpr)
9493 return new (Context)
9494 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9495 RHS.get(), result, VK, OK);
9496
9497 return new (Context) BinaryConditionalOperator(
9498 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9499 ColonLoc, result, VK, OK);
9500}
9501
9502bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9503 unsigned FromAttributes = 0, ToAttributes = 0;
9504 if (const auto *FromFn =
9505 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9506 FromAttributes =
9507 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9508 if (const auto *ToFn =
9509 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9510 ToAttributes =
9511 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9512
9513 return FromAttributes != ToAttributes;
9514}
9515
9516// checkPointerTypesForAssignment - This is a very tricky routine (despite
9517// being closely modeled after the C99 spec:-). The odd characteristic of this
9518// routine is it effectively iqnores the qualifiers on the top level pointee.
9519// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9520// FIXME: add a couple examples in this comment.
9521static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9522 QualType LHSType,
9523 QualType RHSType,
9524 SourceLocation Loc) {
9525 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9526 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9527
9528 // get the "pointed to" type (ignoring qualifiers at the top level)
9529 const Type *lhptee, *rhptee;
9530 Qualifiers lhq, rhq;
9531 std::tie(args&: lhptee, args&: lhq) =
9532 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9533 std::tie(args&: rhptee, args&: rhq) =
9534 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9535
9536 AssignConvertType ConvTy = AssignConvertType::Compatible;
9537
9538 // C99 6.5.16.1p1: This following citation is common to constraints
9539 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9540 // qualifiers of the type *pointed to* by the right;
9541
9542 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9543 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9544 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9545 // Ignore lifetime for further calculation.
9546 lhq.removeObjCLifetime();
9547 rhq.removeObjCLifetime();
9548 }
9549
9550 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9551 // Treat address-space mismatches as fatal.
9552 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9553 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9554
9555 // It's okay to add or remove GC or lifetime qualifiers when converting to
9556 // and from void*.
9557 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9558 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9559 Ctx: S.getASTContext()) &&
9560 (lhptee->isVoidType() || rhptee->isVoidType()))
9561 ; // keep old
9562
9563 // Treat lifetime mismatches as fatal.
9564 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9565 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9566
9567 // Treat pointer-auth mismatches as fatal.
9568 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9569 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9570
9571 // For GCC/MS compatibility, other qualifier mismatches are treated
9572 // as still compatible in C.
9573 else
9574 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9575 }
9576
9577 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9578 // incomplete type and the other is a pointer to a qualified or unqualified
9579 // version of void...
9580 if (lhptee->isVoidType()) {
9581 if (rhptee->isIncompleteOrObjectType())
9582 return ConvTy;
9583
9584 // As an extension, we allow cast to/from void* to function pointer.
9585 assert(rhptee->isFunctionType());
9586 return AssignConvertType::FunctionVoidPointer;
9587 }
9588
9589 if (rhptee->isVoidType()) {
9590 // In C, void * to another pointer type is compatible, but we want to note
9591 // that there will be an implicit conversion happening here.
9592 if (lhptee->isIncompleteOrObjectType())
9593 return ConvTy == AssignConvertType::Compatible &&
9594 !S.getLangOpts().CPlusPlus
9595 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9596 : ConvTy;
9597
9598 // As an extension, we allow cast to/from void* to function pointer.
9599 assert(lhptee->isFunctionType());
9600 return AssignConvertType::FunctionVoidPointer;
9601 }
9602
9603 if (!S.Diags.isIgnored(
9604 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9605 Loc) &&
9606 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9607 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9608 return AssignConvertType::IncompatibleFunctionPointerStrict;
9609
9610 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9611 // unqualified versions of compatible types, ...
9612 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9613
9614 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9615 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9616 QualType LUnderlying =
9617 ltrans->isOverflowBehaviorType()
9618 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9619 : ltrans;
9620 QualType RUnderlying =
9621 rtrans->isOverflowBehaviorType()
9622 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9623 : rtrans;
9624
9625 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9626 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9627
9628 ltrans = LUnderlying;
9629 rtrans = RUnderlying;
9630 }
9631 }
9632
9633 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9634 // Check if the pointee types are compatible ignoring the sign.
9635 // We explicitly check for char so that we catch "char" vs
9636 // "unsigned char" on systems where "char" is unsigned.
9637 if (lhptee->isCharType())
9638 ltrans = S.Context.UnsignedCharTy;
9639 else if (lhptee->hasSignedIntegerRepresentation())
9640 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9641
9642 if (rhptee->isCharType())
9643 rtrans = S.Context.UnsignedCharTy;
9644 else if (rhptee->hasSignedIntegerRepresentation())
9645 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9646
9647 if (ltrans == rtrans) {
9648 // Types are compatible ignoring the sign. Qualifier incompatibility
9649 // takes priority over sign incompatibility because the sign
9650 // warning can be disabled.
9651 if (!S.IsAssignConvertCompatible(ConvTy))
9652 return ConvTy;
9653
9654 return AssignConvertType::IncompatiblePointerSign;
9655 }
9656
9657 // If we are a multi-level pointer, it's possible that our issue is simply
9658 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9659 // the eventual target type is the same and the pointers have the same
9660 // level of indirection, this must be the issue.
9661 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9662 do {
9663 std::tie(args&: lhptee, args&: lhq) =
9664 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9665 std::tie(args&: rhptee, args&: rhq) =
9666 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9667
9668 // Inconsistent address spaces at this point is invalid, even if the
9669 // address spaces would be compatible.
9670 // FIXME: This doesn't catch address space mismatches for pointers of
9671 // different nesting levels, like:
9672 // __local int *** a;
9673 // int ** b = a;
9674 // It's not clear how to actually determine when such pointers are
9675 // invalidly incompatible.
9676 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9677 return AssignConvertType::
9678 IncompatibleNestedPointerAddressSpaceMismatch;
9679
9680 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9681
9682 if (lhptee == rhptee)
9683 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9684 }
9685
9686 // General pointer incompatibility takes priority over qualifiers.
9687 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9688 return AssignConvertType::IncompatibleFunctionPointer;
9689 return AssignConvertType::IncompatiblePointer;
9690 }
9691 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9692 // hasSameType, so we can skip further checks.
9693 const auto *LFT = ltrans->getAs<FunctionType>();
9694 const auto *RFT = rtrans->getAs<FunctionType>();
9695 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9696 // The invocation of IsFunctionConversion below will try to transform rtrans
9697 // to obtain an exact match for ltrans. This should not fail because of
9698 // mismatches in result type and parameter types, they were already checked
9699 // by typesAreCompatible above. So we will recreate rtrans (or where
9700 // appropriate ltrans) using the result type and parameter types from ltrans
9701 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9702 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9703 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9704 if (LFPT && RFPT) {
9705 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9706 Args: LFPT->getParamTypes(),
9707 EPI: RFPT->getExtProtoInfo());
9708 } else if (LFPT) {
9709 FunctionProtoType::ExtProtoInfo EPI;
9710 EPI.ExtInfo = RFT->getExtInfo();
9711 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9712 Args: LFPT->getParamTypes(), EPI);
9713 } else if (RFPT) {
9714 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9715 // all of its ExtProtoInfo. Transform ltrans instead.
9716 FunctionProtoType::ExtProtoInfo EPI;
9717 EPI.ExtInfo = LFT->getExtInfo();
9718 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9719 Args: RFPT->getParamTypes(), EPI);
9720 } else {
9721 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9722 Info: RFT->getExtInfo());
9723 }
9724 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9725 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9726 return AssignConvertType::IncompatibleFunctionPointer;
9727 }
9728 return ConvTy;
9729}
9730
9731/// checkBlockPointerTypesForAssignment - This routine determines whether two
9732/// block pointer types are compatible or whether a block and normal pointer
9733/// are compatible. It is more restrict than comparing two function pointer
9734// types.
9735static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9736 QualType LHSType,
9737 QualType RHSType) {
9738 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9739 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9740
9741 QualType lhptee, rhptee;
9742
9743 // get the "pointed to" type (ignoring qualifiers at the top level)
9744 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9745 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9746
9747 // In C++, the types have to match exactly.
9748 if (S.getLangOpts().CPlusPlus)
9749 return AssignConvertType::IncompatibleBlockPointer;
9750
9751 AssignConvertType ConvTy = AssignConvertType::Compatible;
9752
9753 // For blocks we enforce that qualifiers are identical.
9754 Qualifiers LQuals = lhptee.getLocalQualifiers();
9755 Qualifiers RQuals = rhptee.getLocalQualifiers();
9756 if (S.getLangOpts().OpenCL) {
9757 LQuals.removeAddressSpace();
9758 RQuals.removeAddressSpace();
9759 }
9760 if (LQuals != RQuals)
9761 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9762
9763 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9764 // assignment.
9765 // The current behavior is similar to C++ lambdas. A block might be
9766 // assigned to a variable iff its return type and parameters are compatible
9767 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9768 // an assignment. Presumably it should behave in way that a function pointer
9769 // assignment does in C, so for each parameter and return type:
9770 // * CVR and address space of LHS should be a superset of CVR and address
9771 // space of RHS.
9772 // * unqualified types should be compatible.
9773 if (S.getLangOpts().OpenCL) {
9774 if (!S.Context.typesAreBlockPointerCompatible(
9775 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9776 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9777 return AssignConvertType::IncompatibleBlockPointer;
9778 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9779 return AssignConvertType::IncompatibleBlockPointer;
9780
9781 return ConvTy;
9782}
9783
9784/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9785/// for assignment compatibility.
9786static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9787 QualType LHSType,
9788 QualType RHSType) {
9789 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9790 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9791
9792 if (LHSType->isObjCBuiltinType()) {
9793 // Class is not compatible with ObjC object pointers.
9794 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9795 !RHSType->isObjCQualifiedClassType())
9796 return AssignConvertType::IncompatiblePointer;
9797 return AssignConvertType::Compatible;
9798 }
9799 if (RHSType->isObjCBuiltinType()) {
9800 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9801 !LHSType->isObjCQualifiedClassType())
9802 return AssignConvertType::IncompatiblePointer;
9803 return AssignConvertType::Compatible;
9804 }
9805 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9806 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9807
9808 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9809 // make an exception for id<P>
9810 !LHSType->isObjCQualifiedIdType())
9811 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9812
9813 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9814 return AssignConvertType::Compatible;
9815 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9816 return AssignConvertType::IncompatibleObjCQualifiedId;
9817 return AssignConvertType::IncompatiblePointer;
9818}
9819
9820AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9821 QualType LHSType,
9822 QualType RHSType) {
9823 // Fake up an opaque expression. We don't actually care about what
9824 // cast operations are required, so if CheckAssignmentConstraints
9825 // adds casts to this they'll be wasted, but fortunately that doesn't
9826 // usually happen on valid code.
9827 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9828 ExprResult RHSPtr = &RHSExpr;
9829 CastKind K;
9830
9831 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9832}
9833
9834/// This helper function returns true if QT is a vector type that has element
9835/// type ElementType.
9836static bool isVector(QualType QT, QualType ElementType) {
9837 if (const VectorType *VT = QT->getAs<VectorType>())
9838 return VT->getElementType().getCanonicalType() == ElementType;
9839 return false;
9840}
9841
9842/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9843/// has code to accommodate several GCC extensions when type checking
9844/// pointers. Here are some objectionable examples that GCC considers warnings:
9845///
9846/// int a, *pint;
9847/// short *pshort;
9848/// struct foo *pfoo;
9849///
9850/// pint = pshort; // warning: assignment from incompatible pointer type
9851/// a = pint; // warning: assignment makes integer from pointer without a cast
9852/// pint = a; // warning: assignment makes pointer from integer without a cast
9853/// pint = pfoo; // warning: assignment from incompatible pointer type
9854///
9855/// As a result, the code for dealing with pointers is more complex than the
9856/// C99 spec dictates.
9857///
9858/// Sets 'Kind' for any result kind except Incompatible.
9859AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9860 ExprResult &RHS,
9861 CastKind &Kind,
9862 bool ConvertRHS) {
9863 QualType RHSType = RHS.get()->getType();
9864 QualType OrigLHSType = LHSType;
9865
9866 // Get canonical types. We're not formatting these types, just comparing
9867 // them.
9868 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9869 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9870
9871 // Common case: no conversion required.
9872 if (LHSType == RHSType) {
9873 Kind = CK_NoOp;
9874 return AssignConvertType::Compatible;
9875 }
9876
9877 // If the LHS has an __auto_type, there are no additional type constraints
9878 // to be worried about.
9879 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9880 if (AT->isGNUAutoType()) {
9881 Kind = CK_NoOp;
9882 return AssignConvertType::Compatible;
9883 }
9884 }
9885
9886 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9887 switch (OBTResult) {
9888 case ASTContext::OBTAssignResult::IncompatibleKinds:
9889 Kind = CK_NoOp;
9890 return AssignConvertType::IncompatibleOBTKinds;
9891 case ASTContext::OBTAssignResult::Discards:
9892 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9893 return AssignConvertType::CompatibleOBTDiscards;
9894 case ASTContext::OBTAssignResult::Compatible:
9895 case ASTContext::OBTAssignResult::NotApplicable:
9896 break;
9897 }
9898
9899 // Check for incompatible OBT types in pointer pointee types
9900 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9901 QualType LHSPointee = LHSType->getPointeeType();
9902 QualType RHSPointee = RHSType->getPointeeType();
9903 if ((LHSPointee->isOverflowBehaviorType() ||
9904 RHSPointee->isOverflowBehaviorType()) &&
9905 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9906 Kind = CK_NoOp;
9907 return AssignConvertType::IncompatibleOBTKinds;
9908 }
9909 }
9910
9911 // If we have an atomic type, try a non-atomic assignment, then just add an
9912 // atomic qualification step.
9913 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9914 AssignConvertType Result =
9915 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9916 if (!IsAssignConvertCompatible(ConvTy: Result))
9917 return Result;
9918 if (Kind != CK_NoOp && ConvertRHS)
9919 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9920 Kind = CK_NonAtomicToAtomic;
9921 return Result;
9922 }
9923
9924 // If the left-hand side is a reference type, then we are in a
9925 // (rare!) case where we've allowed the use of references in C,
9926 // e.g., as a parameter type in a built-in function. In this case,
9927 // just make sure that the type referenced is compatible with the
9928 // right-hand side type. The caller is responsible for adjusting
9929 // LHSType so that the resulting expression does not have reference
9930 // type.
9931 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9932 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9933 Kind = CK_LValueBitCast;
9934 return AssignConvertType::Compatible;
9935 }
9936 return AssignConvertType::Incompatible;
9937 }
9938
9939 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9940 // of an ExtVector type to the same ExtVector type.
9941 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9942 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9943 // Implicit conversions require the same number of elements.
9944 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9945 return AssignConvertType::Incompatible;
9946
9947 if (LHSType->isExtVectorBoolType() &&
9948 RHSExtType->getElementType()->isIntegerType()) {
9949 Kind = CK_IntegralToBoolean;
9950 return AssignConvertType::Compatible;
9951 }
9952 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9953 if (Context.getLangOpts().OpenCL &&
9954 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9955 Kind = CK_BitCast;
9956 return AssignConvertType::Compatible;
9957 }
9958 return AssignConvertType::Incompatible;
9959 }
9960 if (RHSType->isArithmeticType()) {
9961 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9962 if (ConvertRHS)
9963 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9964 Kind = CK_VectorSplat;
9965 return AssignConvertType::Compatible;
9966 }
9967 }
9968
9969 // Conversions to or from vector type.
9970 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9971 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9972 // Allow assignments of an AltiVec vector type to an equivalent GCC
9973 // vector type and vice versa
9974 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9975 Kind = CK_BitCast;
9976 return AssignConvertType::Compatible;
9977 }
9978
9979 // If we are allowing lax vector conversions, and LHS and RHS are both
9980 // vectors, the total size only needs to be the same. This is a bitcast;
9981 // no bits are changed but the result type is different.
9982 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9983 // The default for lax vector conversions with Altivec vectors will
9984 // change, so if we are converting between vector types where
9985 // at least one is an Altivec vector, emit a warning.
9986 if (Context.getTargetInfo().getTriple().isPPC() &&
9987 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9988 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9989 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9990 << RHSType << LHSType;
9991 Kind = CK_BitCast;
9992 return AssignConvertType::IncompatibleVectors;
9993 }
9994 }
9995
9996 // When the RHS comes from another lax conversion (e.g. binops between
9997 // scalars and vectors) the result is canonicalized as a vector. When the
9998 // LHS is also a vector, the lax is allowed by the condition above. Handle
9999 // the case where LHS is a scalar.
10000 if (LHSType->isScalarType()) {
10001 const VectorType *VecType = RHSType->getAs<VectorType>();
10002 if (VecType && VecType->getNumElements() == 1 &&
10003 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
10004 if (Context.getTargetInfo().getTriple().isPPC() &&
10005 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
10006 VecType->getVectorKind() == VectorKind::AltiVecBool ||
10007 VecType->getVectorKind() == VectorKind::AltiVecPixel))
10008 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
10009 << RHSType << LHSType;
10010 ExprResult *VecExpr = &RHS;
10011 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
10012 Kind = CK_BitCast;
10013 return AssignConvertType::Compatible;
10014 }
10015 }
10016
10017 // Allow assignments between fixed-length and sizeless SVE vectors.
10018 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10019 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10020 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
10021 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
10022 Kind = CK_BitCast;
10023 return AssignConvertType::Compatible;
10024 }
10025
10026 // Allow assignments between fixed-length and sizeless RVV vectors.
10027 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10028 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10029 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
10030 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
10031 Kind = CK_BitCast;
10032 return AssignConvertType::Compatible;
10033 }
10034 }
10035
10036 return AssignConvertType::Incompatible;
10037 }
10038
10039 // Diagnose attempts to convert between __ibm128, __float128 and long double
10040 // where such conversions currently can't be handled.
10041 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
10042 return AssignConvertType::Incompatible;
10043
10044 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10045 // discards the imaginary part.
10046 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10047 !LHSType->getAs<ComplexType>())
10048 return AssignConvertType::Incompatible;
10049
10050 // Arithmetic conversions.
10051 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10052 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10053 if (ConvertRHS)
10054 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
10055 return AssignConvertType::Compatible;
10056 }
10057
10058 // Conversions to normal pointers.
10059 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
10060 // U* -> T*
10061 if (isa<PointerType>(Val: RHSType)) {
10062 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10063 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10064 if (AddrSpaceL != AddrSpaceR)
10065 Kind = CK_AddressSpaceConversion;
10066 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
10067 Kind = CK_NoOp;
10068 else
10069 Kind = CK_BitCast;
10070 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
10071 Loc: RHS.get()->getBeginLoc());
10072 }
10073
10074 // int -> T*
10075 if (RHSType->isIntegerType()) {
10076 Kind = CK_IntegralToPointer; // FIXME: null?
10077 return AssignConvertType::IntToPointer;
10078 }
10079
10080 // C pointers are not compatible with ObjC object pointers,
10081 // with two exceptions:
10082 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10083 // - conversions to void*
10084 if (LHSPointer->getPointeeType()->isVoidType()) {
10085 Kind = CK_BitCast;
10086 return AssignConvertType::Compatible;
10087 }
10088
10089 // - conversions from 'Class' to the redefinition type
10090 if (RHSType->isObjCClassType() &&
10091 Context.hasSameType(T1: LHSType,
10092 T2: Context.getObjCClassRedefinitionType())) {
10093 Kind = CK_BitCast;
10094 return AssignConvertType::Compatible;
10095 }
10096
10097 Kind = CK_BitCast;
10098 return AssignConvertType::IncompatiblePointer;
10099 }
10100
10101 // U^ -> void*
10102 if (RHSType->getAs<BlockPointerType>()) {
10103 if (LHSPointer->getPointeeType()->isVoidType()) {
10104 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10105 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10106 ->getPointeeType()
10107 .getAddressSpace();
10108 Kind =
10109 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10110 return AssignConvertType::Compatible;
10111 }
10112 }
10113
10114 return AssignConvertType::Incompatible;
10115 }
10116
10117 // Conversions to block pointers.
10118 if (isa<BlockPointerType>(Val: LHSType)) {
10119 // U^ -> T^
10120 if (RHSType->isBlockPointerType()) {
10121 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10122 ->getPointeeType()
10123 .getAddressSpace();
10124 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10125 ->getPointeeType()
10126 .getAddressSpace();
10127 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10128 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10129 }
10130
10131 // int or null -> T^
10132 if (RHSType->isIntegerType()) {
10133 Kind = CK_IntegralToPointer; // FIXME: null
10134 return AssignConvertType::IntToBlockPointer;
10135 }
10136
10137 // id -> T^
10138 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10139 Kind = CK_AnyPointerToBlockPointerCast;
10140 return AssignConvertType::Compatible;
10141 }
10142
10143 // void* -> T^
10144 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10145 if (RHSPT->getPointeeType()->isVoidType()) {
10146 Kind = CK_AnyPointerToBlockPointerCast;
10147 return AssignConvertType::Compatible;
10148 }
10149
10150 return AssignConvertType::Incompatible;
10151 }
10152
10153 // Conversions to Objective-C pointers.
10154 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
10155 // A* -> B*
10156 if (RHSType->isObjCObjectPointerType()) {
10157 Kind = CK_BitCast;
10158 AssignConvertType result =
10159 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
10160 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10161 result == AssignConvertType::Compatible &&
10162 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
10163 result = AssignConvertType::IncompatibleObjCWeakRef;
10164 return result;
10165 }
10166
10167 // int or null -> A*
10168 if (RHSType->isIntegerType()) {
10169 Kind = CK_IntegralToPointer; // FIXME: null
10170 return AssignConvertType::IntToPointer;
10171 }
10172
10173 // In general, C pointers are not compatible with ObjC object pointers,
10174 // with two exceptions:
10175 if (isa<PointerType>(Val: RHSType)) {
10176 Kind = CK_CPointerToObjCPointerCast;
10177
10178 // - conversions from 'void*'
10179 if (RHSType->isVoidPointerType()) {
10180 return AssignConvertType::Compatible;
10181 }
10182
10183 // - conversions to 'Class' from its redefinition type
10184 if (LHSType->isObjCClassType() &&
10185 Context.hasSameType(T1: RHSType,
10186 T2: Context.getObjCClassRedefinitionType())) {
10187 return AssignConvertType::Compatible;
10188 }
10189
10190 return AssignConvertType::IncompatiblePointer;
10191 }
10192
10193 // Only under strict condition T^ is compatible with an Objective-C pointer.
10194 if (RHSType->isBlockPointerType() &&
10195 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10196 if (ConvertRHS)
10197 maybeExtendBlockObject(E&: RHS);
10198 Kind = CK_BlockPointerToObjCPointerCast;
10199 return AssignConvertType::Compatible;
10200 }
10201
10202 return AssignConvertType::Incompatible;
10203 }
10204
10205 // Conversion to nullptr_t (C23 only)
10206 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10207 RHS.get()->isNullPointerConstant(Ctx&: Context,
10208 NPC: Expr::NPC_ValueDependentIsNull)) {
10209 // null -> nullptr_t
10210 Kind = CK_NullToPointer;
10211 return AssignConvertType::Compatible;
10212 }
10213
10214 // Conversions from pointers that are not covered by the above.
10215 if (isa<PointerType>(Val: RHSType)) {
10216 // T* -> _Bool
10217 if (LHSType == Context.BoolTy) {
10218 Kind = CK_PointerToBoolean;
10219 return AssignConvertType::Compatible;
10220 }
10221
10222 // T* -> int
10223 if (LHSType->isIntegerType()) {
10224 Kind = CK_PointerToIntegral;
10225 return AssignConvertType::PointerToInt;
10226 }
10227
10228 return AssignConvertType::Incompatible;
10229 }
10230
10231 // Conversions from Objective-C pointers that are not covered by the above.
10232 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10233 // T* -> _Bool
10234 if (LHSType == Context.BoolTy) {
10235 Kind = CK_PointerToBoolean;
10236 return AssignConvertType::Compatible;
10237 }
10238
10239 // T* -> int
10240 if (LHSType->isIntegerType()) {
10241 Kind = CK_PointerToIntegral;
10242 return AssignConvertType::PointerToInt;
10243 }
10244
10245 return AssignConvertType::Incompatible;
10246 }
10247
10248 // struct A -> struct B
10249 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10250 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10251 Kind = CK_NoOp;
10252 return AssignConvertType::Compatible;
10253 }
10254 }
10255
10256 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10257 Kind = CK_IntToOCLSampler;
10258 return AssignConvertType::Compatible;
10259 }
10260
10261 return AssignConvertType::Incompatible;
10262}
10263
10264/// Constructs a transparent union from an expression that is
10265/// used to initialize the transparent union.
10266static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10267 ExprResult &EResult, QualType UnionType,
10268 FieldDecl *Field) {
10269 // Build an initializer list that designates the appropriate member
10270 // of the transparent union.
10271 Expr *E = EResult.get();
10272 InitListExpr *Initializer = new (C) InitListExpr(
10273 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10274 Initializer->setType(UnionType);
10275 Initializer->setInitializedFieldInUnion(Field);
10276
10277 // Build a compound literal constructing a value of the transparent
10278 // union type from this initializer list.
10279 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10280 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10281 VK_PRValue, Initializer, false);
10282}
10283
10284AssignConvertType
10285Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10286 ExprResult &RHS) {
10287 QualType RHSType = RHS.get()->getType();
10288
10289 // If the ArgType is a Union type, we want to handle a potential
10290 // transparent_union GCC extension.
10291 const RecordType *UT = ArgType->getAsUnionType();
10292 if (!UT)
10293 return AssignConvertType::Incompatible;
10294
10295 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10296 if (!UD->hasAttr<TransparentUnionAttr>())
10297 return AssignConvertType::Incompatible;
10298
10299 // The field to initialize within the transparent union.
10300 FieldDecl *InitField = nullptr;
10301 // It's compatible if the expression matches any of the fields.
10302 for (auto *it : UD->fields()) {
10303 if (it->getType()->isPointerType()) {
10304 // If the transparent union contains a pointer type, we allow:
10305 // 1) void pointer
10306 // 2) null pointer constant
10307 if (RHSType->isPointerType())
10308 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10309 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10310 InitField = it;
10311 break;
10312 }
10313
10314 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10315 NPC: Expr::NPC_ValueDependentIsNull)) {
10316 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10317 CK: CK_NullToPointer);
10318 InitField = it;
10319 break;
10320 }
10321 }
10322
10323 CastKind Kind;
10324 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10325 AssignConvertType::Compatible) {
10326 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10327 InitField = it;
10328 break;
10329 }
10330 }
10331
10332 if (!InitField)
10333 return AssignConvertType::Incompatible;
10334
10335 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10336 return AssignConvertType::Compatible;
10337}
10338
10339AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10340 ExprResult &CallerRHS,
10341 bool Diagnose,
10342 bool DiagnoseCFAudited,
10343 bool ConvertRHS) {
10344 // We need to be able to tell the caller whether we diagnosed a problem, if
10345 // they ask us to issue diagnostics.
10346 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10347
10348 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10349 // we can't avoid *all* modifications at the moment, so we need some somewhere
10350 // to put the updated value.
10351 ExprResult LocalRHS = CallerRHS;
10352 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10353
10354 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10355 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10356 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10357 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10358 Diag(Loc: RHS.get()->getExprLoc(),
10359 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10360 << RHS.get()->getSourceRange();
10361 }
10362 }
10363 }
10364
10365 if (getLangOpts().CPlusPlus) {
10366 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10367 // C++ 5.17p3: If the left operand is not of class type, the
10368 // expression is implicitly converted (C++ 4) to the
10369 // cv-unqualified type of the left operand.
10370 QualType RHSType = RHS.get()->getType();
10371 if (Diagnose) {
10372 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10373 Action: AssignmentAction::Assigning);
10374 } else {
10375 ImplicitConversionSequence ICS =
10376 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10377 /*SuppressUserConversions=*/false,
10378 AllowExplicit: AllowedExplicit::None,
10379 /*InOverloadResolution=*/false,
10380 /*CStyle=*/false,
10381 /*AllowObjCWritebackConversion=*/false);
10382 if (ICS.isFailure())
10383 return AssignConvertType::Incompatible;
10384 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10385 ICS, Action: AssignmentAction::Assigning);
10386 }
10387 if (RHS.isInvalid())
10388 return AssignConvertType::Incompatible;
10389 AssignConvertType result = AssignConvertType::Compatible;
10390 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10391 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10392 result = AssignConvertType::IncompatibleObjCWeakRef;
10393
10394 // Check if OBT is being discarded during assignment
10395 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10396 if (RHSType->isOverflowBehaviorType() &&
10397 !LHSType->isOverflowBehaviorType()) {
10398 result = AssignConvertType::CompatibleOBTDiscards;
10399 }
10400
10401 return result;
10402 }
10403
10404 // FIXME: Currently, we fall through and treat C++ classes like C
10405 // structures.
10406 // FIXME: We also fall through for atomics; not sure what should
10407 // happen there, though.
10408 } else if (RHS.get()->getType() == Context.OverloadTy) {
10409 // As a set of extensions to C, we support overloading on functions. These
10410 // functions need to be resolved here.
10411 DeclAccessPair DAP;
10412 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10413 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10414 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10415 else
10416 return AssignConvertType::Incompatible;
10417 }
10418
10419 // For HLSL records, insert derived-to-base conversion if needed.
10420 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10421 QualType RHSType = RHS.get()->getType();
10422 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10423 CXXBasePaths Paths;
10424 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10425 CXXCastPath CastPath;
10426 BuildBasePathArray(Paths, BasePath&: CastPath);
10427 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10428 BasePath: &CastPath);
10429 }
10430 }
10431 }
10432
10433 // This check seems unnatural, however it is necessary to ensure the proper
10434 // conversion of functions/arrays. If the conversion were done for all
10435 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10436 // expressions that suppress this implicit conversion (&, sizeof). This needs
10437 // to happen before we check for null pointer conversions because C does not
10438 // undergo the same implicit conversions as C++ does above (by the calls to
10439 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10440 // lvalue to rvalue cast before checking for null pointer constraints. This
10441 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10442 //
10443 // Suppress this for references: C++ 8.5.3p5.
10444 if (!LHSType->isReferenceType()) {
10445 // FIXME: We potentially allocate here even if ConvertRHS is false.
10446 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10447 if (RHS.isInvalid())
10448 return AssignConvertType::Incompatible;
10449 }
10450
10451 // The constraints are expressed in terms of the atomic, qualified, or
10452 // unqualified type of the LHS.
10453 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10454
10455 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10456 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10457 if ((LHSTypeAfterConversion->isPointerType() ||
10458 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10459 LHSTypeAfterConversion->isBlockPointerType()) &&
10460 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10461 RHS.get()->isNullPointerConstant(Ctx&: Context,
10462 NPC: Expr::NPC_ValueDependentIsNull))) {
10463 AssignConvertType Ret = AssignConvertType::Compatible;
10464 if (Diagnose || ConvertRHS) {
10465 CastKind Kind;
10466 CXXCastPath Path;
10467 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10468 /*IgnoreBaseAccess=*/false, Diagnose);
10469
10470 // If there is a conversion of some kind, check to see what kind of
10471 // pointer conversion happened so we can diagnose a C++ compatibility
10472 // diagnostic if the conversion is invalid. This only matters if the RHS
10473 // is some kind of void pointer. We have a carve-out when the RHS is from
10474 // a macro expansion because the use of a macro may indicate different
10475 // code between C and C++. Consider: char *s = NULL; where NULL is
10476 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10477 // C++, which is valid in C++. Ignore parentheses around the macro when
10478 // checking where the expression originates.
10479 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10480 !RHS.get()->IgnoreParens()->getBeginLoc().isMacroID()) {
10481 QualType CanRHS =
10482 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10483 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10484 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10485 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10486 Loc: RHS.get()->getExprLoc());
10487 // Anything that's not considered perfectly compatible would be
10488 // incompatible in C++.
10489 if (Ret != AssignConvertType::Compatible)
10490 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10491 }
10492 }
10493
10494 if (ConvertRHS)
10495 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10496 }
10497 return Ret;
10498 }
10499 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10500 // unqualified bool, and the right operand is a pointer or its type is
10501 // nullptr_t.
10502 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10503 RHS.get()->getType()->isNullPtrType()) {
10504 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10505 // only handles nullptr -> _Bool due to needing an extra conversion
10506 // step.
10507 // We model this by converting from nullptr -> void * and then let the
10508 // conversion from void * -> _Bool happen naturally.
10509 if (Diagnose || ConvertRHS) {
10510 CastKind Kind;
10511 CXXCastPath Path;
10512 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10513 /*IgnoreBaseAccess=*/false, Diagnose);
10514 if (ConvertRHS)
10515 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10516 BasePath: &Path);
10517 }
10518 }
10519
10520 // OpenCL queue_t type assignment.
10521 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10522 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10523 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10524 return AssignConvertType::Compatible;
10525 }
10526
10527 CastKind Kind;
10528 AssignConvertType result =
10529 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10530
10531 // If assigning a void * created by an allocation function call to some other
10532 // type, check that the allocated size is sufficient for that type.
10533 if (result != AssignConvertType::Incompatible &&
10534 RHS.get()->getType()->isVoidPointerType())
10535 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10536
10537 // C99 6.5.16.1p2: The value of the right operand is converted to the
10538 // type of the assignment expression.
10539 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10540 // so that we can use references in built-in functions even in C.
10541 // The getNonReferenceType() call makes sure that the resulting expression
10542 // does not have reference type.
10543 if (result != AssignConvertType::Incompatible &&
10544 RHS.get()->getType() != LHSType) {
10545 QualType Ty = LHSType.getNonLValueExprType(Context);
10546 Expr *E = RHS.get();
10547
10548 // Check for various Objective-C errors. If we are not reporting
10549 // diagnostics and just checking for errors, e.g., during overload
10550 // resolution, return Incompatible to indicate the failure.
10551 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10552 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10553 CCK: CheckedConversionKind::Implicit, Diagnose,
10554 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10555 if (!Diagnose)
10556 return AssignConvertType::Incompatible;
10557 }
10558 if (getLangOpts().ObjC &&
10559 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10560 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10561 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10562 if (!Diagnose)
10563 return AssignConvertType::Incompatible;
10564 // Replace the expression with a corrected version and continue so we
10565 // can find further errors.
10566 RHS = E;
10567 return AssignConvertType::Compatible;
10568 }
10569
10570 if (ConvertRHS)
10571 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10572 }
10573
10574 return result;
10575}
10576
10577namespace {
10578/// The original operand to an operator, prior to the application of the usual
10579/// arithmetic conversions and converting the arguments of a builtin operator
10580/// candidate.
10581struct OriginalOperand {
10582 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10583 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10584 Op = MTE->getSubExpr();
10585 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10586 Op = BTE->getSubExpr();
10587 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10588 Orig = ICE->getSubExprAsWritten();
10589 Conversion = ICE->getConversionFunction();
10590 }
10591 }
10592
10593 QualType getType() const { return Orig->getType(); }
10594
10595 Expr *Orig;
10596 NamedDecl *Conversion;
10597};
10598}
10599
10600QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10601 ExprResult &RHS) {
10602 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10603
10604 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10605 << OrigLHS.getType() << OrigRHS.getType()
10606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10607
10608 // If a user-defined conversion was applied to either of the operands prior
10609 // to applying the built-in operator rules, tell the user about it.
10610 if (OrigLHS.Conversion) {
10611 Diag(Loc: OrigLHS.Conversion->getLocation(),
10612 DiagID: diag::note_typecheck_invalid_operands_converted)
10613 << 0 << LHS.get()->getType();
10614 }
10615 if (OrigRHS.Conversion) {
10616 Diag(Loc: OrigRHS.Conversion->getLocation(),
10617 DiagID: diag::note_typecheck_invalid_operands_converted)
10618 << 1 << RHS.get()->getType();
10619 }
10620
10621 return QualType();
10622}
10623
10624QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10625 ExprResult &RHS) {
10626 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10627 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10628
10629 bool LHSNatVec = LHSType->isVectorType();
10630 bool RHSNatVec = RHSType->isVectorType();
10631
10632 if (!(LHSNatVec && RHSNatVec)) {
10633 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10634 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10635 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10636 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10637 << Vector->getSourceRange();
10638 return QualType();
10639 }
10640
10641 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10642 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10643 << RHS.get()->getSourceRange();
10644
10645 return QualType();
10646}
10647
10648/// Try to convert a value of non-vector type to a vector type by converting
10649/// the type to the element type of the vector and then performing a splat.
10650/// If the language is OpenCL, we only use conversions that promote scalar
10651/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10652/// for float->int.
10653///
10654/// OpenCL V2.0 6.2.6.p2:
10655/// An error shall occur if any scalar operand type has greater rank
10656/// than the type of the vector element.
10657///
10658/// \param scalar - if non-null, actually perform the conversions
10659/// \return true if the operation fails (but without diagnosing the failure)
10660static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10661 QualType scalarTy,
10662 QualType vectorEltTy,
10663 QualType vectorTy,
10664 unsigned &DiagID) {
10665 // The conversion to apply to the scalar before splatting it,
10666 // if necessary.
10667 CastKind scalarCast = CK_NoOp;
10668
10669 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10670 scalarCast = CK_IntegralToBoolean;
10671 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10672 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10673 (scalarTy->isIntegerType() &&
10674 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10675 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10676 return true;
10677 }
10678 if (!scalarTy->isIntegralType(Ctx: S.Context))
10679 return true;
10680 scalarCast = CK_IntegralCast;
10681 } else if (vectorEltTy->isRealFloatingType()) {
10682 if (scalarTy->isRealFloatingType()) {
10683 if (S.getLangOpts().OpenCL &&
10684 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10685 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10686 return true;
10687 }
10688 scalarCast = CK_FloatingCast;
10689 }
10690 else if (scalarTy->isIntegralType(Ctx: S.Context))
10691 scalarCast = CK_IntegralToFloating;
10692 else
10693 return true;
10694 } else {
10695 return true;
10696 }
10697
10698 // Adjust scalar if desired.
10699 if (scalar) {
10700 if (scalarCast != CK_NoOp)
10701 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10702 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10703 }
10704 return false;
10705}
10706
10707/// Convert vector E to a vector with the same number of elements but different
10708/// element type.
10709static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10710 const auto *VecTy = E->getType()->getAs<VectorType>();
10711 assert(VecTy && "Expression E must be a vector");
10712 QualType NewVecTy =
10713 VecTy->isExtVectorType()
10714 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10715 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10716 VecKind: VecTy->getVectorKind());
10717
10718 // Look through the implicit cast. Return the subexpression if its type is
10719 // NewVecTy.
10720 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10721 if (ICE->getSubExpr()->getType() == NewVecTy)
10722 return ICE->getSubExpr();
10723
10724 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10725 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10726}
10727
10728/// Test if a (constant) integer Int can be casted to another integer type
10729/// IntTy without losing precision.
10730static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10731 QualType OtherIntTy) {
10732 Expr *E = Int->get();
10733 if (E->containsErrors() || E->isInstantiationDependent())
10734 return false;
10735
10736 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10737
10738 // Reject cases where the value of the Int is unknown as that would
10739 // possibly cause truncation, but accept cases where the scalar can be
10740 // demoted without loss of precision.
10741 Expr::EvalResult EVResult;
10742 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10743 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10744 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10745 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10746
10747 if (CstInt) {
10748 // If the scalar is constant and is of a higher order and has more active
10749 // bits that the vector element type, reject it.
10750 llvm::APSInt Result = EVResult.Val.getInt();
10751 unsigned NumBits = IntSigned
10752 ? (Result.isNegative() ? Result.getSignificantBits()
10753 : Result.getActiveBits())
10754 : Result.getActiveBits();
10755 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10756 return true;
10757
10758 // If the signedness of the scalar type and the vector element type
10759 // differs and the number of bits is greater than that of the vector
10760 // element reject it.
10761 return (IntSigned != OtherIntSigned &&
10762 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10763 }
10764
10765 // Reject cases where the value of the scalar is not constant and it's
10766 // order is greater than that of the vector element type.
10767 return (Order < 0);
10768}
10769
10770/// Test if a (constant) integer Int can be casted to floating point type
10771/// FloatTy without losing precision.
10772static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10773 QualType FloatTy) {
10774 if (Int->get()->containsErrors())
10775 return false;
10776
10777 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10778
10779 // Determine if the integer constant can be expressed as a floating point
10780 // number of the appropriate type.
10781 Expr::EvalResult EVResult;
10782 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10783
10784 uint64_t Bits = 0;
10785 if (CstInt) {
10786 // Reject constants that would be truncated if they were converted to
10787 // the floating point type. Test by simple to/from conversion.
10788 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10789 // could be avoided if there was a convertFromAPInt method
10790 // which could signal back if implicit truncation occurred.
10791 llvm::APSInt Result = EVResult.Val.getInt();
10792 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10793 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10794 RM: llvm::APFloat::rmTowardZero);
10795 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10796 !IntTy->hasSignedIntegerRepresentation());
10797 bool Ignored = false;
10798 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10799 IsExact: &Ignored);
10800 if (Result != ConvertBack)
10801 return true;
10802 } else {
10803 // Reject types that cannot be fully encoded into the mantissa of
10804 // the float.
10805 Bits = S.Context.getTypeSize(T: IntTy);
10806 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10807 S.Context.getFloatTypeSemantics(T: FloatTy));
10808 if (Bits > FloatPrec)
10809 return true;
10810 }
10811
10812 return false;
10813}
10814
10815/// Attempt to convert and splat Scalar into a vector whose types matches
10816/// Vector following GCC conversion rules. The rule is that implicit
10817/// conversion can occur when Scalar can be casted to match Vector's element
10818/// type without causing truncation of Scalar.
10819static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10820 ExprResult *Vector) {
10821 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10822 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10823 QualType VectorEltTy;
10824
10825 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10826 assert(!isa<ExtVectorType>(VT) &&
10827 "ExtVectorTypes should not be handled here!");
10828 VectorEltTy = VT->getElementType();
10829 } else if (VectorTy->isSveVLSBuiltinType()) {
10830 VectorEltTy =
10831 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10832 } else {
10833 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10834 }
10835
10836 // Reject cases where the vector element type or the scalar element type are
10837 // not integral or floating point types.
10838 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10839 return true;
10840
10841 // The conversion to apply to the scalar before splatting it,
10842 // if necessary.
10843 CastKind ScalarCast = CK_NoOp;
10844
10845 // Accept cases where the vector elements are integers and the scalar is
10846 // an integer.
10847 // FIXME: Notionally if the scalar was a floating point value with a precise
10848 // integral representation, we could cast it to an appropriate integer
10849 // type and then perform the rest of the checks here. GCC will perform
10850 // this conversion in some cases as determined by the input language.
10851 // We should accept it on a language independent basis.
10852 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10853 ScalarTy->isIntegralType(Ctx: S.Context) &&
10854 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10855
10856 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10857 return true;
10858
10859 ScalarCast = CK_IntegralCast;
10860 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10861 ScalarTy->isRealFloatingType()) {
10862 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10863 ScalarCast = CK_FloatingToIntegral;
10864 else
10865 return true;
10866 } else if (VectorEltTy->isRealFloatingType()) {
10867 if (ScalarTy->isRealFloatingType()) {
10868
10869 // Reject cases where the scalar type is not a constant and has a higher
10870 // Order than the vector element type.
10871 llvm::APFloat Result(0.0);
10872
10873 // Determine whether this is a constant scalar. In the event that the
10874 // value is dependent (and thus cannot be evaluated by the constant
10875 // evaluator), skip the evaluation. This will then diagnose once the
10876 // expression is instantiated.
10877 bool CstScalar = Scalar->get()->isValueDependent() ||
10878 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10879 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10880 if (!CstScalar && Order < 0)
10881 return true;
10882
10883 // If the scalar cannot be safely casted to the vector element type,
10884 // reject it.
10885 if (CstScalar) {
10886 bool Truncated = false;
10887 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10888 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10889 if (Truncated)
10890 return true;
10891 }
10892
10893 ScalarCast = CK_FloatingCast;
10894 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10895 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10896 return true;
10897
10898 ScalarCast = CK_IntegralToFloating;
10899 } else
10900 return true;
10901 } else if (ScalarTy->isEnumeralType())
10902 return true;
10903
10904 // Adjust scalar if desired.
10905 if (ScalarCast != CK_NoOp)
10906 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10907 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10908 return false;
10909}
10910
10911QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10912 SourceLocation Loc, bool IsCompAssign,
10913 bool AllowBothBool,
10914 bool AllowBoolConversions,
10915 bool AllowBoolOperation) {
10916 if (!IsCompAssign) {
10917 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10918 if (LHS.isInvalid())
10919 return QualType();
10920 }
10921 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10922 if (RHS.isInvalid())
10923 return QualType();
10924
10925 // For conversion purposes, we ignore any qualifiers.
10926 // For example, "const float" and "float" are equivalent.
10927 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10928 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10929
10930 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10931 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10932 assert(LHSVecType || RHSVecType);
10933
10934 if (getLangOpts().HLSL)
10935 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10936 IsCompAssign);
10937
10938 // Any operation with MFloat8 type is only possible with C intrinsics
10939 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10940 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10941 return InvalidOperands(Loc, LHS, RHS);
10942
10943 // AltiVec-style "vector bool op vector bool" combinations are allowed
10944 // for some operators but not others.
10945 if (!AllowBothBool && LHSVecType &&
10946 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10947 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10948 return InvalidOperands(Loc, LHS, RHS);
10949
10950 // This operation may not be performed on boolean vectors.
10951 if (!AllowBoolOperation &&
10952 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10953 return InvalidOperands(Loc, LHS, RHS);
10954
10955 // If the vector types are identical, return.
10956 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10957 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10958
10959 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10960 if (LHSVecType && RHSVecType &&
10961 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10962 if (isa<ExtVectorType>(Val: LHSVecType)) {
10963 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10964 return LHSType;
10965 }
10966
10967 if (!IsCompAssign)
10968 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10969 return RHSType;
10970 }
10971
10972 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10973 // can be mixed, with the result being the non-bool type. The non-bool
10974 // operand must have integer element type.
10975 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10976 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10977 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10978 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10979 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10980 LHSVecType->getElementType()->isIntegerType() &&
10981 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10982 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10983 return LHSType;
10984 }
10985 if (!IsCompAssign &&
10986 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10987 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10988 RHSVecType->getElementType()->isIntegerType()) {
10989 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10990 return RHSType;
10991 }
10992 }
10993
10994 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10995 // invalid since the ambiguity can affect the ABI.
10996 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10997 unsigned &SVEorRVV) {
10998 const VectorType *VecType = SecondType->getAs<VectorType>();
10999 SVEorRVV = 0;
11000 if (FirstType->isSizelessBuiltinType() && VecType) {
11001 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11002 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
11003 return true;
11004 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
11005 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
11006 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
11007 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
11008 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
11009 SVEorRVV = 1;
11010 return true;
11011 }
11012 }
11013
11014 return false;
11015 };
11016
11017 unsigned SVEorRVV;
11018 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11019 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11020 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
11021 << SVEorRVV << LHSType << RHSType;
11022 return QualType();
11023 }
11024
11025 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11026 // invalid since the ambiguity can affect the ABI.
11027 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11028 unsigned &SVEorRVV) {
11029 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11030 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11031
11032 SVEorRVV = 0;
11033 if (FirstVecType && SecondVecType) {
11034 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11035 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11036 SecondVecType->getVectorKind() ==
11037 VectorKind::SveFixedLengthPredicate)
11038 return true;
11039 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
11040 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
11041 SecondVecType->getVectorKind() ==
11042 VectorKind::RVVFixedLengthMask_1 ||
11043 SecondVecType->getVectorKind() ==
11044 VectorKind::RVVFixedLengthMask_2 ||
11045 SecondVecType->getVectorKind() ==
11046 VectorKind::RVVFixedLengthMask_4) {
11047 SVEorRVV = 1;
11048 return true;
11049 }
11050 }
11051 return false;
11052 }
11053
11054 if (SecondVecType &&
11055 SecondVecType->getVectorKind() == VectorKind::Generic) {
11056 if (FirstType->isSVESizelessBuiltinType())
11057 return true;
11058 if (FirstType->isRVVSizelessBuiltinType()) {
11059 SVEorRVV = 1;
11060 return true;
11061 }
11062 }
11063
11064 return false;
11065 };
11066
11067 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11068 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11069 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
11070 << SVEorRVV << LHSType << RHSType;
11071 return QualType();
11072 }
11073
11074 // If there's a vector type and a scalar, try to convert the scalar to
11075 // the vector element type and splat.
11076 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11077 if (!RHSVecType) {
11078 if (isa<ExtVectorType>(Val: LHSVecType)) {
11079 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
11080 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
11081 DiagID))
11082 return LHSType;
11083 } else {
11084 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11085 return LHSType;
11086 }
11087 }
11088 if (!LHSVecType) {
11089 if (isa<ExtVectorType>(Val: RHSVecType)) {
11090 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
11091 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
11092 vectorTy: RHSType, DiagID))
11093 return RHSType;
11094 } else {
11095 if (LHS.get()->isLValue() ||
11096 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11097 return RHSType;
11098 }
11099 }
11100
11101 // FIXME: The code below also handles conversion between vectors and
11102 // non-scalars, we should break this down into fine grained specific checks
11103 // and emit proper diagnostics.
11104 QualType VecType = LHSVecType ? LHSType : RHSType;
11105 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11106 QualType OtherType = LHSVecType ? RHSType : LHSType;
11107 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11108 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
11109 if (Context.getTargetInfo().getTriple().isPPC() &&
11110 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
11111 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
11112 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11113 // If we're allowing lax vector conversions, only the total (data) size
11114 // needs to be the same. For non compound assignment, if one of the types is
11115 // scalar, the result is always the vector type.
11116 if (!IsCompAssign) {
11117 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
11118 return VecType;
11119 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11120 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11121 // type. Note that this is already done by non-compound assignments in
11122 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11123 // <1 x T> -> T. The result is also a vector type.
11124 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11125 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11126 ExprResult *RHSExpr = &RHS;
11127 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
11128 return VecType;
11129 }
11130 }
11131
11132 // Okay, the expression is invalid.
11133
11134 // If there's a non-vector, non-real operand, diagnose that.
11135 if ((!RHSVecType && !RHSType->isRealType()) ||
11136 (!LHSVecType && !LHSType->isRealType())) {
11137 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11138 << LHSType << RHSType
11139 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11140 return QualType();
11141 }
11142
11143 // OpenCL V1.1 6.2.6.p1:
11144 // If the operands are of more than one vector type, then an error shall
11145 // occur. Implicit conversions between vector types are not permitted, per
11146 // section 6.2.1.
11147 if (getLangOpts().OpenCL &&
11148 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
11149 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
11150 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
11151 << RHSType;
11152 return QualType();
11153 }
11154
11155
11156 // If there is a vector type that is not a ExtVector and a scalar, we reach
11157 // this point if scalar could not be converted to the vector's element type
11158 // without truncation.
11159 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
11160 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
11161 QualType Scalar = LHSVecType ? RHSType : LHSType;
11162 QualType Vector = LHSVecType ? LHSType : RHSType;
11163 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11164 Diag(Loc,
11165 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11166 << ScalarOrVector << Scalar << Vector;
11167
11168 return QualType();
11169 }
11170
11171 // Otherwise, use the generic diagnostic.
11172 Diag(Loc, DiagID)
11173 << LHSType << RHSType
11174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11175 return QualType();
11176}
11177
11178QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11179 SourceLocation Loc,
11180 bool IsCompAssign,
11181 ArithConvKind OperationKind) {
11182 if (!IsCompAssign) {
11183 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11184 if (LHS.isInvalid())
11185 return QualType();
11186 }
11187 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11188 if (RHS.isInvalid())
11189 return QualType();
11190
11191 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11192 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11193
11194 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11195 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11196
11197 unsigned DiagID = diag::err_typecheck_invalid_operands;
11198 if ((OperationKind == ArithConvKind::Arithmetic) &&
11199 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11200 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11201 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11202 << RHS.get()->getSourceRange();
11203 return QualType();
11204 }
11205
11206 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11207 return LHSType;
11208
11209 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11210 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11211 return LHSType;
11212 }
11213 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11214 if (LHS.get()->isLValue() ||
11215 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11216 return RHSType;
11217 }
11218
11219 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11220 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11221 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11222 << LHSType << RHSType << LHS.get()->getSourceRange()
11223 << RHS.get()->getSourceRange();
11224 return QualType();
11225 }
11226
11227 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11228 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11229 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11230 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11231 << LHSType << RHSType << LHS.get()->getSourceRange()
11232 << RHS.get()->getSourceRange();
11233 return QualType();
11234 }
11235
11236 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11237 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11238 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11239 bool ScalarOrVector =
11240 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11241
11242 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11243 << ScalarOrVector << Scalar << Vector;
11244
11245 return QualType();
11246 }
11247
11248 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11249 << RHS.get()->getSourceRange();
11250 return QualType();
11251}
11252
11253// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11254// expression. These are mainly cases where the null pointer is used as an
11255// integer instead of a pointer.
11256static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11257 SourceLocation Loc, bool IsCompare) {
11258 // The canonical way to check for a GNU null is with isNullPointerConstant,
11259 // but we use a bit of a hack here for speed; this is a relatively
11260 // hot path, and isNullPointerConstant is slow.
11261 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11262 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11263
11264 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11265
11266 // Avoid analyzing cases where the result will either be invalid (and
11267 // diagnosed as such) or entirely valid and not something to warn about.
11268 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11269 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11270 return;
11271
11272 // Comparison operations would not make sense with a null pointer no matter
11273 // what the other expression is.
11274 if (!IsCompare) {
11275 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11276 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11277 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11278 return;
11279 }
11280
11281 // The rest of the operations only make sense with a null pointer
11282 // if the other expression is a pointer.
11283 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11284 NonNullType->canDecayToPointerType())
11285 return;
11286
11287 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11288 << LHSNull /* LHS is NULL */ << NonNullType
11289 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11290}
11291
11292static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11293 SourceLocation OpLoc) {
11294 // If the divisor is real, then this is real/real or complex/real division.
11295 // Either way there can be no precision loss.
11296 auto *CT = DivisorTy->getAs<ComplexType>();
11297 if (!CT)
11298 return;
11299
11300 QualType ElementType = CT->getElementType().getCanonicalType();
11301 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11302 LangOptions::ComplexRangeKind::CX_Promoted;
11303 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11304 return;
11305
11306 ASTContext &Ctx = S.getASTContext();
11307 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11308 const llvm::fltSemantics &ElementTypeSemantics =
11309 Ctx.getFloatTypeSemantics(T: ElementType);
11310 const llvm::fltSemantics &HigherElementTypeSemantics =
11311 Ctx.getFloatTypeSemantics(T: HigherElementType);
11312
11313 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11314 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11315 (HigherElementType == Ctx.LongDoubleTy &&
11316 !Ctx.getTargetInfo().hasLongDoubleType())) {
11317 // Retain the location of the first use of higher precision type.
11318 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11319 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11320 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11321 if (Type == HigherElementType) {
11322 Num++;
11323 return;
11324 }
11325 }
11326 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11327 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11328 }
11329}
11330
11331static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11332 SourceLocation Loc) {
11333 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11334 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11335 if (!LUE || !RUE)
11336 return;
11337 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11338 RUE->getKind() != UETT_SizeOf)
11339 return;
11340
11341 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11342 QualType LHSTy = LHSArg->getType();
11343 QualType RHSTy;
11344
11345 if (RUE->isArgumentType())
11346 RHSTy = RUE->getArgumentType().getNonReferenceType();
11347 else
11348 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11349
11350 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11351 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11352 return;
11353
11354 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11355 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11356 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11357 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11358 << LHSArgDecl;
11359 }
11360 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11361 QualType ArrayElemTy = ArrayTy->getElementType();
11362 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11363 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11364 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11365 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11366 return;
11367 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11368 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11369 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11370 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11371 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11372 << LHSArgDecl;
11373 }
11374
11375 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11376 }
11377}
11378
11379static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11380 ExprResult &RHS,
11381 SourceLocation Loc, bool IsDiv) {
11382 // Check for division/remainder by zero.
11383 Expr::EvalResult RHSValue;
11384 if (!RHS.get()->isValueDependent() &&
11385 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11386 RHSValue.Val.getInt() == 0)
11387 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11388 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11389 << IsDiv << RHS.get()->getSourceRange());
11390}
11391
11392static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11393 const ExprResult &LHS, const ExprResult &RHS,
11394 BinaryOperatorKind Opc) {
11395 if (!LHS.isUsable() || !RHS.isUsable())
11396 return;
11397 const Expr *LHSExpr = LHS.get();
11398 const Expr *RHSExpr = RHS.get();
11399 const QualType LHSType = LHSExpr->getType();
11400 const QualType RHSType = RHSExpr->getType();
11401 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11402 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11403 if (!LHSIsScoped && !RHSIsScoped)
11404 return;
11405 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11406 return;
11407 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11408 return;
11409 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11410 return;
11411 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11412 SourceLocation BeginLoc = expr->getBeginLoc();
11413 QualType IntType = type->castAs<EnumType>()
11414 ->getDecl()
11415 ->getDefinitionOrSelf()
11416 ->getIntegerType();
11417 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11418 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11419 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11420 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11421 };
11422 if (LHSIsScoped) {
11423 DiagnosticHelper(LHSExpr, LHSType);
11424 }
11425 if (RHSIsScoped) {
11426 DiagnosticHelper(RHSExpr, RHSType);
11427 }
11428}
11429
11430QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11431 SourceLocation Loc,
11432 BinaryOperatorKind Opc) {
11433 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11434 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11435
11436 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11437
11438 QualType LHSTy = LHS.get()->getType();
11439 QualType RHSTy = RHS.get()->getType();
11440 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11441 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11442 /*AllowBothBool*/ getLangOpts().AltiVec,
11443 /*AllowBoolConversions*/ false,
11444 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11445 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11446 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11447 OperationKind: ArithConvKind::Arithmetic);
11448 if (!IsDiv &&
11449 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11450 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11451 // For division, only matrix-by-scalar is supported. Other combinations with
11452 // matrix types are invalid.
11453 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11454 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11455
11456 QualType compType = UsualArithmeticConversions(
11457 LHS, RHS, Loc,
11458 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11459 if (LHS.isInvalid() || RHS.isInvalid())
11460 return QualType();
11461
11462 if (compType.isNull() || !compType->isArithmeticType()) {
11463 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11464 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11465 return ResultTy;
11466 }
11467 if (IsDiv) {
11468 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11469 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11470 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11471 }
11472 return compType;
11473}
11474
11475QualType Sema::CheckRemainderOperands(
11476 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11477 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11478
11479 // Note: This check is here to simplify the double exclusions of
11480 // scalar and vector HLSL checks. No getLangOpts().HLSL
11481 // is needed since all languages exlcude doubles.
11482 if (LHS.get()->getType()->isDoubleType() ||
11483 RHS.get()->getType()->isDoubleType() ||
11484 (LHS.get()->getType()->isVectorType() && LHS.get()
11485 ->getType()
11486 ->getAs<VectorType>()
11487 ->getElementType()
11488 ->isDoubleType()) ||
11489 (RHS.get()->getType()->isVectorType() && RHS.get()
11490 ->getType()
11491 ->getAs<VectorType>()
11492 ->getElementType()
11493 ->isDoubleType()))
11494 return InvalidOperands(Loc, LHS, RHS);
11495
11496 if (LHS.get()->getType()->isVectorType() ||
11497 RHS.get()->getType()->isVectorType()) {
11498 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11499 RHS.get()->getType()->hasIntegerRepresentation()) ||
11500 (getLangOpts().HLSL &&
11501 (LHS.get()->getType()->hasFloatingRepresentation() ||
11502 RHS.get()->getType()->hasFloatingRepresentation())))
11503 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11504 /*AllowBothBool*/ getLangOpts().AltiVec,
11505 /*AllowBoolConversions*/ false,
11506 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11507 return InvalidOperands(Loc, LHS, RHS);
11508 }
11509
11510 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11511 RHS.get()->getType()->isSveVLSBuiltinType()) {
11512 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11513 RHS.get()->getType()->hasIntegerRepresentation())
11514 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11515 OperationKind: ArithConvKind::Arithmetic);
11516
11517 return InvalidOperands(Loc, LHS, RHS);
11518 }
11519
11520 QualType compType = UsualArithmeticConversions(
11521 LHS, RHS, Loc,
11522 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11523 if (LHS.isInvalid() || RHS.isInvalid())
11524 return QualType();
11525
11526 if (compType.isNull() ||
11527 (!compType->isIntegerType() &&
11528 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11529 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11530 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11531 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11532 return ResultTy;
11533 }
11534 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11535 return compType;
11536}
11537
11538/// Diagnose invalid arithmetic on two void pointers.
11539static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11540 Expr *LHSExpr, Expr *RHSExpr) {
11541 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11542 ? diag::err_typecheck_pointer_arith_void_type
11543 : diag::ext_gnu_void_ptr)
11544 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11545 << RHSExpr->getSourceRange();
11546}
11547
11548/// Diagnose invalid arithmetic on a void pointer.
11549static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11550 Expr *Pointer) {
11551 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11552 ? diag::err_typecheck_pointer_arith_void_type
11553 : diag::ext_gnu_void_ptr)
11554 << 0 /* one pointer */ << Pointer->getSourceRange();
11555}
11556
11557/// Diagnose invalid arithmetic on a null pointer.
11558///
11559/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11560/// idiom, which we recognize as a GNU extension.
11561///
11562static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11563 Expr *Pointer, bool IsGNUIdiom) {
11564 if (IsGNUIdiom)
11565 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11566 << Pointer->getSourceRange();
11567 else
11568 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11569 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11570}
11571
11572/// Diagnose invalid subraction on a null pointer.
11573///
11574static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11575 Expr *Pointer, bool BothNull) {
11576 // Null - null is valid in C++ [expr.add]p7
11577 if (BothNull && S.getLangOpts().CPlusPlus)
11578 return;
11579
11580 // Is this s a macro from a system header?
11581 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11582 return;
11583
11584 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11585 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11586 << S.getLangOpts().CPlusPlus
11587 << Pointer->getSourceRange());
11588}
11589
11590/// Diagnose invalid arithmetic on two function pointers.
11591static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11592 Expr *LHS, Expr *RHS) {
11593 assert(LHS->getType()->isAnyPointerType());
11594 assert(RHS->getType()->isAnyPointerType());
11595 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11596 ? diag::err_typecheck_pointer_arith_function_type
11597 : diag::ext_gnu_ptr_func_arith)
11598 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11599 // We only show the second type if it differs from the first.
11600 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11601 T2: RHS->getType())
11602 << RHS->getType()->getPointeeType()
11603 << LHS->getSourceRange() << RHS->getSourceRange();
11604}
11605
11606/// Diagnose invalid arithmetic on a function pointer.
11607static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11608 Expr *Pointer) {
11609 assert(Pointer->getType()->isAnyPointerType());
11610 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11611 ? diag::err_typecheck_pointer_arith_function_type
11612 : diag::ext_gnu_ptr_func_arith)
11613 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11614 << 0 /* one pointer, so only one type */
11615 << Pointer->getSourceRange();
11616}
11617
11618/// Emit error if Operand is incomplete pointer type
11619///
11620/// \returns True if pointer has incomplete type
11621static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11622 Expr *Operand) {
11623 QualType ResType = Operand->getType();
11624 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11625 ResType = ResAtomicType->getValueType();
11626
11627 assert(ResType->isAnyPointerType());
11628 QualType PointeeTy = ResType->getPointeeType();
11629 return S.RequireCompleteSizedType(
11630 Loc, T: PointeeTy,
11631 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11632 Args: Operand->getSourceRange());
11633}
11634
11635/// Check the validity of an arithmetic pointer operand.
11636///
11637/// If the operand has pointer type, this code will check for pointer types
11638/// which are invalid in arithmetic operations. These will be diagnosed
11639/// appropriately, including whether or not the use is supported as an
11640/// extension.
11641///
11642/// \returns True when the operand is valid to use (even if as an extension).
11643static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11644 Expr *Operand) {
11645 QualType ResType = Operand->getType();
11646 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11647 ResType = ResAtomicType->getValueType();
11648
11649 if (!ResType->isAnyPointerType()) return true;
11650
11651 QualType PointeeTy = ResType->getPointeeType();
11652 if (PointeeTy->isVoidType()) {
11653 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11654 return !S.getLangOpts().CPlusPlus;
11655 }
11656 if (PointeeTy->isFunctionType()) {
11657 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11658 return !S.getLangOpts().CPlusPlus;
11659 }
11660
11661 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11662
11663 return true;
11664}
11665
11666/// Check the validity of a binary arithmetic operation w.r.t. pointer
11667/// operands.
11668///
11669/// This routine will diagnose any invalid arithmetic on pointer operands much
11670/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11671/// for emitting a single diagnostic even for operations where both LHS and RHS
11672/// are (potentially problematic) pointers.
11673///
11674/// \returns True when the operand is valid to use (even if as an extension).
11675static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11676 Expr *LHSExpr, Expr *RHSExpr) {
11677 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11678 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11679 if (!isLHSPointer && !isRHSPointer) return true;
11680
11681 QualType LHSPointeeTy, RHSPointeeTy;
11682 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11683 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11684
11685 // if both are pointers check if operation is valid wrt address spaces
11686 if (isLHSPointer && isRHSPointer) {
11687 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11688 Ctx: S.getASTContext())) {
11689 S.Diag(Loc,
11690 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11691 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11692 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11693 return false;
11694 }
11695 }
11696
11697 // Check for arithmetic on pointers to incomplete types.
11698 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11699 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11700 if (isLHSVoidPtr || isRHSVoidPtr) {
11701 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11702 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11703 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11704
11705 return !S.getLangOpts().CPlusPlus;
11706 }
11707
11708 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11709 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11710 if (isLHSFuncPtr || isRHSFuncPtr) {
11711 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11712 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11713 Pointer: RHSExpr);
11714 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11715
11716 return !S.getLangOpts().CPlusPlus;
11717 }
11718
11719 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11720 return false;
11721 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11722 return false;
11723
11724 return true;
11725}
11726
11727/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11728/// literal.
11729static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11730 Expr *LHSExpr, Expr *RHSExpr) {
11731 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11732 Expr* IndexExpr = RHSExpr;
11733 if (!StrExpr) {
11734 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11735 IndexExpr = LHSExpr;
11736 }
11737
11738 bool IsStringPlusInt = StrExpr &&
11739 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11740 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11741 return;
11742
11743 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11744 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11745 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11746
11747 // Only print a fixit for "str" + int, not for int + "str".
11748 if (IndexExpr == RHSExpr) {
11749 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11750 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11751 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11752 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11753 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11754 } else
11755 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11756}
11757
11758/// Emit a warning when adding a char literal to a string.
11759static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11760 Expr *LHSExpr, Expr *RHSExpr) {
11761 const Expr *StringRefExpr = LHSExpr;
11762 const CharacterLiteral *CharExpr =
11763 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11764
11765 if (!CharExpr) {
11766 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11767 StringRefExpr = RHSExpr;
11768 }
11769
11770 if (!CharExpr || !StringRefExpr)
11771 return;
11772
11773 const QualType StringType = StringRefExpr->getType();
11774
11775 // Return if not a PointerType.
11776 if (!StringType->isAnyPointerType())
11777 return;
11778
11779 // Return if not a CharacterType.
11780 if (!StringType->getPointeeType()->isAnyCharacterType())
11781 return;
11782
11783 ASTContext &Ctx = Self.getASTContext();
11784 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11785
11786 const QualType CharType = CharExpr->getType();
11787 if (!CharType->isAnyCharacterType() &&
11788 CharType->isIntegerType() &&
11789 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11790 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11791 << DiagRange << Ctx.CharTy;
11792 } else {
11793 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11794 << DiagRange << CharExpr->getType();
11795 }
11796
11797 // Only print a fixit for str + char, not for char + str.
11798 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11799 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11800 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11801 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11802 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11803 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11804 } else {
11805 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11806 }
11807}
11808
11809/// Emit error when two pointers are incompatible.
11810static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11811 Expr *LHSExpr, Expr *RHSExpr) {
11812 assert(LHSExpr->getType()->isAnyPointerType());
11813 assert(RHSExpr->getType()->isAnyPointerType());
11814 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11815 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11816 << RHSExpr->getSourceRange();
11817}
11818
11819// C99 6.5.6
11820QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11821 SourceLocation Loc, BinaryOperatorKind Opc,
11822 QualType* CompLHSTy) {
11823 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11824
11825 if (LHS.get()->getType()->isVectorType() ||
11826 RHS.get()->getType()->isVectorType()) {
11827 QualType compType =
11828 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11829 /*AllowBothBool*/ getLangOpts().AltiVec,
11830 /*AllowBoolConversions*/ getLangOpts().ZVector,
11831 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11832 if (CompLHSTy) *CompLHSTy = compType;
11833 return compType;
11834 }
11835
11836 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11837 RHS.get()->getType()->isSveVLSBuiltinType()) {
11838 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11839 OperationKind: ArithConvKind::Arithmetic);
11840 if (CompLHSTy)
11841 *CompLHSTy = compType;
11842 return compType;
11843 }
11844
11845 if (LHS.get()->getType()->isConstantMatrixType() ||
11846 RHS.get()->getType()->isConstantMatrixType()) {
11847 QualType compType =
11848 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11849 if (CompLHSTy)
11850 *CompLHSTy = compType;
11851 return compType;
11852 }
11853
11854 QualType compType = UsualArithmeticConversions(
11855 LHS, RHS, Loc,
11856 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11857 if (LHS.isInvalid() || RHS.isInvalid())
11858 return QualType();
11859
11860 // Diagnose "string literal" '+' int and string '+' "char literal".
11861 if (Opc == BO_Add) {
11862 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11863 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11864 }
11865
11866 // handle the common case first (both operands are arithmetic).
11867 if (!compType.isNull() && compType->isArithmeticType()) {
11868 if (CompLHSTy) *CompLHSTy = compType;
11869 return compType;
11870 }
11871
11872 // Type-checking. Ultimately the pointer's going to be in PExp;
11873 // note that we bias towards the LHS being the pointer.
11874 Expr *PExp = LHS.get(), *IExp = RHS.get();
11875
11876 bool isObjCPointer;
11877 if (PExp->getType()->isPointerType()) {
11878 isObjCPointer = false;
11879 } else if (PExp->getType()->isObjCObjectPointerType()) {
11880 isObjCPointer = true;
11881 } else {
11882 std::swap(a&: PExp, b&: IExp);
11883 if (PExp->getType()->isPointerType()) {
11884 isObjCPointer = false;
11885 } else if (PExp->getType()->isObjCObjectPointerType()) {
11886 isObjCPointer = true;
11887 } else {
11888 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11889 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11890 return ResultTy;
11891 }
11892 }
11893 assert(PExp->getType()->isAnyPointerType());
11894
11895 if (!IExp->getType()->isIntegerType())
11896 return InvalidOperands(Loc, LHS, RHS);
11897
11898 // Adding to a null pointer results in undefined behavior.
11899 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11900 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11901 // In C++ adding zero to a null pointer is defined.
11902 Expr::EvalResult KnownVal;
11903 if (!getLangOpts().CPlusPlus ||
11904 (!IExp->isValueDependent() &&
11905 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11906 KnownVal.Val.getInt() != 0))) {
11907 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11908 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11909 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11910 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11911 }
11912 }
11913
11914 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11915 return QualType();
11916
11917 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11918 return QualType();
11919
11920 // Arithmetic on label addresses is normally allowed, except when we add
11921 // a ptrauth signature to the addresses.
11922 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11923 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11924 << /*addition*/ 1;
11925 return QualType();
11926 }
11927
11928 // Check array bounds for pointer arithemtic
11929 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11930
11931 if (CompLHSTy) {
11932 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11933 if (LHSTy.isNull()) {
11934 LHSTy = LHS.get()->getType();
11935 if (Context.isPromotableIntegerType(T: LHSTy))
11936 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11937 }
11938 *CompLHSTy = LHSTy;
11939 }
11940
11941 return PExp->getType();
11942}
11943
11944/// Determine whether the size of \p T is provably zero: some array dimension
11945/// is provably zero or the base element type has zero size. A variable
11946/// dimension that does not fold to an integer constant is assumed nonzero.
11947static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
11948 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
11949 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
11950 if (CAT->isZeroSize())
11951 return true;
11952 } else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
11953 if (const Expr *Bound = VAT->getSizeExpr())
11954 if (std::optional<llvm::APSInt> Size =
11955 Bound->getIntegerConstantExpr(Ctx))
11956 if (*Size == 0)
11957 return true;
11958 }
11959 T = AT->getElementType();
11960 }
11961 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
11962}
11963
11964// C99 6.5.6
11965QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11966 SourceLocation Loc,
11967 BinaryOperatorKind Opc,
11968 QualType *CompLHSTy) {
11969 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11970
11971 if (LHS.get()->getType()->isVectorType() ||
11972 RHS.get()->getType()->isVectorType()) {
11973 QualType compType =
11974 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11975 /*AllowBothBool*/ getLangOpts().AltiVec,
11976 /*AllowBoolConversions*/ getLangOpts().ZVector,
11977 /*AllowBooleanOperation*/ AllowBoolOperation: false);
11978 if (CompLHSTy) *CompLHSTy = compType;
11979 return compType;
11980 }
11981
11982 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11983 RHS.get()->getType()->isSveVLSBuiltinType()) {
11984 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11985 OperationKind: ArithConvKind::Arithmetic);
11986 if (CompLHSTy)
11987 *CompLHSTy = compType;
11988 return compType;
11989 }
11990
11991 if (LHS.get()->getType()->isConstantMatrixType() ||
11992 RHS.get()->getType()->isConstantMatrixType()) {
11993 QualType compType =
11994 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11995 if (CompLHSTy)
11996 *CompLHSTy = compType;
11997 return compType;
11998 }
11999
12000 QualType compType = UsualArithmeticConversions(
12001 LHS, RHS, Loc,
12002 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
12003 if (LHS.isInvalid() || RHS.isInvalid())
12004 return QualType();
12005
12006 // Enforce type constraints: C99 6.5.6p3.
12007
12008 // Handle the common case first (both operands are arithmetic).
12009 if (!compType.isNull() && compType->isArithmeticType()) {
12010 if (CompLHSTy) *CompLHSTy = compType;
12011 return compType;
12012 }
12013
12014 // Either ptr - int or ptr - ptr.
12015 if (LHS.get()->getType()->isAnyPointerType()) {
12016 QualType lpointee = LHS.get()->getType()->getPointeeType();
12017
12018 // Diagnose bad cases where we step over interface counts.
12019 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12020 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
12021 return QualType();
12022
12023 // Arithmetic on label addresses is normally allowed, except when we add
12024 // a ptrauth signature to the addresses.
12025 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
12026 getLangOpts().PointerAuthIndirectGotos) {
12027 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
12028 << /*subtraction*/ 0;
12029 return QualType();
12030 }
12031
12032 // The result type of a pointer-int computation is the pointer type.
12033 if (RHS.get()->getType()->isIntegerType()) {
12034 // Subtracting from a null pointer should produce a warning.
12035 // The last argument to the diagnose call says this doesn't match the
12036 // GNU int-to-pointer idiom.
12037 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
12038 NPC: Expr::NPC_ValueDependentIsNotNull)) {
12039 // In C++ adding zero to a null pointer is defined.
12040 Expr::EvalResult KnownVal;
12041 if (!getLangOpts().CPlusPlus ||
12042 (!RHS.get()->isValueDependent() &&
12043 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
12044 KnownVal.Val.getInt() != 0))) {
12045 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
12046 }
12047 }
12048
12049 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
12050 return QualType();
12051
12052 // Check array bounds for pointer arithemtic
12053 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
12054 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12055
12056 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12057 return LHS.get()->getType();
12058 }
12059
12060 // Handle pointer-pointer subtractions.
12061 if (const PointerType *RHSPTy
12062 = RHS.get()->getType()->getAs<PointerType>()) {
12063 QualType rpointee = RHSPTy->getPointeeType();
12064
12065 if (getLangOpts().CPlusPlus) {
12066 // Pointee types must be the same: C++ [expr.add]
12067 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
12068 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12069 }
12070 } else {
12071 // Pointee types must be compatible C99 6.5.6p3
12072 if (!Context.typesAreCompatible(
12073 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
12074 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
12075 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
12076 return QualType();
12077 }
12078 }
12079
12080 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
12081 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
12082 return QualType();
12083
12084 // For pointer subtraction, if the address spaces differ but overlap,
12085 // convert both pointers to the composite (superset) address space.
12086 // This is needed because address spaces may use different
12087 // representations, such as a private offset vs a flat address.
12088 LangAS LAddrSpace = lpointee.getAddressSpace();
12089 LangAS RAddrSpace = rpointee.getAddressSpace();
12090 if (LAddrSpace != RAddrSpace) {
12091 Qualifiers LQual = lpointee.getQualifiers();
12092 Qualifiers RQual = rpointee.getQualifiers();
12093 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(other: RQual, Ctx: Context)
12094 ? LAddrSpace
12095 : RAddrSpace;
12096
12097 if (LAddrSpace != ResultAddrSpace) {
12098 QualType NewPteTy = Context.getAddrSpaceQualType(
12099 T: lpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12100 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12101 LHS =
12102 ImpCastExprToType(E: LHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12103 }
12104 if (RAddrSpace != ResultAddrSpace) {
12105 QualType NewPteTy = Context.getAddrSpaceQualType(
12106 T: rpointee.getUnqualifiedType(), AddressSpace: ResultAddrSpace);
12107 QualType NewPtrTy = Context.getPointerType(T: NewPteTy);
12108 RHS =
12109 ImpCastExprToType(E: RHS.get(), Type: NewPtrTy, CK: CK_AddressSpaceConversion);
12110 }
12111 }
12112
12113 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12114 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12115 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12116 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
12117
12118 // Subtracting nullptr or from nullptr is suspect
12119 if (LHSIsNullPtr)
12120 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
12121 if (RHSIsNullPtr)
12122 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
12123
12124 // The pointee type may have zero size. As an extension, a structure or
12125 // union may have zero size or an array may have zero length. In this
12126 // case subtraction does not make sense. For a variably modified type,
12127 // warn only when the size is provably zero.
12128 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12129 isProvablyZeroSize(Ctx: Context, T: rpointee))
12130 Diag(Loc, DiagID: diag::warn_sub_ptr_zero_size_types)
12131 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12132 << RHS.get()->getSourceRange();
12133
12134 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12135 return Context.getPointerDiffType();
12136 }
12137 }
12138
12139 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12140 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12141 return ResultTy;
12142}
12143
12144static bool isScopedEnumerationType(QualType T) {
12145 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12146 return ET->getDecl()->isScoped();
12147 return false;
12148}
12149
12150static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12151 SourceLocation Loc, BinaryOperatorKind Opc,
12152 QualType LHSType) {
12153 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12154 // so skip remaining warnings as we don't want to modify values within Sema.
12155 if (S.getLangOpts().OpenCL)
12156 return;
12157
12158 if (Opc == BO_Shr &&
12159 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
12160 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
12161
12162 // Check right/shifter operand
12163 Expr::EvalResult RHSResult;
12164 if (RHS.get()->isValueDependent() ||
12165 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
12166 return;
12167 llvm::APSInt Right = RHSResult.Val.getInt();
12168
12169 if (Right.isNegative()) {
12170 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12171 PD: S.PDiag(DiagID: diag::warn_shift_negative)
12172 << RHS.get()->getSourceRange());
12173 return;
12174 }
12175
12176 QualType LHSExprType = LHS.get()->getType();
12177 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
12178 if (LHSExprType->isBitIntType())
12179 LeftSize = S.Context.getIntWidth(T: LHSExprType);
12180 else if (LHSExprType->isFixedPointType()) {
12181 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
12182 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12183 }
12184 if (Right.uge(RHS: LeftSize)) {
12185 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
12186 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
12187 << RHS.get()->getSourceRange());
12188 return;
12189 }
12190
12191 // FIXME: We probably need to handle fixed point types specially here.
12192 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12193 return;
12194
12195 // When left shifting an ICE which is signed, we can check for overflow which
12196 // according to C++ standards prior to C++2a has undefined behavior
12197 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12198 // more than the maximum value representable in the result type, so never
12199 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12200 // expression is still probably a bug.)
12201 Expr::EvalResult LHSResult;
12202 if (LHS.get()->isValueDependent() ||
12203 LHSType->hasUnsignedIntegerRepresentation() ||
12204 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
12205 return;
12206 llvm::APSInt Left = LHSResult.Val.getInt();
12207
12208 // Don't warn if signed overflow is defined, then all the rest of the
12209 // diagnostics will not be triggered because the behavior is defined.
12210 // Also don't warn in C++20 mode (and newer), as signed left shifts
12211 // always wrap and never overflow.
12212 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12213 return;
12214
12215 // If LHS does not have a non-negative value then, the
12216 // behavior is undefined before C++2a. Warn about it.
12217 if (Left.isNegative()) {
12218 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
12219 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
12220 << LHS.get()->getSourceRange());
12221 return;
12222 }
12223
12224 llvm::APInt ResultBits =
12225 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12226 if (ResultBits.ule(RHS: LeftSize))
12227 return;
12228 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12229 Result = Result.shl(ShiftAmt: Right);
12230
12231 // Print the bit representation of the signed integer as an unsigned
12232 // hexadecimal number.
12233 SmallString<40> HexResult;
12234 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12235
12236 // If we are only missing a sign bit, this is less likely to result in actual
12237 // bugs -- if the result is cast back to an unsigned type, it will have the
12238 // expected value. Thus we place this behind a different warning that can be
12239 // turned off separately if needed.
12240 if (ResultBits - 1 == LeftSize) {
12241 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12242 << HexResult << LHSType
12243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12244 return;
12245 }
12246
12247 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12248 << HexResult.str() << Result.getSignificantBits() << LHSType
12249 << Left.getBitWidth() << LHS.get()->getSourceRange()
12250 << RHS.get()->getSourceRange();
12251}
12252
12253/// Return the resulting type when a vector is shifted
12254/// by a scalar or vector shift amount.
12255static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12256 SourceLocation Loc, bool IsCompAssign) {
12257 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12258 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12259 !LHS.get()->getType()->isVectorType()) {
12260 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12261 << RHS.get()->getType() << LHS.get()->getType()
12262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12263 return QualType();
12264 }
12265
12266 if (!IsCompAssign) {
12267 LHS = S.UsualUnaryConversions(E: LHS.get());
12268 if (LHS.isInvalid()) return QualType();
12269 }
12270
12271 RHS = S.UsualUnaryConversions(E: RHS.get());
12272 if (RHS.isInvalid()) return QualType();
12273
12274 QualType LHSType = LHS.get()->getType();
12275 // Note that LHS might be a scalar because the routine calls not only in
12276 // OpenCL case.
12277 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12278 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12279
12280 // Note that RHS might not be a vector.
12281 QualType RHSType = RHS.get()->getType();
12282 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12283 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12284
12285 // Do not allow shifts for boolean vectors.
12286 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12287 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12288 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12289 << LHS.get()->getType() << RHS.get()->getType()
12290 << LHS.get()->getSourceRange();
12291 return QualType();
12292 }
12293
12294 // The operands need to be integers.
12295 if (!LHSEleType->isIntegerType()) {
12296 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12297 << LHS.get()->getType() << LHS.get()->getSourceRange();
12298 return QualType();
12299 }
12300
12301 if (!RHSEleType->isIntegerType()) {
12302 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12303 << RHS.get()->getType() << RHS.get()->getSourceRange();
12304 return QualType();
12305 }
12306
12307 if (!LHSVecTy) {
12308 assert(RHSVecTy);
12309 if (IsCompAssign)
12310 return RHSType;
12311 if (LHSEleType != RHSEleType) {
12312 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12313 LHSEleType = RHSEleType;
12314 }
12315 QualType VecTy =
12316 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12317 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12318 LHSType = VecTy;
12319 } else if (RHSVecTy) {
12320 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12321 // are applied component-wise. So if RHS is a vector, then ensure
12322 // that the number of elements is the same as LHS...
12323 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12324 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12325 << LHS.get()->getType() << RHS.get()->getType()
12326 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12327 return QualType();
12328 }
12329 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12330 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12331 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12332 if (LHSBT != RHSBT &&
12333 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12334 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12335 << LHS.get()->getType() << RHS.get()->getType()
12336 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12337 }
12338 }
12339 } else {
12340 // ...else expand RHS to match the number of elements in LHS.
12341 QualType VecTy =
12342 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12343 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12344 }
12345
12346 return LHSType;
12347}
12348
12349static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12350 ExprResult &RHS, SourceLocation Loc,
12351 bool IsCompAssign) {
12352 if (!IsCompAssign) {
12353 LHS = S.UsualUnaryConversions(E: LHS.get());
12354 if (LHS.isInvalid())
12355 return QualType();
12356 }
12357
12358 RHS = S.UsualUnaryConversions(E: RHS.get());
12359 if (RHS.isInvalid())
12360 return QualType();
12361
12362 QualType LHSType = LHS.get()->getType();
12363 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12364 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12365 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12366 : LHSType;
12367
12368 // Note that RHS might not be a vector
12369 QualType RHSType = RHS.get()->getType();
12370 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12371 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12372 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12373 : RHSType;
12374
12375 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12376 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12377 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12378 << LHSType << RHSType << LHS.get()->getSourceRange();
12379 return QualType();
12380 }
12381
12382 if (!LHSEleType->isIntegerType()) {
12383 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12384 << LHS.get()->getType() << LHS.get()->getSourceRange();
12385 return QualType();
12386 }
12387
12388 if (!RHSEleType->isIntegerType()) {
12389 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12390 << RHS.get()->getType() << RHS.get()->getSourceRange();
12391 return QualType();
12392 }
12393
12394 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12395 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12396 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12397 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12398 << LHSType << RHSType << LHS.get()->getSourceRange()
12399 << RHS.get()->getSourceRange();
12400 return QualType();
12401 }
12402
12403 if (!LHSType->isSveVLSBuiltinType()) {
12404 assert(RHSType->isSveVLSBuiltinType());
12405 if (IsCompAssign)
12406 return RHSType;
12407 if (LHSEleType != RHSEleType) {
12408 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12409 LHSEleType = RHSEleType;
12410 }
12411 const llvm::ElementCount VecSize =
12412 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12413 QualType VecTy =
12414 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12415 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12416 LHSType = VecTy;
12417 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12418 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12419 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12420 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12421 << LHSType << RHSType << LHS.get()->getSourceRange()
12422 << RHS.get()->getSourceRange();
12423 return QualType();
12424 }
12425 } else {
12426 const llvm::ElementCount VecSize =
12427 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12428 if (LHSEleType != RHSEleType) {
12429 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12430 RHSEleType = LHSEleType;
12431 }
12432 QualType VecTy =
12433 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12434 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12435 }
12436
12437 return LHSType;
12438}
12439
12440// C99 6.5.7
12441QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12442 SourceLocation Loc, BinaryOperatorKind Opc,
12443 bool IsCompAssign) {
12444 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12445
12446 // Vector shifts promote their scalar inputs to vector type.
12447 if (LHS.get()->getType()->isVectorType() ||
12448 RHS.get()->getType()->isVectorType()) {
12449 if (LangOpts.ZVector) {
12450 // The shift operators for the z vector extensions work basically
12451 // like general shifts, except that neither the LHS nor the RHS is
12452 // allowed to be a "vector bool".
12453 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12454 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12455 return InvalidOperands(Loc, LHS, RHS);
12456 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12457 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12458 return InvalidOperands(Loc, LHS, RHS);
12459 }
12460 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12461 }
12462
12463 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12464 RHS.get()->getType()->isSveVLSBuiltinType())
12465 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12466
12467 // Shifts don't perform usual arithmetic conversions, they just do integer
12468 // promotions on each operand. C99 6.5.7p3
12469
12470 // For the LHS, do usual unary conversions, but then reset them away
12471 // if this is a compound assignment.
12472 ExprResult OldLHS = LHS;
12473 LHS = UsualUnaryConversions(E: LHS.get());
12474 if (LHS.isInvalid())
12475 return QualType();
12476 QualType LHSType = LHS.get()->getType();
12477 if (IsCompAssign) LHS = OldLHS;
12478
12479 // The RHS is simpler.
12480 RHS = UsualUnaryConversions(E: RHS.get());
12481 if (RHS.isInvalid())
12482 return QualType();
12483 QualType RHSType = RHS.get()->getType();
12484
12485 // C99 6.5.7p2: Each of the operands shall have integer type.
12486 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12487 if ((!LHSType->isFixedPointOrIntegerType() &&
12488 !LHSType->hasIntegerRepresentation()) ||
12489 !RHSType->hasIntegerRepresentation()) {
12490 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12491 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12492 return ResultTy;
12493 }
12494
12495 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12496
12497 // "The type of the result is that of the promoted left operand."
12498 return LHSType;
12499}
12500
12501/// Diagnose bad pointer comparisons.
12502static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12503 ExprResult &LHS, ExprResult &RHS,
12504 bool IsError) {
12505 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12506 : diag::ext_typecheck_comparison_of_distinct_pointers)
12507 << LHS.get()->getType() << RHS.get()->getType()
12508 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12509}
12510
12511/// Returns false if the pointers are converted to a composite type,
12512/// true otherwise.
12513static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12514 ExprResult &LHS, ExprResult &RHS) {
12515 // C++ [expr.rel]p2:
12516 // [...] Pointer conversions (4.10) and qualification
12517 // conversions (4.4) are performed on pointer operands (or on
12518 // a pointer operand and a null pointer constant) to bring
12519 // them to their composite pointer type. [...]
12520 //
12521 // C++ [expr.eq]p1 uses the same notion for (in)equality
12522 // comparisons of pointers.
12523
12524 QualType LHSType = LHS.get()->getType();
12525 QualType RHSType = RHS.get()->getType();
12526 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12527 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12528
12529 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12530 if (T.isNull()) {
12531 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12532 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12533 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12534 else
12535 S.InvalidOperands(Loc, LHS, RHS);
12536 return true;
12537 }
12538
12539 return false;
12540}
12541
12542static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12543 ExprResult &LHS,
12544 ExprResult &RHS,
12545 bool IsError) {
12546 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12547 : diag::ext_typecheck_comparison_of_fptr_to_void)
12548 << LHS.get()->getType() << RHS.get()->getType()
12549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12550}
12551
12552static bool isObjCObjectLiteral(ExprResult &E) {
12553 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12554 case Stmt::ObjCArrayLiteralClass:
12555 case Stmt::ObjCDictionaryLiteralClass:
12556 case Stmt::ObjCStringLiteralClass:
12557 case Stmt::ObjCBoxedExprClass:
12558 return true;
12559 default:
12560 // Note that ObjCBoolLiteral is NOT an object literal!
12561 return false;
12562 }
12563}
12564
12565static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12566 const ObjCObjectPointerType *Type =
12567 LHS->getType()->getAs<ObjCObjectPointerType>();
12568
12569 // If this is not actually an Objective-C object, bail out.
12570 if (!Type)
12571 return false;
12572
12573 // Get the LHS object's interface type.
12574 QualType InterfaceType = Type->getPointeeType();
12575
12576 // If the RHS isn't an Objective-C object, bail out.
12577 if (!RHS->getType()->isObjCObjectPointerType())
12578 return false;
12579
12580 // Try to find the -isEqual: method.
12581 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12582 ObjCMethodDecl *Method =
12583 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12584 /*IsInstance=*/true);
12585 if (!Method) {
12586 if (Type->isObjCIdType()) {
12587 // For 'id', just check the global pool.
12588 Method =
12589 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12590 /*receiverId=*/receiverIdOrClass: true);
12591 } else {
12592 // Check protocols.
12593 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12594 /*IsInstance=*/true);
12595 }
12596 }
12597
12598 if (!Method)
12599 return false;
12600
12601 QualType T = Method->parameters()[0]->getType();
12602 if (!T->isObjCObjectPointerType())
12603 return false;
12604
12605 QualType R = Method->getReturnType();
12606 if (!R->isScalarType())
12607 return false;
12608
12609 return true;
12610}
12611
12612static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12613 ExprResult &LHS, ExprResult &RHS,
12614 BinaryOperator::Opcode Opc){
12615 Expr *Literal;
12616 Expr *Other;
12617 if (isObjCObjectLiteral(E&: LHS)) {
12618 Literal = LHS.get();
12619 Other = RHS.get();
12620 } else {
12621 Literal = RHS.get();
12622 Other = LHS.get();
12623 }
12624
12625 // Don't warn on comparisons against nil.
12626 Other = Other->IgnoreParenCasts();
12627 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12628 NPC: Expr::NPC_ValueDependentIsNotNull))
12629 return;
12630
12631 // This should be kept in sync with warn_objc_literal_comparison.
12632 // LK_String should always be after the other literals, since it has its own
12633 // warning flag.
12634 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12635 assert(LiteralKind != SemaObjC::LK_Block);
12636 if (LiteralKind == SemaObjC::LK_None) {
12637 llvm_unreachable("Unknown Objective-C object literal kind");
12638 }
12639
12640 if (LiteralKind == SemaObjC::LK_String)
12641 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12642 << Literal->getSourceRange();
12643 else
12644 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12645 << LiteralKind << Literal->getSourceRange();
12646
12647 if (BinaryOperator::isEqualityOp(Opc) &&
12648 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12649 SourceLocation Start = LHS.get()->getBeginLoc();
12650 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12651 CharSourceRange OpRange =
12652 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12653
12654 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12655 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12656 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12657 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12658 }
12659}
12660
12661/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12662static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12663 ExprResult &RHS, SourceLocation Loc,
12664 BinaryOperatorKind Opc) {
12665 // Check that left hand side is !something.
12666 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12667 if (!UO || UO->getOpcode() != UO_LNot) return;
12668
12669 // Only check if the right hand side is non-bool arithmetic type.
12670 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12671
12672 // Make sure that the something in !something is not bool.
12673 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12674 if (SubExpr->isKnownToHaveBooleanValue()) return;
12675
12676 // Emit warning.
12677 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12678 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12679 << Loc << IsBitwiseOp;
12680
12681 // First note suggest !(x < y)
12682 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12683 SourceLocation FirstClose = RHS.get()->getEndLoc();
12684 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12685 if (FirstClose.isInvalid())
12686 FirstOpen = SourceLocation();
12687 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12688 << IsBitwiseOp
12689 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12690 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12691
12692 // Second note suggests (!x) < y
12693 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12694 SourceLocation SecondClose = LHS.get()->getEndLoc();
12695 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12696 if (SecondClose.isInvalid())
12697 SecondOpen = SourceLocation();
12698 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12699 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12700 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12701}
12702
12703// Returns true if E refers to a non-weak array.
12704static bool checkForArray(const Expr *E) {
12705 const ValueDecl *D = nullptr;
12706 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12707 D = DR->getDecl();
12708 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12709 if (Mem->isImplicitAccess())
12710 D = Mem->getMemberDecl();
12711 }
12712 if (!D)
12713 return false;
12714 return D->getType()->isArrayType() && !D->isWeak();
12715}
12716
12717/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12718/// pointer and size is an unsigned integer. Return whether the result is
12719/// always true/false.
12720static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12721 const Expr *RHS,
12722 BinaryOperatorKind Opc) {
12723 if (!LHS->getType()->isPointerType() ||
12724 S.getLangOpts().PointerOverflowDefined)
12725 return std::nullopt;
12726
12727 // Canonicalize to >= or < predicate.
12728 switch (Opc) {
12729 case BO_GE:
12730 case BO_LT:
12731 break;
12732 case BO_GT:
12733 std::swap(a&: LHS, b&: RHS);
12734 Opc = BO_LT;
12735 break;
12736 case BO_LE:
12737 std::swap(a&: LHS, b&: RHS);
12738 Opc = BO_GE;
12739 break;
12740 default:
12741 return std::nullopt;
12742 }
12743
12744 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12745 if (!BO || BO->getOpcode() != BO_Add)
12746 return std::nullopt;
12747
12748 Expr *Other;
12749 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12750 Other = BO->getRHS();
12751 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12752 Other = BO->getLHS();
12753 else
12754 return std::nullopt;
12755
12756 if (!Other->getType()->isUnsignedIntegerType())
12757 return std::nullopt;
12758
12759 return Opc == BO_GE;
12760}
12761
12762/// Diagnose some forms of syntactically-obvious tautological comparison.
12763static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12764 Expr *LHS, Expr *RHS,
12765 BinaryOperatorKind Opc) {
12766 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12767 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12768
12769 QualType LHSType = LHS->getType();
12770 QualType RHSType = RHS->getType();
12771 if (LHSType->hasFloatingRepresentation() ||
12772 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12773 S.inTemplateInstantiation())
12774 return;
12775
12776 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12777 // Tautological diagnostics.
12778 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12779 return;
12780
12781 // Comparisons between two array types are ill-formed for operator<=>, so
12782 // we shouldn't emit any additional warnings about it.
12783 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12784 return;
12785
12786 // For non-floating point types, check for self-comparisons of the form
12787 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12788 // often indicate logic errors in the program.
12789 //
12790 // NOTE: Don't warn about comparison expressions resulting from macro
12791 // expansion. Also don't warn about comparisons which are only self
12792 // comparisons within a template instantiation. The warnings should catch
12793 // obvious cases in the definition of the template anyways. The idea is to
12794 // warn when the typed comparison operator will always evaluate to the same
12795 // result.
12796
12797 // Used for indexing into %select in warn_comparison_always
12798 enum {
12799 AlwaysConstant,
12800 AlwaysTrue,
12801 AlwaysFalse,
12802 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12803 };
12804
12805 // C++1a [array.comp]:
12806 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12807 // operands of array type.
12808 // C++2a [depr.array.comp]:
12809 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12810 // operands of array type are deprecated.
12811 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12812 RHSStripped->getType()->isArrayType()) {
12813 auto IsDeprArrayComparionIgnored =
12814 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12815 auto DiagID = S.getLangOpts().CPlusPlus26
12816 ? diag::warn_array_comparison_cxx26
12817 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12818 ? diag::warn_array_comparison
12819 : diag::warn_depr_array_comparison;
12820 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12821 << LHSStripped->getType() << RHSStripped->getType();
12822 // Carry on to produce the tautological comparison warning, if this
12823 // expression is potentially-evaluated, we can resolve the array to a
12824 // non-weak declaration, and so on.
12825 }
12826
12827 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12828 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12829 unsigned Result;
12830 switch (Opc) {
12831 case BO_EQ:
12832 case BO_LE:
12833 case BO_GE:
12834 Result = AlwaysTrue;
12835 break;
12836 case BO_NE:
12837 case BO_LT:
12838 case BO_GT:
12839 Result = AlwaysFalse;
12840 break;
12841 case BO_Cmp:
12842 Result = AlwaysEqual;
12843 break;
12844 default:
12845 Result = AlwaysConstant;
12846 break;
12847 }
12848 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12849 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12850 << 0 /*self-comparison*/
12851 << Result);
12852 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12853 // What is it always going to evaluate to?
12854 unsigned Result;
12855 switch (Opc) {
12856 case BO_EQ: // e.g. array1 == array2
12857 Result = AlwaysFalse;
12858 break;
12859 case BO_NE: // e.g. array1 != array2
12860 Result = AlwaysTrue;
12861 break;
12862 default: // e.g. array1 <= array2
12863 // The best we can say is 'a constant'
12864 Result = AlwaysConstant;
12865 break;
12866 }
12867 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12868 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12869 << 1 /*array comparison*/
12870 << Result);
12871 } else if (std::optional<bool> Res =
12872 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12873 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12874 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12875 << 2 /*pointer comparison*/
12876 << (*Res ? AlwaysTrue : AlwaysFalse));
12877 }
12878 }
12879
12880 if (isa<CastExpr>(Val: LHSStripped))
12881 LHSStripped = LHSStripped->IgnoreParenCasts();
12882 if (isa<CastExpr>(Val: RHSStripped))
12883 RHSStripped = RHSStripped->IgnoreParenCasts();
12884
12885 // Warn about comparisons against a string constant (unless the other
12886 // operand is null); the user probably wants string comparison function.
12887 Expr *LiteralString = nullptr;
12888 Expr *LiteralStringStripped = nullptr;
12889 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12890 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12891 NPC: Expr::NPC_ValueDependentIsNull)) {
12892 LiteralString = LHS;
12893 LiteralStringStripped = LHSStripped;
12894 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12895 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12896 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12897 NPC: Expr::NPC_ValueDependentIsNull)) {
12898 LiteralString = RHS;
12899 LiteralStringStripped = RHSStripped;
12900 }
12901
12902 if (LiteralString) {
12903 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12904 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12905 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12906 << LiteralString->getSourceRange());
12907 }
12908}
12909
12910static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12911 switch (CK) {
12912 default: {
12913#ifndef NDEBUG
12914 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12915 << "\n";
12916#endif
12917 llvm_unreachable("unhandled cast kind");
12918 }
12919 case CK_UserDefinedConversion:
12920 return ICK_Identity;
12921 case CK_LValueToRValue:
12922 return ICK_Lvalue_To_Rvalue;
12923 case CK_ArrayToPointerDecay:
12924 return ICK_Array_To_Pointer;
12925 case CK_FunctionToPointerDecay:
12926 return ICK_Function_To_Pointer;
12927 case CK_IntegralCast:
12928 return ICK_Integral_Conversion;
12929 case CK_FloatingCast:
12930 return ICK_Floating_Conversion;
12931 case CK_IntegralToFloating:
12932 case CK_FloatingToIntegral:
12933 return ICK_Floating_Integral;
12934 case CK_IntegralComplexCast:
12935 case CK_FloatingComplexCast:
12936 case CK_FloatingComplexToIntegralComplex:
12937 case CK_IntegralComplexToFloatingComplex:
12938 return ICK_Complex_Conversion;
12939 case CK_FloatingComplexToReal:
12940 case CK_FloatingRealToComplex:
12941 case CK_IntegralComplexToReal:
12942 case CK_IntegralRealToComplex:
12943 return ICK_Complex_Real;
12944 case CK_HLSLArrayRValue:
12945 return ICK_HLSL_Array_RValue;
12946 }
12947}
12948
12949static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12950 QualType FromType,
12951 SourceLocation Loc) {
12952 // Check for a narrowing implicit conversion.
12953 StandardConversionSequence SCS;
12954 SCS.setAsIdentityConversion();
12955 SCS.setToType(Idx: 0, T: FromType);
12956 SCS.setToType(Idx: 1, T: ToType);
12957 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12958 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12959
12960 APValue PreNarrowingValue;
12961 QualType PreNarrowingType;
12962 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12963 ConstantType&: PreNarrowingType,
12964 /*IgnoreFloatToIntegralConversion*/ true)) {
12965 case NK_Dependent_Narrowing:
12966 // Implicit conversion to a narrower type, but the expression is
12967 // value-dependent so we can't tell whether it's actually narrowing.
12968 case NK_Not_Narrowing:
12969 return false;
12970
12971 case NK_Constant_Narrowing:
12972 // Implicit conversion to a narrower type, and the value is not a constant
12973 // expression.
12974 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12975 << /*Constant*/ 1
12976 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12977 return true;
12978
12979 case NK_Variable_Narrowing:
12980 // Implicit conversion to a narrower type, and the value is not a constant
12981 // expression.
12982 case NK_Type_Narrowing:
12983 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12984 << /*Constant*/ 0 << FromType << ToType;
12985 // TODO: It's not a constant expression, but what if the user intended it
12986 // to be? Can we produce notes to help them figure out why it isn't?
12987 return true;
12988 }
12989 llvm_unreachable("unhandled case in switch");
12990}
12991
12992static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12993 ExprResult &LHS,
12994 ExprResult &RHS,
12995 SourceLocation Loc) {
12996 QualType LHSType = LHS.get()->getType();
12997 QualType RHSType = RHS.get()->getType();
12998 // Dig out the original argument type and expression before implicit casts
12999 // were applied. These are the types/expressions we need to check the
13000 // [expr.spaceship] requirements against.
13001 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
13002 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
13003 QualType LHSStrippedType = LHSStripped.get()->getType();
13004 QualType RHSStrippedType = RHSStripped.get()->getType();
13005
13006 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
13007 // other is not, the program is ill-formed.
13008 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
13009 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
13010 return QualType();
13011 }
13012
13013 // FIXME: Consider combining this with checkEnumArithmeticConversions.
13014 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
13015 RHSStrippedType->isEnumeralType();
13016 if (NumEnumArgs == 1) {
13017 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
13018 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
13019 if (OtherTy->hasFloatingRepresentation()) {
13020 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
13021 return QualType();
13022 }
13023 }
13024 if (NumEnumArgs == 2) {
13025 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
13026 // type E, the operator yields the result of converting the operands
13027 // to the underlying type of E and applying <=> to the converted operands.
13028 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
13029 S.InvalidOperands(Loc, LHS, RHS);
13030 return QualType();
13031 }
13032 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
13033 assert(IntType->isArithmeticType());
13034
13035 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
13036 // promote the boolean type, and all other promotable integer types, to
13037 // avoid this.
13038 if (S.Context.isPromotableIntegerType(T: IntType))
13039 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
13040
13041 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
13042 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
13043 LHSType = RHSType = IntType;
13044 }
13045
13046 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13047 // usual arithmetic conversions are applied to the operands.
13048 QualType Type =
13049 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13050 if (LHS.isInvalid() || RHS.isInvalid())
13051 return QualType();
13052 if (Type.isNull()) {
13053 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13054 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
13055 return ResultTy;
13056 }
13057
13058 std::optional<ComparisonCategoryType> CCT =
13059 getComparisonCategoryForBuiltinCmp(T: Type);
13060 if (!CCT)
13061 return S.InvalidOperands(Loc, LHS, RHS);
13062
13063 bool HasNarrowing = checkThreeWayNarrowingConversion(
13064 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
13065 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
13066 Loc: RHS.get()->getBeginLoc());
13067 if (HasNarrowing)
13068 return QualType();
13069
13070 assert(!Type.isNull() && "composite type for <=> has not been set");
13071
13072 return S.CheckComparisonCategoryType(
13073 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
13074}
13075
13076static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13077 ExprResult &RHS,
13078 SourceLocation Loc,
13079 BinaryOperatorKind Opc) {
13080 if (Opc == BO_Cmp)
13081 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13082
13083 // C99 6.5.8p3 / C99 6.5.9p4
13084 QualType Type =
13085 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
13086 if (LHS.isInvalid() || RHS.isInvalid())
13087 return QualType();
13088 if (Type.isNull()) {
13089 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13090 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13091 return ResultTy;
13092 }
13093 assert(Type->isArithmeticType() || Type->isEnumeralType());
13094
13095 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13096 return S.InvalidOperands(Loc, LHS, RHS);
13097
13098 // Check for comparisons of floating point operands using != and ==.
13099 if (Type->hasFloatingRepresentation())
13100 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13101
13102 // The result of comparisons is 'bool' in C++, 'int' in C.
13103 return S.Context.getLogicalOperationType();
13104}
13105
13106void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13107 if (!NullE.get()->getType()->isAnyPointerType())
13108 return;
13109 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
13110 if (!E.get()->getType()->isAnyPointerType() &&
13111 E.get()->isNullPointerConstant(Ctx&: Context,
13112 NPC: Expr::NPC_ValueDependentIsNotNull) ==
13113 Expr::NPCK_ZeroExpression) {
13114 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
13115 if (CL->getValue() == 0)
13116 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13117 << NullValue
13118 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13119 Code: NullValue ? "NULL" : "(void *)0");
13120 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
13121 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13122 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
13123 if (T == Context.CharTy)
13124 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
13125 << NullValue
13126 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
13127 Code: NullValue ? "NULL" : "(void *)0");
13128 }
13129 }
13130}
13131
13132// C99 6.5.8, C++ [expr.rel]
13133QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13134 SourceLocation Loc,
13135 BinaryOperatorKind Opc) {
13136 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13137 bool IsThreeWay = Opc == BO_Cmp;
13138 bool IsOrdered = IsRelational || IsThreeWay;
13139 auto IsAnyPointerType = [](ExprResult E) {
13140 QualType Ty = E.get()->getType();
13141 return Ty->isPointerType() || Ty->isMemberPointerType();
13142 };
13143
13144 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13145 // type, array-to-pointer, ..., conversions are performed on both operands to
13146 // bring them to their composite type.
13147 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13148 // any type-related checks.
13149 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13150 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13151 if (LHS.isInvalid())
13152 return QualType();
13153 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13154 if (RHS.isInvalid())
13155 return QualType();
13156 } else {
13157 LHS = DefaultLvalueConversion(E: LHS.get());
13158 if (LHS.isInvalid())
13159 return QualType();
13160 RHS = DefaultLvalueConversion(E: RHS.get());
13161 if (RHS.isInvalid())
13162 return QualType();
13163 }
13164
13165 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
13166 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13167 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
13168 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
13169 }
13170
13171 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13172 RHS.get()->getType()->isConstantMatrixType()))
13173 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13174
13175 // Handle vector comparisons separately.
13176 if (LHS.get()->getType()->isVectorType() ||
13177 RHS.get()->getType()->isVectorType())
13178 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13179
13180 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13181 RHS.get()->getType()->isSveVLSBuiltinType())
13182 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13183
13184 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13185 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13186
13187 QualType LHSType = LHS.get()->getType();
13188 QualType RHSType = RHS.get()->getType();
13189 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13190 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13191 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
13192
13193 if ((LHSType->isPointerType() &&
13194 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13195 (RHSType->isPointerType() &&
13196 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13197 return InvalidOperands(Loc, LHS, RHS);
13198
13199 const Expr::NullPointerConstantKind LHSNullKind =
13200 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13201 const Expr::NullPointerConstantKind RHSNullKind =
13202 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
13203 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13204 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13205
13206 auto computeResultTy = [&]() {
13207 if (Opc != BO_Cmp)
13208 return QualType(Context.getLogicalOperationType());
13209 assert(getLangOpts().CPlusPlus);
13210 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13211
13212 QualType CompositeTy = LHS.get()->getType();
13213 assert(!CompositeTy->isReferenceType());
13214
13215 std::optional<ComparisonCategoryType> CCT =
13216 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
13217 if (!CCT)
13218 return InvalidOperands(Loc, LHS, RHS);
13219
13220 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13221 // P0946R0: Comparisons between a null pointer constant and an object
13222 // pointer result in std::strong_equality, which is ill-formed under
13223 // P1959R0.
13224 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13225 << (LHSIsNull ? LHS.get()->getSourceRange()
13226 : RHS.get()->getSourceRange());
13227 return QualType();
13228 }
13229
13230 return CheckComparisonCategoryType(
13231 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13232 };
13233
13234 if (LHSType->isMetaInfoType() && RHSType->isMetaInfoType()) {
13235 if (!BinaryOperator::isEqualityOp(Opc)) {
13236 return InvalidOperands(Loc, LHS, RHS);
13237 }
13238 return computeResultTy();
13239 }
13240
13241 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13242 bool IsEquality = Opc == BO_EQ;
13243 if (RHSIsNull)
13244 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13245 Range: RHS.get()->getSourceRange());
13246 else
13247 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13248 Range: LHS.get()->getSourceRange());
13249 }
13250
13251 if (IsOrdered && LHSType->isFunctionPointerType() &&
13252 RHSType->isFunctionPointerType()) {
13253 // Valid unless a relational comparison of function pointers
13254 bool IsError = Opc == BO_Cmp;
13255 auto DiagID =
13256 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13257 : getLangOpts().CPlusPlus
13258 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13259 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13260 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13261 << RHS.get()->getSourceRange();
13262 if (IsError)
13263 return QualType();
13264 }
13265
13266 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13267 (RHSType->isIntegerType() && !RHSIsNull)) {
13268 // Skip normal pointer conversion checks in this case; we have better
13269 // diagnostics for this below.
13270 } else if (getLangOpts().CPlusPlus) {
13271 // Equality comparison of a function pointer to a void pointer is invalid,
13272 // but we allow it as an extension.
13273 // FIXME: If we really want to allow this, should it be part of composite
13274 // pointer type computation so it works in conditionals too?
13275 if (!IsOrdered &&
13276 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13277 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13278 // This is a gcc extension compatibility comparison.
13279 // In a SFINAE context, we treat this as a hard error to maintain
13280 // conformance with the C++ standard.
13281 bool IsError = isSFINAEContext();
13282 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13283
13284 if (IsError)
13285 return QualType();
13286
13287 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13288 return computeResultTy();
13289 }
13290
13291 // C++ [expr.eq]p2:
13292 // If at least one operand is a pointer [...] bring them to their
13293 // composite pointer type.
13294 // C++ [expr.spaceship]p6
13295 // If at least one of the operands is of pointer type, [...] bring them
13296 // to their composite pointer type.
13297 // C++ [expr.rel]p2:
13298 // If both operands are pointers, [...] bring them to their composite
13299 // pointer type.
13300 // For <=>, the only valid non-pointer types are arrays and functions, and
13301 // we already decayed those, so this is really the same as the relational
13302 // comparison rule.
13303 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13304 (IsOrdered ? 2 : 1) &&
13305 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13306 RHSType->isObjCObjectPointerType()))) {
13307 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13308 return QualType();
13309 return computeResultTy();
13310 }
13311 } else if (LHSType->isPointerType() &&
13312 RHSType->isPointerType()) { // C99 6.5.8p2
13313 // All of the following pointer-related warnings are GCC extensions, except
13314 // when handling null pointer constants.
13315 QualType LCanPointeeTy =
13316 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13317 QualType RCanPointeeTy =
13318 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13319
13320 // C99 6.5.9p2 and C99 6.5.8p2
13321 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13322 T2: RCanPointeeTy.getUnqualifiedType())) {
13323 if (IsRelational) {
13324 // Pointers both need to point to complete or incomplete types
13325 if ((LCanPointeeTy->isIncompleteType() !=
13326 RCanPointeeTy->isIncompleteType()) &&
13327 !getLangOpts().C11) {
13328 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13329 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13330 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13331 << RCanPointeeTy->isIncompleteType();
13332 }
13333 }
13334 } else if (!IsRelational &&
13335 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13336 // Valid unless comparison between non-null pointer and function pointer
13337 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13338 && !LHSIsNull && !RHSIsNull)
13339 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13340 /*isError*/IsError: false);
13341 } else {
13342 // Invalid
13343 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13344 }
13345 if (LCanPointeeTy != RCanPointeeTy) {
13346 // Treat NULL constant as a special case in OpenCL.
13347 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13348 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13349 Ctx: getASTContext())) {
13350 Diag(Loc,
13351 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13352 << LHSType << RHSType << 0 /* comparison */
13353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13354 }
13355 }
13356 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13357 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13358 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13359 : CK_BitCast;
13360
13361 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13362 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13363 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13364 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13365 bool ChangingCFIUncheckedCallee =
13366 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13367
13368 if (LHSIsNull && !RHSIsNull)
13369 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13370 else if (!ChangingCFIUncheckedCallee)
13371 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13372 }
13373 return computeResultTy();
13374 }
13375
13376
13377 // C++ [expr.eq]p4:
13378 // Two operands of type std::nullptr_t or one operand of type
13379 // std::nullptr_t and the other a null pointer constant compare
13380 // equal.
13381 // C23 6.5.9p5:
13382 // If both operands have type nullptr_t or one operand has type nullptr_t
13383 // and the other is a null pointer constant, they compare equal if the
13384 // former is a null pointer.
13385 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13386 if (LHSType->isNullPtrType()) {
13387 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13388 return computeResultTy();
13389 }
13390 if (RHSType->isNullPtrType()) {
13391 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13392 return computeResultTy();
13393 }
13394 }
13395
13396 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13397 // C23 6.5.9p6:
13398 // Otherwise, at least one operand is a pointer. If one is a pointer and
13399 // the other is a null pointer constant or has type nullptr_t, they
13400 // compare equal
13401 if (LHSIsNull && RHSType->isPointerType()) {
13402 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13403 return computeResultTy();
13404 }
13405 if (RHSIsNull && LHSType->isPointerType()) {
13406 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13407 return computeResultTy();
13408 }
13409 }
13410
13411 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13412 // These aren't covered by the composite pointer type rules.
13413 if (!IsOrdered && RHSType->isNullPtrType() &&
13414 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13415 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13416 return computeResultTy();
13417 }
13418 if (!IsOrdered && LHSType->isNullPtrType() &&
13419 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13420 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13421 return computeResultTy();
13422 }
13423
13424 if (getLangOpts().CPlusPlus) {
13425 if (IsRelational &&
13426 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13427 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13428 // HACK: Relational comparison of nullptr_t against a pointer type is
13429 // invalid per DR583, but we allow it within std::less<> and friends,
13430 // since otherwise common uses of it break.
13431 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13432 // friends to have std::nullptr_t overload candidates.
13433 DeclContext *DC = CurContext;
13434 if (isa<FunctionDecl>(Val: DC))
13435 DC = DC->getParent();
13436 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13437 if (CTSD->isInStdNamespace() &&
13438 llvm::StringSwitch<bool>(CTSD->getName())
13439 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13440 .Default(Value: false)) {
13441 if (RHSType->isNullPtrType())
13442 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13443 else
13444 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13445 return computeResultTy();
13446 }
13447 }
13448 }
13449
13450 // C++ [expr.eq]p2:
13451 // If at least one operand is a pointer to member, [...] bring them to
13452 // their composite pointer type.
13453 if (!IsOrdered &&
13454 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13455 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13456 return QualType();
13457 else
13458 return computeResultTy();
13459 }
13460 }
13461
13462 // Handle block pointer types.
13463 if (!IsOrdered && LHSType->isBlockPointerType() &&
13464 RHSType->isBlockPointerType()) {
13465 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13466 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13467
13468 if (!LHSIsNull && !RHSIsNull &&
13469 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13470 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13471 << LHSType << RHSType << LHS.get()->getSourceRange()
13472 << RHS.get()->getSourceRange();
13473 }
13474 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13475 return computeResultTy();
13476 }
13477
13478 // Allow block pointers to be compared with null pointer constants.
13479 if (!IsOrdered
13480 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13481 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13482 if (!LHSIsNull && !RHSIsNull) {
13483 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13484 ->getPointeeType()->isVoidType())
13485 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13486 ->getPointeeType()->isVoidType())))
13487 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13488 << LHSType << RHSType << LHS.get()->getSourceRange()
13489 << RHS.get()->getSourceRange();
13490 }
13491 if (LHSIsNull && !RHSIsNull)
13492 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13493 CK: RHSType->isPointerType() ? CK_BitCast
13494 : CK_AnyPointerToBlockPointerCast);
13495 else
13496 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13497 CK: LHSType->isPointerType() ? CK_BitCast
13498 : CK_AnyPointerToBlockPointerCast);
13499 return computeResultTy();
13500 }
13501
13502 if (LHSType->isObjCObjectPointerType() ||
13503 RHSType->isObjCObjectPointerType()) {
13504 const PointerType *LPT = LHSType->getAs<PointerType>();
13505 const PointerType *RPT = RHSType->getAs<PointerType>();
13506 if (LPT || RPT) {
13507 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13508 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13509
13510 if (!LPtrToVoid && !RPtrToVoid &&
13511 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13512 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13513 /*isError*/IsError: false);
13514 }
13515 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13516 // the RHS, but we have test coverage for this behavior.
13517 // FIXME: Consider using convertPointersToCompositeType in C++.
13518 if (LHSIsNull && !RHSIsNull) {
13519 Expr *E = LHS.get();
13520 if (getLangOpts().ObjCAutoRefCount)
13521 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13522 CCK: CheckedConversionKind::Implicit);
13523 LHS = ImpCastExprToType(E, Type: RHSType,
13524 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13525 }
13526 else {
13527 Expr *E = RHS.get();
13528 if (getLangOpts().ObjCAutoRefCount)
13529 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13530 CCK: CheckedConversionKind::Implicit,
13531 /*Diagnose=*/true,
13532 /*DiagnoseCFAudited=*/false, Opc);
13533 RHS = ImpCastExprToType(E, Type: LHSType,
13534 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13535 }
13536 return computeResultTy();
13537 }
13538 if (LHSType->isObjCObjectPointerType() &&
13539 RHSType->isObjCObjectPointerType()) {
13540 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13541 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13542 /*isError*/IsError: false);
13543 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13544 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13545
13546 if (LHSIsNull && !RHSIsNull)
13547 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13548 else
13549 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13550 return computeResultTy();
13551 }
13552
13553 if (!IsOrdered && LHSType->isBlockPointerType() &&
13554 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13555 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13556 CK: CK_BlockPointerToObjCPointerCast);
13557 return computeResultTy();
13558 } else if (!IsOrdered &&
13559 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13560 RHSType->isBlockPointerType()) {
13561 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13562 CK: CK_BlockPointerToObjCPointerCast);
13563 return computeResultTy();
13564 }
13565 }
13566 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13567 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13568 unsigned DiagID = 0;
13569 bool isError = false;
13570 if (LangOpts.DebuggerSupport) {
13571 // Under a debugger, allow the comparison of pointers to integers,
13572 // since users tend to want to compare addresses.
13573 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13574 (RHSIsNull && RHSType->isIntegerType())) {
13575 if (IsOrdered) {
13576 isError = getLangOpts().CPlusPlus;
13577 DiagID =
13578 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13579 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13580 }
13581 } else if (getLangOpts().CPlusPlus) {
13582 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13583 isError = true;
13584 } else if (IsOrdered)
13585 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13586 else
13587 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13588
13589 if (DiagID) {
13590 Diag(Loc, DiagID)
13591 << LHSType << RHSType << LHS.get()->getSourceRange()
13592 << RHS.get()->getSourceRange();
13593 if (isError)
13594 return QualType();
13595 }
13596
13597 if (LHSType->isIntegerType())
13598 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13599 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13600 else
13601 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13602 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13603 return computeResultTy();
13604 }
13605
13606 // Handle block pointers.
13607 if (!IsOrdered && RHSIsNull
13608 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13609 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13610 return computeResultTy();
13611 }
13612 if (!IsOrdered && LHSIsNull
13613 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13614 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13615 return computeResultTy();
13616 }
13617
13618 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13619 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13620 return computeResultTy();
13621 }
13622
13623 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13624 return computeResultTy();
13625 }
13626
13627 if (LHSIsNull && RHSType->isQueueT()) {
13628 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13629 return computeResultTy();
13630 }
13631
13632 if (LHSType->isQueueT() && RHSIsNull) {
13633 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13634 return computeResultTy();
13635 }
13636 }
13637
13638 return InvalidOperands(Loc, LHS, RHS);
13639}
13640
13641QualType Sema::GetSignedVectorType(QualType V) {
13642 const VectorType *VTy = V->castAs<VectorType>();
13643 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13644
13645 if (isa<ExtVectorType>(Val: VTy)) {
13646 if (VTy->isExtVectorBoolType())
13647 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13648 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13649 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13650 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13651 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13652 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13653 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13654 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13655 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13656 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13657 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13658 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13659 "Unhandled vector element size in vector compare");
13660 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13661 }
13662
13663 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13664 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13665 VecKind: VectorKind::Generic);
13666 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13667 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13668 VecKind: VectorKind::Generic);
13669 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13670 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13671 VecKind: VectorKind::Generic);
13672 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13673 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13674 VecKind: VectorKind::Generic);
13675 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13676 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13677 VecKind: VectorKind::Generic);
13678 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13679 "Unhandled vector element size in vector compare");
13680 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13681 VecKind: VectorKind::Generic);
13682}
13683
13684QualType Sema::GetSignedSizelessVectorType(QualType V) {
13685 const BuiltinType *VTy = V->castAs<BuiltinType>();
13686 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13687
13688 const QualType ETy = V->getSveEltType(Ctx: Context);
13689 const auto TypeSize = Context.getTypeSize(T: ETy);
13690
13691 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13692 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13693 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13694}
13695
13696QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13697 SourceLocation Loc,
13698 BinaryOperatorKind Opc) {
13699 if (Opc == BO_Cmp) {
13700 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13701 return QualType();
13702 }
13703
13704 // Check to make sure we're operating on vectors of the same type and width,
13705 // Allowing one side to be a scalar of element type.
13706 QualType vType =
13707 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13708 /*AllowBothBool*/ true,
13709 /*AllowBoolConversions*/ getLangOpts().ZVector,
13710 /*AllowBooleanOperation*/ AllowBoolOperation: true);
13711 if (vType.isNull())
13712 return vType;
13713
13714 QualType LHSType = LHS.get()->getType();
13715
13716 // Determine the return type of a vector compare. By default clang will return
13717 // a scalar for all vector compares except vector bool and vector pixel.
13718 // With the gcc compiler we will always return a vector type and with the xl
13719 // compiler we will always return a scalar type. This switch allows choosing
13720 // which behavior is prefered.
13721 if (getLangOpts().AltiVec) {
13722 switch (getLangOpts().getAltivecSrcCompat()) {
13723 case LangOptions::AltivecSrcCompatKind::Mixed:
13724 // If AltiVec, the comparison results in a numeric type, i.e.
13725 // bool for C++, int for C
13726 if (vType->castAs<VectorType>()->getVectorKind() ==
13727 VectorKind::AltiVecVector)
13728 return Context.getLogicalOperationType();
13729 else
13730 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13731 break;
13732 case LangOptions::AltivecSrcCompatKind::GCC:
13733 // For GCC we always return the vector type.
13734 break;
13735 case LangOptions::AltivecSrcCompatKind::XL:
13736 return Context.getLogicalOperationType();
13737 break;
13738 }
13739 }
13740
13741 // For non-floating point types, check for self-comparisons of the form
13742 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13743 // often indicate logic errors in the program.
13744 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13745
13746 // Check for comparisons of floating point operands using != and ==.
13747 if (LHSType->hasFloatingRepresentation()) {
13748 assert(RHS.get()->getType()->hasFloatingRepresentation());
13749 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13750 }
13751
13752 // Return a signed type for the vector.
13753 return GetSignedVectorType(V: vType);
13754}
13755
13756QualType Sema::CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
13757 SourceLocation Loc,
13758 BinaryOperatorKind Opc) {
13759 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13760 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13761
13762 QualType MatrixTy =
13763 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13764 if (MatrixTy.isNull())
13765 return QualType();
13766
13767 if (!LHS.get()->getType()->isMatrixType()) {
13768 LHS = prepareMatrixSplat(MatrixTy, SplattedExpr: LHS.get());
13769 if (LHS.isInvalid())
13770 return QualType();
13771 LHS = ImpCastExprToType(E: LHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13772 }
13773 if (!RHS.get()->getType()->isMatrixType()) {
13774 RHS = prepareMatrixSplat(MatrixTy, SplattedExpr: RHS.get());
13775 if (RHS.isInvalid())
13776 return QualType();
13777 RHS = ImpCastExprToType(E: RHS.get(), Type: MatrixTy, CK: CK_HLSLAggregateSplatCast);
13778 }
13779
13780 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13781 return Context.getConstantMatrixType(ElementType: Context.BoolTy, NumRows: MT->getNumRows(),
13782 NumColumns: MT->getNumColumns());
13783}
13784
13785QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13786 ExprResult &RHS,
13787 SourceLocation Loc,
13788 BinaryOperatorKind Opc) {
13789 if (Opc == BO_Cmp) {
13790 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13791 return QualType();
13792 }
13793
13794 // Check to make sure we're operating on vectors of the same type and width,
13795 // Allowing one side to be a scalar of element type.
13796 QualType vType = CheckSizelessVectorOperands(
13797 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13798
13799 if (vType.isNull())
13800 return vType;
13801
13802 QualType LHSType = LHS.get()->getType();
13803
13804 // For non-floating point types, check for self-comparisons of the form
13805 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13806 // often indicate logic errors in the program.
13807 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13808
13809 // Check for comparisons of floating point operands using != and ==.
13810 if (LHSType->hasFloatingRepresentation()) {
13811 assert(RHS.get()->getType()->hasFloatingRepresentation());
13812 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13813 }
13814
13815 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13816 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13817
13818 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13819 RHSBuiltinTy->isSVEBool())
13820 return LHSType;
13821
13822 // Return a signed type for the vector.
13823 return GetSignedSizelessVectorType(V: vType);
13824}
13825
13826static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13827 const ExprResult &XorRHS,
13828 const SourceLocation Loc) {
13829 // Do not diagnose macros.
13830 if (Loc.isMacroID())
13831 return;
13832
13833 // Do not diagnose if both LHS and RHS are macros.
13834 if (XorLHS.get()->getExprLoc().isMacroID() &&
13835 XorRHS.get()->getExprLoc().isMacroID())
13836 return;
13837
13838 bool Negative = false;
13839 bool ExplicitPlus = false;
13840 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13841 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13842
13843 if (!LHSInt)
13844 return;
13845 if (!RHSInt) {
13846 // Check negative literals.
13847 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13848 UnaryOperatorKind Opc = UO->getOpcode();
13849 if (Opc != UO_Minus && Opc != UO_Plus)
13850 return;
13851 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13852 if (!RHSInt)
13853 return;
13854 Negative = (Opc == UO_Minus);
13855 ExplicitPlus = !Negative;
13856 } else {
13857 return;
13858 }
13859 }
13860
13861 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13862 llvm::APInt RightSideValue = RHSInt->getValue();
13863 if (LeftSideValue != 2 && LeftSideValue != 10)
13864 return;
13865
13866 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13867 return;
13868
13869 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13870 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13871 llvm::StringRef ExprStr =
13872 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13873
13874 CharSourceRange XorRange =
13875 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13876 llvm::StringRef XorStr =
13877 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13878 // Do not diagnose if xor keyword/macro is used.
13879 if (XorStr == "xor")
13880 return;
13881
13882 std::string LHSStr = std::string(Lexer::getSourceText(
13883 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13884 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13885 std::string RHSStr = std::string(Lexer::getSourceText(
13886 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13887 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13888
13889 if (Negative) {
13890 RightSideValue = -RightSideValue;
13891 RHSStr = "-" + RHSStr;
13892 } else if (ExplicitPlus) {
13893 RHSStr = "+" + RHSStr;
13894 }
13895
13896 StringRef LHSStrRef = LHSStr;
13897 StringRef RHSStrRef = RHSStr;
13898 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13899 // literals.
13900 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13901 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13902 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13903 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13904 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13905 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13906 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13907 return;
13908
13909 bool SuggestXor =
13910 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13911 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13912 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13913 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13914 std::string SuggestedExpr = "1 << " + RHSStr;
13915 bool Overflow = false;
13916 llvm::APInt One = (LeftSideValue - 1);
13917 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13918 if (Overflow) {
13919 if (RightSideIntValue < 64)
13920 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13921 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13922 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13923 else if (RightSideIntValue == 64)
13924 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13925 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13926 else
13927 return;
13928 } else {
13929 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13930 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13931 << toString(I: PowValue, Radix: 10, Signed: true)
13932 << FixItHint::CreateReplacement(
13933 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13934 }
13935
13936 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13937 << ("0x2 ^ " + RHSStr) << SuggestXor;
13938 } else if (LeftSideValue == 10) {
13939 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13940 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13941 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13942 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13943 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13944 << ("0xA ^ " + RHSStr) << SuggestXor;
13945 }
13946}
13947
13948QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13949 SourceLocation Loc,
13950 BinaryOperatorKind Opc) {
13951 // Ensure that either both operands are of the same vector type, or
13952 // one operand is of a vector type and the other is of its element type.
13953 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13954 /*AllowBothBool*/ true,
13955 /*AllowBoolConversions*/ false,
13956 /*AllowBooleanOperation*/ AllowBoolOperation: false);
13957 if (vType.isNull())
13958 return QualType();
13959 if (getLangOpts().OpenCL &&
13960 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13961 vType->hasFloatingRepresentation())
13962 return InvalidOperands(Loc, LHS, RHS);
13963 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13964 // usage of the logical operators && and || with vectors in C. This
13965 // check could be notionally dropped.
13966 if (!getLangOpts().CPlusPlus &&
13967 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13968 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13969 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13970 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13971 // `select` functions.
13972 if (getLangOpts().HLSL &&
13973 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13974 (void)InvalidOperands(Loc, LHS, RHS);
13975 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13976 return QualType();
13977 }
13978
13979 return GetSignedVectorType(V: LHS.get()->getType());
13980}
13981
13982QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13983 SourceLocation Loc,
13984 BinaryOperatorKind Opc) {
13985
13986 if (!getLangOpts().HLSL) {
13987 SemaRef.Diag(Loc, DiagID: diag::err_matrix_logical_operations_supported_for_hlsl);
13988 return QualType();
13989 }
13990
13991 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13992 (void)InvalidOperands(Loc, LHS, RHS);
13993 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13994 return QualType();
13995 }
13996 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13997 << getLangOpts().getHLSLVersion();
13998 return QualType();
13999}
14000
14001QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
14002 SourceLocation Loc,
14003 bool IsCompAssign) {
14004 if (!IsCompAssign) {
14005 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14006 if (LHS.isInvalid())
14007 return QualType();
14008 }
14009 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14010 if (RHS.isInvalid())
14011 return QualType();
14012
14013 // For conversion purposes, we ignore any qualifiers.
14014 // For example, "const float" and "float" are equivalent.
14015 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
14016 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
14017
14018 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
14019 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
14020 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14021
14022 if (Context.hasSameType(T1: LHSType, T2: RHSType))
14023 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
14024
14025 // Type conversion may change LHS/RHS. Keep copies to the original results, in
14026 // case we have to return InvalidOperands.
14027 ExprResult OriginalLHS = LHS;
14028 ExprResult OriginalRHS = RHS;
14029 if (LHSMatType && !RHSMatType) {
14030 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
14031 if (!RHS.isInvalid())
14032 return LHSType;
14033
14034 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14035 }
14036
14037 if (!LHSMatType && RHSMatType) {
14038 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
14039 if (!LHS.isInvalid())
14040 return RHSType;
14041 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
14042 }
14043
14044 return InvalidOperands(Loc, LHS, RHS);
14045}
14046
14047QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
14048 SourceLocation Loc,
14049 bool IsCompAssign) {
14050 if (!IsCompAssign) {
14051 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
14052 if (LHS.isInvalid())
14053 return QualType();
14054 }
14055 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
14056 if (RHS.isInvalid())
14057 return QualType();
14058
14059 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14060 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14061 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14062
14063 if (LHSMatType && RHSMatType) {
14064 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14065 return InvalidOperands(Loc, LHS, RHS);
14066
14067 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
14068 return Context.getCommonSugaredType(
14069 X: LHS.get()->getType().getUnqualifiedType(),
14070 Y: RHS.get()->getType().getUnqualifiedType());
14071
14072 QualType LHSELTy = LHSMatType->getElementType(),
14073 RHSELTy = RHSMatType->getElementType();
14074 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
14075 return InvalidOperands(Loc, LHS, RHS);
14076
14077 return Context.getConstantMatrixType(
14078 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
14079 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
14080 }
14081 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14082}
14083
14084static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
14085 switch (Opc) {
14086 default:
14087 return false;
14088 case BO_And:
14089 case BO_AndAssign:
14090 case BO_Or:
14091 case BO_OrAssign:
14092 case BO_Xor:
14093 case BO_XorAssign:
14094 return true;
14095 }
14096}
14097
14098inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
14099 SourceLocation Loc,
14100 BinaryOperatorKind Opc) {
14101 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
14102
14103 bool IsCompAssign =
14104 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14105
14106 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14107
14108 if (LHS.get()->getType()->isVectorType() ||
14109 RHS.get()->getType()->isVectorType()) {
14110 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14111 RHS.get()->getType()->hasIntegerRepresentation())
14112 return CheckVectorOperands(
14113 LHS, RHS, Loc, IsCompAssign,
14114 /*AllowBothBool*/ true,
14115 /*AllowBoolConversions*/ getLangOpts().ZVector,
14116 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator);
14117 return InvalidOperands(Loc, LHS, RHS);
14118 }
14119
14120 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14121 RHS.get()->getType()->isSveVLSBuiltinType()) {
14122 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14123 RHS.get()->getType()->hasIntegerRepresentation())
14124 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14125 OperationKind: ArithConvKind::BitwiseOp);
14126 return InvalidOperands(Loc, LHS, RHS);
14127 }
14128
14129 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14130 RHS.get()->getType()->isSveVLSBuiltinType()) {
14131 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14132 RHS.get()->getType()->hasIntegerRepresentation())
14133 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14134 OperationKind: ArithConvKind::BitwiseOp);
14135 return InvalidOperands(Loc, LHS, RHS);
14136 }
14137
14138 if (Opc == BO_And)
14139 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
14140
14141 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14142 RHS.get()->getType()->hasFloatingRepresentation())
14143 return InvalidOperands(Loc, LHS, RHS);
14144
14145 ExprResult LHSResult = LHS, RHSResult = RHS;
14146 QualType compType = UsualArithmeticConversions(
14147 LHS&: LHSResult, RHS&: RHSResult, Loc,
14148 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
14149 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14150 return QualType();
14151 LHS = LHSResult.get();
14152 RHS = RHSResult.get();
14153
14154 if (Opc == BO_Xor)
14155 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
14156
14157 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14158 return compType;
14159 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14160 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14161 return ResultTy;
14162}
14163
14164// C99 6.5.[13,14]
14165inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14166 SourceLocation Loc,
14167 BinaryOperatorKind Opc) {
14168 // Check vector operands differently.
14169 if (LHS.get()->getType()->isVectorType() ||
14170 RHS.get()->getType()->isVectorType())
14171 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14172
14173 if (LHS.get()->getType()->isConstantMatrixType() ||
14174 RHS.get()->getType()->isConstantMatrixType())
14175 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14176
14177 bool EnumConstantInBoolContext = false;
14178 for (const ExprResult &HS : {LHS, RHS}) {
14179 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
14180 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
14181 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14182 EnumConstantInBoolContext = true;
14183 }
14184 }
14185
14186 if (EnumConstantInBoolContext)
14187 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
14188
14189 // WebAssembly tables can't be used with logical operators.
14190 QualType LHSTy = LHS.get()->getType();
14191 QualType RHSTy = RHS.get()->getType();
14192 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
14193 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
14194 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14195 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14196 return InvalidOperands(Loc, LHS, RHS);
14197 }
14198
14199 // Diagnose cases where the user write a logical and/or but probably meant a
14200 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14201 // is a constant.
14202 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14203 !LHS.get()->getType()->isBooleanType() &&
14204 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14205 // Don't warn in macros or template instantiations.
14206 !Loc.isMacroID() && !inTemplateInstantiation()) {
14207 // If the RHS can be constant folded, and if it constant folds to something
14208 // that isn't 0 or 1 (which indicate a potential logical operation that
14209 // happened to fold to true/false) then warn.
14210 // Parens on the RHS are ignored.
14211 Expr::EvalResult EVResult;
14212 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
14213 llvm::APSInt Result = EVResult.Val.getInt();
14214 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14215 !RHS.get()->getExprLoc().isMacroID()) ||
14216 (Result != 0 && Result != 1)) {
14217 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
14218 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14219 // Suggest replacing the logical operator with the bitwise version
14220 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
14221 << (Opc == BO_LAnd ? "&" : "|")
14222 << FixItHint::CreateReplacement(
14223 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
14224 Code: Opc == BO_LAnd ? "&" : "|");
14225 if (Opc == BO_LAnd)
14226 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14227 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
14228 << FixItHint::CreateRemoval(
14229 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
14230 RHS.get()->getEndLoc()));
14231 }
14232 }
14233 }
14234
14235 if (!Context.getLangOpts().CPlusPlus) {
14236 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14237 // not operate on the built-in scalar and vector float types.
14238 if (Context.getLangOpts().OpenCL &&
14239 Context.getLangOpts().OpenCLVersion < 120) {
14240 if (LHS.get()->getType()->isFloatingType() ||
14241 RHS.get()->getType()->isFloatingType())
14242 return InvalidOperands(Loc, LHS, RHS);
14243 }
14244
14245 LHS = UsualUnaryConversions(E: LHS.get());
14246 if (LHS.isInvalid())
14247 return QualType();
14248
14249 RHS = UsualUnaryConversions(E: RHS.get());
14250 if (RHS.isInvalid())
14251 return QualType();
14252
14253 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14254 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
14255 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14256 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
14257
14258 if (!LHS.get()->getType()->isScalarType() ||
14259 !RHS.get()->getType()->isScalarType())
14260 return InvalidOperands(Loc, LHS, RHS);
14261
14262 return Context.IntTy;
14263 }
14264
14265 // The following is safe because we only use this method for
14266 // non-overloadable operands.
14267
14268 // C++ [expr.log.and]p1
14269 // C++ [expr.log.or]p1
14270 // The operands are both contextually converted to type bool.
14271 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14272 if (LHSRes.isInvalid()) {
14273 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14274 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14275 return ResultTy;
14276 }
14277 LHS = LHSRes;
14278
14279 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14280 if (RHSRes.isInvalid()) {
14281 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14282 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14283 return ResultTy;
14284 }
14285 RHS = RHSRes;
14286
14287 // C++ [expr.log.and]p2
14288 // C++ [expr.log.or]p2
14289 // The result is a bool.
14290 return Context.BoolTy;
14291}
14292
14293static bool IsReadonlyMessage(Expr *E, Sema &S) {
14294 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14295 if (!ME) return false;
14296 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14297 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14298 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14299 if (!Base) return false;
14300 return Base->getMethodDecl() != nullptr;
14301}
14302
14303/// Is the given expression (which must be 'const') a reference to a
14304/// variable which was originally non-const, but which has become
14305/// 'const' due to being captured within a block?
14306enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14307static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14308 assert(E->isLValue() && E->getType().isConstQualified());
14309 E = E->IgnoreParens();
14310
14311 // Must be a reference to a declaration from an enclosing scope.
14312 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14313 if (!DRE) return NCCK_None;
14314 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14315
14316 ValueDecl *Value = DRE->getDecl();
14317
14318 // The declaration must be a value which is not declared 'const'.
14319 if (Value->getType().isConstQualified())
14320 return NCCK_None;
14321
14322 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14323 if (Binding) {
14324 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14325 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14326 return NCCK_Lambda;
14327 }
14328
14329 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14330 if (!Var)
14331 return NCCK_None;
14332 if (Var->getType()->isReferenceType())
14333 return NCCK_None;
14334
14335 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14336
14337 // Decide whether the first capture was for a block or a lambda.
14338 DeclContext *DC = S.CurContext, *Prev = nullptr;
14339 // Decide whether the first capture was for a block or a lambda.
14340 while (DC) {
14341 // For init-capture, it is possible that the variable belongs to the
14342 // template pattern of the current context.
14343 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14344 if (Var->isInitCapture() &&
14345 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14346 break;
14347 if (DC == Var->getDeclContext())
14348 break;
14349 Prev = DC;
14350 DC = DC->getParent();
14351 }
14352 // Unless we have an init-capture, we've gone one step too far.
14353 if (!Var->isInitCapture())
14354 DC = Prev;
14355 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14356}
14357
14358static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14359 Ty = Ty.getNonReferenceType();
14360 if (IsDereference && Ty->isPointerType())
14361 Ty = Ty->getPointeeType();
14362 return !Ty.isConstQualified();
14363}
14364
14365// Update err_typecheck_assign_const and note_typecheck_assign_const
14366// when this enum is changed.
14367enum {
14368 ConstFunction,
14369 ConstVariable,
14370 ConstMember,
14371 NestedConstMember,
14372 ConstUnknown, // Keep as last element
14373};
14374
14375/// Emit the "read-only variable not assignable" error and print notes to give
14376/// more information about why the variable is not assignable, such as pointing
14377/// to the declaration of a const variable, showing that a method is const, or
14378/// that the function is returning a const reference.
14379static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14380 SourceLocation Loc) {
14381 SourceRange ExprRange = E->getSourceRange();
14382
14383 // Only emit one error on the first const found. All other consts will emit
14384 // a note to the error.
14385 bool DiagnosticEmitted = false;
14386
14387 // Track if the current expression is the result of a dereference, and if the
14388 // next checked expression is the result of a dereference.
14389 bool IsDereference = false;
14390 bool NextIsDereference = false;
14391
14392 // Loop to process MemberExpr chains.
14393 while (true) {
14394 IsDereference = NextIsDereference;
14395
14396 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14397 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14398 NextIsDereference = ME->isArrow();
14399 const ValueDecl *VD = ME->getMemberDecl();
14400 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14401 // Mutable fields can be modified even if the class is const.
14402 if (Field->isMutable()) {
14403 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14404 break;
14405 }
14406
14407 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14408 if (!DiagnosticEmitted) {
14409 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14410 << ExprRange << ConstMember << false /*static*/ << Field
14411 << Field->getType();
14412 DiagnosticEmitted = true;
14413 }
14414 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14415 << ConstMember << false /*static*/ << Field << Field->getType()
14416 << Field->getSourceRange();
14417 }
14418 E = ME->getBase();
14419 continue;
14420 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14421 if (VDecl->getType().isConstQualified()) {
14422 if (!DiagnosticEmitted) {
14423 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14424 << ExprRange << ConstMember << true /*static*/ << VDecl
14425 << VDecl->getType();
14426 DiagnosticEmitted = true;
14427 }
14428 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14429 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14430 << VDecl->getSourceRange();
14431 }
14432 // Static fields do not inherit constness from parents.
14433 break;
14434 }
14435 break; // End MemberExpr
14436 } else if (const ArraySubscriptExpr *ASE =
14437 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14438 E = ASE->getBase()->IgnoreParenImpCasts();
14439 continue;
14440 } else if (const ExtVectorElementExpr *EVE =
14441 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14442 E = EVE->getBase()->IgnoreParenImpCasts();
14443 continue;
14444 }
14445 break;
14446 }
14447
14448 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14449 // Function calls
14450 const FunctionDecl *FD = CE->getDirectCallee();
14451 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14452 if (!DiagnosticEmitted) {
14453 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14454 << ConstFunction << FD;
14455 DiagnosticEmitted = true;
14456 }
14457 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14458 DiagID: diag::note_typecheck_assign_const)
14459 << ConstFunction << FD << FD->getReturnType()
14460 << FD->getReturnTypeSourceRange();
14461 }
14462 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14463 // Point to variable declaration.
14464 if (const ValueDecl *VD = DRE->getDecl()) {
14465 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14466 if (!DiagnosticEmitted) {
14467 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14468 << ExprRange << ConstVariable << VD << VD->getType();
14469 DiagnosticEmitted = true;
14470 }
14471 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14472 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14473 }
14474 }
14475 } else if (isa<CXXThisExpr>(Val: E)) {
14476 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14477 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14478 if (MD->isConst()) {
14479 if (!DiagnosticEmitted) {
14480 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14481 << ExprRange << MD;
14482 DiagnosticEmitted = true;
14483 }
14484 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14485 << MD << MD->getSourceRange();
14486 }
14487 }
14488 }
14489 }
14490
14491 if (DiagnosticEmitted)
14492 return;
14493
14494 // Can't determine a more specific message, so display the generic error.
14495 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14496}
14497
14498enum OriginalExprKind {
14499 OEK_Variable,
14500 OEK_Member,
14501 OEK_LValue
14502};
14503
14504static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14505 const RecordType *Ty,
14506 SourceLocation Loc, SourceRange Range,
14507 OriginalExprKind OEK,
14508 bool &DiagnosticEmitted) {
14509 std::vector<const RecordType *> RecordTypeList;
14510 RecordTypeList.push_back(x: Ty);
14511 unsigned NextToCheckIndex = 0;
14512 // We walk the record hierarchy breadth-first to ensure that we print
14513 // diagnostics in field nesting order.
14514 while (RecordTypeList.size() > NextToCheckIndex) {
14515 bool IsNested = NextToCheckIndex > 0;
14516 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14517 ->getDecl()
14518 ->getDefinitionOrSelf()
14519 ->fields()) {
14520 // First, check every field for constness.
14521 QualType FieldTy = Field->getType();
14522 if (FieldTy.isConstQualified()) {
14523 if (!DiagnosticEmitted) {
14524 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14525 << Range << NestedConstMember << OEK << VD
14526 << IsNested << Field;
14527 DiagnosticEmitted = true;
14528 }
14529 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14530 << NestedConstMember << IsNested << Field
14531 << FieldTy << Field->getSourceRange();
14532 }
14533
14534 // Then we append it to the list to check next in order.
14535 FieldTy = FieldTy.getCanonicalType();
14536 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14537 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14538 RecordTypeList.push_back(x: FieldRecTy);
14539 }
14540 }
14541 ++NextToCheckIndex;
14542 }
14543}
14544
14545/// Emit an error for the case where a record we are trying to assign to has a
14546/// const-qualified field somewhere in its hierarchy.
14547static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14548 SourceLocation Loc) {
14549 QualType Ty = E->getType();
14550 assert(Ty->isRecordType() && "lvalue was not record?");
14551 SourceRange Range = E->getSourceRange();
14552 const auto *RTy = Ty->getAsCanonical<RecordType>();
14553 bool DiagEmitted = false;
14554
14555 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14556 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14557 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14558 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14559 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14560 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14561 else
14562 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14563 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14564 if (!DiagEmitted)
14565 DiagnoseConstAssignment(S, E, Loc);
14566}
14567
14568/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14569/// emit an error and return true. If so, return false.
14570static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14571 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14572
14573 S.CheckShadowingDeclModification(E, Loc);
14574
14575 SourceLocation OrigLoc = Loc;
14576 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14577 Loc: &Loc);
14578 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14579 IsLV = Expr::MLV_InvalidMessageExpression;
14580 if (IsLV == Expr::MLV_Valid)
14581 return false;
14582
14583 unsigned DiagID = 0;
14584 bool NeedType = false;
14585 switch (IsLV) { // C99 6.5.16p2
14586 case Expr::MLV_ConstQualified:
14587 // Use a specialized diagnostic when we're assigning to an object
14588 // from an enclosing function or block.
14589 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14590 if (NCCK == NCCK_Block)
14591 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14592 else
14593 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14594 break;
14595 }
14596
14597 // In ARC, use some specialized diagnostics for occasions where we
14598 // infer 'const'. These are always pseudo-strong variables.
14599 if (S.getLangOpts().ObjCAutoRefCount) {
14600 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14601 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14602 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14603
14604 // Use the normal diagnostic if it's pseudo-__strong but the
14605 // user actually wrote 'const'.
14606 if (var->isARCPseudoStrong() &&
14607 (!var->getTypeSourceInfo() ||
14608 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14609 // There are three pseudo-strong cases:
14610 // - self
14611 ObjCMethodDecl *method = S.getCurMethodDecl();
14612 if (method && var == method->getSelfDecl()) {
14613 DiagID = method->isClassMethod()
14614 ? diag::err_typecheck_arc_assign_self_class_method
14615 : diag::err_typecheck_arc_assign_self;
14616
14617 // - Objective-C externally_retained attribute.
14618 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14619 isa<ParmVarDecl>(Val: var)) {
14620 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14621
14622 // - fast enumeration variables
14623 } else {
14624 DiagID = diag::err_typecheck_arr_assign_enumeration;
14625 }
14626
14627 SourceRange Assign;
14628 if (Loc != OrigLoc)
14629 Assign = SourceRange(OrigLoc, OrigLoc);
14630 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14631 // We need to preserve the AST regardless, so migration tool
14632 // can do its job.
14633 return false;
14634 }
14635 }
14636 }
14637
14638 // If none of the special cases above are triggered, then this is a
14639 // simple const assignment.
14640 if (DiagID == 0) {
14641 DiagnoseConstAssignment(S, E, Loc);
14642 return true;
14643 }
14644
14645 break;
14646 case Expr::MLV_ConstAddrSpace:
14647 DiagnoseConstAssignment(S, E, Loc);
14648 return true;
14649 case Expr::MLV_ConstQualifiedField:
14650 DiagnoseRecursiveConstFields(S, E, Loc);
14651 return true;
14652 case Expr::MLV_ArrayType:
14653 case Expr::MLV_ArrayTemporary:
14654 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14655 NeedType = true;
14656 break;
14657 case Expr::MLV_NotObjectType:
14658 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14659 NeedType = true;
14660 break;
14661 case Expr::MLV_LValueCast:
14662 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14663 break;
14664 case Expr::MLV_Valid:
14665 llvm_unreachable("did not take early return for MLV_Valid");
14666 case Expr::MLV_InvalidExpression:
14667 case Expr::MLV_MemberFunction:
14668 case Expr::MLV_ClassTemporary: {
14669 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E)) {
14670 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14671 if (UnaryOp->getOpcode() == UO_Imag &&
14672 !Op->getType()->isAnyComplexType()) {
14673 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14674 NeedType = true;
14675 break;
14676 }
14677 }
14678
14679 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14680 break;
14681 }
14682 case Expr::MLV_IncompleteType:
14683 case Expr::MLV_IncompleteVoidType:
14684 return S.RequireCompleteType(Loc, T: E->getType(),
14685 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14686 case Expr::MLV_DuplicateVectorComponents:
14687 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14688 break;
14689 case Expr::MLV_DuplicateMatrixComponents:
14690 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14691 break;
14692 case Expr::MLV_NoSetterProperty:
14693 llvm_unreachable("readonly properties should be processed differently");
14694 case Expr::MLV_InvalidMessageExpression:
14695 DiagID = diag::err_readonly_message_assignment;
14696 break;
14697 case Expr::MLV_SubObjCPropertySetting:
14698 DiagID = diag::err_no_subobject_property_setting;
14699 break;
14700 }
14701
14702 SourceRange Assign;
14703 if (Loc != OrigLoc)
14704 Assign = SourceRange(OrigLoc, OrigLoc);
14705 if (NeedType)
14706 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14707 else
14708 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14709 return true;
14710}
14711
14712static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14713 SourceLocation Loc,
14714 Sema &Sema) {
14715 if (Sema.inTemplateInstantiation())
14716 return;
14717 if (Sema.isUnevaluatedContext())
14718 return;
14719 if (Loc.isInvalid() || Loc.isMacroID())
14720 return;
14721 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14722 return;
14723
14724 // C / C++ fields
14725 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14726 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14727 if (ML && MR) {
14728 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14729 return;
14730 const ValueDecl *LHSDecl =
14731 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14732 const ValueDecl *RHSDecl =
14733 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14734 if (LHSDecl != RHSDecl)
14735 return;
14736 if (LHSDecl->getType().isVolatileQualified())
14737 return;
14738 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14739 if (RefTy->getPointeeType().isVolatileQualified())
14740 return;
14741
14742 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14743 }
14744
14745 // Objective-C instance variables
14746 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14747 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14748 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14749 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14750 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14751 if (RL && RR && RL->getDecl() == RR->getDecl())
14752 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14753 }
14754}
14755
14756// C99 6.5.16.1
14757QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14758 SourceLocation Loc,
14759 QualType CompoundType,
14760 BinaryOperatorKind Opc) {
14761 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14762
14763 // Verify that LHS is a modifiable lvalue, and emit error if not.
14764 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14765 return QualType();
14766
14767 QualType LHSType = LHSExpr->getType();
14768 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14769 CompoundType;
14770
14771 if (RHS.isUsable()) {
14772 // Even if this check fails don't return early to allow the best
14773 // possible error recovery and to allow any subsequent diagnostics to
14774 // work.
14775 const ValueDecl *Assignee = nullptr;
14776 bool ShowFullyQualifiedAssigneeName = false;
14777 // In simple cases describe what is being assigned to
14778 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14779 Assignee = DR->getDecl();
14780 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14781 Assignee = ME->getMemberDecl();
14782 ShowFullyQualifiedAssigneeName = true;
14783 }
14784
14785 BoundsSafetyCheckAssignmentToCountAttrPtr(
14786 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14787 ShowFullyQualifiedAssigneeName);
14788 }
14789
14790 // OpenCL v1.2 s6.1.1.1 p2:
14791 // The half data type can only be used to declare a pointer to a buffer that
14792 // contains half values
14793 if (getLangOpts().OpenCL &&
14794 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14795 LHSType->isHalfType()) {
14796 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14797 << LHSType.getUnqualifiedType();
14798 return QualType();
14799 }
14800
14801 // WebAssembly tables can't be used on RHS of an assignment expression.
14802 if (RHSType->isWebAssemblyTableType()) {
14803 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14804 return QualType();
14805 }
14806
14807 AssignConvertType ConvTy;
14808 if (CompoundType.isNull()) {
14809 Expr *RHSCheck = RHS.get();
14810
14811 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14812
14813 QualType LHSTy(LHSType);
14814 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14815 if (RHS.isInvalid())
14816 return QualType();
14817 // Special case of NSObject attributes on c-style pointer types.
14818 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14819 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14820 RHSType->isObjCObjectPointerType()) ||
14821 (Context.isObjCNSObjectType(Ty: RHSType) &&
14822 LHSType->isObjCObjectPointerType())))
14823 ConvTy = AssignConvertType::Compatible;
14824
14825 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14826 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14827
14828 // If the RHS is a unary plus or minus, check to see if they = and + are
14829 // right next to each other. If so, the user may have typo'd "x =+ 4"
14830 // instead of "x += 4".
14831 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14832 RHSCheck = ICE->getSubExpr();
14833 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14834 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14835 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14836 // Only if the two operators are exactly adjacent.
14837 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14838 // And there is a space or other character before the subexpr of the
14839 // unary +/-. We don't want to warn on "x=-1".
14840 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14841 UO->getSubExpr()->getBeginLoc().isFileID()) {
14842 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14843 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14844 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14845 }
14846 }
14847
14848 if (IsAssignConvertCompatible(ConvTy)) {
14849 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14850 // Warn about retain cycles where a block captures the LHS, but
14851 // not if the LHS is a simple variable into which the block is
14852 // being stored...unless that variable can be captured by reference!
14853 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14854 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14855 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14856 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14857 }
14858
14859 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14860 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14861 // It is safe to assign a weak reference into a strong variable.
14862 // Although this code can still have problems:
14863 // id x = self.weakProp;
14864 // id y = self.weakProp;
14865 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14866 // paths through the function. This should be revisited if
14867 // -Wrepeated-use-of-weak is made flow-sensitive.
14868 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14869 // variable, which will be valid for the current autorelease scope.
14870 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14871 Loc: RHS.get()->getBeginLoc()))
14872 getCurFunction()->markSafeWeakUse(E: RHS.get());
14873
14874 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14875 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14876 }
14877 }
14878 } else {
14879 // Compound assignment "x += y"
14880 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14881 }
14882
14883 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14884 Action: AssignmentAction::Assigning))
14885 return QualType();
14886
14887 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14888
14889 AssignedEntity AE{.LHS: LHSExpr};
14890 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14891
14892 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14893 if (CompoundType.isNull()) {
14894 // C++2a [expr.ass]p5:
14895 // A simple-assignment whose left operand is of a volatile-qualified
14896 // type is deprecated unless the assignment is either a discarded-value
14897 // expression or an unevaluated operand
14898 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14899 }
14900 }
14901
14902 // C11 6.5.16p3: The type of an assignment expression is the type of the
14903 // left operand would have after lvalue conversion.
14904 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14905 // qualified type, the value has the unqualified version of the type of the
14906 // lvalue; additionally, if the lvalue has atomic type, the value has the
14907 // non-atomic version of the type of the lvalue.
14908 // C++ 5.17p1: the type of the assignment expression is that of its left
14909 // operand.
14910 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14911}
14912
14913// Scenarios to ignore if expression E is:
14914// 1. an explicit cast expression into void
14915// 2. a function call expression that returns void
14916static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14917 E = E->IgnoreParens();
14918
14919 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14920 if (CE->getCastKind() == CK_ToVoid) {
14921 return true;
14922 }
14923
14924 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14925 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14926 CE->getSubExpr()->getType()->isDependentType()) {
14927 return true;
14928 }
14929 }
14930
14931 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14932 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14933 return false;
14934}
14935
14936void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14937 // No warnings in macros
14938 if (Loc.isMacroID())
14939 return;
14940
14941 // Don't warn in template instantiations.
14942 if (inTemplateInstantiation())
14943 return;
14944
14945 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14946 // instead, skip more than needed, then call back into here with the
14947 // CommaVisitor in SemaStmt.cpp.
14948 // The listed locations are the initialization and increment portions
14949 // of a for loop. The additional checks are on the condition of
14950 // if statements, do/while loops, and for loops.
14951 if (getCurScope()->isControlScope())
14952 return;
14953
14954 // If there are multiple comma operators used together, get the RHS of the
14955 // of the comma operator as the LHS.
14956 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14957 if (BO->getOpcode() != BO_Comma)
14958 break;
14959 LHS = BO->getRHS();
14960 }
14961
14962 // Only allow some expressions on LHS to not warn.
14963 if (IgnoreCommaOperand(E: LHS, Context))
14964 return;
14965
14966 Diag(Loc, DiagID: diag::warn_comma_operator);
14967 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14968 << LHS->getSourceRange()
14969 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14970 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14971 : "(void)(")
14972 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14973 Code: ")");
14974}
14975
14976// C99 6.5.17
14977static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14978 SourceLocation Loc) {
14979 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14980 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14981 if (LHS.isInvalid() || RHS.isInvalid())
14982 return QualType();
14983
14984 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14985 // operands, but not unary promotions.
14986 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14987
14988 // So we treat the LHS as a ignored value, and in C++ we allow the
14989 // containing site to determine what should be done with the RHS.
14990 LHS = S.IgnoredValueConversions(E: LHS.get());
14991 if (LHS.isInvalid())
14992 return QualType();
14993
14994 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14995
14996 if (!S.getLangOpts().CPlusPlus) {
14997 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14998 if (RHS.isInvalid())
14999 return QualType();
15000 if (!RHS.get()->getType()->isVoidType())
15001 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
15002 DiagID: diag::err_incomplete_type);
15003 }
15004
15005 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
15006 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
15007
15008 return RHS.get()->getType();
15009}
15010
15011/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
15012/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
15013static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
15014 ExprValueKind &VK,
15015 ExprObjectKind &OK,
15016 SourceLocation OpLoc, bool IsInc,
15017 bool IsPrefix) {
15018 QualType ResType = Op->getType();
15019 // Atomic types can be used for increment / decrement where the non-atomic
15020 // versions can, so ignore the _Atomic() specifier for the purpose of
15021 // checking.
15022 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
15023 ResType = ResAtomicType->getValueType();
15024
15025 assert(!ResType.isNull() && "no type for increment/decrement expression");
15026
15027 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
15028 // Decrement of bool is not allowed.
15029 if (!IsInc) {
15030 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
15031 return QualType();
15032 }
15033 // Increment of bool sets it to true, but is deprecated.
15034 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
15035 : diag::warn_increment_bool)
15036 << Op->getSourceRange();
15037 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
15038 // Error on enum increments and decrements in C++ mode
15039 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
15040 return QualType();
15041 } else if (ResType->isRealType()) {
15042 // OK!
15043 } else if (ResType->isPointerType()) {
15044 // C99 6.5.2.4p2, 6.5.6p2
15045 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
15046 return QualType();
15047 } else if (ResType->isOverflowBehaviorType()) {
15048 // OK!
15049 } else if (ResType->isObjCObjectPointerType()) {
15050 // On modern runtimes, ObjC pointer arithmetic is forbidden.
15051 // Otherwise, we just need a complete type.
15052 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
15053 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
15054 return QualType();
15055 } else if (ResType->isAnyComplexType()) {
15056 // C99 does not support ++/-- on complex types, we allow as an extension.
15057 S.DiagCompat(Loc: OpLoc, CompatDiagId: diag_compat::increment_complex)
15058 << IsInc << Op->getSourceRange();
15059 } else if (ResType->isPlaceholderType()) {
15060 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15061 if (PR.isInvalid()) return QualType();
15062 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
15063 IsInc, IsPrefix);
15064 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15065 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15066 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15067 (ResType->castAs<VectorType>()->getVectorKind() !=
15068 VectorKind::AltiVecBool)) {
15069 // The z vector extensions allow ++ and -- for non-bool vectors.
15070 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15071 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15072 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15073 } else {
15074 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
15075 << ResType << int(IsInc) << Op->getSourceRange();
15076 return QualType();
15077 }
15078 // At this point, we know we have a real, complex or pointer type.
15079 // Now make sure the operand is a modifiable lvalue.
15080 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
15081 return QualType();
15082 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15083 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15084 // An operand with volatile-qualified type is deprecated
15085 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
15086 << IsInc << ResType;
15087 }
15088 // In C++, a prefix increment is the same type as the operand. Otherwise
15089 // (in C or with postfix), the increment is the unqualified type of the
15090 // operand.
15091 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15092 VK = VK_LValue;
15093 OK = Op->getObjectKind();
15094 return ResType;
15095 } else {
15096 VK = VK_PRValue;
15097 return ResType.getUnqualifiedType();
15098 }
15099}
15100
15101/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15102/// This routine allows us to typecheck complex/recursive expressions
15103/// where the declaration is needed for type checking. We only need to
15104/// handle cases when the expression references a function designator
15105/// or is an lvalue. Here are some examples:
15106/// - &(x) => x
15107/// - &*****f => f for f a function designator.
15108/// - &s.xx => s
15109/// - &s.zz[1].yy -> s, if zz is an array
15110/// - *(x + 1) -> x, if x is an array
15111/// - &"123"[2] -> 0
15112/// - & __real__ x -> x
15113///
15114/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15115/// members.
15116static ValueDecl *getPrimaryDecl(Expr *E) {
15117 switch (E->getStmtClass()) {
15118 case Stmt::DeclRefExprClass:
15119 return cast<DeclRefExpr>(Val: E)->getDecl();
15120 case Stmt::MemberExprClass:
15121 // If this is an arrow operator, the address is an offset from
15122 // the base's value, so the object the base refers to is
15123 // irrelevant.
15124 if (cast<MemberExpr>(Val: E)->isArrow())
15125 return nullptr;
15126 // Otherwise, the expression refers to a part of the base
15127 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
15128 case Stmt::ArraySubscriptExprClass: {
15129 // FIXME: This code shouldn't be necessary! We should catch the implicit
15130 // promotion of register arrays earlier.
15131 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
15132 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
15133 if (ICE->getSubExpr()->getType()->isArrayType())
15134 return getPrimaryDecl(E: ICE->getSubExpr());
15135 }
15136 return nullptr;
15137 }
15138 case Stmt::UnaryOperatorClass: {
15139 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
15140
15141 switch(UO->getOpcode()) {
15142 case UO_Real:
15143 case UO_Imag:
15144 case UO_Extension:
15145 return getPrimaryDecl(E: UO->getSubExpr());
15146 default:
15147 return nullptr;
15148 }
15149 }
15150 case Stmt::ParenExprClass:
15151 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
15152 case Stmt::ImplicitCastExprClass:
15153 // If the result of an implicit cast is an l-value, we care about
15154 // the sub-expression; otherwise, the result here doesn't matter.
15155 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
15156 case Stmt::CXXUuidofExprClass:
15157 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
15158 default:
15159 return nullptr;
15160 }
15161}
15162
15163namespace {
15164enum {
15165 AO_Bit_Field = 0,
15166 AO_Vector_Element = 1,
15167 AO_Property_Expansion = 2,
15168 AO_Register_Variable = 3,
15169 AO_Matrix_Element = 4,
15170 AO_No_Error = 5
15171};
15172}
15173/// Diagnose invalid operand for address of operations.
15174///
15175/// \param Type The type of operand which cannot have its address taken.
15176static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
15177 Expr *E, unsigned Type) {
15178 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
15179}
15180
15181bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
15182 const Expr *Op,
15183 const CXXMethodDecl *MD) {
15184 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
15185
15186 if (Op != DRE)
15187 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
15188 << Op->getSourceRange();
15189
15190 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15191 if (isa<CXXDestructorDecl>(Val: MD))
15192 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
15193 << DRE->getSourceRange();
15194
15195 if (DRE->getQualifier())
15196 return false;
15197
15198 if (MD->getParent()->getName().empty())
15199 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15200 << DRE->getSourceRange();
15201
15202 SmallString<32> Str;
15203 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
15204 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
15205 << DRE->getSourceRange()
15206 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
15207}
15208
15209QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15210 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15211 if (PTy->getKind() == BuiltinType::Overload) {
15212 Expr *E = OrigOp.get()->IgnoreParens();
15213 if (!isa<OverloadExpr>(Val: E)) {
15214 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15215 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15216 << OrigOp.get()->getSourceRange();
15217 return QualType();
15218 }
15219
15220 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
15221 if (isa<UnresolvedMemberExpr>(Val: Ovl))
15222 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
15223 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15224 << OrigOp.get()->getSourceRange();
15225 return QualType();
15226 }
15227
15228 return Context.OverloadTy;
15229 }
15230
15231 if (PTy->getKind() == BuiltinType::UnknownAny)
15232 return Context.UnknownAnyTy;
15233
15234 if (PTy->getKind() == BuiltinType::BoundMember) {
15235 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15236 << OrigOp.get()->getSourceRange();
15237 return QualType();
15238 }
15239
15240 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
15241 if (OrigOp.isInvalid()) return QualType();
15242 }
15243
15244 if (OrigOp.get()->isTypeDependent())
15245 return Context.DependentTy;
15246
15247 assert(!OrigOp.get()->hasPlaceholderType());
15248
15249 // Make sure to ignore parentheses in subsequent checks
15250 Expr *op = OrigOp.get()->IgnoreParens();
15251
15252 // In OpenCL captures for blocks called as lambda functions
15253 // are located in the private address space. Blocks used in
15254 // enqueue_kernel can be located in a different address space
15255 // depending on a vendor implementation. Thus preventing
15256 // taking an address of the capture to avoid invalid AS casts.
15257 if (LangOpts.OpenCL) {
15258 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
15259 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15260 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
15261 return QualType();
15262 }
15263 }
15264
15265 if (getLangOpts().C99) {
15266 // Implement C99-only parts of addressof rules.
15267 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
15268 if (uOp->getOpcode() == UO_Deref)
15269 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15270 // (assuming the deref expression is valid).
15271 return uOp->getSubExpr()->getType();
15272 }
15273 // Technically, there should be a check for array subscript
15274 // expressions here, but the result of one is always an lvalue anyway.
15275 }
15276 ValueDecl *dcl = getPrimaryDecl(E: op);
15277
15278 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15279 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15280 Loc: op->getBeginLoc()))
15281 return QualType();
15282
15283 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15284 unsigned AddressOfError = AO_No_Error;
15285
15286 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15287 bool IsError = isSFINAEContext();
15288 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15289 : diag::ext_typecheck_addrof_temporary)
15290 << op->getType() << op->getSourceRange();
15291 if (IsError)
15292 return QualType();
15293 // Materialize the temporary as an lvalue so that we can take its address.
15294 OrigOp = op =
15295 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15296 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15297 return Context.getPointerType(T: op->getType());
15298 } else if (lval == Expr::LV_MemberFunction) {
15299 // If it's an instance method, make a member pointer.
15300 // The expression must have exactly the form &A::foo.
15301
15302 // If the underlying expression isn't a decl ref, give up.
15303 if (!isa<DeclRefExpr>(Val: op)) {
15304 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15305 << OrigOp.get()->getSourceRange();
15306 return QualType();
15307 }
15308 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15309 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15310
15311 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15312 QualType MPTy = Context.getMemberPointerType(
15313 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15314
15315 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15316 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15317 // When pointer authentication is enabled, argument and return types of
15318 // vitual member functions must be complete. This is because vitrual
15319 // member function pointers are implemented using virtual dispatch
15320 // thunks and the thunks cannot be emitted if the argument or return
15321 // types are incomplete.
15322 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15323 SourceLocation DeclRefLoc,
15324 SourceLocation RetArgTypeLoc) {
15325 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15326 Diag(Loc: DeclRefLoc,
15327 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15328 Diag(Loc: RetArgTypeLoc,
15329 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15330 << T;
15331 return true;
15332 }
15333 return false;
15334 };
15335 QualType RetTy = MD->getReturnType();
15336 bool IsIncomplete =
15337 !RetTy->isVoidType() &&
15338 ReturnOrParamTypeIsIncomplete(
15339 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15340 for (auto *PVD : MD->parameters())
15341 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15342 PVD->getBeginLoc());
15343 if (IsIncomplete)
15344 return QualType();
15345 }
15346
15347 // Under the MS ABI, lock down the inheritance model now.
15348 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15349 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15350 return MPTy;
15351 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15352 // C99 6.5.3.2p1
15353 // The operand must be either an l-value or a function designator
15354 if (!op->getType()->isFunctionType()) {
15355 // Use a special diagnostic for loads from property references.
15356 if (isa<PseudoObjectExpr>(Val: op)) {
15357 AddressOfError = AO_Property_Expansion;
15358 } else {
15359 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15360 << op->getType() << op->getSourceRange();
15361 return QualType();
15362 }
15363 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15364 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15365 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15366 }
15367
15368 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15369 // The operand cannot be a bit-field
15370 AddressOfError = AO_Bit_Field;
15371 } else if (op->getObjectKind() == OK_VectorComponent) {
15372 // The operand cannot be an element of a vector
15373 AddressOfError = AO_Vector_Element;
15374 } else if (op->getObjectKind() == OK_MatrixComponent) {
15375 // The operand cannot be an element of a matrix.
15376 AddressOfError = AO_Matrix_Element;
15377 } else if (dcl) { // C99 6.5.3.2p1
15378 // We have an lvalue with a decl. Make sure the decl is not declared
15379 // with the register storage-class specifier.
15380 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15381 // in C++ it is not error to take address of a register
15382 // variable (c++03 7.1.1P3)
15383 if (vd->getStorageClass() == SC_Register &&
15384 !getLangOpts().CPlusPlus) {
15385 AddressOfError = AO_Register_Variable;
15386 }
15387 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15388 AddressOfError = AO_Property_Expansion;
15389 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15390 return Context.OverloadTy;
15391 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15392 // Okay: we can take the address of a field.
15393 // Could be a pointer to member, though, if there is an explicit
15394 // scope qualifier for the class.
15395
15396 // [C++26] [expr.prim.id.general]
15397 // If an id-expression E denotes a non-static non-type member
15398 // of some class C [...] and if E is a qualified-id, E is
15399 // not the un-parenthesized operand of the unary & operator [...]
15400 // the id-expression is transformed into a class member access expression.
15401 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15402 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15403 DeclContext *Ctx = dcl->getDeclContext();
15404 if (Ctx && Ctx->isRecord()) {
15405 if (dcl->getType()->isReferenceType()) {
15406 Diag(Loc: OpLoc,
15407 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15408 << dcl->getDeclName() << dcl->getType();
15409 return QualType();
15410 }
15411
15412 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15413 Ctx = Ctx->getParent();
15414
15415 QualType MPTy = Context.getMemberPointerType(
15416 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15417 // Under the MS ABI, lock down the inheritance model now.
15418 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15419 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15420 return MPTy;
15421 }
15422 }
15423 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15424 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15425 UnnamedGlobalConstantDecl>(Val: dcl))
15426 llvm_unreachable("Unknown/unexpected decl type");
15427 }
15428
15429 if (AddressOfError != AO_No_Error) {
15430 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15431 return QualType();
15432 }
15433
15434 if (lval == Expr::LV_IncompleteVoidType) {
15435 // Taking the address of a void variable is technically illegal, but we
15436 // allow it in cases which are otherwise valid.
15437 // Example: "extern void x; void* y = &x;".
15438 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15439 }
15440
15441 // If the operand has type "type", the result has type "pointer to type".
15442 if (op->getType()->isObjCObjectType())
15443 return Context.getObjCObjectPointerType(OIT: op->getType());
15444
15445 // Cannot take the address of WebAssembly references or tables.
15446 if (Context.getTargetInfo().getTriple().isWasm()) {
15447 QualType OpTy = op->getType();
15448 if (OpTy.isWebAssemblyReferenceType()) {
15449 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15450 << 1 << OrigOp.get()->getSourceRange();
15451 return QualType();
15452 }
15453 if (OpTy->isWebAssemblyTableType()) {
15454 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15455 << 1 << OrigOp.get()->getSourceRange();
15456 return QualType();
15457 }
15458 }
15459
15460 CheckAddressOfPackedMember(rhs: op);
15461
15462 return Context.getPointerType(T: op->getType());
15463}
15464
15465static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15466 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15467 if (!DRE)
15468 return;
15469 const Decl *D = DRE->getDecl();
15470 if (!D)
15471 return;
15472 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15473 if (!Param)
15474 return;
15475 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15476 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15477 return;
15478 if (FunctionScopeInfo *FD = S.getCurFunction())
15479 FD->ModifiedNonNullParams.insert(Ptr: Param);
15480}
15481
15482/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15483static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15484 SourceLocation OpLoc,
15485 bool IsAfterAmp = false) {
15486 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15487 if (ConvResult.isInvalid())
15488 return QualType();
15489 Op = ConvResult.get();
15490 QualType OpTy = Op->getType();
15491 QualType Result;
15492
15493 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15494 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15495 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15496 Range: Op->getSourceRange());
15497 }
15498
15499 if (const PointerType *PT = OpTy->getAs<PointerType>())
15500 {
15501 Result = PT->getPointeeType();
15502 }
15503 else if (const ObjCObjectPointerType *OPT =
15504 OpTy->getAs<ObjCObjectPointerType>())
15505 Result = OPT->getPointeeType();
15506 else {
15507 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15508 if (PR.isInvalid()) return QualType();
15509 if (PR.get() != Op)
15510 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15511 }
15512
15513 if (Result.isNull()) {
15514 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15515 << OpTy << Op->getSourceRange();
15516 return QualType();
15517 }
15518
15519 if (Result->isVoidType()) {
15520 // C++ [expr.unary.op]p1:
15521 // [...] the expression to which [the unary * operator] is applied shall
15522 // be a pointer to an object type, or a pointer to a function type
15523 LangOptions LO = S.getLangOpts();
15524 if (LO.CPlusPlus)
15525 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15526 << OpTy << Op->getSourceRange();
15527 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15528 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15529 << OpTy << Op->getSourceRange();
15530 }
15531
15532 // Dereferences are usually l-values...
15533 VK = VK_LValue;
15534
15535 // ...except that certain expressions are never l-values in C.
15536 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15537 VK = VK_PRValue;
15538
15539 return Result;
15540}
15541
15542BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15543 BinaryOperatorKind Opc;
15544 switch (Kind) {
15545 default: llvm_unreachable("Unknown binop!");
15546 case tok::periodstar: Opc = BO_PtrMemD; break;
15547 case tok::arrowstar: Opc = BO_PtrMemI; break;
15548 case tok::star: Opc = BO_Mul; break;
15549 case tok::slash: Opc = BO_Div; break;
15550 case tok::percent: Opc = BO_Rem; break;
15551 case tok::plus: Opc = BO_Add; break;
15552 case tok::minus: Opc = BO_Sub; break;
15553 case tok::lessless: Opc = BO_Shl; break;
15554 case tok::greatergreater: Opc = BO_Shr; break;
15555 case tok::lessequal: Opc = BO_LE; break;
15556 case tok::less: Opc = BO_LT; break;
15557 case tok::greaterequal: Opc = BO_GE; break;
15558 case tok::greater: Opc = BO_GT; break;
15559 case tok::exclaimequal: Opc = BO_NE; break;
15560 case tok::equalequal: Opc = BO_EQ; break;
15561 case tok::spaceship: Opc = BO_Cmp; break;
15562 case tok::amp: Opc = BO_And; break;
15563 case tok::caret: Opc = BO_Xor; break;
15564 case tok::pipe: Opc = BO_Or; break;
15565 case tok::ampamp: Opc = BO_LAnd; break;
15566 case tok::pipepipe: Opc = BO_LOr; break;
15567 case tok::equal: Opc = BO_Assign; break;
15568 case tok::starequal: Opc = BO_MulAssign; break;
15569 case tok::slashequal: Opc = BO_DivAssign; break;
15570 case tok::percentequal: Opc = BO_RemAssign; break;
15571 case tok::plusequal: Opc = BO_AddAssign; break;
15572 case tok::minusequal: Opc = BO_SubAssign; break;
15573 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15574 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15575 case tok::ampequal: Opc = BO_AndAssign; break;
15576 case tok::caretequal: Opc = BO_XorAssign; break;
15577 case tok::pipeequal: Opc = BO_OrAssign; break;
15578 case tok::comma: Opc = BO_Comma; break;
15579 }
15580 return Opc;
15581}
15582
15583static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15584 tok::TokenKind Kind) {
15585 UnaryOperatorKind Opc;
15586 switch (Kind) {
15587 default: llvm_unreachable("Unknown unary op!");
15588 case tok::plusplus: Opc = UO_PreInc; break;
15589 case tok::minusminus: Opc = UO_PreDec; break;
15590 case tok::amp: Opc = UO_AddrOf; break;
15591 case tok::star: Opc = UO_Deref; break;
15592 case tok::plus: Opc = UO_Plus; break;
15593 case tok::minus: Opc = UO_Minus; break;
15594 case tok::tilde: Opc = UO_Not; break;
15595 case tok::exclaim: Opc = UO_LNot; break;
15596 case tok::kw___real: Opc = UO_Real; break;
15597 case tok::kw___imag: Opc = UO_Imag; break;
15598 case tok::kw___extension__: Opc = UO_Extension; break;
15599 }
15600 return Opc;
15601}
15602
15603const FieldDecl *
15604Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15605 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15606 // common for setters.
15607 // struct A {
15608 // int X;
15609 // -void setX(int X) { X = X; }
15610 // +void setX(int X) { this->X = X; }
15611 // };
15612
15613 // Only consider parameters for self assignment fixes.
15614 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15615 return nullptr;
15616 const auto *Method =
15617 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15618 if (!Method)
15619 return nullptr;
15620
15621 const CXXRecordDecl *Parent = Method->getParent();
15622 // In theory this is fixable if the lambda explicitly captures this, but
15623 // that's added complexity that's rarely going to be used.
15624 if (Parent->isLambda())
15625 return nullptr;
15626
15627 // FIXME: Use an actual Lookup operation instead of just traversing fields
15628 // in order to get base class fields.
15629 auto Field =
15630 llvm::find_if(Range: Parent->fields(),
15631 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15632 return F->getDeclName() == Name;
15633 });
15634 return (Field != Parent->field_end()) ? *Field : nullptr;
15635}
15636
15637/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15638/// This warning suppressed in the event of macro expansions.
15639static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15640 SourceLocation OpLoc, bool IsBuiltin) {
15641 if (S.inTemplateInstantiation())
15642 return;
15643 if (S.isUnevaluatedContext())
15644 return;
15645 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15646 return;
15647 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15648 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15649 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15650 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15651 if (!LHSDeclRef || !RHSDeclRef ||
15652 LHSDeclRef->getLocation().isMacroID() ||
15653 RHSDeclRef->getLocation().isMacroID())
15654 return;
15655 const ValueDecl *LHSDecl =
15656 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15657 const ValueDecl *RHSDecl =
15658 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15659 if (LHSDecl != RHSDecl)
15660 return;
15661 if (LHSDecl->getType().isVolatileQualified())
15662 return;
15663 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15664 if (RefTy->getPointeeType().isVolatileQualified())
15665 return;
15666
15667 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15668 : diag::warn_self_assignment_overloaded)
15669 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15670 << RHSExpr->getSourceRange();
15671 if (const FieldDecl *SelfAssignField =
15672 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15673 Diag << 1 << SelfAssignField
15674 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15675 else
15676 Diag << 0;
15677}
15678
15679/// Check if a bitwise-& is performed on an Objective-C pointer. This
15680/// is usually indicative of introspection within the Objective-C pointer.
15681static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15682 SourceLocation OpLoc) {
15683 if (!S.getLangOpts().ObjC)
15684 return;
15685
15686 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15687 const Expr *LHS = L.get();
15688 const Expr *RHS = R.get();
15689
15690 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15691 ObjCPointerExpr = LHS;
15692 OtherExpr = RHS;
15693 }
15694 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15695 ObjCPointerExpr = RHS;
15696 OtherExpr = LHS;
15697 }
15698
15699 // This warning is deliberately made very specific to reduce false
15700 // positives with logic that uses '&' for hashing. This logic mainly
15701 // looks for code trying to introspect into tagged pointers, which
15702 // code should generally never do.
15703 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15704 unsigned Diag = diag::warn_objc_pointer_masking;
15705 // Determine if we are introspecting the result of performSelectorXXX.
15706 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15707 // Special case messages to -performSelector and friends, which
15708 // can return non-pointer values boxed in a pointer value.
15709 // Some clients may wish to silence warnings in this subcase.
15710 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15711 Selector S = ME->getSelector();
15712 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15713 if (SelArg0.starts_with(Prefix: "performSelector"))
15714 Diag = diag::warn_objc_pointer_masking_performSelector;
15715 }
15716
15717 S.Diag(Loc: OpLoc, DiagID: Diag)
15718 << ObjCPointerExpr->getSourceRange();
15719 }
15720}
15721
15722// This helper function promotes a binary operator's operands (which are of a
15723// half vector type) to a vector of floats and then truncates the result to
15724// a vector of either half or short.
15725static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15726 BinaryOperatorKind Opc, QualType ResultTy,
15727 ExprValueKind VK, ExprObjectKind OK,
15728 bool IsCompAssign, SourceLocation OpLoc,
15729 FPOptionsOverride FPFeatures) {
15730 auto &Context = S.getASTContext();
15731 assert((isVector(ResultTy, Context.HalfTy) ||
15732 isVector(ResultTy, Context.ShortTy)) &&
15733 "Result must be a vector of half or short");
15734 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15735 isVector(RHS.get()->getType(), Context.HalfTy) &&
15736 "both operands expected to be a half vector");
15737
15738 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15739 QualType BinOpResTy = RHS.get()->getType();
15740
15741 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15742 // change BinOpResTy to a vector of ints.
15743 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15744 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15745
15746 if (IsCompAssign)
15747 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15748 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15749 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15750
15751 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15752 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15753 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15754 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15755}
15756
15757/// Returns true if conversion between vectors of halfs and vectors of floats
15758/// is needed.
15759static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15760 QualType ResultTy, Expr *E0,
15761 Expr *E1 = nullptr) {
15762 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15763 return false;
15764
15765 // The conversion truncates the result to a half/short vector, so it shouldn't
15766 // apply when the result is not that type (e.g. HLSL comparisons).
15767 if (ResultTy->isVectorType() && !isVector(QT: ResultTy, ElementType: Ctx.HalfTy) &&
15768 !isVector(QT: ResultTy, ElementType: Ctx.ShortTy))
15769 return false;
15770
15771 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15772 QualType Ty = E->IgnoreImplicit()->getType();
15773
15774 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15775 // to vectors of floats. Although the element type of the vectors is __fp16,
15776 // the vectors shouldn't be treated as storage-only types. See the
15777 // discussion here: https://reviews.llvm.org/rG825235c140e7
15778 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15779 if (VT->getVectorKind() == VectorKind::Neon)
15780 return false;
15781 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15782 }
15783 return false;
15784 };
15785
15786 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15787}
15788
15789ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15790 BinaryOperatorKind Opc, Expr *LHSExpr,
15791 Expr *RHSExpr, bool ForFoldExpression) {
15792 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15793 // The syntax only allows initializer lists on the RHS of assignment,
15794 // so we don't need to worry about accepting invalid code for
15795 // non-assignment operators.
15796 // C++11 5.17p9:
15797 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15798 // of x = {} is x = T().
15799 InitializationKind Kind = InitializationKind::CreateDirectList(
15800 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15801 InitializedEntity Entity =
15802 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15803 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15804 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15805 if (Init.isInvalid())
15806 return Init;
15807 RHSExpr = Init.get();
15808 }
15809
15810 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15811 QualType ResultTy; // Result type of the binary operator.
15812 // The following two variables are used for compound assignment operators
15813 QualType CompLHSTy; // Type of LHS after promotions for computation
15814 QualType CompResultTy; // Type of computation result
15815 ExprValueKind VK = VK_PRValue;
15816 ExprObjectKind OK = OK_Ordinary;
15817 bool ConvertHalfVec = false;
15818
15819 if (!LHS.isUsable() || !RHS.isUsable())
15820 return ExprError();
15821
15822 if (getLangOpts().OpenCL) {
15823 QualType LHSTy = LHSExpr->getType();
15824 QualType RHSTy = RHSExpr->getType();
15825 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15826 // the ATOMIC_VAR_INIT macro.
15827 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15828 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15829 if (BO_Assign == Opc)
15830 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15831 else
15832 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15833 return ExprError();
15834 }
15835
15836 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15837 // only with a builtin functions and therefore should be disallowed here.
15838 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15839 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15840 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15841 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15842 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15843 return ExprError();
15844 }
15845 }
15846
15847 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15848 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15849
15850 switch (Opc) {
15851 case BO_Assign:
15852 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15853 if (getLangOpts().CPlusPlus &&
15854 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15855 VK = LHS.get()->getValueKind();
15856 OK = LHS.get()->getObjectKind();
15857 }
15858 if (!ResultTy.isNull()) {
15859 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15860 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15861
15862 // Avoid copying a block to the heap if the block is assigned to a local
15863 // auto variable that is declared in the same scope as the block. This
15864 // optimization is unsafe if the local variable is declared in an outer
15865 // scope. For example:
15866 //
15867 // BlockTy b;
15868 // {
15869 // b = ^{...};
15870 // }
15871 // // It is unsafe to invoke the block here if it wasn't copied to the
15872 // // heap.
15873 // b();
15874
15875 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15876 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15877 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15878 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15879 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15880
15881 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15882 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15883 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15884 }
15885 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15886 break;
15887 case BO_PtrMemD:
15888 case BO_PtrMemI:
15889 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15890 isIndirect: Opc == BO_PtrMemI);
15891 break;
15892 case BO_Mul:
15893 case BO_Div:
15894 ConvertHalfVec = true;
15895 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15896 break;
15897 case BO_Rem:
15898 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15899 break;
15900 case BO_Add:
15901 ConvertHalfVec = true;
15902 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15903 break;
15904 case BO_Sub:
15905 ConvertHalfVec = true;
15906 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15907 break;
15908 case BO_Shl:
15909 case BO_Shr:
15910 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15911 break;
15912 case BO_LE:
15913 case BO_LT:
15914 case BO_GE:
15915 case BO_GT:
15916 ConvertHalfVec = true;
15917 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15918
15919 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15920 !ForFoldExpression && BI && BI->isComparisonOp())
15921 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15922 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15923
15924 break;
15925 case BO_EQ:
15926 case BO_NE:
15927 ConvertHalfVec = true;
15928 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15929 break;
15930 case BO_Cmp:
15931 ConvertHalfVec = true;
15932 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15933 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15934 break;
15935 case BO_And:
15936 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15937 [[fallthrough]];
15938 case BO_Xor:
15939 case BO_Or:
15940 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15941 break;
15942 case BO_LAnd:
15943 case BO_LOr:
15944 ConvertHalfVec = true;
15945 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15946 break;
15947 case BO_MulAssign:
15948 case BO_DivAssign:
15949 ConvertHalfVec = true;
15950 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15951 CompLHSTy = CompResultTy;
15952 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15953 ResultTy =
15954 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15955 break;
15956 case BO_RemAssign:
15957 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15958 CompLHSTy = CompResultTy;
15959 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15960 ResultTy =
15961 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15962 break;
15963 case BO_AddAssign:
15964 ConvertHalfVec = true;
15965 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15966 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15967 ResultTy =
15968 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15969 break;
15970 case BO_SubAssign:
15971 ConvertHalfVec = true;
15972 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15973 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15974 ResultTy =
15975 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15976 break;
15977 case BO_ShlAssign:
15978 case BO_ShrAssign:
15979 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15980 CompLHSTy = CompResultTy;
15981 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15982 ResultTy =
15983 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15984 break;
15985 case BO_AndAssign:
15986 case BO_OrAssign: // fallthrough
15987 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15988 [[fallthrough]];
15989 case BO_XorAssign:
15990 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15991 CompLHSTy = CompResultTy;
15992 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15993 ResultTy =
15994 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15995 break;
15996 case BO_Comma:
15997 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15998 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15999 VK = RHS.get()->getValueKind();
16000 OK = RHS.get()->getObjectKind();
16001 }
16002 break;
16003 }
16004 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
16005 return ExprError();
16006
16007 // Some of the binary operations require promoting operands of half vector to
16008 // float vectors and truncating the result back to half vector. For now, we do
16009 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
16010 // arm64).
16011 assert(
16012 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
16013 isVector(LHS.get()->getType(), Context.HalfTy)) &&
16014 "both sides are half vectors or neither sides are");
16015 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, ResultTy,
16016 E0: LHS.get(), E1: RHS.get());
16017
16018 // Check for array bounds violations for both sides of the BinaryOperator
16019 CheckArrayAccess(E: LHS.get());
16020 CheckArrayAccess(E: RHS.get());
16021
16022 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
16023 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
16024 Name: &Context.Idents.get(Name: "object_setClass"),
16025 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
16026 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
16027 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
16028 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
16029 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
16030 Code: "object_setClass(")
16031 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
16032 Code: ",")
16033 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
16034 }
16035 else
16036 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
16037 }
16038 else if (const ObjCIvarRefExpr *OIRE =
16039 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
16040 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
16041
16042 // Opc is not a compound assignment if CompResultTy is null.
16043 if (CompResultTy.isNull()) {
16044 if (ConvertHalfVec)
16045 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
16046 OpLoc, FPFeatures: CurFPFeatureOverrides());
16047 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
16048 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16049 }
16050
16051 // Handle compound assignments.
16052 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16053 OK_ObjCProperty) {
16054 VK = VK_LValue;
16055 OK = LHS.get()->getObjectKind();
16056 }
16057
16058 // The LHS is not converted to the result type for fixed-point compound
16059 // assignment as the common type is computed on demand. Reset the CompLHSTy
16060 // to the LHS type we would have gotten after unary conversions.
16061 if (CompResultTy->isFixedPointType())
16062 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
16063
16064 if (ConvertHalfVec)
16065 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
16066 OpLoc, FPFeatures: CurFPFeatureOverrides());
16067
16068 return CompoundAssignOperator::Create(
16069 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
16070 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
16071}
16072
16073/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16074/// operators are mixed in a way that suggests that the programmer forgot that
16075/// comparison operators have higher precedence. The most typical example of
16076/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16077static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
16078 SourceLocation OpLoc, Expr *LHSExpr,
16079 Expr *RHSExpr) {
16080 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
16081 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
16082
16083 // Check that one of the sides is a comparison operator and the other isn't.
16084 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16085 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16086 if (isLeftComp == isRightComp)
16087 return;
16088
16089 // Bitwise operations are sometimes used as eager logical ops.
16090 // Don't diagnose this.
16091 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16092 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16093 if (isLeftBitwise || isRightBitwise)
16094 return;
16095
16096 SourceRange DiagRange = isLeftComp
16097 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16098 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16099 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16100 SourceRange ParensRange =
16101 isLeftComp
16102 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16103 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16104
16105 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
16106 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
16107 SuggestParentheses(Self, Loc: OpLoc,
16108 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
16109 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16110 SuggestParentheses(Self, Loc: OpLoc,
16111 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
16112 << BinaryOperator::getOpcodeStr(Op: Opc),
16113 ParenRange: ParensRange);
16114}
16115
16116/// It accepts a '&&' expr that is inside a '||' one.
16117/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16118/// in parentheses.
16119static void
16120EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
16121 BinaryOperator *Bop) {
16122 assert(Bop->getOpcode() == BO_LAnd);
16123 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
16124 << Bop->getSourceRange() << OpLoc;
16125 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
16126 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
16127 << Bop->getOpcodeStr(),
16128 ParenRange: Bop->getSourceRange());
16129}
16130
16131/// Look for '&&' in the left hand of a '||' expr.
16132static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
16133 Expr *LHSExpr, Expr *RHSExpr) {
16134 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
16135 if (Bop->getOpcode() == BO_LAnd) {
16136 // If it's "string_literal && a || b" don't warn since the precedence
16137 // doesn't matter.
16138 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
16139 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16140 } else if (Bop->getOpcode() == BO_LOr) {
16141 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
16142 // If it's "a || b && string_literal || c" we didn't warn earlier for
16143 // "a || b && string_literal", but warn now.
16144 if (RBop->getOpcode() == BO_LAnd &&
16145 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
16146 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
16147 }
16148 }
16149 }
16150}
16151
16152/// Look for '&&' in the right hand of a '||' expr.
16153static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
16154 Expr *LHSExpr, Expr *RHSExpr) {
16155 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
16156 if (Bop->getOpcode() == BO_LAnd) {
16157 // If it's "a || b && string_literal" don't warn since the precedence
16158 // doesn't matter.
16159 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
16160 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
16161 }
16162 }
16163}
16164
16165/// Look for bitwise op in the left or right hand of a bitwise op with
16166/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16167/// the '&' expression in parentheses.
16168static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
16169 SourceLocation OpLoc, Expr *SubExpr) {
16170 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16171 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16172 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
16173 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
16174 << Bop->getSourceRange() << OpLoc;
16175 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16176 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16177 << Bop->getOpcodeStr(),
16178 ParenRange: Bop->getSourceRange());
16179 }
16180 }
16181}
16182
16183static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
16184 Expr *SubExpr, StringRef Shift) {
16185 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
16186 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16187 StringRef Op = Bop->getOpcodeStr();
16188 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
16189 << Bop->getSourceRange() << OpLoc << Shift << Op;
16190 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
16191 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
16192 ParenRange: Bop->getSourceRange());
16193 }
16194 }
16195}
16196
16197static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16198 Expr *LHSExpr, Expr *RHSExpr) {
16199 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
16200 if (!OCE)
16201 return;
16202
16203 FunctionDecl *FD = OCE->getDirectCallee();
16204 if (!FD || !FD->isOverloadedOperator())
16205 return;
16206
16207 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16208 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16209 return;
16210
16211 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
16212 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16213 << (Kind == OO_LessLess);
16214 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
16215 Note: S.PDiag(DiagID: diag::note_precedence_silence)
16216 << (Kind == OO_LessLess ? "<<" : ">>"),
16217 ParenRange: OCE->getSourceRange());
16218 SuggestParentheses(
16219 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
16220 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
16221}
16222
16223/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16224/// precedence.
16225static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16226 SourceLocation OpLoc, Expr *LHSExpr,
16227 Expr *RHSExpr){
16228 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16229 if (BinaryOperator::isBitwiseOp(Opc))
16230 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16231
16232 // Diagnose "arg1 & arg2 | arg3"
16233 if ((Opc == BO_Or || Opc == BO_Xor) &&
16234 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16235 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
16236 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
16237 }
16238
16239 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16240 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16241 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16242 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16243 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
16244 }
16245
16246 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
16247 || Opc == BO_Shr) {
16248 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
16249 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
16250 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
16251 }
16252
16253 // Warn on overloaded shift operators and comparisons, such as:
16254 // cout << 5 == 4;
16255 if (BinaryOperator::isComparisonOp(Opc))
16256 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
16257}
16258
16259ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16260 tok::TokenKind Kind,
16261 Expr *LHSExpr, Expr *RHSExpr) {
16262 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16263 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16264 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16265
16266 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16267 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
16268
16269 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
16270 ? BuiltinCountedByRefKind::Assignment
16271 : BuiltinCountedByRefKind::BinaryExpr;
16272
16273 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
16274 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
16275
16276 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16277}
16278
16279void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16280 UnresolvedSetImpl &Functions) {
16281 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16282 if (OverOp != OO_None && OverOp != OO_Equal)
16283 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16284
16285 // In C++20 onwards, we may have a second operator to look up.
16286 if (getLangOpts().CPlusPlus20) {
16287 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16288 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16289 }
16290}
16291
16292/// Build an overloaded binary operator expression in the given scope.
16293static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16294 BinaryOperatorKind Opc,
16295 Expr *LHS, Expr *RHS) {
16296 switch (Opc) {
16297 case BO_Assign:
16298 // In the non-overloaded case, we warn about self-assignment (x = x) for
16299 // both simple assignment and certain compound assignments where algebra
16300 // tells us the operation yields a constant result. When the operator is
16301 // overloaded, we can't do the latter because we don't want to assume that
16302 // those algebraic identities still apply; for example, a path-building
16303 // library might use operator/= to append paths. But it's still reasonable
16304 // to assume that simple assignment is just moving/copying values around
16305 // and so self-assignment is likely a bug.
16306 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16307 [[fallthrough]];
16308 case BO_DivAssign:
16309 case BO_RemAssign:
16310 case BO_SubAssign:
16311 case BO_AndAssign:
16312 case BO_OrAssign:
16313 case BO_XorAssign:
16314 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16315 break;
16316 default:
16317 break;
16318 }
16319
16320 // Find all of the overloaded operators visible from this point.
16321 UnresolvedSet<16> Functions;
16322 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16323
16324 // Build the (potentially-overloaded, potentially-dependent)
16325 // binary operation.
16326 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16327}
16328
16329ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16330 BinaryOperatorKind Opc, Expr *LHSExpr,
16331 Expr *RHSExpr, bool ForFoldExpression) {
16332 if (!LHSExpr || !RHSExpr)
16333 return ExprError();
16334
16335 // We want to end up calling one of SemaPseudoObject::checkAssignment
16336 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16337 // both expressions are overloadable or either is type-dependent),
16338 // or CreateBuiltinBinOp (in any other case). We also want to get
16339 // any placeholder types out of the way.
16340
16341 // Handle pseudo-objects in the LHS.
16342 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16343 // Assignments with a pseudo-object l-value need special analysis.
16344 if (pty->getKind() == BuiltinType::PseudoObject &&
16345 BinaryOperator::isAssignmentOp(Opc))
16346 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16347
16348 // Don't resolve overloads if the other type is overloadable.
16349 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16350 // We can't actually test that if we still have a placeholder,
16351 // though. Fortunately, none of the exceptions we see in that
16352 // code below are valid when the LHS is an overload set. Note
16353 // that an overload set can be dependently-typed, but it never
16354 // instantiates to having an overloadable type.
16355 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16356 if (resolvedRHS.isInvalid()) return ExprError();
16357 RHSExpr = resolvedRHS.get();
16358
16359 if (RHSExpr->isTypeDependent() ||
16360 RHSExpr->getType()->isOverloadableType())
16361 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16362 }
16363
16364 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16365 // template, diagnose the missing 'template' keyword instead of diagnosing
16366 // an invalid use of a bound member function.
16367 //
16368 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16369 // to C++1z [over.over]/1.4, but we already checked for that case above.
16370 if (Opc == BO_LT && inTemplateInstantiation() &&
16371 (pty->getKind() == BuiltinType::BoundMember ||
16372 pty->getKind() == BuiltinType::Overload)) {
16373 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16374 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16375 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16376 return isa<FunctionTemplateDecl>(Val: ND);
16377 })) {
16378 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16379 : OE->getNameLoc(),
16380 DiagID: diag::err_template_kw_missing)
16381 << OE->getName().getAsIdentifierInfo();
16382 return ExprError();
16383 }
16384 }
16385
16386 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16387 if (LHS.isInvalid()) return ExprError();
16388 LHSExpr = LHS.get();
16389 }
16390
16391 // Handle pseudo-objects in the RHS.
16392 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16393 // An overload in the RHS can potentially be resolved by the type
16394 // being assigned to.
16395 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16396 if (getLangOpts().CPlusPlus &&
16397 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16398 LHSExpr->getType()->isOverloadableType()))
16399 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16400
16401 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16402 ForFoldExpression);
16403 }
16404
16405 // Don't resolve overloads if the other type is overloadable.
16406 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16407 LHSExpr->getType()->isOverloadableType())
16408 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16409
16410 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16411 if (!resolvedRHS.isUsable()) return ExprError();
16412 RHSExpr = resolvedRHS.get();
16413 }
16414
16415 if (getLangOpts().HLSL) {
16416 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16417 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16418 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16419 return ExprError();
16420 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16421 std::optional<ExprResult> ConvRHS =
16422 HLSL().tryPerformConstantBufferConversion(BaseExpr: RHSExpr);
16423 if (ConvRHS && Context.hasSameUnqualifiedType(
16424 T1: LHSExpr->getType(), T2: ConvRHS->get()->getType())) {
16425 assert(!ConvRHS->isInvalid());
16426 RHSExpr = ConvRHS->get();
16427 }
16428 }
16429 }
16430
16431 if (getLangOpts().CPlusPlus) {
16432 bool CanOverloadBinOp =
16433 !getLangOpts().HLSL ||
16434 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16435 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16436 bool TypeDependent =
16437 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16438 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16439 RHSExpr->getType()->isOverloadableType();
16440 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16441 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16442 }
16443
16444 if (getLangOpts().RecoveryAST &&
16445 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16446 assert(!getLangOpts().CPlusPlus);
16447 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16448 "Should only occur in error-recovery path.");
16449 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16450 // C [6.15.16] p3:
16451 // An assignment expression has the value of the left operand after the
16452 // assignment, but is not an lvalue.
16453 return CompoundAssignOperator::Create(
16454 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16455 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16456 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16457 QualType ResultType;
16458 switch (Opc) {
16459 case BO_Assign:
16460 ResultType = LHSExpr->getType().getUnqualifiedType();
16461 break;
16462 case BO_LT:
16463 case BO_GT:
16464 case BO_LE:
16465 case BO_GE:
16466 case BO_EQ:
16467 case BO_NE:
16468 case BO_LAnd:
16469 case BO_LOr:
16470 // These operators have a fixed result type regardless of operands.
16471 ResultType = Context.IntTy;
16472 break;
16473 case BO_Comma:
16474 ResultType = RHSExpr->getType();
16475 break;
16476 default:
16477 ResultType = Context.DependentTy;
16478 break;
16479 }
16480 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16481 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16482 FPFeatures: CurFPFeatureOverrides());
16483 }
16484
16485 // Build a built-in binary operation.
16486 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16487}
16488
16489static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16490 if (T.isNull() || T->isDependentType())
16491 return false;
16492
16493 if (!Ctx.isPromotableIntegerType(T))
16494 return true;
16495
16496 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16497}
16498
16499ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16500 UnaryOperatorKind Opc, Expr *InputExpr,
16501 bool IsAfterAmp) {
16502 ExprResult Input = InputExpr;
16503 ExprValueKind VK = VK_PRValue;
16504 ExprObjectKind OK = OK_Ordinary;
16505 QualType resultType;
16506 bool CanOverflow = false;
16507
16508 bool ConvertHalfVec = false;
16509 if (getLangOpts().OpenCL) {
16510 QualType Ty = InputExpr->getType();
16511 // The only legal unary operation for atomics is '&'.
16512 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16513 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16514 // only with a builtin functions and therefore should be disallowed here.
16515 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16516 || Ty->isBlockPointerType())) {
16517 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16518 << InputExpr->getType()
16519 << Input.get()->getSourceRange());
16520 }
16521 }
16522
16523 if (getLangOpts().HLSL && OpLoc.isValid()) {
16524 if (Opc == UO_AddrOf)
16525 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16526 if (Opc == UO_Deref)
16527 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16528 }
16529
16530 if (InputExpr->isTypeDependent() &&
16531 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16532 resultType = Context.DependentTy;
16533 } else {
16534 switch (Opc) {
16535 case UO_PreInc:
16536 case UO_PreDec:
16537 case UO_PostInc:
16538 case UO_PostDec:
16539 resultType =
16540 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16541 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16542 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16543 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16544 break;
16545 case UO_AddrOf:
16546 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16547 CheckAddressOfNoDeref(E: InputExpr);
16548 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16549 break;
16550 case UO_Deref: {
16551 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16552 if (Input.isInvalid())
16553 return ExprError();
16554 resultType =
16555 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16556 break;
16557 }
16558 case UO_Plus:
16559 case UO_Minus:
16560 CanOverflow = Opc == UO_Minus &&
16561 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16562 Input = UsualUnaryConversions(E: Input.get());
16563 if (Input.isInvalid())
16564 return ExprError();
16565 // Unary plus and minus require promoting an operand of half vector to a
16566 // float vector and truncating the result back to a half vector. For now,
16567 // we do this only when HalfArgsAndReturns is set (that is, when the
16568 // target is arm or arm64).
16569 ConvertHalfVec = needsConversionOfHalfVec(
16570 OpRequiresConversion: true, Ctx&: Context, ResultTy: Input.get()->getType(), E0: Input.get());
16571
16572 // If the operand is a half vector, promote it to a float vector.
16573 if (ConvertHalfVec)
16574 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16575 resultType = Input.get()->getType();
16576 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16577 break;
16578 else if (resultType->isVectorType() &&
16579 // The z vector extensions don't allow + or - with bool vectors.
16580 (!Context.getLangOpts().ZVector ||
16581 resultType->castAs<VectorType>()->getVectorKind() !=
16582 VectorKind::AltiVecBool))
16583 break;
16584 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16585 break;
16586 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16587 Opc == UO_Plus && resultType->isPointerType())
16588 break;
16589
16590 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16591 << resultType << Input.get()->getSourceRange());
16592
16593 case UO_Not: // bitwise complement
16594 Input = UsualUnaryConversions(E: Input.get());
16595 if (Input.isInvalid())
16596 return ExprError();
16597 resultType = Input.get()->getType();
16598 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16599 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16600 // C99 does not support '~' for complex conjugation.
16601 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16602 << resultType << Input.get()->getSourceRange();
16603 else if (resultType->hasIntegerRepresentation())
16604 break;
16605 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16606 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16607 // on vector float types.
16608 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16609 if (!T->isIntegerType())
16610 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16611 << resultType << Input.get()->getSourceRange());
16612 } else {
16613 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16614 << resultType << Input.get()->getSourceRange());
16615 }
16616 break;
16617
16618 case UO_LNot: // logical negation
16619 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16620 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16621 if (Input.isInvalid())
16622 return ExprError();
16623 resultType = Input.get()->getType();
16624
16625 // Though we still have to promote half FP to float...
16626 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16627 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16628 .get();
16629 resultType = Context.FloatTy;
16630 }
16631
16632 // WebAsembly tables can't be used in unary expressions.
16633 if (resultType->isPointerType() &&
16634 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16635 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16636 << resultType << Input.get()->getSourceRange());
16637 }
16638
16639 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType) &&
16640 !resultType->isMetaInfoType()) {
16641 // Before C++26, scalar types are contextually converted to bool,
16642 // std::meta::info is a scalar type but not an arithmetic type.
16643
16644 // C99 6.5.3.3p1: ok, fallthrough;
16645 if (Context.getLangOpts().CPlusPlus) {
16646 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16647 // operand contextually converted to bool.
16648 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16649 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16650 } else if (Context.getLangOpts().OpenCL &&
16651 Context.getLangOpts().OpenCLVersion < 120) {
16652 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16653 // operate on scalar float types.
16654 if (!resultType->isIntegerType() && !resultType->isPointerType())
16655 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16656 << resultType << Input.get()->getSourceRange());
16657 }
16658 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16659 !resultType->hasBooleanRepresentation()) {
16660 // HLSL unary logical 'not' behaves like C++, which states that the
16661 // operand is converted to bool and the result is bool, however HLSL
16662 // extends this property to vectors.
16663 const VectorType *VTy = resultType->castAs<VectorType>();
16664 resultType =
16665 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16666
16667 Input = ImpCastExprToType(
16668 E: Input.get(), Type: resultType,
16669 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16670 .get();
16671 break;
16672 } else if (resultType->isExtVectorType()) {
16673 if (Context.getLangOpts().OpenCL &&
16674 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16675 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16676 // operate on vector float types.
16677 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16678 if (!T->isIntegerType())
16679 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16680 << resultType << Input.get()->getSourceRange());
16681 }
16682 // Vector logical not returns the signed variant of the operand type.
16683 resultType = GetSignedVectorType(V: resultType);
16684 break;
16685 } else if (Context.getLangOpts().CPlusPlus &&
16686 resultType->isVectorType()) {
16687 const VectorType *VTy = resultType->castAs<VectorType>();
16688 if (VTy->getVectorKind() != VectorKind::Generic)
16689 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16690 << resultType << Input.get()->getSourceRange());
16691
16692 // Vector logical not returns the signed variant of the operand type.
16693 resultType = GetSignedVectorType(V: resultType);
16694 break;
16695 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16696 resultType = Context.getLogicalOperationType();
16697 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16698 break;
16699 } else {
16700 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16701 << resultType << Input.get()->getSourceRange());
16702 }
16703
16704 // LNot always has type int. C99 6.5.3.3p5.
16705 // In C++, it's bool. C++ 5.3.1p8
16706 resultType = Context.getLogicalOperationType();
16707 break;
16708 case UO_Real:
16709 case UO_Imag:
16710 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16711 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16712 // ordinary complex l-values to ordinary l-values and all other values to
16713 // r-values.
16714 if (Input.isInvalid())
16715 return ExprError();
16716 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16717 if (Input.get()->isGLValue() &&
16718 Input.get()->getObjectKind() == OK_Ordinary)
16719 VK = Input.get()->getValueKind();
16720 } else if (!getLangOpts().CPlusPlus) {
16721 // In C, a volatile scalar is read by __imag. In C++, it is not.
16722 Input = DefaultLvalueConversion(E: Input.get());
16723 }
16724 break;
16725 case UO_Extension:
16726 resultType = Input.get()->getType();
16727 VK = Input.get()->getValueKind();
16728 OK = Input.get()->getObjectKind();
16729 break;
16730 case UO_Coawait:
16731 // It's unnecessary to represent the pass-through operator co_await in the
16732 // AST; just return the input expression instead.
16733 assert(!Input.get()->getType()->isDependentType() &&
16734 "the co_await expression must be non-dependant before "
16735 "building operator co_await");
16736 return Input;
16737 }
16738 }
16739 if (resultType.isNull() || Input.isInvalid())
16740 return ExprError();
16741
16742 // Check for array bounds violations in the operand of the UnaryOperator,
16743 // except for the '*' and '&' operators that have to be handled specially
16744 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16745 // that are explicitly defined as valid by the standard).
16746 if (Opc != UO_AddrOf && Opc != UO_Deref)
16747 CheckArrayAccess(E: Input.get());
16748
16749 auto *UO =
16750 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16751 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16752
16753 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16754 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16755 !isUnevaluatedContext())
16756 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16757
16758 // Convert the result back to a half vector.
16759 if (ConvertHalfVec)
16760 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16761 return UO;
16762}
16763
16764bool Sema::isQualifiedMemberAccess(Expr *E) {
16765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16766 if (!DRE->getQualifier())
16767 return false;
16768
16769 ValueDecl *VD = DRE->getDecl();
16770 if (!VD->isCXXClassMember())
16771 return false;
16772
16773 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16774 return true;
16775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16776 return Method->isImplicitObjectMemberFunction();
16777
16778 return false;
16779 }
16780
16781 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16782 if (!ULE->getQualifier())
16783 return false;
16784
16785 for (NamedDecl *D : ULE->decls()) {
16786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16787 if (Method->isImplicitObjectMemberFunction())
16788 return true;
16789 } else {
16790 // Overload set does not contain methods.
16791 break;
16792 }
16793 }
16794
16795 return false;
16796 }
16797
16798 return false;
16799}
16800
16801ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16802 UnaryOperatorKind Opc, Expr *Input,
16803 bool IsAfterAmp) {
16804 // First things first: handle placeholders so that the
16805 // overloaded-operator check considers the right type.
16806 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16807 // Increment and decrement of pseudo-object references.
16808 if (pty->getKind() == BuiltinType::PseudoObject &&
16809 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16810 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16811
16812 // extension is always a builtin operator.
16813 if (Opc == UO_Extension)
16814 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16815
16816 // & gets special logic for several kinds of placeholder.
16817 // The builtin code knows what to do.
16818 if (Opc == UO_AddrOf &&
16819 (pty->getKind() == BuiltinType::Overload ||
16820 pty->getKind() == BuiltinType::UnknownAny ||
16821 pty->getKind() == BuiltinType::BoundMember))
16822 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16823
16824 // Anything else needs to be handled now.
16825 ExprResult Result = CheckPlaceholderExpr(E: Input);
16826 if (Result.isInvalid()) return ExprError();
16827 Input = Result.get();
16828 }
16829
16830 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16831 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16832 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16833 // Find all of the overloaded operators visible from this point.
16834 UnresolvedSet<16> Functions;
16835 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16836 if (S && OverOp != OO_None)
16837 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16838
16839 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16840 }
16841
16842 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16843}
16844
16845ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16846 Expr *Input, bool IsAfterAmp) {
16847 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16848 IsAfterAmp);
16849}
16850
16851ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16852 LabelDecl *TheDecl) {
16853 TheDecl->markUsed(C&: Context);
16854 // Create the AST node. The address of a label always has type 'void*'.
16855 auto *Res = new (Context) AddrLabelExpr(
16856 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16857
16858 if (getCurFunction())
16859 getCurFunction()->AddrLabels.push_back(Elt: Res);
16860
16861 return Res;
16862}
16863
16864void Sema::ActOnStartStmtExpr() {
16865 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16866 // Make sure we diagnose jumping into a statement expression.
16867 setFunctionHasBranchProtectedScope();
16868}
16869
16870void Sema::ActOnStmtExprError() {
16871 // Note that function is also called by TreeTransform when leaving a
16872 // StmtExpr scope without rebuilding anything.
16873
16874 DiscardCleanupsInEvaluationContext();
16875 PopExpressionEvaluationContext();
16876}
16877
16878ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16879 SourceLocation RPLoc) {
16880 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16881}
16882
16883ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16884 SourceLocation RPLoc, unsigned TemplateDepth) {
16885 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16886 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16887
16888 if (hasAnyUnrecoverableErrorsInThisFunction())
16889 DiscardCleanupsInEvaluationContext();
16890 assert(!Cleanup.exprNeedsCleanups() &&
16891 "cleanups within StmtExpr not correctly bound!");
16892 PopExpressionEvaluationContext();
16893
16894 // FIXME: there are a variety of strange constraints to enforce here, for
16895 // example, it is not possible to goto into a stmt expression apparently.
16896 // More semantic analysis is needed.
16897
16898 // If there are sub-stmts in the compound stmt, take the type of the last one
16899 // as the type of the stmtexpr.
16900 QualType Ty = Context.VoidTy;
16901 bool StmtExprMayBindToTemp = false;
16902 if (!Compound->body_empty()) {
16903 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16904 if (const Expr *Value = LastStmt->getExprStmt()) {
16905 StmtExprMayBindToTemp = true;
16906 Ty = Value->getType();
16907 }
16908 }
16909 }
16910
16911 // FIXME: Check that expression type is complete/non-abstract; statement
16912 // expressions are not lvalues.
16913 Expr *ResStmtExpr =
16914 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16915 if (StmtExprMayBindToTemp)
16916 return MaybeBindToTemporary(E: ResStmtExpr);
16917 return ResStmtExpr;
16918}
16919
16920ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16921 if (ER.isInvalid())
16922 return ExprError();
16923
16924 // Do function/array conversion on the last expression, but not
16925 // lvalue-to-rvalue. However, initialize an unqualified type.
16926 ER = DefaultFunctionArrayConversion(E: ER.get());
16927 if (ER.isInvalid())
16928 return ExprError();
16929 Expr *E = ER.get();
16930
16931 if (E->isTypeDependent())
16932 return E;
16933
16934 // In ARC, if the final expression ends in a consume, splice
16935 // the consume out and bind it later. In the alternate case
16936 // (when dealing with a retainable type), the result
16937 // initialization will create a produce. In both cases the
16938 // result will be +1, and we'll need to balance that out with
16939 // a bind.
16940 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16941 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16942 return Cast->getSubExpr();
16943
16944 // FIXME: Provide a better location for the initialization.
16945 return PerformCopyInitialization(
16946 Entity: InitializedEntity::InitializeStmtExprResult(
16947 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16948 EqualLoc: SourceLocation(), Init: E);
16949}
16950
16951ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16952 TypeSourceInfo *TInfo,
16953 const Designation &Desig,
16954 SourceLocation RParenLoc) {
16955 QualType ArgTy = TInfo->getType();
16956 bool Dependent = ArgTy->isDependentType();
16957 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16958
16959 // We must have at least one component that refers to the type, and the first
16960 // one is known to be a field designator. Verify that the ArgTy represents
16961 // a struct/union/class.
16962 if (!Dependent && !ArgTy->isRecordType())
16963 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16964 << ArgTy << TypeRange);
16965
16966 // Type must be complete per C99 7.17p3 because a declaring a variable
16967 // with an incomplete type would be ill-formed.
16968 if (!Dependent
16969 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16970 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16971 return ExprError();
16972
16973 bool DidWarnAboutNonPOD = false;
16974 QualType CurrentType = ArgTy;
16975 SmallVector<OffsetOfNode, 4> Comps;
16976 SmallVector<Expr *, 4> Exprs;
16977 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16978 const Designator &D = Desig.getDesignator(Idx: I);
16979 assert(!D.isArrayRangeDesignator());
16980 if (D.isArrayDesignator()) {
16981 // Offset of an array sub-field. TODO: Should we allow vector elements?
16982 if (!CurrentType->isDependentType()) {
16983 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16984 if(!AT)
16985 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16986 << CurrentType);
16987 CurrentType = AT->getElementType();
16988 } else
16989 CurrentType = Context.DependentTy;
16990
16991 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16992 if (IdxRval.isInvalid())
16993 return ExprError();
16994 Expr *Idx = IdxRval.get();
16995
16996 // The expression must be an integral expression.
16997 // FIXME: An integral constant expression?
16998 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16999 !Idx->getType()->isIntegerType())
17000 return ExprError(
17001 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
17002 << Idx->getSourceRange());
17003
17004 // Record this array index.
17005 Comps.push_back(
17006 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
17007 Exprs.push_back(Elt: Idx);
17008 continue;
17009 }
17010
17011 assert(D.isFieldDesignator());
17012 const IdentifierInfo *Name = D.getFieldDecl();
17013
17014 // Offset of a field.
17015 if (CurrentType->isDependentType()) {
17016 // We have the offset of a field, but we can't look into the dependent
17017 // type. Just record the identifier of the field.
17018 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
17019 CurrentType = Context.DependentTy;
17020 continue;
17021 }
17022
17023 // We need to have a complete type to look into.
17024 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
17025 DiagID: diag::err_offsetof_incomplete_type))
17026 return ExprError();
17027
17028 // Look for the designated field.
17029 auto *RD = CurrentType->getAsRecordDecl();
17030 if (!RD)
17031 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
17032 << CurrentType);
17033
17034 // C++ [lib.support.types]p5:
17035 // The macro offsetof accepts a restricted set of type arguments in this
17036 // International Standard. type shall be a POD structure or a POD union
17037 // (clause 9).
17038 // C++11 [support.types]p4:
17039 // If type is not a standard-layout class (Clause 9), the results are
17040 // undefined.
17041 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
17042 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
17043 unsigned DiagID =
17044 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
17045 : diag::ext_offsetof_non_pod_type;
17046
17047 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
17048 Diag(Loc: BuiltinLoc, DiagID)
17049 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
17050 << CurrentType;
17051 DidWarnAboutNonPOD = true;
17052 }
17053 }
17054
17055 // Look for the field.
17056 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17057 LookupQualifiedName(R, LookupCtx: RD);
17058 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17059 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17060 if (!MemberDecl) {
17061 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17062 MemberDecl = IndirectMemberDecl->getAnonField();
17063 }
17064
17065 if (!MemberDecl) {
17066 // Lookup could be ambiguous when looking up a placeholder variable
17067 // __builtin_offsetof(S, _).
17068 // In that case we would already have emitted a diagnostic
17069 if (!R.isAmbiguous())
17070 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
17071 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17072 return ExprError();
17073 }
17074
17075 // C99 7.17p3:
17076 // (If the specified member is a bit-field, the behavior is undefined.)
17077 //
17078 // We diagnose this as an error.
17079 if (MemberDecl->isBitField()) {
17080 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
17081 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17082 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
17083 return ExprError();
17084 }
17085
17086 RecordDecl *Parent = MemberDecl->getParent();
17087 if (IndirectMemberDecl)
17088 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
17089
17090 // If the member was found in a base class, introduce OffsetOfNodes for
17091 // the base class indirections.
17092 CXXBasePaths Paths;
17093 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
17094 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
17095 if (Paths.getDetectedVirtual()) {
17096 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
17097 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17098 return ExprError();
17099 }
17100
17101 CXXBasePath &Path = Paths.front();
17102 for (const CXXBasePathElement &B : Path)
17103 Comps.push_back(Elt: OffsetOfNode(B.Base));
17104 }
17105
17106 if (IndirectMemberDecl) {
17107 for (auto *FI : IndirectMemberDecl->chain()) {
17108 assert(isa<FieldDecl>(FI));
17109 Comps.push_back(
17110 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
17111 }
17112 } else
17113 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17114
17115 CurrentType = MemberDecl->getType().getNonReferenceType();
17116 }
17117
17118 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
17119 comps: Comps, exprs: Exprs, RParenLoc);
17120}
17121
17122ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
17123 SourceLocation TypeLoc,
17124 ParsedType ParsedArgTy,
17125 const Designation &Desig,
17126 SourceLocation RParenLoc) {
17127
17128 TypeSourceInfo *ArgTInfo;
17129 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
17130 if (ArgTy.isNull())
17131 return ExprError();
17132
17133 if (!ArgTInfo)
17134 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
17135
17136 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
17137}
17138
17139ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
17140 Expr *CondExpr,
17141 Expr *LHSExpr, Expr *RHSExpr,
17142 SourceLocation RPLoc) {
17143 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17144
17145 ExprValueKind VK = VK_PRValue;
17146 ExprObjectKind OK = OK_Ordinary;
17147 QualType resType;
17148 bool CondIsTrue = false;
17149 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17150 resType = Context.DependentTy;
17151 } else {
17152 // The conditional expression is required to be a constant expression.
17153 llvm::APSInt condEval(32);
17154 ExprResult CondICE = VerifyIntegerConstantExpression(
17155 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
17156 if (CondICE.isInvalid())
17157 return ExprError();
17158 CondExpr = CondICE.get();
17159 CondIsTrue = condEval.getZExtValue();
17160
17161 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17162 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17163
17164 resType = ActiveExpr->getType();
17165 VK = ActiveExpr->getValueKind();
17166 OK = ActiveExpr->getObjectKind();
17167 }
17168
17169 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17170 resType, VK, OK, RPLoc, CondIsTrue);
17171}
17172
17173//===----------------------------------------------------------------------===//
17174// Clang Extensions.
17175//===----------------------------------------------------------------------===//
17176
17177void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17178 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
17179
17180 if (LangOpts.CPlusPlus) {
17181 MangleNumberingContext *MCtx;
17182 Decl *ManglingContextDecl;
17183 std::tie(args&: MCtx, args&: ManglingContextDecl) =
17184 getCurrentMangleNumberContext(DC: Block->getDeclContext());
17185 if (MCtx) {
17186 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
17187 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
17188 }
17189 }
17190
17191 PushBlockScope(BlockScope: CurScope, Block);
17192 CurContext->addDecl(D: Block);
17193 if (CurScope)
17194 PushDeclContext(S: CurScope, DC: Block);
17195 else
17196 CurContext = Block;
17197
17198 getCurBlock()->HasImplicitReturnType = true;
17199
17200 // Enter a new evaluation context to insulate the block from any
17201 // cleanups from the enclosing full-expression.
17202 PushExpressionEvaluationContext(
17203 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
17204}
17205
17206void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
17207 Scope *CurScope) {
17208 assert(ParamInfo.getIdentifier() == nullptr &&
17209 "block-id should have no identifier!");
17210 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17211 BlockScopeInfo *CurBlock = getCurBlock();
17212
17213 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
17214 QualType T = Sig->getType();
17215 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
17216
17217 // GetTypeForDeclarator always produces a function type for a block
17218 // literal signature. Furthermore, it is always a FunctionProtoType
17219 // unless the function was written with a typedef.
17220 assert(T->isFunctionType() &&
17221 "GetTypeForDeclarator made a non-function block signature");
17222
17223 // Look for an explicit signature in that function type.
17224 FunctionProtoTypeLoc ExplicitSignature;
17225
17226 if ((ExplicitSignature = Sig->getTypeLoc()
17227 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17228
17229 // Check whether that explicit signature was synthesized by
17230 // GetTypeForDeclarator. If so, don't save that as part of the
17231 // written signature.
17232 if (ExplicitSignature.getLocalRangeBegin() ==
17233 ExplicitSignature.getLocalRangeEnd()) {
17234 // This would be much cheaper if we stored TypeLocs instead of
17235 // TypeSourceInfos.
17236 TypeLoc Result = ExplicitSignature.getReturnLoc();
17237 unsigned Size = Result.getFullDataSize();
17238 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
17239 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
17240
17241 ExplicitSignature = FunctionProtoTypeLoc();
17242 }
17243 }
17244
17245 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17246 CurBlock->FunctionType = T;
17247
17248 const auto *Fn = T->castAs<FunctionType>();
17249 QualType RetTy = Fn->getReturnType();
17250 bool isVariadic =
17251 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
17252
17253 CurBlock->TheDecl->setIsVariadic(isVariadic);
17254
17255 // Context.DependentTy is used as a placeholder for a missing block
17256 // return type. TODO: what should we do with declarators like:
17257 // ^ * { ... }
17258 // If the answer is "apply template argument deduction"....
17259 if (RetTy != Context.DependentTy) {
17260 CurBlock->ReturnType = RetTy;
17261 CurBlock->TheDecl->setBlockMissingReturnType(false);
17262 CurBlock->HasImplicitReturnType = false;
17263 }
17264
17265 // Push block parameters from the declarator if we had them.
17266 SmallVector<ParmVarDecl*, 8> Params;
17267 if (ExplicitSignature) {
17268 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17269 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
17270 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17271 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17272 // Diagnose this as an extension in C17 and earlier.
17273 if (!getLangOpts().C23)
17274 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
17275 }
17276 Params.push_back(Elt: Param);
17277 }
17278
17279 // Fake up parameter variables if we have a typedef, like
17280 // ^ fntype { ... }
17281 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17282 for (const auto &I : Fn->param_types()) {
17283 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17284 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
17285 Params.push_back(Elt: Param);
17286 }
17287 }
17288
17289 // Set the parameters on the block decl.
17290 if (!Params.empty()) {
17291 CurBlock->TheDecl->setParams(Params);
17292 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17293 /*CheckParameterNames=*/false);
17294 }
17295
17296 // Finally we can process decl attributes.
17297 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17298
17299 // Put the parameter variables in scope.
17300 for (auto *AI : CurBlock->TheDecl->parameters()) {
17301 AI->setOwningFunction(CurBlock->TheDecl);
17302
17303 // If this has an identifier, add it to the scope stack.
17304 if (AI->getIdentifier()) {
17305 CheckShadow(S: CurBlock->TheScope, D: AI);
17306
17307 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17308 }
17309
17310 if (AI->isInvalidDecl())
17311 CurBlock->TheDecl->setInvalidDecl();
17312 }
17313}
17314
17315void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17316 // Leave the expression-evaluation context.
17317 DiscardCleanupsInEvaluationContext();
17318 PopExpressionEvaluationContext();
17319
17320 // Pop off CurBlock, handle nested blocks.
17321 PopDeclContext();
17322 PopFunctionScopeInfo();
17323}
17324
17325ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17326 Stmt *Body, Scope *CurScope) {
17327 // If blocks are disabled, emit an error.
17328 if (!LangOpts.Blocks)
17329 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17330
17331 // Leave the expression-evaluation context.
17332 if (hasAnyUnrecoverableErrorsInThisFunction())
17333 DiscardCleanupsInEvaluationContext();
17334 assert(!Cleanup.exprNeedsCleanups() &&
17335 "cleanups within block not correctly bound!");
17336 PopExpressionEvaluationContext();
17337
17338 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17339 BlockDecl *BD = BSI->TheDecl;
17340
17341 maybeAddDeclWithEffects(D: BD);
17342
17343 if (BSI->HasImplicitReturnType)
17344 deduceClosureReturnType(CSI&: *BSI);
17345
17346 QualType RetTy = Context.VoidTy;
17347 if (!BSI->ReturnType.isNull())
17348 RetTy = BSI->ReturnType;
17349
17350 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17351 QualType BlockTy;
17352
17353 // If the user wrote a function type in some form, try to use that.
17354 if (!BSI->FunctionType.isNull()) {
17355 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17356
17357 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17358 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17359
17360 // Turn protoless block types into nullary block types.
17361 if (isa<FunctionNoProtoType>(Val: FTy)) {
17362 FunctionProtoType::ExtProtoInfo EPI;
17363 EPI.ExtInfo = Ext;
17364 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17365
17366 // Otherwise, if we don't need to change anything about the function type,
17367 // preserve its sugar structure.
17368 } else if (FTy->getReturnType() == RetTy &&
17369 (!NoReturn || FTy->getNoReturnAttr())) {
17370 BlockTy = BSI->FunctionType;
17371
17372 // Otherwise, make the minimal modifications to the function type.
17373 } else {
17374 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17375 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17376 EPI.TypeQuals = Qualifiers();
17377 EPI.ExtInfo = Ext;
17378 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17379 }
17380
17381 // If we don't have a function type, just build one from nothing.
17382 } else {
17383 FunctionProtoType::ExtProtoInfo EPI;
17384 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17385 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17386 }
17387
17388 DiagnoseUnusedParameters(Parameters: BD->parameters());
17389 BlockTy = Context.getBlockPointerType(T: BlockTy);
17390
17391 // If needed, diagnose invalid gotos and switches in the block.
17392 if (getCurFunction()->NeedsScopeChecking() &&
17393 !PP.isCodeCompletionEnabled())
17394 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17395
17396 BD->setBody(cast<CompoundStmt>(Val: Body));
17397
17398 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17399 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17400
17401 // Try to apply the named return value optimization. We have to check again
17402 // if we can do this, though, because blocks keep return statements around
17403 // to deduce an implicit return type.
17404 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17405 !BD->isDependentContext())
17406 computeNRVO(Body, Scope: BSI);
17407
17408 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17409 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17410 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17411 UseContext: NonTrivialCUnionContext::FunctionReturn,
17412 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17413
17414 PopDeclContext();
17415
17416 // Set the captured variables on the block.
17417 SmallVector<BlockDecl::Capture, 4> Captures;
17418 for (Capture &Cap : BSI->Captures) {
17419 if (Cap.isInvalid() || Cap.isThisCapture())
17420 continue;
17421 // Cap.getVariable() is always a VarDecl because
17422 // blocks cannot capture structured bindings or other ValueDecl kinds.
17423 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17424 Expr *CopyExpr = nullptr;
17425 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17426 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17427 // The capture logic needs the destructor, so make sure we mark it.
17428 // Usually this is unnecessary because most local variables have
17429 // their destructors marked at declaration time, but parameters are
17430 // an exception because it's technically only the call site that
17431 // actually requires the destructor.
17432 if (isa<ParmVarDecl>(Val: Var))
17433 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17434
17435 // Enter a separate potentially-evaluated context while building block
17436 // initializers to isolate their cleanups from those of the block
17437 // itself.
17438 // FIXME: Is this appropriate even when the block itself occurs in an
17439 // unevaluated operand?
17440 EnterExpressionEvaluationContext EvalContext(
17441 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17442
17443 SourceLocation Loc = Cap.getLocation();
17444
17445 ExprResult Result = BuildDeclarationNameExpr(
17446 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17447
17448 // According to the blocks spec, the capture of a variable from
17449 // the stack requires a const copy constructor. This is not true
17450 // of the copy/move done to move a __block variable to the heap.
17451 if (!Result.isInvalid() &&
17452 !Result.get()->getType().isConstQualified()) {
17453 Result = ImpCastExprToType(E: Result.get(),
17454 Type: Result.get()->getType().withConst(),
17455 CK: CK_NoOp, VK: VK_LValue);
17456 }
17457
17458 if (!Result.isInvalid()) {
17459 Result = PerformCopyInitialization(
17460 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17461 Type: Cap.getCaptureType()),
17462 EqualLoc: Loc, Init: Result.get());
17463 }
17464
17465 // Build a full-expression copy expression if initialization
17466 // succeeded and used a non-trivial constructor. Recover from
17467 // errors by pretending that the copy isn't necessary.
17468 if (!Result.isInvalid() &&
17469 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17470 ->isTrivial()) {
17471 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17472 CopyExpr = Result.get();
17473 }
17474 }
17475 }
17476
17477 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17478 CopyExpr);
17479 Captures.push_back(Elt: NewCap);
17480 }
17481 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17482
17483 // Pop the block scope now but keep it alive to the end of this function.
17484 AnalysisBasedWarnings::Policy WP =
17485 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17486 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17487
17488 BlockExpr *Result = new (Context)
17489 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17490
17491 // If the block isn't obviously global, i.e. it captures anything at
17492 // all, then we need to do a few things in the surrounding context:
17493 if (Result->getBlockDecl()->hasCaptures()) {
17494 // First, this expression has a new cleanup object.
17495 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17496 Cleanup.setExprNeedsCleanups(true);
17497
17498 // It also gets a branch-protected scope if any of the captured
17499 // variables needs destruction.
17500 for (const auto &CI : Result->getBlockDecl()->captures()) {
17501 const VarDecl *var = CI.getVariable();
17502 if (var->getType().isDestructedType() != QualType::DK_none) {
17503 setFunctionHasBranchProtectedScope();
17504 break;
17505 }
17506 }
17507 }
17508
17509 if (getCurFunction())
17510 getCurFunction()->addBlock(BD);
17511
17512 // This can happen if the block's return type is deduced, but
17513 // the return expression is invalid.
17514 if (BD->isInvalidDecl())
17515 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17516 SubExprs: {Result}, T: Result->getType());
17517 return Result;
17518}
17519
17520ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17521 SourceLocation RPLoc) {
17522 TypeSourceInfo *TInfo;
17523 GetTypeFromParser(Ty, TInfo: &TInfo);
17524 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17525}
17526
17527ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17528 Expr *E, TypeSourceInfo *TInfo,
17529 SourceLocation RPLoc) {
17530 Expr *OrigExpr = E;
17531 VAArgExpr::VarArgKind VAKind = VAArgExpr::VA_Std;
17532
17533 // CUDA device global function does not support varargs.
17534 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17535 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17536 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17537 if (T == CUDAFunctionTarget::Global)
17538 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17539 }
17540 }
17541
17542 // NVPTX does not support va_arg expression.
17543 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17544 Context.getTargetInfo().getTriple().isNVPTX())
17545 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17546
17547 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17548 // as Microsoft ABI on an actual Microsoft platform, where
17549 // __builtin_ms_va_list and __builtin_va_list are the same.)
17550 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17551 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17552 QualType MSVaListType = Context.getBuiltinMSVaListType();
17553 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17554 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17555 return ExprError();
17556 VAKind = VAArgExpr::VA_MS;
17557 }
17558 }
17559
17560 // Get the va_list type
17561 QualType VaListType = Context.getBuiltinVaListType();
17562
17563 // It might be a __builtin_zos_va_list!
17564 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17565 // E->getType() can be:
17566 // - va_list: equal to array (char*)[2] (inside function)
17567 // - char **: decayed array (va_list passed as parameter)
17568 // We need to check for both cases.
17569 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17570 assert(ZOSVaListType->isArrayType() &&
17571 "__builtin_zos_va_list must be an array type");
17572 QualType DecayedType = Context.getArrayDecayedType(T: ZOSVaListType);
17573 if (Context.hasSameType(T1: ZOSVaListType, T2: E->getType()) ||
17574 Context.hasSameType(T1: DecayedType, T2: E->getType())) {
17575 VAKind = VAArgExpr::VA_ZOS;
17576 VaListType = ZOSVaListType;
17577 }
17578 }
17579
17580 if (VAKind != VAArgExpr::VA_MS) {
17581 if (VaListType->isArrayType()) {
17582 // Deal with implicit array decay; for example, on x86-64,
17583 // va_list is an array, but it's supposed to decay to
17584 // a pointer for va_arg.
17585 VaListType = Context.getArrayDecayedType(T: VaListType);
17586 // Make sure the input expression also decays appropriately.
17587 ExprResult Result = UsualUnaryConversions(E);
17588 if (Result.isInvalid())
17589 return ExprError();
17590 E = Result.get();
17591 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17592 // If va_list is a record type and we are compiling in C++ mode,
17593 // check the argument using reference binding.
17594 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17595 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17596 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17597 if (Init.isInvalid())
17598 return ExprError();
17599 E = Init.getAs<Expr>();
17600 } else {
17601 // Otherwise, the va_list argument must be an l-value because
17602 // it is modified by va_arg.
17603 if (!E->isTypeDependent() &&
17604 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17605 return ExprError();
17606 }
17607 }
17608
17609 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17610 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17611 return ExprError(
17612 Diag(Loc: E->getBeginLoc(),
17613 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17614 << OrigExpr->getType() << E->getSourceRange());
17615
17616 if (!TInfo->getType()->isDependentType()) {
17617 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17618 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17619 Args: TInfo->getTypeLoc()))
17620 return ExprError();
17621
17622 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17623 T: TInfo->getType(),
17624 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17625 Args: TInfo->getTypeLoc()))
17626 return ExprError();
17627
17628 if (!TInfo->getType().isPODType(Context)) {
17629 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17630 DiagID: TInfo->getType()->isObjCLifetimeType()
17631 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17632 : diag::warn_second_parameter_to_va_arg_not_pod)
17633 << TInfo->getType()
17634 << TInfo->getTypeLoc().getSourceRange();
17635 }
17636
17637 if (TInfo->getType()->isArrayType()) {
17638 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17639 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17640 << TInfo->getType()
17641 << TInfo->getTypeLoc().getSourceRange());
17642 }
17643
17644 // Check for va_arg where arguments of the given type will be promoted
17645 // (i.e. this va_arg is guaranteed to have undefined behavior).
17646 QualType PromoteType;
17647 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17648 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17649 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17650 // and C23 7.16.1.1p2 says, in part:
17651 // If type is not compatible with the type of the actual next argument
17652 // (as promoted according to the default argument promotions), the
17653 // behavior is undefined, except for the following cases:
17654 // - both types are pointers to qualified or unqualified versions of
17655 // compatible types;
17656 // - one type is compatible with a signed integer type, the other
17657 // type is compatible with the corresponding unsigned integer type,
17658 // and the value is representable in both types;
17659 // - one type is pointer to qualified or unqualified void and the
17660 // other is a pointer to a qualified or unqualified character type;
17661 // - or, the type of the next argument is nullptr_t and type is a
17662 // pointer type that has the same representation and alignment
17663 // requirements as a pointer to a character type.
17664 // Given that type compatibility is the primary requirement (ignoring
17665 // qualifications), you would think we could call typesAreCompatible()
17666 // directly to test this. However, in C++, that checks for *same type*,
17667 // which causes false positives when passing an enumeration type to
17668 // va_arg. Instead, get the underlying type of the enumeration and pass
17669 // that.
17670 QualType UnderlyingType = TInfo->getType();
17671 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17672 UnderlyingType = ED->getIntegerType();
17673 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17674 /*CompareUnqualified*/ true))
17675 PromoteType = QualType();
17676
17677 // If the types are still not compatible, we need to test whether the
17678 // promoted type and the underlying type are the same except for
17679 // signedness. Ask the AST for the correctly corresponding type and see
17680 // if that's compatible.
17681 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17682 PromoteType->isUnsignedIntegerType() !=
17683 UnderlyingType->isUnsignedIntegerType()) {
17684 UnderlyingType =
17685 UnderlyingType->isUnsignedIntegerType()
17686 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17687 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17688 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17689 /*CompareUnqualified*/ true))
17690 PromoteType = QualType();
17691 }
17692 }
17693 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17694 PromoteType = Context.DoubleTy;
17695 if (!PromoteType.isNull())
17696 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17697 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17698 << TInfo->getType()
17699 << PromoteType
17700 << TInfo->getTypeLoc().getSourceRange());
17701 }
17702
17703 QualType T = TInfo->getType().getNonLValueExprType(Context);
17704 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17705}
17706
17707ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17708 // The type of __null will be int or long, depending on the size of
17709 // pointers on the target.
17710 QualType Ty;
17711 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17712 if (pw == Context.getTargetInfo().getIntWidth())
17713 Ty = Context.IntTy;
17714 else if (pw == Context.getTargetInfo().getLongWidth())
17715 Ty = Context.LongTy;
17716 else if (pw == Context.getTargetInfo().getLongLongWidth())
17717 Ty = Context.LongLongTy;
17718 else {
17719 llvm_unreachable("I don't know size of pointer!");
17720 }
17721
17722 return new (Context) GNUNullExpr(Ty, TokenLoc);
17723}
17724
17725static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17726 CXXRecordDecl *ImplDecl = nullptr;
17727
17728 // Fetch the std::source_location::__impl decl.
17729 if (NamespaceDecl *Std = S.getStdNamespace()) {
17730 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17731 Loc, Sema::LookupOrdinaryName);
17732 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17733 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17734 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17735 Loc, Sema::LookupOrdinaryName);
17736 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17737 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17738 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17739 }
17740 }
17741 }
17742 }
17743
17744 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17745 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17746 return nullptr;
17747 }
17748
17749 // Verify that __impl is a trivial struct type, with no base classes, and with
17750 // only the four expected fields.
17751 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17752 ImplDecl->getNumBases() != 0) {
17753 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17754 return nullptr;
17755 }
17756
17757 unsigned Count = 0;
17758 for (FieldDecl *F : ImplDecl->fields()) {
17759 StringRef Name = F->getName();
17760
17761 if (Name == "_M_file_name") {
17762 if (F->getType() !=
17763 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17764 break;
17765 Count++;
17766 } else if (Name == "_M_function_name") {
17767 if (F->getType() !=
17768 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17769 break;
17770 Count++;
17771 } else if (Name == "_M_line") {
17772 if (!F->getType()->isIntegerType())
17773 break;
17774 Count++;
17775 } else if (Name == "_M_column") {
17776 if (!F->getType()->isIntegerType())
17777 break;
17778 Count++;
17779 } else {
17780 Count = 100; // invalid
17781 break;
17782 }
17783 }
17784 if (Count != 4) {
17785 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17786 return nullptr;
17787 }
17788
17789 return ImplDecl;
17790}
17791
17792ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17793 SourceLocation BuiltinLoc,
17794 SourceLocation RPLoc) {
17795 QualType ResultTy;
17796 switch (Kind) {
17797 case SourceLocIdentKind::File:
17798 case SourceLocIdentKind::FileName:
17799 case SourceLocIdentKind::Function:
17800 case SourceLocIdentKind::FuncSig: {
17801 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17802 ResultTy =
17803 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17804 break;
17805 }
17806 case SourceLocIdentKind::Line:
17807 case SourceLocIdentKind::Column:
17808 ResultTy = Context.UnsignedIntTy;
17809 break;
17810 case SourceLocIdentKind::SourceLocStruct:
17811 if (!StdSourceLocationImplDecl) {
17812 StdSourceLocationImplDecl =
17813 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17814 if (!StdSourceLocationImplDecl)
17815 return ExprError();
17816 }
17817 ResultTy = Context.getPointerType(
17818 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17819 break;
17820 }
17821
17822 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17823}
17824
17825ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17826 SourceLocation BuiltinLoc,
17827 SourceLocation RPLoc,
17828 DeclContext *ParentContext) {
17829 return new (Context)
17830 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17831}
17832
17833ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17834 StringLiteral *BinaryData, StringRef FileName) {
17835 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17836 Data->BinaryData = BinaryData;
17837 Data->FileName = FileName;
17838 return new (Context)
17839 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17840 Data->getDataElementCount());
17841}
17842
17843static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17844 const Expr *SrcExpr) {
17845 if (!DstType->isFunctionPointerType() ||
17846 !SrcExpr->getType()->isFunctionType())
17847 return false;
17848
17849 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17850 if (!DRE)
17851 return false;
17852
17853 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17854 if (!FD)
17855 return false;
17856
17857 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17858 /*Complain=*/true,
17859 Loc: SrcExpr->getBeginLoc());
17860}
17861
17862bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17863 SourceLocation Loc,
17864 QualType DstType, QualType SrcType,
17865 Expr *SrcExpr, AssignmentAction Action,
17866 bool *Complained) {
17867 if (Complained)
17868 *Complained = false;
17869
17870 // Decode the result (notice that AST's are still created for extensions).
17871 bool CheckInferredResultType = false;
17872 bool isInvalid = false;
17873 unsigned DiagKind = 0;
17874 ConversionFixItGenerator ConvHints;
17875 bool MayHaveConvFixit = false;
17876 bool MayHaveFunctionDiff = false;
17877 const ObjCInterfaceDecl *IFace = nullptr;
17878 const ObjCProtocolDecl *PDecl = nullptr;
17879
17880 switch (ConvTy) {
17881 case AssignConvertType::Compatible:
17882 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17883 return false;
17884 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17885 // Still a valid conversion, but we may want to diagnose for C++
17886 // compatibility reasons.
17887 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17888 break;
17889 case AssignConvertType::PointerToInt:
17890 if (getLangOpts().CPlusPlus) {
17891 DiagKind = diag::err_typecheck_convert_pointer_int;
17892 isInvalid = true;
17893 } else {
17894 DiagKind = diag::ext_typecheck_convert_pointer_int;
17895 }
17896 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17897 MayHaveConvFixit = true;
17898 break;
17899 case AssignConvertType::IntToPointer:
17900 if (getLangOpts().CPlusPlus) {
17901 DiagKind = diag::err_typecheck_convert_int_pointer;
17902 isInvalid = true;
17903 } else {
17904 DiagKind = diag::ext_typecheck_convert_int_pointer;
17905 }
17906 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17907 MayHaveConvFixit = true;
17908 break;
17909 case AssignConvertType::IncompatibleFunctionPointerStrict:
17910 DiagKind =
17911 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17912 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17913 MayHaveConvFixit = true;
17914 break;
17915 case AssignConvertType::IncompatibleFunctionPointer:
17916 if (getLangOpts().CPlusPlus) {
17917 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17918 isInvalid = true;
17919 } else {
17920 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17921 }
17922 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17923 MayHaveConvFixit = true;
17924 break;
17925 case AssignConvertType::IncompatiblePointer:
17926 if (Action == AssignmentAction::Passing_CFAudited) {
17927 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17928 } else if (getLangOpts().CPlusPlus) {
17929 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17930 isInvalid = true;
17931 } else {
17932 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17933 }
17934 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17935 SrcType->isObjCObjectPointerType();
17936 if (CheckInferredResultType) {
17937 SrcType = SrcType.getUnqualifiedType();
17938 DstType = DstType.getUnqualifiedType();
17939 } else {
17940 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17941 }
17942 MayHaveConvFixit = true;
17943 break;
17944 case AssignConvertType::IncompatiblePointerSign:
17945 if (getLangOpts().CPlusPlus) {
17946 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17947 isInvalid = true;
17948 } else {
17949 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17950 }
17951 break;
17952 case AssignConvertType::FunctionVoidPointer:
17953 if (getLangOpts().CPlusPlus) {
17954 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17955 isInvalid = true;
17956 } else {
17957 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17958 }
17959 break;
17960 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17961 // Perform decay if necessary.
17962 if (SrcType->canDecayToPointerType())
17963 SrcType = Context.getDecayedType(T: SrcType);
17964
17965 isInvalid = true;
17966
17967 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17968 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17969 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17970 DiagKind = diag::err_typecheck_incompatible_address_space;
17971 break;
17972 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17973 DiagKind = diag::err_typecheck_incompatible_ownership;
17974 break;
17975 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17976 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17977 break;
17978 }
17979
17980 llvm_unreachable("unknown error case for discarding qualifiers!");
17981 // fallthrough
17982 }
17983 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17984 if (SrcType->isArrayType())
17985 SrcType = Context.getArrayDecayedType(T: SrcType);
17986
17987 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17988 break;
17989 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17990 // If the qualifiers lost were because we were applying the
17991 // (deprecated) C++ conversion from a string literal to a char*
17992 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17993 // Ideally, this check would be performed in
17994 // checkPointerTypesForAssignment. However, that would require a
17995 // bit of refactoring (so that the second argument is an
17996 // expression, rather than a type), which should be done as part
17997 // of a larger effort to fix checkPointerTypesForAssignment for
17998 // C++ semantics.
17999 if (getLangOpts().CPlusPlus &&
18000 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
18001 return false;
18002 if (getLangOpts().CPlusPlus) {
18003 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
18004 isInvalid = true;
18005 } else {
18006 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
18007 }
18008
18009 break;
18010 case AssignConvertType::IncompatibleNestedPointerQualifiers:
18011 if (getLangOpts().CPlusPlus) {
18012 isInvalid = true;
18013 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
18014 } else {
18015 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
18016 }
18017 break;
18018 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
18019 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
18020 isInvalid = true;
18021 break;
18022 case AssignConvertType::IntToBlockPointer:
18023 DiagKind = diag::err_int_to_block_pointer;
18024 isInvalid = true;
18025 break;
18026 case AssignConvertType::IncompatibleBlockPointer:
18027 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
18028 isInvalid = true;
18029 break;
18030 case AssignConvertType::IncompatibleObjCQualifiedId: {
18031 if (SrcType->isObjCQualifiedIdType()) {
18032 const ObjCObjectPointerType *srcOPT =
18033 SrcType->castAs<ObjCObjectPointerType>();
18034 for (auto *srcProto : srcOPT->quals()) {
18035 PDecl = srcProto;
18036 break;
18037 }
18038 if (const ObjCInterfaceType *IFaceT =
18039 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18040 IFace = IFaceT->getDecl();
18041 }
18042 else if (DstType->isObjCQualifiedIdType()) {
18043 const ObjCObjectPointerType *dstOPT =
18044 DstType->castAs<ObjCObjectPointerType>();
18045 for (auto *dstProto : dstOPT->quals()) {
18046 PDecl = dstProto;
18047 break;
18048 }
18049 if (const ObjCInterfaceType *IFaceT =
18050 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
18051 IFace = IFaceT->getDecl();
18052 }
18053 if (getLangOpts().CPlusPlus) {
18054 DiagKind = diag::err_incompatible_qualified_id;
18055 isInvalid = true;
18056 } else {
18057 DiagKind = diag::warn_incompatible_qualified_id;
18058 }
18059 break;
18060 }
18061 case AssignConvertType::IncompatibleVectors:
18062 if (getLangOpts().CPlusPlus) {
18063 DiagKind = diag::err_incompatible_vectors;
18064 isInvalid = true;
18065 } else {
18066 DiagKind = diag::warn_incompatible_vectors;
18067 }
18068 break;
18069 case AssignConvertType::IncompatibleObjCWeakRef:
18070 DiagKind = diag::err_arc_weak_unavailable_assign;
18071 isInvalid = true;
18072 break;
18073 case AssignConvertType::CompatibleOBTDiscards:
18074 return false;
18075 case AssignConvertType::IncompatibleOBTKinds: {
18076 assert(!SrcType->isFunctionType() &&
18077 "Unexpected function type found in IncompatibleOBTKinds assignment");
18078 if (SrcType->canDecayToPointerType())
18079 SrcType = Context.getDecayedType(T: SrcType);
18080
18081 auto getOBTKindName = [](QualType Ty) -> StringRef {
18082 if (Ty->isPointerType())
18083 Ty = Ty->getPointeeType();
18084 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18085 return OBT->getBehaviorKind() ==
18086 OverflowBehaviorType::OverflowBehaviorKind::Trap
18087 ? "__ob_trap"
18088 : "__ob_wrap";
18089 }
18090 llvm_unreachable("OBT kind unhandled");
18091 };
18092
18093 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
18094 << DstType << SrcType << getOBTKindName(DstType)
18095 << getOBTKindName(SrcType);
18096 isInvalid = true;
18097 return true;
18098 }
18099 case AssignConvertType::Incompatible:
18100 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
18101 if (Complained)
18102 *Complained = true;
18103 return true;
18104 }
18105
18106 DiagKind = diag::err_typecheck_convert_incompatible;
18107 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
18108 MayHaveConvFixit = true;
18109 isInvalid = true;
18110 MayHaveFunctionDiff = true;
18111 break;
18112 }
18113
18114 QualType FirstType, SecondType;
18115 switch (Action) {
18116 case AssignmentAction::Assigning:
18117 case AssignmentAction::Initializing:
18118 // The destination type comes first.
18119 FirstType = DstType;
18120 SecondType = SrcType;
18121 break;
18122
18123 case AssignmentAction::Returning:
18124 case AssignmentAction::Passing:
18125 case AssignmentAction::Passing_CFAudited:
18126 case AssignmentAction::Converting:
18127 case AssignmentAction::Sending:
18128 case AssignmentAction::Casting:
18129 // The source type comes first.
18130 FirstType = SrcType;
18131 SecondType = DstType;
18132 break;
18133 }
18134
18135 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
18136 AssignmentAction ActionForDiag = Action;
18137 if (Action == AssignmentAction::Passing_CFAudited)
18138 ActionForDiag = AssignmentAction::Passing;
18139
18140 FDiag << FirstType << SecondType << ActionForDiag
18141 << SrcExpr->getSourceRange();
18142
18143 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18144 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18145 auto isPlainChar = [](const clang::Type *Type) {
18146 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
18147 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
18148 };
18149 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18150 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18151 }
18152
18153 // If we can fix the conversion, suggest the FixIts.
18154 if (!ConvHints.isNull()) {
18155 for (FixItHint &H : ConvHints.Hints)
18156 FDiag << H;
18157 }
18158
18159 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18160
18161 if (MayHaveFunctionDiff)
18162 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
18163
18164 Diag(Loc, PD: FDiag);
18165 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18166 DiagKind == diag::err_incompatible_qualified_id) &&
18167 PDecl && IFace && !IFace->hasDefinition())
18168 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
18169 << IFace << PDecl;
18170
18171 if (SecondType == Context.OverloadTy)
18172 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
18173 DestType: FirstType, /*TakingAddress=*/true);
18174
18175 if (CheckInferredResultType)
18176 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
18177
18178 if (Action == AssignmentAction::Returning &&
18179 ConvTy == AssignConvertType::IncompatiblePointer)
18180 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
18181
18182 if (Complained)
18183 *Complained = true;
18184 return isInvalid;
18185}
18186
18187ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18188 llvm::APSInt *Result,
18189 AllowFoldKind CanFold) {
18190 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18191 public:
18192 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18193 QualType T) override {
18194 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
18195 << T << S.LangOpts.CPlusPlus;
18196 }
18197 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18198 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18199 }
18200 } Diagnoser;
18201
18202 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18203}
18204
18205ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
18206 llvm::APSInt *Result,
18207 unsigned DiagID,
18208 AllowFoldKind CanFold) {
18209 class IDDiagnoser : public VerifyICEDiagnoser {
18210 unsigned DiagID;
18211
18212 public:
18213 IDDiagnoser(unsigned DiagID)
18214 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18215
18216 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18217 return S.Diag(Loc, DiagID);
18218 }
18219 } Diagnoser(DiagID);
18220
18221 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18222}
18223
18224Sema::SemaDiagnosticBuilder
18225Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
18226 QualType T) {
18227 return diagnoseNotICE(S, Loc);
18228}
18229
18230Sema::SemaDiagnosticBuilder
18231Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18232 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18233}
18234
18235ExprResult
18236Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18237 VerifyICEDiagnoser &Diagnoser,
18238 AllowFoldKind CanFold) {
18239 SourceLocation DiagLoc = E->getBeginLoc();
18240
18241 if (getLangOpts().CPlusPlus11) {
18242 // C++11 [expr.const]p5:
18243 // If an expression of literal class type is used in a context where an
18244 // integral constant expression is required, then that class type shall
18245 // have a single non-explicit conversion function to an integral or
18246 // unscoped enumeration type
18247 ExprResult Converted;
18248 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18249 VerifyICEDiagnoser &BaseDiagnoser;
18250 public:
18251 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18252 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18253 BaseDiagnoser.Suppress, true),
18254 BaseDiagnoser(BaseDiagnoser) {}
18255
18256 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18257 QualType T) override {
18258 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18259 }
18260
18261 SemaDiagnosticBuilder diagnoseIncomplete(
18262 Sema &S, SourceLocation Loc, QualType T) override {
18263 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
18264 }
18265
18266 SemaDiagnosticBuilder diagnoseExplicitConv(
18267 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18268 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
18269 }
18270
18271 SemaDiagnosticBuilder noteExplicitConv(
18272 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18273 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18274 << ConvTy->isEnumeralType() << ConvTy;
18275 }
18276
18277 SemaDiagnosticBuilder diagnoseAmbiguous(
18278 Sema &S, SourceLocation Loc, QualType T) override {
18279 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
18280 }
18281
18282 SemaDiagnosticBuilder noteAmbiguous(
18283 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18284 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
18285 << ConvTy->isEnumeralType() << ConvTy;
18286 }
18287
18288 SemaDiagnosticBuilder diagnoseConversion(
18289 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18290 llvm_unreachable("conversion functions are permitted");
18291 }
18292 } ConvertDiagnoser(Diagnoser);
18293
18294 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
18295 Converter&: ConvertDiagnoser);
18296 if (Converted.isInvalid())
18297 return Converted;
18298 E = Converted.get();
18299 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18300 // don't try to evaluate it later. We also don't want to return the
18301 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18302 // this function will attempt to use 'Value'.
18303 if (isa<RecoveryExpr>(Val: E))
18304 return ExprError();
18305 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18306 return ExprError();
18307 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18308 // An ICE must be of integral or unscoped enumeration type.
18309 if (!Diagnoser.Suppress)
18310 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18311 << E->getSourceRange();
18312 return ExprError();
18313 }
18314
18315 ExprResult RValueExpr = DefaultLvalueConversion(E);
18316 if (RValueExpr.isInvalid())
18317 return ExprError();
18318
18319 E = RValueExpr.get();
18320
18321 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18322 // in the non-ICE case.
18323 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18324 SmallVector<PartialDiagnosticAt, 8> Notes;
18325 if (Result)
18326 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18327 if (!isa<ConstantExpr>(Val: E))
18328 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18329 : ConstantExpr::Create(Context, E);
18330
18331 if (Notes.empty())
18332 return E;
18333
18334 // If our only note is the usual "invalid subexpression" note, just point
18335 // the caret at its location rather than producing an essentially
18336 // redundant note.
18337 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18338 diag::note_invalid_subexpr_in_const_expr) {
18339 DiagLoc = Notes[0].first;
18340 Notes.clear();
18341 }
18342
18343 if (getLangOpts().CPlusPlus) {
18344 if (!Diagnoser.Suppress) {
18345 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18346 for (const PartialDiagnosticAt &Note : Notes)
18347 Diag(Loc: Note.first, PD: Note.second);
18348 }
18349 return ExprError();
18350 }
18351
18352 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18353 for (const PartialDiagnosticAt &Note : Notes)
18354 Diag(Loc: Note.first, PD: Note.second);
18355
18356 return E;
18357 }
18358
18359 Expr::EvalResult EvalResult;
18360 SmallVector<PartialDiagnosticAt, 8> Notes;
18361 SmallVector<PartialDiagnosticAt> MSWarning;
18362 EvalResult.Diag = &Notes;
18363 EvalResult.ExtendedDiag = &MSWarning;
18364
18365 // Try to evaluate the expression, and produce diagnostics explaining why it's
18366 // not a constant expression as a side-effect.
18367 bool Folded =
18368 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18369 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18370 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18371
18372 if (!isa<ConstantExpr>(Val: E))
18373 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18374
18375 // For -fms-compatibility mode we relax some requirements
18376 // for constant folding in non-SFINAE contexts
18377 if (!MSWarning.empty()) {
18378 if (isSFINAEContext()) {
18379 Folded = false;
18380 } else {
18381 for (auto &Info : MSWarning)
18382 Diag(Loc: Info.first, PD: Info.second);
18383 }
18384 }
18385
18386 // In C++11, we can rely on diagnostics being produced for any expression
18387 // which is not a constant expression. If no diagnostics were produced, then
18388 // this is a constant expression.
18389 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18390 if (Result)
18391 *Result = EvalResult.Val.getInt();
18392 return E;
18393 }
18394
18395 // If our only note is the usual "invalid subexpression" note, just point
18396 // the caret at its location rather than producing an essentially
18397 // redundant note.
18398 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18399 diag::note_invalid_subexpr_in_const_expr) {
18400 DiagLoc = Notes[0].first;
18401 Notes.clear();
18402 }
18403
18404 if (!Folded || CanFold == AllowFoldKind::No) {
18405 if (!Diagnoser.Suppress) {
18406 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18407 for (const PartialDiagnosticAt &Note : Notes)
18408 Diag(Loc: Note.first, PD: Note.second);
18409 }
18410
18411 return ExprError();
18412 }
18413
18414 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18415 for (const PartialDiagnosticAt &Note : Notes)
18416 Diag(Loc: Note.first, PD: Note.second);
18417
18418 if (Result)
18419 *Result = EvalResult.Val.getInt();
18420 return E;
18421}
18422
18423namespace {
18424 // Handle the case where we conclude a expression which we speculatively
18425 // considered to be unevaluated is actually evaluated.
18426 class TransformToPE : public TreeTransform<TransformToPE> {
18427 typedef TreeTransform<TransformToPE> BaseTransform;
18428
18429 public:
18430 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18431
18432 // Make sure we redo semantic analysis
18433 bool AlwaysRebuild() { return true; }
18434 bool ReplacingOriginal() { return true; }
18435
18436 // We need to special-case DeclRefExprs referring to FieldDecls which
18437 // are not part of a member pointer formation; normal TreeTransforming
18438 // doesn't catch this case because of the way we represent them in the AST.
18439 // FIXME: This is a bit ugly; is it really the best way to handle this
18440 // case?
18441 //
18442 // Error on DeclRefExprs referring to FieldDecls.
18443 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18444 if (isa<FieldDecl>(Val: E->getDecl()) &&
18445 !SemaRef.isUnevaluatedContext())
18446 return SemaRef.Diag(Loc: E->getLocation(),
18447 DiagID: diag::err_invalid_non_static_member_use)
18448 << E->getDecl() << E->getSourceRange();
18449
18450 return BaseTransform::TransformDeclRefExpr(E);
18451 }
18452
18453 // Exception: filter out member pointer formation
18454 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18455 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18456 return E;
18457
18458 return BaseTransform::TransformUnaryOperator(E);
18459 }
18460
18461 // The body of a lambda-expression is in a separate expression evaluation
18462 // context so never needs to be transformed.
18463 // FIXME: Ideally we wouldn't transform the closure type either, and would
18464 // just recreate the capture expressions and lambda expression.
18465 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18466 return SkipLambdaBody(E, S: Body);
18467 }
18468 };
18469}
18470
18471ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18472 assert(isUnevaluatedContext() &&
18473 "Should only transform unevaluated expressions");
18474 ExprEvalContexts.back().Context =
18475 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18476 if (isUnevaluatedContext())
18477 return E;
18478 return TransformToPE(*this).TransformExpr(E);
18479}
18480
18481TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18482 assert(isUnevaluatedContext() &&
18483 "Should only transform unevaluated expressions");
18484 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18485 if (isUnevaluatedContext())
18486 return TInfo;
18487 return TransformToPE(*this).TransformType(TSI: TInfo);
18488}
18489
18490void
18491Sema::PushExpressionEvaluationContext(
18492 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18493 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18494 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18495 Args&: LambdaContextDecl, Args&: ExprContext);
18496
18497 // Discarded statements and immediate contexts nested in other
18498 // discarded statements or immediate context are themselves
18499 // a discarded statement or an immediate context, respectively.
18500 ExprEvalContexts.back().InDiscardedStatement =
18501 parentEvaluationContext().isDiscardedStatementContext();
18502
18503 // C++23 [expr.const]/p15
18504 // An expression or conversion is in an immediate function context if [...]
18505 // it is a subexpression of a manifestly constant-evaluated expression or
18506 // conversion.
18507 const auto &Prev = parentEvaluationContext();
18508 ExprEvalContexts.back().InImmediateFunctionContext =
18509 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18510
18511 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18512 Prev.InImmediateEscalatingFunctionContext;
18513
18514 Cleanup.reset();
18515 if (!MaybeODRUseExprs.empty())
18516 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18517}
18518
18519void
18520Sema::PushExpressionEvaluationContext(
18521 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18522 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18523 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18524 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18525}
18526
18527void Sema::PushExpressionEvaluationContextForFunction(
18528 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18529 // [expr.const]/p14.1
18530 // An expression or conversion is in an immediate function context if it is
18531 // potentially evaluated and either: its innermost enclosing non-block scope
18532 // is a function parameter scope of an immediate function.
18533 PushExpressionEvaluationContext(
18534 NewContext: FD && FD->isConsteval()
18535 ? ExpressionEvaluationContext::ImmediateFunctionContext
18536 : NewContext);
18537 const Sema::ExpressionEvaluationContextRecord &Parent =
18538 parentEvaluationContext();
18539 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18540
18541 Current.InDiscardedStatement = false;
18542
18543 if (FD) {
18544
18545 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18546 // context is nested in an immediate function context, so smaller contexts
18547 // that appear inside immediate functions (like variable initializers) are
18548 // considered to be inside an immediate function context even though by
18549 // themselves they are not immediate function contexts. But when a new
18550 // function is entered, we need to reset this tracking, since the entered
18551 // function might be not an immediate function.
18552
18553 Current.InImmediateEscalatingFunctionContext =
18554 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18555
18556 if (isLambdaMethod(DC: FD) && !isLambdaCallOperator(DC: FD))
18557 Current.InImmediateFunctionContext = FD->isConsteval() ||
18558 Parent.isConstantEvaluated() ||
18559 Parent.isImmediateFunctionContext();
18560 else
18561 Current.InImmediateFunctionContext = FD->isConsteval();
18562 }
18563}
18564
18565ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18566 TypeSourceInfo *TSI) {
18567 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18568}
18569
18570ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18571 TypeSourceInfo *TSI) {
18572 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TSI);
18573}
18574
18575namespace {
18576
18577const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18578 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18579 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18580 if (E->getOpcode() == UO_Deref)
18581 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18582 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18583 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18584 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18585 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18586 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18587 QualType Inner;
18588 QualType Ty = E->getType();
18589 if (const auto *Ptr = Ty->getAs<PointerType>())
18590 Inner = Ptr->getPointeeType();
18591 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18592 Inner = Arr->getElementType();
18593 else
18594 return nullptr;
18595
18596 if (Inner->hasAttr(AK: attr::NoDeref))
18597 return E;
18598 }
18599 return nullptr;
18600}
18601
18602} // namespace
18603
18604void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18605 for (const Expr *E : Rec.PossibleDerefs) {
18606 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18607 if (DeclRef) {
18608 const ValueDecl *Decl = DeclRef->getDecl();
18609 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18610 << Decl->getName() << E->getSourceRange();
18611 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18612 } else {
18613 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18614 << E->getSourceRange();
18615 }
18616 }
18617 Rec.PossibleDerefs.clear();
18618}
18619
18620void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18621 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18622 return;
18623
18624 // Note: ignoring parens here is not justified by the standard rules, but
18625 // ignoring parentheses seems like a more reasonable approach, and this only
18626 // drives a deprecation warning so doesn't affect conformance.
18627 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18628 if (BO->getOpcode() == BO_Assign) {
18629 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18630 llvm::erase(C&: LHSs, V: BO->getLHS());
18631 }
18632 }
18633}
18634
18635void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18636 assert(getLangOpts().CPlusPlus20 &&
18637 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18638 "Cannot mark an immediate escalating expression outside of an "
18639 "immediate escalating context");
18640 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18641 Call && Call->getCallee()) {
18642 if (auto *DeclRef =
18643 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18644 DeclRef->setIsImmediateEscalating(true);
18645 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18646 Ctr->setIsImmediateEscalating(true);
18647 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18648 DeclRef->setIsImmediateEscalating(true);
18649 } else {
18650 assert(false && "expected an immediately escalating expression");
18651 }
18652 if (FunctionScopeInfo *FI = getCurFunction())
18653 FI->FoundImmediateEscalatingExpression = true;
18654}
18655
18656ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18657 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18658 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18659 isCheckingDefaultArgumentOrInitializer() ||
18660 RebuildingImmediateInvocation || isImmediateFunctionContext())
18661 return E;
18662
18663 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18664 /// It's OK if this fails; we'll also remove this in
18665 /// HandleImmediateInvocations, but catching it here allows us to avoid
18666 /// walking the AST looking for it in simple cases.
18667 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18668 if (auto *DeclRef =
18669 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18670 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18671
18672 // C++23 [expr.const]/p16
18673 // An expression or conversion is immediate-escalating if it is not initially
18674 // in an immediate function context and it is [...] an immediate invocation
18675 // that is not a constant expression and is not a subexpression of an
18676 // immediate invocation.
18677 APValue Cached;
18678 auto CheckConstantExpressionAndKeepResult = [&]() {
18679 Expr::EvalResult Eval;
18680 bool Res = E.get()->EvaluateAsConstantExpr(
18681 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18682 if (Res && !Eval.DiagEmitted) {
18683 Cached = std::move(Eval.Val);
18684 return true;
18685 }
18686 return false;
18687 };
18688
18689 if (!E.get()->isValueDependent() &&
18690 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18691 !CheckConstantExpressionAndKeepResult()) {
18692 MarkExpressionAsImmediateEscalating(E: E.get());
18693 return E;
18694 }
18695
18696 if (Cleanup.exprNeedsCleanups()) {
18697 // Since an immediate invocation is a full expression itself - it requires
18698 // an additional ExprWithCleanups node, but it can participate to a bigger
18699 // full expression which actually requires cleanups to be run after so
18700 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18701 // may discard cleanups for outer expression too early.
18702
18703 // Note that ExprWithCleanups created here must always have empty cleanup
18704 // objects:
18705 // - compound literals do not create cleanup objects in C++ and immediate
18706 // invocations are C++-only.
18707 // - blocks are not allowed inside constant expressions and compiler will
18708 // issue an error if they appear there.
18709 //
18710 // Hence, in correct code any cleanup objects created inside current
18711 // evaluation context must be outside the immediate invocation.
18712 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18713 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18714 }
18715
18716 ConstantExpr *Res = ConstantExpr::Create(
18717 Context: getASTContext(), E: E.get(),
18718 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18719 Context: getASTContext()),
18720 /*IsImmediateInvocation*/ true);
18721 if (Cached.hasValue())
18722 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18723 /// Value-dependent constant expressions should not be immediately
18724 /// evaluated until they are instantiated.
18725 if (!Res->isValueDependent())
18726 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18727 return Res;
18728}
18729
18730static void EvaluateAndDiagnoseImmediateInvocation(
18731 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18732 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18733 Expr::EvalResult Eval;
18734 Eval.Diag = &Notes;
18735 ConstantExpr *CE = Candidate.getPointer();
18736 bool Result = CE->EvaluateAsConstantExpr(
18737 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18738 if (!Result || !Notes.empty()) {
18739 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18740 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18741 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18742 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18743 FunctionDecl *FD = nullptr;
18744 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18745 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18746 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18747 FD = Call->getConstructor();
18748 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18749 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18750
18751 assert(FD && FD->isImmediateFunction() &&
18752 "could not find an immediate function in this expression");
18753 if (FD->isInvalidDecl())
18754 return;
18755 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18756 << FD << FD->isConsteval();
18757 if (auto Context =
18758 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18759 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18760 << Context->Decl;
18761 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18762 }
18763 if (!FD->isConsteval())
18764 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18765 for (auto &Note : Notes)
18766 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18767 return;
18768 }
18769 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18770}
18771
18772static void RemoveNestedImmediateInvocation(
18773 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18774 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18775 struct ComplexRemove : TreeTransform<ComplexRemove> {
18776 using Base = TreeTransform<ComplexRemove>;
18777 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18778 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18779 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18780 CurrentII;
18781 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18782 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18783 SmallVector<Sema::ImmediateInvocationCandidate,
18784 4>::reverse_iterator Current)
18785 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18786 void RemoveImmediateInvocation(ConstantExpr* E) {
18787 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18788 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18789 return Elem.getPointer() == E;
18790 });
18791 // It is possible that some subexpression of the current immediate
18792 // invocation was handled from another expression evaluation context. Do
18793 // not handle the current immediate invocation if some of its
18794 // subexpressions failed before.
18795 if (It == IISet.rend()) {
18796 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18797 CurrentII->setInt(1);
18798 } else {
18799 It->setInt(1); // Mark as deleted
18800 }
18801 }
18802 ExprResult TransformConstantExpr(ConstantExpr *E) {
18803 if (!E->isImmediateInvocation())
18804 return Base::TransformConstantExpr(E);
18805 RemoveImmediateInvocation(E);
18806 return Base::TransformExpr(E: E->getSubExpr());
18807 }
18808 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18809 /// we need to remove its DeclRefExpr from the DRSet.
18810 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18811 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18812 return Base::TransformCXXOperatorCallExpr(E);
18813 }
18814 /// Base::TransformUserDefinedLiteral doesn't preserve the
18815 /// UserDefinedLiteral node.
18816 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18817 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18818 /// here.
18819 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18820 if (!Init)
18821 return Init;
18822
18823 // We cannot use IgnoreImpCasts because we need to preserve
18824 // full expressions.
18825 while (true) {
18826 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18827 Init = ICE->getSubExpr();
18828 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18829 Init = ICE->getSubExpr();
18830 else
18831 break;
18832 }
18833 /// ConstantExprs are the first layer of implicit node to be removed so if
18834 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18835 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18836 CE && CE->isImmediateInvocation())
18837 RemoveImmediateInvocation(E: CE);
18838 return Base::TransformInitializer(Init, NotCopyInit);
18839 }
18840 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18841 DRSet.erase(Ptr: E);
18842 return E;
18843 }
18844 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18845 // Do not rebuild lambdas to avoid creating a new type.
18846 // Lambdas have already been processed inside their eval contexts.
18847 return E;
18848 }
18849
18850 // We do not have enough information to transform opaque expressions and
18851 // assume they do not contain immediate subexpressions.
18852 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18853
18854 bool AlwaysRebuild() { return false; }
18855 bool ReplacingOriginal() { return true; }
18856 bool AllowSkippingCXXConstructExpr() {
18857 bool Res = AllowSkippingFirstCXXConstructExpr;
18858 AllowSkippingFirstCXXConstructExpr = true;
18859 return Res;
18860 }
18861 bool AllowSkippingFirstCXXConstructExpr = true;
18862 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18863 Rec.ImmediateInvocationCandidates, It);
18864
18865 /// CXXConstructExpr with a single argument are getting skipped by
18866 /// TreeTransform in some situtation because they could be implicit. This
18867 /// can only occur for the top-level CXXConstructExpr because it is used
18868 /// nowhere in the expression being transformed therefore will not be rebuilt.
18869 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18870 /// skipping the first CXXConstructExpr.
18871 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18872 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18873
18874 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18875 // The result may not be usable in case of previous compilation errors.
18876 // In this case evaluation of the expression may result in crash so just
18877 // don't do anything further with the result.
18878 if (Res.isUsable()) {
18879 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18880 It->getPointer()->setSubExpr(Res.get());
18881 }
18882}
18883
18884static void
18885HandleImmediateInvocations(Sema &SemaRef,
18886 Sema::ExpressionEvaluationContextRecord &Rec) {
18887 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18888 Rec.ReferenceToConsteval.size() == 0) ||
18889 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18890 return;
18891
18892 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18893 // [...]
18894 // - the initializer of a variable that is usable in constant expressions or
18895 // has constant initialization.
18896 if (SemaRef.getLangOpts().CPlusPlus23 &&
18897 Rec.ExprContext ==
18898 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18899 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18900 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18901 VD->hasConstantInitialization())) {
18902 // An expression or conversion is in an 'immediate function context' if it
18903 // is potentially evaluated and either:
18904 // [...]
18905 // - it is a subexpression of a manifestly constant-evaluated expression
18906 // or conversion.
18907 return;
18908 }
18909 }
18910
18911 /// When we have more than 1 ImmediateInvocationCandidates or previously
18912 /// failed immediate invocations, we need to check for nested
18913 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18914 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18915 /// invocation.
18916 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18917 !SemaRef.FailedImmediateInvocations.empty()) {
18918
18919 /// Prevent sema calls during the tree transform from adding pointers that
18920 /// are already in the sets.
18921 llvm::SaveAndRestore DisableIITracking(
18922 SemaRef.RebuildingImmediateInvocation, true);
18923
18924 /// Prevent diagnostic during tree transfrom as they are duplicates
18925 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18926
18927 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18928 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18929 if (!It->getInt())
18930 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18931 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18932 Rec.ReferenceToConsteval.size()) {
18933 struct SimpleRemove : DynamicRecursiveASTVisitor {
18934 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18935 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18936 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18937 DRSet.erase(Ptr: E);
18938 return DRSet.size();
18939 }
18940 } Visitor(Rec.ReferenceToConsteval);
18941 Visitor.TraverseStmt(
18942 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18943 }
18944 for (auto CE : Rec.ImmediateInvocationCandidates)
18945 if (!CE.getInt())
18946 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18947 for (auto *DR : Rec.ReferenceToConsteval) {
18948 // If the expression is immediate escalating, it is not an error;
18949 // The outer context itself becomes immediate and further errors,
18950 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18951 if (DR->isImmediateEscalating())
18952 continue;
18953 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18954 const NamedDecl *ND = FD;
18955 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18956 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18957 ND = MD->getParent();
18958
18959 // C++23 [expr.const]/p16
18960 // An expression or conversion is immediate-escalating if it is not
18961 // initially in an immediate function context and it is [...] a
18962 // potentially-evaluated id-expression that denotes an immediate function
18963 // that is not a subexpression of an immediate invocation.
18964 bool ImmediateEscalating = false;
18965 bool IsPotentiallyEvaluated =
18966 Rec.Context ==
18967 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18968 Rec.Context ==
18969 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18970 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18971 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18972
18973 if (!Rec.InImmediateEscalatingFunctionContext ||
18974 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18975 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18976 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18977 if (!FD->getBuiltinID())
18978 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18979 if (auto Context =
18980 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18981 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18982 << Context->Decl;
18983 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18984 }
18985 if (FD->isImmediateEscalating() && !FD->isConsteval())
18986 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18987
18988 } else {
18989 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18990 }
18991 }
18992}
18993
18994void Sema::PopExpressionEvaluationContext() {
18995 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18996 if (!Rec.Lambdas.empty()) {
18997 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18998 if (!getLangOpts().CPlusPlus20 &&
18999 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
19000 Rec.isUnevaluated() ||
19001 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
19002 unsigned D;
19003 if (Rec.isUnevaluated()) {
19004 // C++11 [expr.prim.lambda]p2:
19005 // A lambda-expression shall not appear in an unevaluated operand
19006 // (Clause 5).
19007 D = diag::err_lambda_unevaluated_operand;
19008 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
19009 // C++1y [expr.const]p2:
19010 // A conditional-expression e is a core constant expression unless the
19011 // evaluation of e, following the rules of the abstract machine, would
19012 // evaluate [...] a lambda-expression.
19013 D = diag::err_lambda_in_constant_expression;
19014 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
19015 // C++17 [expr.prim.lamda]p2:
19016 // A lambda-expression shall not appear [...] in a template-argument.
19017 D = diag::err_lambda_in_invalid_context;
19018 } else
19019 llvm_unreachable("Couldn't infer lambda error message.");
19020
19021 for (const auto *L : Rec.Lambdas)
19022 Diag(Loc: L->getBeginLoc(), DiagID: D);
19023 }
19024 }
19025
19026 // Append the collected materialized temporaries into previous context before
19027 // exit if the previous also is a lifetime extending context.
19028 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
19029 parentEvaluationContext().InLifetimeExtendingContext &&
19030 !Rec.ForRangeLifetimeExtendTemps.empty()) {
19031 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
19032 RHS: Rec.ForRangeLifetimeExtendTemps);
19033 }
19034
19035 WarnOnPendingNoDerefs(Rec);
19036 HandleImmediateInvocations(SemaRef&: *this, Rec);
19037
19038 // Warn on any volatile-qualified simple-assignments that are not discarded-
19039 // value expressions nor unevaluated operands (those cases get removed from
19040 // this list by CheckUnusedVolatileAssignment).
19041 for (auto *BO : Rec.VolatileAssignmentLHSs)
19042 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
19043 << BO->getType();
19044
19045 // When are coming out of an unevaluated context, clear out any
19046 // temporaries that we may have created as part of the evaluation of
19047 // the expression in that context: they aren't relevant because they
19048 // will never be constructed.
19049 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
19050 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
19051 CE: ExprCleanupObjects.end());
19052 Cleanup = Rec.ParentCleanup;
19053 CleanupVarDeclMarking();
19054 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
19055 // Otherwise, merge the contexts together.
19056 } else {
19057 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
19058 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
19059 }
19060
19061 DiagnoseMisalignedMembers();
19062
19063 // Pop the current expression evaluation context off the stack.
19064 ExprEvalContexts.pop_back();
19065}
19066
19067void Sema::DiscardCleanupsInEvaluationContext() {
19068 ExprCleanupObjects.erase(
19069 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19070 CE: ExprCleanupObjects.end());
19071 Cleanup.reset();
19072 MaybeODRUseExprs.clear();
19073}
19074
19075ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
19076 ExprResult Result = CheckPlaceholderExpr(E);
19077 if (Result.isInvalid())
19078 return ExprError();
19079 E = Result.get();
19080 if (!E->getType()->isVariablyModifiedType())
19081 return E;
19082 return TransformToPotentiallyEvaluated(E);
19083}
19084
19085/// Are we in a context that is potentially constant evaluated per C++20
19086/// [expr.const]p12?
19087static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
19088 /// C++2a [expr.const]p12:
19089 // An expression or conversion is potentially constant evaluated if it is
19090 switch (SemaRef.ExprEvalContexts.back().Context) {
19091 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
19092 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
19093
19094 // -- a manifestly constant-evaluated expression,
19095 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
19096 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19097 case Sema::ExpressionEvaluationContext::DiscardedStatement:
19098 // -- a potentially-evaluated expression,
19099 case Sema::ExpressionEvaluationContext::UnevaluatedList:
19100 // -- an immediate subexpression of a braced-init-list,
19101
19102 // -- [FIXME] an expression of the form & cast-expression that occurs
19103 // within a templated entity
19104 // -- a subexpression of one of the above that is not a subexpression of
19105 // a nested unevaluated operand.
19106 return true;
19107
19108 case Sema::ExpressionEvaluationContext::Unevaluated:
19109 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
19110 // Expressions in this context are never evaluated.
19111 return false;
19112 }
19113 llvm_unreachable("Invalid context");
19114}
19115
19116/// Return true if this function has a calling convention that requires mangling
19117/// in the size of the parameter pack.
19118static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
19119 // These manglings are only applicable for targets whcih use Microsoft
19120 // mangling scheme for C.
19121 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
19122 return false;
19123
19124 // If this is C++ and this isn't an extern "C" function, parameters do not
19125 // need to be complete. In this case, C++ mangling will apply, which doesn't
19126 // use the size of the parameters.
19127 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19128 return false;
19129
19130 // Stdcall, fastcall, and vectorcall need this special treatment.
19131 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19132 switch (CC) {
19133 case CC_X86StdCall:
19134 case CC_X86FastCall:
19135 case CC_X86VectorCall:
19136 return true;
19137 default:
19138 break;
19139 }
19140 return false;
19141}
19142
19143/// Require that all of the parameter types of function be complete. Normally,
19144/// parameter types are only required to be complete when a function is called
19145/// or defined, but to mangle functions with certain calling conventions, the
19146/// mangler needs to know the size of the parameter list. In this situation,
19147/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19148/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19149/// result in a linker error. Clang doesn't implement this behavior, and instead
19150/// attempts to error at compile time.
19151static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
19152 SourceLocation Loc) {
19153 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19154 FunctionDecl *FD;
19155 ParmVarDecl *Param;
19156
19157 public:
19158 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19159 : FD(FD), Param(Param) {}
19160
19161 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19162 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19163 StringRef CCName;
19164 switch (CC) {
19165 case CC_X86StdCall:
19166 CCName = "stdcall";
19167 break;
19168 case CC_X86FastCall:
19169 CCName = "fastcall";
19170 break;
19171 case CC_X86VectorCall:
19172 CCName = "vectorcall";
19173 break;
19174 default:
19175 llvm_unreachable("CC does not need mangling");
19176 }
19177
19178 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
19179 << Param->getDeclName() << FD->getDeclName() << CCName;
19180 }
19181 };
19182
19183 for (ParmVarDecl *Param : FD->parameters()) {
19184 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19185 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
19186 }
19187}
19188
19189namespace {
19190enum class OdrUseContext {
19191 /// Declarations in this context are not odr-used.
19192 None,
19193 /// Declarations in this context are formally odr-used, but this is a
19194 /// dependent context.
19195 Dependent,
19196 /// Declarations in this context are odr-used but not actually used (yet).
19197 FormallyOdrUsed,
19198 /// Declarations in this context are used.
19199 Used
19200};
19201}
19202
19203/// Are we within a context in which references to resolved functions or to
19204/// variables result in odr-use?
19205static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19206 const Sema::ExpressionEvaluationContextRecord &Context =
19207 SemaRef.currentEvaluationContext();
19208
19209 if (Context.isUnevaluated())
19210 return OdrUseContext::None;
19211
19212 if (SemaRef.CurContext->isDependentContext())
19213 return OdrUseContext::Dependent;
19214
19215 if (Context.isDiscardedStatementContext())
19216 return OdrUseContext::FormallyOdrUsed;
19217
19218 else if (Context.Context ==
19219 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
19220 return OdrUseContext::FormallyOdrUsed;
19221
19222 return OdrUseContext::Used;
19223}
19224
19225static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
19226 if (!Func->isConstexpr())
19227 return false;
19228
19229 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19230 return true;
19231
19232 // Lambda conversion operators are never user provided.
19233 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
19234 return isLambdaConversionOperator(C: Conv);
19235
19236 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
19237 return CCD && CCD->getInheritedConstructor();
19238}
19239
19240void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
19241 bool MightBeOdrUse) {
19242 assert(Func && "No function?");
19243
19244 Func->setReferenced();
19245
19246 // Recursive functions aren't really used until they're used from some other
19247 // context.
19248 bool IsRecursiveCall = CurContext == Func;
19249
19250 // C++11 [basic.def.odr]p3:
19251 // A function whose name appears as a potentially-evaluated expression is
19252 // odr-used if it is the unique lookup result or the selected member of a
19253 // set of overloaded functions [...].
19254 //
19255 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19256 // can just check that here.
19257 OdrUseContext OdrUse =
19258 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
19259 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19260 OdrUse = OdrUseContext::FormallyOdrUsed;
19261
19262 // Trivial default constructors and destructors are never actually used.
19263 // FIXME: What about other special members?
19264 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19265 OdrUse == OdrUseContext::Used) {
19266 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
19267 if (Constructor->isDefaultConstructor())
19268 OdrUse = OdrUseContext::FormallyOdrUsed;
19269 if (isa<CXXDestructorDecl>(Val: Func))
19270 OdrUse = OdrUseContext::FormallyOdrUsed;
19271 }
19272
19273 // C++20 [expr.const]p12:
19274 // A function [...] is needed for constant evaluation if it is [...] a
19275 // constexpr function that is named by an expression that is potentially
19276 // constant evaluated
19277 bool NeededForConstantEvaluation =
19278 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
19279 isImplicitlyDefinableConstexprFunction(Func);
19280
19281 // Determine whether we require a function definition to exist, per
19282 // C++11 [temp.inst]p3:
19283 // Unless a function template specialization has been explicitly
19284 // instantiated or explicitly specialized, the function template
19285 // specialization is implicitly instantiated when the specialization is
19286 // referenced in a context that requires a function definition to exist.
19287 // C++20 [temp.inst]p7:
19288 // The existence of a definition of a [...] function is considered to
19289 // affect the semantics of the program if the [...] function is needed for
19290 // constant evaluation by an expression
19291 // C++20 [basic.def.odr]p10:
19292 // Every program shall contain exactly one definition of every non-inline
19293 // function or variable that is odr-used in that program outside of a
19294 // discarded statement
19295 // C++20 [special]p1:
19296 // The implementation will implicitly define [defaulted special members]
19297 // if they are odr-used or needed for constant evaluation.
19298 //
19299 // Note that we skip the implicit instantiation of templates that are only
19300 // used in unused default arguments or by recursive calls to themselves.
19301 // This is formally non-conforming, but seems reasonable in practice.
19302 bool NeedDefinition =
19303 !IsRecursiveCall &&
19304 (OdrUse == OdrUseContext::Used ||
19305 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19306
19307 // C++14 [temp.expl.spec]p6:
19308 // If a template [...] is explicitly specialized then that specialization
19309 // shall be declared before the first use of that specialization that would
19310 // cause an implicit instantiation to take place, in every translation unit
19311 // in which such a use occurs
19312 if (NeedDefinition &&
19313 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19314 Func->getMemberSpecializationInfo()))
19315 checkSpecializationReachability(Loc, Spec: Func);
19316
19317 if (getLangOpts().CUDA)
19318 CUDA().CheckCall(Loc, Callee: Func);
19319
19320 // If we need a definition, try to create one.
19321 if (NeedDefinition && !Func->getBody()) {
19322 runWithSufficientStackSpace(Loc, Fn: [&] {
19323 if (CXXConstructorDecl *Constructor =
19324 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19325 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19326 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19327 if (Constructor->isDefaultConstructor()) {
19328 if (Constructor->isTrivial() &&
19329 !Constructor->hasAttr<DLLExportAttr>())
19330 return;
19331 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19332 } else if (Constructor->isCopyConstructor()) {
19333 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19334 } else if (Constructor->isMoveConstructor()) {
19335 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19336 }
19337 } else if (Constructor->getInheritedConstructor()) {
19338 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19339 }
19340 } else if (CXXDestructorDecl *Destructor =
19341 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19342 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19343 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19344 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19345 return;
19346 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19347 }
19348 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19349 MarkVTableUsed(Loc, Class: Destructor->getParent());
19350 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19351 if (MethodDecl->isOverloadedOperator() &&
19352 MethodDecl->getOverloadedOperator() == OO_Equal) {
19353 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19354 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19355 if (MethodDecl->isCopyAssignmentOperator())
19356 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19357 else if (MethodDecl->isMoveAssignmentOperator())
19358 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19359 }
19360 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19361 MethodDecl->getParent()->isLambda()) {
19362 CXXConversionDecl *Conversion =
19363 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19364 if (Conversion->isLambdaToBlockPointerConversion())
19365 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19366 else
19367 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19368 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19369 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19370 }
19371
19372 if (Func->isDefaulted() && !Func->isDeleted()) {
19373 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19374 if (DCK != DefaultedComparisonKind::None)
19375 DefineDefaultedComparison(Loc, FD: Func, DCK);
19376 }
19377
19378 // Implicit instantiation of function templates and member functions of
19379 // class templates.
19380 if (Func->isImplicitlyInstantiable()) {
19381 TemplateSpecializationKind TSK =
19382 Func->getTemplateSpecializationKindForInstantiation();
19383 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19384 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19385 if (FirstInstantiation) {
19386 PointOfInstantiation = Loc;
19387 if (auto *MSI = Func->getMemberSpecializationInfo())
19388 MSI->setPointOfInstantiation(Loc);
19389 // FIXME: Notify listener.
19390 else
19391 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19392 } else if (TSK != TSK_ImplicitInstantiation) {
19393 // Use the point of use as the point of instantiation, instead of the
19394 // point of explicit instantiation (which we track as the actual point
19395 // of instantiation). This gives better backtraces in diagnostics.
19396 PointOfInstantiation = Loc;
19397 }
19398
19399 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19400 Func->isConstexpr()) {
19401 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19402 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19403 CodeSynthesisContexts.size())
19404 PendingLocalImplicitInstantiations.push_back(
19405 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19406 else if (Func->isConstexpr())
19407 // Do not defer instantiations of constexpr functions, to avoid the
19408 // expression evaluator needing to call back into Sema if it sees a
19409 // call to such a function.
19410 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19411 else {
19412 Func->setInstantiationIsPending(true);
19413 PendingInstantiations.push_back(
19414 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19415 if (llvm::isTimeTraceVerbose()) {
19416 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19417 std::string Name;
19418 llvm::raw_string_ostream OS(Name);
19419 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19420 /*Qualified=*/true);
19421 return Name;
19422 });
19423 }
19424 // Notify the consumer that a function was implicitly instantiated.
19425 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19426 }
19427 }
19428 } else {
19429 // Walk redefinitions, as some of them may be instantiable.
19430 for (auto *i : Func->redecls()) {
19431 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19432 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19433 }
19434 }
19435 });
19436 }
19437
19438 // If a constructor was defined in the context of a default parameter
19439 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19440 // context), its initializers may not be referenced yet.
19441 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19442 EnterExpressionEvaluationContext EvalContext(
19443 *this,
19444 Constructor->isImmediateFunction()
19445 ? ExpressionEvaluationContext::ImmediateFunctionContext
19446 : ExpressionEvaluationContext::PotentiallyEvaluated,
19447 Constructor);
19448 for (CXXCtorInitializer *Init : Constructor->inits()) {
19449 if (Init->isInClassMemberInitializer())
19450 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19451 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19452 });
19453 }
19454 }
19455
19456 // C++14 [except.spec]p17:
19457 // An exception-specification is considered to be needed when:
19458 // - the function is odr-used or, if it appears in an unevaluated operand,
19459 // would be odr-used if the expression were potentially-evaluated;
19460 //
19461 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19462 // function is a pure virtual function we're calling, and in that case the
19463 // function was selected by overload resolution and we need to resolve its
19464 // exception specification for a different reason.
19465 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19466 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19467 ResolveExceptionSpec(Loc, FPT);
19468
19469 // A callee could be called by a host function then by a device function.
19470 // If we only try recording once, we will miss recording the use on device
19471 // side. Therefore keep trying until it is recorded.
19472 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19473 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19474 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19475
19476 // If this is the first "real" use, act on that.
19477 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19478 // Keep track of used but undefined functions.
19479 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19480 if (mightHaveNonExternalLinkage(FD: Func))
19481 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19482 else if (Func->getMostRecentDecl()->isInlined() &&
19483 !LangOpts.GNUInline &&
19484 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19485 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19486 else if (isExternalWithNoLinkageType(VD: Func))
19487 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19488 }
19489
19490 // Some x86 Windows calling conventions mangle the size of the parameter
19491 // pack into the name. Computing the size of the parameters requires the
19492 // parameter types to be complete. Check that now.
19493 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19494 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19495
19496 // In the MS C++ ABI, the compiler emits destructor variants where they are
19497 // used. If the destructor is used here but defined elsewhere, mark the
19498 // virtual base destructors referenced. If those virtual base destructors
19499 // are inline, this will ensure they are defined when emitting the complete
19500 // destructor variant. This checking may be redundant if the destructor is
19501 // provided later in this TU.
19502 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19503 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19504 CXXRecordDecl *Parent = Dtor->getParent();
19505 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19506 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19507 }
19508 }
19509
19510 Func->markUsed(C&: Context);
19511 }
19512}
19513
19514/// Directly mark a variable odr-used. Given a choice, prefer to use
19515/// MarkVariableReferenced since it does additional checks and then
19516/// calls MarkVarDeclODRUsed.
19517/// If the variable must be captured:
19518/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19519/// - else capture it in the DeclContext that maps to the
19520/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19521static void
19522MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19523 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19524 // Keep track of used but undefined variables.
19525 // FIXME: We shouldn't suppress this warning for static data members.
19526 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19527 assert(Var && "expected a capturable variable");
19528
19529 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19530 (!Var->isExternallyVisible() || Var->isInline() ||
19531 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19532 !(Var->isStaticDataMember() && Var->hasInit())) {
19533 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19534 if (old.isInvalid())
19535 old = Loc;
19536 }
19537 QualType CaptureType, DeclRefType;
19538 if (SemaRef.LangOpts.OpenMP)
19539 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19540 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19541 /*EllipsisLoc*/ SourceLocation(),
19542 /*BuildAndDiagnose*/ true, CaptureType,
19543 DeclRefType, FunctionScopeIndexToStopAt);
19544
19545 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19546 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19547 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19548 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19549 if (VarTarget == SemaCUDA::CVT_Host &&
19550 (UserTarget == CUDAFunctionTarget::Device ||
19551 UserTarget == CUDAFunctionTarget::HostDevice ||
19552 UserTarget == CUDAFunctionTarget::Global)) {
19553 // Diagnose ODR-use of host global variables in device functions.
19554 // Reference of device global variables in host functions is allowed
19555 // through shadow variables therefore it is not diagnosed.
19556 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19557 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19558 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19559 SemaRef.targetDiag(Loc: Var->getLocation(),
19560 DiagID: Var->getType().isConstQualified()
19561 ? diag::note_cuda_const_var_unpromoted
19562 : diag::note_cuda_host_var);
19563 }
19564 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19565 // Also capture __device__ const variables, which are classified
19566 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19567 // an explicit CUDADeviceAttr to distinguish them from plain
19568 // const variables (no __device__), which also get CVT_Both but
19569 // only have an implicit CUDADeviceAttr.
19570 (VarTarget == SemaCUDA::CVT_Both &&
19571 Var->hasAttr<CUDADeviceAttr>() &&
19572 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19573 !Var->hasAttr<CUDASharedAttr>() &&
19574 (UserTarget == CUDAFunctionTarget::Host ||
19575 UserTarget == CUDAFunctionTarget::HostDevice)) {
19576 // Record a CUDA/HIP device side variable if it is ODR-used
19577 // by host code. This is done conservatively, when the variable is
19578 // referenced in any of the following contexts:
19579 // - a non-function context
19580 // - a host function
19581 // - a host device function
19582 // This makes the ODR-use of the device side variable by host code to
19583 // be visible in the device compilation for the compiler to be able to
19584 // emit template variables instantiated by host code only and to
19585 // externalize the static device side variable ODR-used by host code.
19586 if (!Var->hasExternalStorage())
19587 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19588 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19589 (!FD || (!FD->getDescribedFunctionTemplate() &&
19590 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19591 GVA_StrongExternal)))
19592 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19593 }
19594 }
19595
19596 V->markUsed(C&: SemaRef.Context);
19597}
19598
19599void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19600 SourceLocation Loc,
19601 unsigned CapturingScopeIndex) {
19602 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19603}
19604
19605static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19606 SourceLocation loc,
19607 ValueDecl *var) {
19608 DeclContext *VarDC =
19609 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19610
19611 // If the parameter still belongs to the translation unit, then
19612 // we're actually just using one parameter in the declaration of
19613 // the next.
19614 if (isa<ParmVarDecl>(Val: var) &&
19615 isa<TranslationUnitDecl>(Val: VarDC))
19616 return;
19617
19618 // For C code, don't diagnose about capture if we're not actually in code
19619 // right now; it's impossible to write a non-constant expression outside of
19620 // function context, so we'll get other (more useful) diagnostics later.
19621 //
19622 // For C++, things get a bit more nasty... it would be nice to suppress this
19623 // diagnostic for certain cases like using a local variable in an array bound
19624 // for a member of a local class, but the correct predicate is not obvious.
19625 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19626 return;
19627
19628 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19629 unsigned ContextKind = 3; // unknown
19630 if (isa<CXXMethodDecl>(Val: VarDC) &&
19631 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19632 ContextKind = 2;
19633 } else if (isa<FunctionDecl>(Val: VarDC)) {
19634 ContextKind = 0;
19635 } else if (isa<BlockDecl>(Val: VarDC)) {
19636 ContextKind = 1;
19637 }
19638
19639 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19640 << var << ValueKind << ContextKind << VarDC;
19641 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19642 << var;
19643
19644 // FIXME: Add additional diagnostic info about class etc. which prevents
19645 // capture.
19646}
19647
19648static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19649 ValueDecl *Var,
19650 bool &SubCapturesAreNested,
19651 QualType &CaptureType,
19652 QualType &DeclRefType) {
19653 // Check whether we've already captured it.
19654 if (CSI->CaptureMap.count(Val: Var)) {
19655 // If we found a capture, any subcaptures are nested.
19656 SubCapturesAreNested = true;
19657
19658 // Retrieve the capture type for this variable.
19659 CaptureType = CSI->getCapture(Var).getCaptureType();
19660
19661 // Compute the type of an expression that refers to this variable.
19662 DeclRefType = CaptureType.getNonReferenceType();
19663
19664 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19665 // are mutable in the sense that user can change their value - they are
19666 // private instances of the captured declarations.
19667 const Capture &Cap = CSI->getCapture(Var);
19668 // C++ [expr.prim.lambda]p10:
19669 // The type of such a data member is [...] an lvalue reference to the
19670 // referenced function type if the entity is a reference to a function.
19671 // [...]
19672 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19673 !(isa<LambdaScopeInfo>(Val: CSI) &&
19674 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19675 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19676 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19677 DeclRefType.addConst();
19678 return true;
19679 }
19680 return false;
19681}
19682
19683// Only block literals, captured statements, and lambda expressions can
19684// capture; other scopes don't work.
19685static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19686 ValueDecl *Var,
19687 SourceLocation Loc,
19688 const bool Diagnose,
19689 Sema &S) {
19690 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19691 return getLambdaAwareParentOfDeclContext(DC);
19692
19693 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19694 if (Underlying) {
19695 if (Underlying->hasLocalStorage() && Diagnose)
19696 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19697 }
19698 return nullptr;
19699}
19700
19701// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19702// certain types of variables (unnamed, variably modified types etc.)
19703// so check for eligibility.
19704static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19705 SourceLocation Loc, const bool Diagnose,
19706 Sema &S) {
19707
19708 assert((isa<VarDecl, BindingDecl>(Var)) &&
19709 "Only variables and structured bindings can be captured");
19710
19711 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19712 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19713
19714 // Reject bindings referenced from a lambda or block that wraps an OpenMP
19715 // region.
19716 if ((IsLambda || IsBlock) && S.getLangOpts().OpenMP &&
19717 isa<DecompositionDecl>(Val: Var)) {
19718 if (Diagnose)
19719 S.Diag(Loc, DiagID: diag::err_omp_unsupported_on_binding) << 3;
19720 return false;
19721 }
19722
19723 // Lambdas are not allowed to capture unnamed variables
19724 // (e.g. anonymous unions).
19725 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19726 // assuming that's the intent.
19727 if (IsLambda && !Var->getDeclName()) {
19728 if (Diagnose) {
19729 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19730 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19731 }
19732 return false;
19733 }
19734
19735 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19736 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19737 if (Diagnose) {
19738 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19739 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19740 }
19741 return false;
19742 }
19743 // Prohibit structs with flexible array members too.
19744 // We cannot capture what is in the tail end of the struct.
19745 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19746 VTD && VTD->hasFlexibleArrayMember()) {
19747 if (Diagnose) {
19748 if (IsBlock)
19749 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19750 else
19751 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19752 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19753 }
19754 return false;
19755 }
19756 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19757 // Lambdas and captured statements are not allowed to capture __block
19758 // variables; they don't support the expected semantics.
19759 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19760 if (Diagnose) {
19761 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19762 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19763 }
19764 return false;
19765 }
19766 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19767 if (S.getLangOpts().OpenCL && IsBlock &&
19768 Var->getType()->isBlockPointerType()) {
19769 if (Diagnose)
19770 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19771 return false;
19772 }
19773
19774 if (auto *BD = dyn_cast<BindingDecl>(Val: Var)) {
19775 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19776 if (RSI->CapRegionKind == CR_OpenMP) {
19777 if (BD->getHoldingVar()) {
19778 if (Diagnose) {
19779 S.Diag(Loc, DiagID: diag::err_capture_tuple_binding_openmp) << Var;
19780 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19781 }
19782 return false;
19783 }
19784 if (Diagnose && S.getLangOpts().CPlusPlus) {
19785 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19786 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19787 }
19788 return true;
19789 }
19790 }
19791 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19792 if (Diagnose)
19793 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19794 return false;
19795 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19796 S.DiagCompat(Loc, CompatDiagId: diag_compat::capture_binding) << Var;
19797 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19798 }
19799 }
19800
19801 return true;
19802}
19803
19804// Returns true if the capture by block was successful.
19805static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19806 SourceLocation Loc, const bool BuildAndDiagnose,
19807 QualType &CaptureType, QualType &DeclRefType,
19808 const bool Nested, Sema &S, bool Invalid) {
19809 bool ByRef = false;
19810
19811 // Blocks are not allowed to capture arrays, excepting OpenCL.
19812 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19813 // (decayed to pointers).
19814 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19815 if (BuildAndDiagnose) {
19816 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19817 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19818 Invalid = true;
19819 } else {
19820 return false;
19821 }
19822 }
19823
19824 // Forbid the block-capture of autoreleasing variables.
19825 if (!Invalid &&
19826 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19827 if (BuildAndDiagnose) {
19828 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19829 << /*block*/ 0;
19830 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19831 Invalid = true;
19832 } else {
19833 return false;
19834 }
19835 }
19836
19837 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19838 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19839 QualType PointeeTy = PT->getPointeeType();
19840
19841 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19842 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19843 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19844 if (BuildAndDiagnose) {
19845 SourceLocation VarLoc = Var->getLocation();
19846 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19847 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19848 }
19849 }
19850 }
19851
19852 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19853 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19854 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19855 // Block capture by reference does not change the capture or
19856 // declaration reference types.
19857 ByRef = true;
19858 } else {
19859 // Block capture by copy introduces 'const'.
19860 CaptureType = CaptureType.getNonReferenceType().withConst();
19861 DeclRefType = CaptureType;
19862 }
19863
19864 // Actually capture the variable.
19865 if (BuildAndDiagnose)
19866 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19867 CaptureType, Invalid);
19868
19869 return !Invalid;
19870}
19871
19872/// Capture the given variable in the captured region.
19873static bool captureInCapturedRegion(
19874 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19875 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19876 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19877 Sema &S, bool Invalid) {
19878 // By default, capture variables by reference.
19879 bool ByRef = true;
19880 bool IsBindingDecl = isa<BindingDecl>(Val: Var);
19881 ValueDecl *DSAVar = Var;
19882 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19883 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19884 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19885 // Using an LValue reference type is consistent with Lambdas (see below).
19886 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19887 Var = VD; // Capture the DecompositionDecl.
19888 bool HasConst = DeclRefType.isConstQualified();
19889 // Note: DeclRefType should remain the BindingDecl's type (e.g., int),
19890 // not the DecompositionDecl's type (e.g., Point). The variable being
19891 // captured is the DecompositionDecl, but expressions still reference
19892 // the individual binding's type.
19893 DeclRefType = DeclRefType.getUnqualifiedType();
19894 // Don't lose diagnostics about assignments to const.
19895 if (HasConst)
19896 DeclRefType.addConst();
19897 }
19898 // Do not capture firstprivates in tasks. For bindings the DSA is on the
19899 // binding, not on the DecompositionDecl; the task firstprivate path still
19900 // needs the DecompositionDecl capture, so skip only private.
19901 OpenMPClauseKind PrivateKind = S.OpenMP().isOpenMPPrivateDecl(
19902 D: IsBindingDecl ? DSAVar : Var, Level: RSI->OpenMPLevel,
19903 CapLevel: RSI->OpenMPCaptureLevel);
19904 if (IsBindingDecl ? PrivateKind == OMPC_private
19905 : PrivateKind != OMPC_unknown)
19906 return true;
19907 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: DSAVar, Level: RSI->OpenMPLevel,
19908 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19909 // Bindings share the DecompositionDecl storage; a second capture with
19910 // a different capture kind is not representable.
19911 if (BuildAndDiagnose && IsBindingDecl) {
19912 unsigned Idx = RSI->CaptureMap.lookup(Val: Var);
19913 if (Idx != 0 && RSI->Captures[Idx - 1].isReferenceCapture() != ByRef) {
19914 S.Diag(Loc,
19915 DiagID: diag::err_omp_decomposition_bindings_different_capture_kinds)
19916 << DSAVar;
19917 return false;
19918 }
19919 }
19920 }
19921
19922 if (ByRef)
19923 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19924 else
19925 CaptureType = DeclRefType;
19926
19927 // Actually capture the variable.
19928 if (BuildAndDiagnose)
19929 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19930 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19931
19932 if (BuildAndDiagnose && IsBindingDecl)
19933 // Key the binding to its own capture entry so repeated uses hit the
19934 // already-captured path.
19935 RSI->CaptureMap[DSAVar] = RSI->Captures.size();
19936
19937 return !Invalid;
19938}
19939
19940/// Capture the given variable in the lambda.
19941static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19942 SourceLocation Loc, const bool BuildAndDiagnose,
19943 QualType &CaptureType, QualType &DeclRefType,
19944 const bool RefersToCapturedVariable,
19945 const TryCaptureKind Kind,
19946 SourceLocation EllipsisLoc, const bool IsTopScope,
19947 Sema &S, bool Invalid) {
19948 // Determine whether we are capturing by reference or by value.
19949 bool ByRef = false;
19950 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19951 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19952 } else {
19953 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19954 }
19955
19956 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19957 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19958 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19959 Invalid = true;
19960 }
19961
19962 // Compute the type of the field that will capture this variable.
19963 if (ByRef) {
19964 // C++11 [expr.prim.lambda]p15:
19965 // An entity is captured by reference if it is implicitly or
19966 // explicitly captured but not captured by copy. It is
19967 // unspecified whether additional unnamed non-static data
19968 // members are declared in the closure type for entities
19969 // captured by reference.
19970 //
19971 // FIXME: It is not clear whether we want to build an lvalue reference
19972 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19973 // to do the former, while EDG does the latter. Core issue 1249 will
19974 // clarify, but for now we follow GCC because it's a more permissive and
19975 // easily defensible position.
19976 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19977 } else {
19978 // C++11 [expr.prim.lambda]p14:
19979 // For each entity captured by copy, an unnamed non-static
19980 // data member is declared in the closure type. The
19981 // declaration order of these members is unspecified. The type
19982 // of such a data member is the type of the corresponding
19983 // captured entity if the entity is not a reference to an
19984 // object, or the referenced type otherwise. [Note: If the
19985 // captured entity is a reference to a function, the
19986 // corresponding data member is also a reference to a
19987 // function. - end note ]
19988 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19989 if (!RefType->getPointeeType()->isFunctionType())
19990 CaptureType = RefType->getPointeeType();
19991 }
19992
19993 // Forbid the lambda copy-capture of autoreleasing variables.
19994 if (!Invalid &&
19995 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19996 if (BuildAndDiagnose) {
19997 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19998 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19999 << Var->getDeclName();
20000 Invalid = true;
20001 } else {
20002 return false;
20003 }
20004 }
20005
20006 // Make sure that by-copy captures are of a complete and non-abstract type.
20007 if (!Invalid && BuildAndDiagnose) {
20008 if (!CaptureType->isDependentType() &&
20009 S.RequireCompleteSizedType(
20010 Loc, T: CaptureType,
20011 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
20012 Args: Var->getDeclName()))
20013 Invalid = true;
20014 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
20015 DiagID: diag::err_capture_of_abstract_type))
20016 Invalid = true;
20017 }
20018 }
20019
20020 // Compute the type of a reference to this captured variable.
20021 if (ByRef)
20022 DeclRefType = CaptureType.getNonReferenceType();
20023 else {
20024 // C++ [expr.prim.lambda]p5:
20025 // The closure type for a lambda-expression has a public inline
20026 // function call operator [...]. This function call operator is
20027 // declared const (9.3.1) if and only if the lambda-expression's
20028 // parameter-declaration-clause is not followed by mutable.
20029 DeclRefType = CaptureType.getNonReferenceType();
20030 bool Const = LSI->lambdaCaptureShouldBeConst();
20031 // C++ [expr.prim.lambda]p10:
20032 // The type of such a data member is [...] an lvalue reference to the
20033 // referenced function type if the entity is a reference to a function.
20034 // [...]
20035 if (Const && !CaptureType->isReferenceType() &&
20036 !DeclRefType->isFunctionType())
20037 DeclRefType.addConst();
20038 }
20039
20040 // Add the capture.
20041 if (BuildAndDiagnose)
20042 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
20043 Loc, EllipsisLoc, CaptureType, Invalid);
20044
20045 return !Invalid;
20046}
20047
20048static bool canCaptureVariableByCopy(ValueDecl *Var,
20049 const ASTContext &Context) {
20050 // Offer a Copy fix even if the type is dependent.
20051 if (Var->getType()->isDependentType())
20052 return true;
20053 QualType T = Var->getType().getNonReferenceType();
20054 if (T.isTriviallyCopyableType(Context))
20055 return true;
20056 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
20057
20058 if (!(RD = RD->getDefinition()))
20059 return false;
20060 if (RD->hasSimpleCopyConstructor())
20061 return true;
20062 if (RD->hasUserDeclaredCopyConstructor())
20063 for (CXXConstructorDecl *Ctor : RD->ctors())
20064 if (Ctor->isCopyConstructor())
20065 return !Ctor->isDeleted();
20066 }
20067 return false;
20068}
20069
20070/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
20071/// default capture. Fixes may be omitted if they aren't allowed by the
20072/// standard, for example we can't emit a default copy capture fix-it if we
20073/// already explicitly copy capture capture another variable.
20074static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
20075 ValueDecl *Var) {
20076 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
20077 // Don't offer Capture by copy of default capture by copy fixes if Var is
20078 // known not to be copy constructible.
20079 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
20080
20081 SmallString<32> FixBuffer;
20082 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
20083 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
20084 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
20085 if (ShouldOfferCopyFix) {
20086 // Offer fixes to insert an explicit capture for the variable.
20087 // [] -> [VarName]
20088 // [OtherCapture] -> [OtherCapture, VarName]
20089 FixBuffer.assign(Refs: {Separator, Var->getName()});
20090 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20091 << Var << /*value*/ 0
20092 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20093 }
20094 // As above but capture by reference.
20095 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
20096 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
20097 << Var << /*reference*/ 1
20098 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
20099 }
20100
20101 // Only try to offer default capture if there are no captures excluding this
20102 // and init captures.
20103 // [this]: OK.
20104 // [X = Y]: OK.
20105 // [&A, &B]: Don't offer.
20106 // [A, B]: Don't offer.
20107 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
20108 return !C.isThisCapture() && !C.isInitCapture();
20109 }))
20110 return;
20111
20112 // The default capture specifiers, '=' or '&', must appear first in the
20113 // capture body.
20114 SourceLocation DefaultInsertLoc =
20115 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
20116
20117 if (ShouldOfferCopyFix) {
20118 bool CanDefaultCopyCapture = true;
20119 // [=, *this] OK since c++17
20120 // [=, this] OK since c++20
20121 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20122 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20123 ? LSI->getCXXThisCapture().isCopyCapture()
20124 : false;
20125 // We can't use default capture by copy if any captures already specified
20126 // capture by copy.
20127 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20128 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20129 })) {
20130 FixBuffer.assign(Refs: {"=", Separator});
20131 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20132 << /*value*/ 0
20133 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20134 }
20135 }
20136
20137 // We can't use default capture by reference if any captures already specified
20138 // capture by reference.
20139 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
20140 return !C.isInitCapture() && C.isReferenceCapture() &&
20141 !C.isThisCapture();
20142 })) {
20143 FixBuffer.assign(Refs: {"&", Separator});
20144 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
20145 << /*reference*/ 1
20146 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
20147 }
20148}
20149
20150bool Sema::tryCaptureVariable(
20151 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20152 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20153 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20154 // An init-capture is notionally from the context surrounding its
20155 // declaration, but its parent DC is the lambda class.
20156 DeclContext *VarDC =
20157 Var->getDeclContext()->getEnclosingNonExpansionStatementContext();
20158 DeclContext *DC = CurContext;
20159
20160 // Skip past RequiresExprBodys because they don't constitute function scopes.
20161 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20162 DC = DC->getParent();
20163
20164 // tryCaptureVariable is called every time a DeclRef is formed,
20165 // it can therefore have non-negigible impact on performances.
20166 // For local variables and when there is no capturing scope,
20167 // we can bailout early.
20168 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20169 return true;
20170
20171 // Exception: Function parameters are not tied to the function's DeclContext
20172 // until we enter the function definition. Capturing them anyway would result
20173 // in an out-of-bounds error while traversing DC and its parents.
20174 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
20175 return true;
20176
20177 const auto *VD = dyn_cast<VarDecl>(Val: Var);
20178 if (VD) {
20179 if (VD->isInitCapture())
20180 VarDC = VarDC->getParent();
20181 } else {
20182 VD = Var->getPotentiallyDecomposedVarDecl();
20183 }
20184 assert(VD && "Cannot capture a null variable");
20185
20186 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20187 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20188 // We need to sync up the Declaration Context with the
20189 // FunctionScopeIndexToStopAt
20190 if (FunctionScopeIndexToStopAt) {
20191 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20192 unsigned FSIndex = FunctionScopes.size() - 1;
20193 // When we're parsing the lambda parameter list, the current DeclContext is
20194 // NOT the lambda but its parent. So move away the current LSI before
20195 // aligning DC and FunctionScopeIndexToStopAt.
20196 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
20197 FSIndex && LSI && !LSI->AfterParameterList)
20198 --FSIndex;
20199 assert(MaxFunctionScopesIndex <= FSIndex &&
20200 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20201 "FunctionScopes.");
20202 while (FSIndex != MaxFunctionScopesIndex) {
20203 DC = getLambdaAwareParentOfDeclContext(DC);
20204 --FSIndex;
20205 }
20206 }
20207
20208 // Capture global variables if it is required to use private copy of this
20209 // variable.
20210 bool IsGlobal = !VD->hasLocalStorage();
20211 if (IsGlobal && !(LangOpts.OpenMP &&
20212 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
20213 StopAt: MaxFunctionScopesIndex)))
20214 return true;
20215
20216 if (isa<VarDecl>(Val: Var))
20217 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
20218
20219 // Walk up the stack to determine whether we can capture the variable,
20220 // performing the "simple" checks that don't depend on type. We stop when
20221 // we've either hit the declared scope of the variable or find an existing
20222 // capture of that variable. We start from the innermost capturing-entity
20223 // (the DC) and ensure that all intervening capturing-entities
20224 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20225 // declcontext can either capture the variable or have already captured
20226 // the variable.
20227 CaptureType = Var->getType();
20228 DeclRefType = CaptureType.getNonReferenceType();
20229 bool Nested = false;
20230 bool Explicit = (Kind != TryCaptureKind::Implicit);
20231 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20232 do {
20233
20234 LambdaScopeInfo *LSI = nullptr;
20235 if (!FunctionScopes.empty())
20236 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20237 Val: FunctionScopes[FunctionScopesIndex]);
20238
20239 bool IsInScopeDeclarationContext =
20240 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20241
20242 if (LSI && !LSI->AfterParameterList) {
20243 // This allows capturing parameters from a default value which does not
20244 // seems correct
20245 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
20246 return true;
20247 }
20248 // If the variable is declared in the current context, there is no need to
20249 // capture it.
20250 if (IsInScopeDeclarationContext &&
20251 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20252 return true;
20253
20254 // Only block literals, captured statements, and lambda expressions can
20255 // capture; other scopes don't work.
20256 DeclContext *ParentDC =
20257 !IsInScopeDeclarationContext
20258 ? DC->getParent()
20259 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
20260 Diagnose: BuildAndDiagnose, S&: *this);
20261 // We need to check for the parent *first* because, if we *have*
20262 // private-captured a global variable, we need to recursively capture it in
20263 // intermediate blocks, lambdas, etc.
20264 if (!ParentDC) {
20265 if (IsGlobal) {
20266 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20267 break;
20268 }
20269 return true;
20270 }
20271
20272 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20273 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
20274
20275 // Check whether we've already captured it.
20276 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
20277 DeclRefType)) {
20278 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
20279 break;
20280 }
20281
20282 // When evaluating some attributes (like enable_if) we might refer to a
20283 // function parameter appertaining to the same declaration as that
20284 // attribute.
20285 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
20286 Parm && Parm->getDeclContext() == DC)
20287 return true;
20288
20289 // If we are instantiating a generic lambda call operator body,
20290 // we do not want to capture new variables. What was captured
20291 // during either a lambdas transformation or initial parsing
20292 // should be used.
20293 if (isGenericLambdaCallOperatorSpecialization(DC)) {
20294 if (BuildAndDiagnose) {
20295 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20296 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
20297 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20298 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20299 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20300 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20301 } else
20302 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
20303 }
20304 return true;
20305 }
20306
20307 // Try to capture variable-length arrays types.
20308 if (Var->getType()->isVariablyModifiedType()) {
20309 // We're going to walk down into the type and look for VLA
20310 // expressions.
20311 QualType QTy = Var->getType();
20312 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20313 QTy = PVD->getOriginalType();
20314 captureVariablyModifiedType(Context, T: QTy, CSI);
20315 }
20316
20317 if (getLangOpts().OpenMP) {
20318 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20319 // OpenMP private variables should not be captured in outer scope, so
20320 // just break here. Similarly, global variables that are captured in a
20321 // target region should not be captured outside the scope of the region.
20322 if (RSI->CapRegionKind == CR_OpenMP) {
20323 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20324 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
20325 // If the variable is private (i.e. not captured) and has variably
20326 // modified type, we still need to capture the type for correct
20327 // codegen in all regions, associated with the construct. Currently,
20328 // it is captured in the innermost captured region only.
20329 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20330 Var->getType()->isVariablyModifiedType()) {
20331 QualType QTy = Var->getType();
20332 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
20333 QTy = PVD->getOriginalType();
20334 for (int I = 1,
20335 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
20336 I < E; ++I) {
20337 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20338 Val: FunctionScopes[FunctionScopesIndex - I]);
20339 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20340 "Wrong number of captured regions associated with the "
20341 "OpenMP construct.");
20342 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
20343 }
20344 }
20345 bool IsTargetCap =
20346 IsOpenMPPrivateDecl != OMPC_private &&
20347 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
20348 CaptureLevel: RSI->OpenMPCaptureLevel);
20349 // Do not capture global if it is not privatized in outer regions.
20350 bool IsGlobalCap =
20351 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20352 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
20353
20354 // When we detect target captures we are looking from inside the
20355 // target region, therefore we need to propagate the capture from the
20356 // enclosing region. Therefore, the capture is not initially nested.
20357 if (IsTargetCap)
20358 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20359 Level: RSI->OpenMPLevel);
20360
20361 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20362 (IsGlobal && !IsGlobalCap)) {
20363 Nested = !IsTargetCap;
20364 bool HasConst = DeclRefType.isConstQualified();
20365 DeclRefType = DeclRefType.getUnqualifiedType();
20366 // Don't lose diagnostics about assignments to const.
20367 if (HasConst)
20368 DeclRefType.addConst();
20369 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20370 break;
20371 }
20372 }
20373 }
20374 }
20375 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20376 // No capture-default, and this is not an explicit capture
20377 // so cannot capture this variable.
20378 if (BuildAndDiagnose) {
20379 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20380 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20381 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20382 if (LSI->Lambda) {
20383 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20384 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20385 }
20386 // FIXME: If we error out because an outer lambda can not implicitly
20387 // capture a variable that an inner lambda explicitly captures, we
20388 // should have the inner lambda do the explicit capture - because
20389 // it makes for cleaner diagnostics later. This would purely be done
20390 // so that the diagnostic does not misleadingly claim that a variable
20391 // can not be captured by a lambda implicitly even though it is captured
20392 // explicitly. Suggestion:
20393 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20394 // at the function head
20395 // - cache the StartingDeclContext - this must be a lambda
20396 // - captureInLambda in the innermost lambda the variable.
20397 }
20398 return true;
20399 }
20400 Explicit = false;
20401 FunctionScopesIndex--;
20402 if (IsInScopeDeclarationContext)
20403 DC = ParentDC;
20404 } while (!VarDC->Equals(DC));
20405
20406 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20407 // computing the type of the capture at each step, checking type-specific
20408 // requirements, and adding captures if requested.
20409 // If the variable had already been captured previously, we start capturing
20410 // at the lambda nested within that one.
20411 bool Invalid = false;
20412 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20413 ++I) {
20414 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20415
20416 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20417 // certain types of variables (unnamed, variably modified types etc.)
20418 // so check for eligibility.
20419 if (!Invalid)
20420 Invalid =
20421 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20422
20423 // After encountering an error, if we're actually supposed to capture, keep
20424 // capturing in nested contexts to suppress any follow-on diagnostics.
20425 if (Invalid && !BuildAndDiagnose)
20426 return true;
20427
20428 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20429 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20430 DeclRefType, Nested, S&: *this, Invalid);
20431 Nested = true;
20432 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20433 Invalid = !captureInCapturedRegion(
20434 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20435 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20436 Nested = true;
20437 } else {
20438 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20439 Invalid =
20440 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20441 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20442 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20443 Nested = true;
20444 }
20445
20446 if (Invalid && !BuildAndDiagnose)
20447 return true;
20448 }
20449 return Invalid;
20450}
20451
20452bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20453 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20454 QualType CaptureType;
20455 QualType DeclRefType;
20456 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20457 /*BuildAndDiagnose=*/true, CaptureType,
20458 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20459}
20460
20461bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20462 QualType CaptureType;
20463 QualType DeclRefType;
20464 return !tryCaptureVariable(
20465 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20466 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20467}
20468
20469QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20470 assert(Var && "Null value cannot be captured");
20471
20472 QualType CaptureType;
20473 QualType DeclRefType;
20474
20475 // Determine whether we can capture this variable.
20476 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20477 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20478 FunctionScopeIndexToStopAt: nullptr))
20479 return QualType();
20480
20481 return DeclRefType;
20482}
20483
20484namespace {
20485// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20486// The produced TemplateArgumentListInfo* points to data stored within this
20487// object, so should only be used in contexts where the pointer will not be
20488// used after the CopiedTemplateArgs object is destroyed.
20489class CopiedTemplateArgs {
20490 bool HasArgs;
20491 TemplateArgumentListInfo TemplateArgStorage;
20492public:
20493 template<typename RefExpr>
20494 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20495 if (HasArgs)
20496 E->copyTemplateArgumentsInto(TemplateArgStorage);
20497 }
20498 operator TemplateArgumentListInfo*()
20499#ifdef __has_cpp_attribute
20500#if __has_cpp_attribute(clang::lifetimebound)
20501 [[clang::lifetimebound]]
20502#endif
20503#endif
20504 {
20505 return HasArgs ? &TemplateArgStorage : nullptr;
20506 }
20507};
20508}
20509
20510/// Walk the set of potential results of an expression and mark them all as
20511/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20512///
20513/// \return A new expression if we found any potential results, ExprEmpty() if
20514/// not, and ExprError() if we diagnosed an error.
20515static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20516 NonOdrUseReason NOUR) {
20517 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20518 // an object that satisfies the requirements for appearing in a
20519 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20520 // is immediately applied." This function handles the lvalue-to-rvalue
20521 // conversion part.
20522 //
20523 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20524 // transform it into the relevant kind of non-odr-use node and rebuild the
20525 // tree of nodes leading to it.
20526 //
20527 // This is a mini-TreeTransform that only transforms a restricted subset of
20528 // nodes (and only certain operands of them).
20529
20530 // Rebuild a subexpression.
20531 auto Rebuild = [&](Expr *Sub) {
20532 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20533 };
20534
20535 // Check whether a potential result satisfies the requirements of NOUR.
20536 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20537 // Any entity other than a VarDecl is always odr-used whenever it's named
20538 // in a potentially-evaluated expression.
20539 auto *VD = dyn_cast<VarDecl>(Val: D);
20540 if (!VD)
20541 return true;
20542
20543 // C++2a [basic.def.odr]p4:
20544 // A variable x whose name appears as a potentially-evalauted expression
20545 // e is odr-used by e unless
20546 // -- x is a reference that is usable in constant expressions, or
20547 // -- x is a variable of non-reference type that is usable in constant
20548 // expressions and has no mutable subobjects, and e is an element of
20549 // the set of potential results of an expression of
20550 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20551 // conversion is applied, or
20552 // -- x is a variable of non-reference type, and e is an element of the
20553 // set of potential results of a discarded-value expression to which
20554 // the lvalue-to-rvalue conversion is not applied
20555 //
20556 // We check the first bullet and the "potentially-evaluated" condition in
20557 // BuildDeclRefExpr. We check the type requirements in the second bullet
20558 // in CheckLValueToRValueConversionOperand below.
20559 switch (NOUR) {
20560 case NOUR_None:
20561 case NOUR_Unevaluated:
20562 llvm_unreachable("unexpected non-odr-use-reason");
20563
20564 case NOUR_Constant:
20565 // Constant references were handled when they were built.
20566 if (VD->getType()->isReferenceType())
20567 return true;
20568 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20569 if (RD->hasDefinition() && RD->hasMutableFields())
20570 return true;
20571 if (!VD->isUsableInConstantExpressions(C: S.Context))
20572 return true;
20573 break;
20574
20575 case NOUR_Discarded:
20576 if (VD->getType()->isReferenceType())
20577 return true;
20578 break;
20579 }
20580 return false;
20581 };
20582
20583 // Check whether this expression may be odr-used in CUDA/HIP.
20584 auto MaybeCUDAODRUsed = [&]() -> bool {
20585 if (!S.LangOpts.CUDA)
20586 return false;
20587 LambdaScopeInfo *LSI = S.getCurLambda();
20588 if (!LSI)
20589 return false;
20590 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20591 if (!DRE)
20592 return false;
20593 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20594 if (!VD)
20595 return false;
20596 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20597 };
20598
20599 // Mark that this expression does not constitute an odr-use.
20600 auto MarkNotOdrUsed = [&] {
20601 if (!MaybeCUDAODRUsed()) {
20602 S.MaybeODRUseExprs.remove(X: E);
20603 if (LambdaScopeInfo *LSI = S.getCurLambda())
20604 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20605 }
20606 };
20607
20608 // C++2a [basic.def.odr]p2:
20609 // The set of potential results of an expression e is defined as follows:
20610 switch (E->getStmtClass()) {
20611 // -- If e is an id-expression, ...
20612 case Expr::DeclRefExprClass: {
20613 auto *DRE = cast<DeclRefExpr>(Val: E);
20614 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20615 break;
20616
20617 // Rebuild as a non-odr-use DeclRefExpr.
20618 MarkNotOdrUsed();
20619 return DeclRefExpr::Create(
20620 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20621 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20622 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20623 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20624 }
20625
20626 case Expr::FunctionParmPackExprClass: {
20627 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20628 // If any of the declarations in the pack is odr-used, then the expression
20629 // as a whole constitutes an odr-use.
20630 for (ValueDecl *D : *FPPE)
20631 if (IsPotentialResultOdrUsed(D))
20632 return ExprEmpty();
20633
20634 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20635 // nothing cares about whether we marked this as an odr-use, but it might
20636 // be useful for non-compiler tools.
20637 MarkNotOdrUsed();
20638 break;
20639 }
20640
20641 // -- If e is a subscripting operation with an array operand...
20642 case Expr::ArraySubscriptExprClass: {
20643 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20644 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20645 if (!OldBase->getType()->isArrayType())
20646 break;
20647 ExprResult Base = Rebuild(OldBase);
20648 if (!Base.isUsable())
20649 return Base;
20650 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20651 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20652 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20653 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20654 rbLoc: ASE->getRBracketLoc());
20655 }
20656
20657 case Expr::MemberExprClass: {
20658 auto *ME = cast<MemberExpr>(Val: E);
20659 // -- If e is a class member access expression [...] naming a non-static
20660 // data member...
20661 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20662 ExprResult Base = Rebuild(ME->getBase());
20663 if (!Base.isUsable())
20664 return Base;
20665 return MemberExpr::Create(
20666 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20667 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20668 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20669 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20670 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20671 }
20672
20673 if (ME->getMemberDecl()->isCXXInstanceMember())
20674 break;
20675
20676 // -- If e is a class member access expression naming a static data member,
20677 // ...
20678 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20679 break;
20680
20681 // Rebuild as a non-odr-use MemberExpr.
20682 MarkNotOdrUsed();
20683 return MemberExpr::Create(
20684 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20685 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20686 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20687 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20688 }
20689
20690 case Expr::BinaryOperatorClass: {
20691 auto *BO = cast<BinaryOperator>(Val: E);
20692 Expr *LHS = BO->getLHS();
20693 Expr *RHS = BO->getRHS();
20694 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20695 if (BO->getOpcode() == BO_PtrMemD) {
20696 ExprResult Sub = Rebuild(LHS);
20697 if (!Sub.isUsable())
20698 return Sub;
20699 BO->setLHS(Sub.get());
20700 // -- If e is a comma expression, ...
20701 } else if (BO->getOpcode() == BO_Comma) {
20702 ExprResult Sub = Rebuild(RHS);
20703 if (!Sub.isUsable())
20704 return Sub;
20705 BO->setRHS(Sub.get());
20706 } else {
20707 break;
20708 }
20709 return ExprResult(BO);
20710 }
20711
20712 // -- If e has the form (e1)...
20713 case Expr::ParenExprClass: {
20714 auto *PE = cast<ParenExpr>(Val: E);
20715 ExprResult Sub = Rebuild(PE->getSubExpr());
20716 if (!Sub.isUsable())
20717 return Sub;
20718 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20719 }
20720
20721 // -- If e is a glvalue conditional expression, ...
20722 // We don't apply this to a binary conditional operator. FIXME: Should we?
20723 case Expr::ConditionalOperatorClass: {
20724 auto *CO = cast<ConditionalOperator>(Val: E);
20725 ExprResult LHS = Rebuild(CO->getLHS());
20726 if (LHS.isInvalid())
20727 return ExprError();
20728 ExprResult RHS = Rebuild(CO->getRHS());
20729 if (RHS.isInvalid())
20730 return ExprError();
20731 if (!LHS.isUsable() && !RHS.isUsable())
20732 return ExprEmpty();
20733 if (!LHS.isUsable())
20734 LHS = CO->getLHS();
20735 if (!RHS.isUsable())
20736 RHS = CO->getRHS();
20737 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20738 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20739 }
20740
20741 // [Clang extension]
20742 // -- If e has the form __extension__ e1...
20743 case Expr::UnaryOperatorClass: {
20744 auto *UO = cast<UnaryOperator>(Val: E);
20745 if (UO->getOpcode() != UO_Extension)
20746 break;
20747 ExprResult Sub = Rebuild(UO->getSubExpr());
20748 if (!Sub.isUsable())
20749 return Sub;
20750 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20751 Input: Sub.get());
20752 }
20753
20754 // [Clang extension]
20755 // -- If e has the form _Generic(...), the set of potential results is the
20756 // union of the sets of potential results of the associated expressions.
20757 case Expr::GenericSelectionExprClass: {
20758 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20759
20760 SmallVector<Expr *, 4> AssocExprs;
20761 bool AnyChanged = false;
20762 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20763 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20764 if (AssocExpr.isInvalid())
20765 return ExprError();
20766 if (AssocExpr.isUsable()) {
20767 AssocExprs.push_back(Elt: AssocExpr.get());
20768 AnyChanged = true;
20769 } else {
20770 AssocExprs.push_back(Elt: OrigAssocExpr);
20771 }
20772 }
20773
20774 void *ExOrTy = nullptr;
20775 bool IsExpr = GSE->isExprPredicate();
20776 if (IsExpr)
20777 ExOrTy = GSE->getControllingExpr();
20778 else
20779 ExOrTy = GSE->getControllingType();
20780 return AnyChanged ? S.CreateGenericSelectionExpr(
20781 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20782 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20783 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20784 : ExprEmpty();
20785 }
20786
20787 // [Clang extension]
20788 // -- If e has the form __builtin_choose_expr(...), the set of potential
20789 // results is the union of the sets of potential results of the
20790 // second and third subexpressions.
20791 case Expr::ChooseExprClass: {
20792 auto *CE = cast<ChooseExpr>(Val: E);
20793
20794 ExprResult LHS = Rebuild(CE->getLHS());
20795 if (LHS.isInvalid())
20796 return ExprError();
20797
20798 ExprResult RHS = Rebuild(CE->getLHS());
20799 if (RHS.isInvalid())
20800 return ExprError();
20801
20802 if (!LHS.get() && !RHS.get())
20803 return ExprEmpty();
20804 if (!LHS.isUsable())
20805 LHS = CE->getLHS();
20806 if (!RHS.isUsable())
20807 RHS = CE->getRHS();
20808
20809 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20810 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20811 }
20812
20813 // Step through non-syntactic nodes.
20814 case Expr::ConstantExprClass: {
20815 auto *CE = cast<ConstantExpr>(Val: E);
20816 ExprResult Sub = Rebuild(CE->getSubExpr());
20817 if (!Sub.isUsable())
20818 return Sub;
20819 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20820 }
20821
20822 // We could mostly rely on the recursive rebuilding to rebuild implicit
20823 // casts, but not at the top level, so rebuild them here.
20824 case Expr::ImplicitCastExprClass: {
20825 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20826 // Only step through the narrow set of cast kinds we expect to encounter.
20827 // Anything else suggests we've left the region in which potential results
20828 // can be found.
20829 switch (ICE->getCastKind()) {
20830 case CK_NoOp:
20831 case CK_DerivedToBase:
20832 case CK_UncheckedDerivedToBase: {
20833 ExprResult Sub = Rebuild(ICE->getSubExpr());
20834 if (!Sub.isUsable())
20835 return Sub;
20836 CXXCastPath Path(ICE->path());
20837 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20838 VK: ICE->getValueKind(), BasePath: &Path);
20839 }
20840
20841 default:
20842 break;
20843 }
20844 break;
20845 }
20846
20847 default:
20848 break;
20849 }
20850
20851 // Can't traverse through this node. Nothing to do.
20852 return ExprEmpty();
20853}
20854
20855ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20856 // Check whether the operand is or contains an object of non-trivial C union
20857 // type.
20858 if (E->getType().isVolatileQualified() &&
20859 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20860 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20861 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20862 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20863 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20864
20865 // C++2a [basic.def.odr]p4:
20866 // [...] an expression of non-volatile-qualified non-class type to which
20867 // the lvalue-to-rvalue conversion is applied [...]
20868 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20869 return E;
20870
20871 ExprResult Result =
20872 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20873 if (Result.isInvalid())
20874 return ExprError();
20875 return Result.get() ? Result : E;
20876}
20877
20878ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20879 if (!Res.isUsable())
20880 return Res;
20881
20882 // If a constant-expression is a reference to a variable where we delay
20883 // deciding whether it is an odr-use, just assume we will apply the
20884 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20885 // (a non-type template argument), we have special handling anyway.
20886 return CheckLValueToRValueConversionOperand(E: Res.get());
20887}
20888
20889void Sema::CleanupVarDeclMarking() {
20890 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20891 // call.
20892 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20893 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20894
20895 for (Expr *E : LocalMaybeODRUseExprs) {
20896 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20897 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20898 Loc: DRE->getLocation(), SemaRef&: *this);
20899 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20900 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20901 SemaRef&: *this);
20902 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20903 for (ValueDecl *VD : *FP)
20904 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20905 } else {
20906 llvm_unreachable("Unexpected expression");
20907 }
20908 }
20909
20910 assert(MaybeODRUseExprs.empty() &&
20911 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20912}
20913
20914static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20915 ValueDecl *Var, Expr *E) {
20916 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20917 if (!VD)
20918 return;
20919
20920 const bool RefersToEnclosingScope =
20921 (SemaRef.CurContext != VD->getDeclContext() &&
20922 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20923 if (RefersToEnclosingScope) {
20924 LambdaScopeInfo *const LSI =
20925 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20926 if (LSI && (!LSI->CallOperator ||
20927 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20928 // If a variable could potentially be odr-used, defer marking it so
20929 // until we finish analyzing the full expression for any
20930 // lvalue-to-rvalue
20931 // or discarded value conversions that would obviate odr-use.
20932 // Add it to the list of potential captures that will be analyzed
20933 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20934 // unless the variable is a reference that was initialized by a constant
20935 // expression (this will never need to be captured or odr-used).
20936 //
20937 // FIXME: We can simplify this a lot after implementing P0588R1.
20938 assert(E && "Capture variable should be used in an expression.");
20939 if (!Var->getType()->isReferenceType() ||
20940 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20941 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20942 }
20943 }
20944}
20945
20946static void DoMarkVarDeclReferenced(
20947 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20948 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20949 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20950 isa<FunctionParmPackExpr>(E)) &&
20951 "Invalid Expr argument to DoMarkVarDeclReferenced");
20952 Var->setReferenced();
20953
20954 if (Var->isInvalidDecl())
20955 return;
20956
20957 auto *MSI = Var->getMemberSpecializationInfo();
20958 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20959 : Var->getTemplateSpecializationKind();
20960
20961 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20962 bool UsableInConstantExpr =
20963 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20964
20965 // Only track variables with internal linkage or local scope.
20966 // Use canonical decl so in-class declarations and out-of-class definitions
20967 // of static data members in anonymous namespaces are tracked as a single
20968 // entry.
20969 const VarDecl *CanonVar = Var->getCanonicalDecl();
20970 if ((CanonVar->isLocalVarDeclOrParm() ||
20971 CanonVar->isInternalLinkageFileVar()) &&
20972 !CanonVar->hasExternalStorage()) {
20973 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20974 }
20975
20976 // C++20 [expr.const]p12:
20977 // A variable [...] is needed for constant evaluation if it is [...] a
20978 // variable whose name appears as a potentially constant evaluated
20979 // expression that is either a contexpr variable or is of non-volatile
20980 // const-qualified integral type or of reference type
20981 bool NeededForConstantEvaluation =
20982 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20983
20984 bool NeedDefinition =
20985 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20986 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20987 Var->getType()->isUndeducedType());
20988
20989 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20990 "Can't instantiate a partial template specialization.");
20991
20992 // If this might be a member specialization of a static data member, check
20993 // the specialization is visible. We already did the checks for variable
20994 // template specializations when we created them.
20995 if (NeedDefinition && TSK != TSK_Undeclared &&
20996 !isa<VarTemplateSpecializationDecl>(Val: Var))
20997 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20998
20999 // Perform implicit instantiation of static data members, static data member
21000 // templates of class templates, and variable template specializations. Delay
21001 // instantiations of variable templates, except for those that could be used
21002 // in a constant expression.
21003 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
21004 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
21005 // instantiation declaration if a variable is usable in a constant
21006 // expression (among other cases).
21007 bool TryInstantiating =
21008 TSK == TSK_ImplicitInstantiation ||
21009 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
21010
21011 if (TryInstantiating) {
21012 SourceLocation PointOfInstantiation =
21013 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
21014 bool FirstInstantiation = PointOfInstantiation.isInvalid();
21015 if (FirstInstantiation) {
21016 PointOfInstantiation = Loc;
21017 if (MSI)
21018 MSI->setPointOfInstantiation(PointOfInstantiation);
21019 // FIXME: Notify listener.
21020 else
21021 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
21022 }
21023
21024 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
21025 // Do not defer instantiations of variables that could be used in a
21026 // constant expression.
21027 // The type deduction also needs a complete initializer.
21028 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
21029 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
21030 });
21031
21032 // The size of an incomplete array type can be updated by
21033 // instantiating the initializer. The DeclRefExpr's type should be
21034 // updated accordingly too, or users of it would be confused!
21035 if (E)
21036 SemaRef.getCompletedType(E);
21037
21038 // Re-set the member to trigger a recomputation of the dependence bits
21039 // for the expression.
21040 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21041 DRE->setDecl(DRE->getDecl());
21042 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21043 ME->setMemberDecl(ME->getMemberDecl());
21044 } else if (FirstInstantiation) {
21045 SemaRef.PendingInstantiations
21046 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21047 } else {
21048 bool Inserted = false;
21049 for (auto &I : SemaRef.SavedPendingInstantiations) {
21050 auto Iter = llvm::find_if(
21051 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
21052 return P.first == Var;
21053 });
21054 if (Iter != I.end()) {
21055 SemaRef.PendingInstantiations.push_back(x: *Iter);
21056 I.erase(position: Iter);
21057 Inserted = true;
21058 break;
21059 }
21060 }
21061
21062 // FIXME: For a specialization of a variable template, we don't
21063 // distinguish between "declaration and type implicitly instantiated"
21064 // and "implicit instantiation of definition requested", so we have
21065 // no direct way to avoid enqueueing the pending instantiation
21066 // multiple times.
21067 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
21068 SemaRef.PendingInstantiations
21069 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
21070 }
21071 }
21072 }
21073
21074 // C++2a [basic.def.odr]p4:
21075 // A variable x whose name appears as a potentially-evaluated expression e
21076 // is odr-used by e unless
21077 // -- x is a reference that is usable in constant expressions
21078 // -- x is a variable of non-reference type that is usable in constant
21079 // expressions and has no mutable subobjects [FIXME], and e is an
21080 // element of the set of potential results of an expression of
21081 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
21082 // conversion is applied
21083 // -- x is a variable of non-reference type, and e is an element of the set
21084 // of potential results of a discarded-value expression to which the
21085 // lvalue-to-rvalue conversion is not applied [FIXME]
21086 //
21087 // We check the first part of the second bullet here, and
21088 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
21089 // FIXME: To get the third bullet right, we need to delay this even for
21090 // variables that are not usable in constant expressions.
21091
21092 // If we already know this isn't an odr-use, there's nothing more to do.
21093 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
21094 if (DRE->isNonOdrUse())
21095 return;
21096 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
21097 if (ME->isNonOdrUse())
21098 return;
21099
21100 switch (OdrUse) {
21101 case OdrUseContext::None:
21102 // In some cases, a variable may not have been marked unevaluated, if it
21103 // appears in a defaukt initializer.
21104 assert((!E || isa<FunctionParmPackExpr>(E) ||
21105 SemaRef.isUnevaluatedContext()) &&
21106 "missing non-odr-use marking for unevaluated decl ref");
21107 break;
21108
21109 case OdrUseContext::FormallyOdrUsed:
21110 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21111 // behavior.
21112 break;
21113
21114 case OdrUseContext::Used:
21115 // If we might later find that this expression isn't actually an odr-use,
21116 // delay the marking.
21117 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
21118 SemaRef.MaybeODRUseExprs.insert(X: E);
21119 else
21120 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
21121 break;
21122
21123 case OdrUseContext::Dependent:
21124 // If this is a dependent context, we don't need to mark variables as
21125 // odr-used, but we may still need to track them for lambda capture.
21126 // FIXME: Do we also need to do this inside dependent typeid expressions
21127 // (which are modeled as unevaluated at this point)?
21128 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21129 break;
21130 }
21131}
21132
21133static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
21134 BindingDecl *BD, Expr *E) {
21135 BD->setReferenced();
21136
21137 if (BD->isInvalidDecl())
21138 return;
21139
21140 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21141 if (OdrUse == OdrUseContext::Used) {
21142 QualType CaptureType, DeclRefType;
21143 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
21144 /*EllipsisLoc*/ SourceLocation(),
21145 /*BuildAndDiagnose*/ true, CaptureType,
21146 DeclRefType,
21147 /*FunctionScopeIndexToStopAt*/ nullptr);
21148 } else if (OdrUse == OdrUseContext::Dependent) {
21149 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
21150 }
21151}
21152
21153void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
21154 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
21155}
21156
21157// C++ [temp.dep.expr]p3:
21158// An id-expression is type-dependent if it contains:
21159// - an identifier associated by name lookup with an entity captured by copy
21160// in a lambda-expression that has an explicit object parameter whose type
21161// is dependent ([dcl.fct]),
21162static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
21163 Sema &SemaRef, ValueDecl *D, Expr *E) {
21164 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
21165 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21166 return;
21167
21168 // If any enclosing lambda with a dependent explicit object parameter either
21169 // explicitly captures the variable by value, or has a capture default of '='
21170 // and does not capture the variable by reference, then the type of the DRE
21171 // is dependent on the type of that lambda's explicit object parameter.
21172 auto IsDependent = [&]() {
21173 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
21174 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
21175 if (!LSI)
21176 continue;
21177
21178 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
21179 LSI->AfterParameterList)
21180 return false;
21181
21182 const auto *MD = LSI->CallOperator;
21183 if (MD->getType().isNull())
21184 continue;
21185
21186 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21187 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21188 !Ty->getParamType(i: 0)->isDependentType())
21189 continue;
21190
21191 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
21192 if (C->isCopyCapture())
21193 return true;
21194 continue;
21195 }
21196
21197 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21198 return true;
21199 }
21200 return false;
21201 }();
21202
21203 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21204 Set: IsDependent, Context: SemaRef.getASTContext());
21205}
21206
21207static void
21208MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
21209 bool MightBeOdrUse,
21210 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21211 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
21212 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
21213
21214 if (SemaRef.getLangOpts().OpenACC)
21215 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21216
21217 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
21218 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
21219 if (SemaRef.getLangOpts().CPlusPlus)
21220 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21221 D: Var, E);
21222 return;
21223 }
21224
21225 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
21226 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
21227 if (SemaRef.getLangOpts().CPlusPlus)
21228 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
21229 D: Decl, E);
21230 return;
21231 }
21232 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21233
21234 // If this is a call to a method via a cast, also mark the method in the
21235 // derived class used in case codegen can devirtualize the call.
21236 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
21237 if (!ME)
21238 return;
21239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
21240 if (!MD)
21241 return;
21242 // Only attempt to devirtualize if this is truly a virtual call.
21243 bool IsVirtualCall = MD->isVirtual() &&
21244 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
21245 if (!IsVirtualCall)
21246 return;
21247
21248 // If it's possible to devirtualize the call, mark the called function
21249 // referenced.
21250 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
21251 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
21252 if (DM)
21253 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
21254}
21255
21256void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
21257 // [basic.def.odr] (CWG 1614)
21258 // A function is named by an expression or conversion [...]
21259 // unless it is a pure virtual function and either the expression is not an
21260 // id-expression naming the function with an explicitly qualified name or
21261 // the expression forms a pointer to member
21262 bool OdrUse = true;
21263 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
21264 if (Method->isVirtual() &&
21265 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
21266 OdrUse = false;
21267
21268 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
21269 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
21270 !isImmediateFunctionContext() &&
21271 !isCheckingDefaultArgumentOrInitializer() &&
21272 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21273 !FD->isDependentContext())
21274 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
21275 }
21276 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
21277 RefsMinusAssignments);
21278}
21279
21280void Sema::MarkMemberReferenced(MemberExpr *E) {
21281 // C++11 [basic.def.odr]p2:
21282 // A non-overloaded function whose name appears as a potentially-evaluated
21283 // expression or a member of a set of candidate functions, if selected by
21284 // overload resolution when referred to from a potentially-evaluated
21285 // expression, is odr-used, unless it is a pure virtual function and its
21286 // name is not explicitly qualified.
21287 bool MightBeOdrUse = true;
21288 if (E->performsVirtualDispatch(LO: getLangOpts())) {
21289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
21290 if (Method->isPureVirtual())
21291 MightBeOdrUse = false;
21292 }
21293 SourceLocation Loc =
21294 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21295 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
21296 RefsMinusAssignments);
21297}
21298
21299void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
21300 for (ValueDecl *VD : *E)
21301 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
21302 RefsMinusAssignments);
21303}
21304
21305/// Perform marking for a reference to an arbitrary declaration. It
21306/// marks the declaration referenced, and performs odr-use checking for
21307/// functions and variables. This method should not be used when building a
21308/// normal expression which refers to a variable.
21309void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
21310 bool MightBeOdrUse) {
21311 if (MightBeOdrUse) {
21312 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
21313 MarkVariableReferenced(Loc, Var: VD);
21314 return;
21315 }
21316 }
21317 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
21318 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
21319 return;
21320 }
21321 D->setReferenced();
21322}
21323
21324namespace {
21325 // Mark all of the declarations used by a type as referenced.
21326 // FIXME: Not fully implemented yet! We need to have a better understanding
21327 // of when we're entering a context we should not recurse into.
21328 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21329 // TreeTransforms rebuilding the type in a new context. Rather than
21330 // duplicating the TreeTransform logic, we should consider reusing it here.
21331 // Currently that causes problems when rebuilding LambdaExprs.
21332class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21333 Sema &S;
21334 SourceLocation Loc;
21335
21336public:
21337 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21338
21339 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21340};
21341}
21342
21343bool MarkReferencedDecls::TraverseTemplateArgument(
21344 const TemplateArgument &Arg) {
21345 {
21346 // A non-type template argument is a constant-evaluated context.
21347 EnterExpressionEvaluationContext Evaluated(
21348 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
21349 if (Arg.getKind() == TemplateArgument::Declaration) {
21350 if (Decl *D = Arg.getAsDecl())
21351 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
21352 } else if (Arg.getKind() == TemplateArgument::Expression) {
21353 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
21354 }
21355 }
21356
21357 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
21358}
21359
21360void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
21361 MarkReferencedDecls Marker(*this, Loc);
21362 Marker.TraverseType(T);
21363}
21364
21365namespace {
21366/// Helper class that marks all of the declarations referenced by
21367/// potentially-evaluated subexpressions as "referenced".
21368class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21369public:
21370 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21371 bool SkipLocalVariables;
21372 ArrayRef<const Expr *> StopAt;
21373
21374 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21375 ArrayRef<const Expr *> StopAt)
21376 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21377
21378 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21379 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21380 }
21381
21382 void Visit(Expr *E) {
21383 if (llvm::is_contained(Range&: StopAt, Element: E))
21384 return;
21385 Inherited::Visit(S: E);
21386 }
21387
21388 void VisitConstantExpr(ConstantExpr *E) {
21389 // Don't mark declarations within a ConstantExpression, as this expression
21390 // will be evaluated and folded to a value.
21391 }
21392
21393 void VisitDeclRefExpr(DeclRefExpr *E) {
21394 // If we were asked not to visit local variables, don't.
21395 if (SkipLocalVariables) {
21396 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21397 if (VD->hasLocalStorage())
21398 return;
21399 }
21400
21401 // FIXME: This can trigger the instantiation of the initializer of a
21402 // variable, which can cause the expression to become value-dependent
21403 // or error-dependent. Do we need to propagate the new dependence bits?
21404 S.MarkDeclRefReferenced(E);
21405 }
21406
21407 void VisitMemberExpr(MemberExpr *E) {
21408 S.MarkMemberReferenced(E);
21409 Visit(E: E->getBase());
21410 }
21411};
21412} // namespace
21413
21414void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21415 bool SkipLocalVariables,
21416 ArrayRef<const Expr*> StopAt) {
21417 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21418}
21419
21420/// Emit a diagnostic when statements are reachable.
21421bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21422 const PartialDiagnostic &PD) {
21423 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21424 // The initializer of a constexpr variable or of the first declaration of a
21425 // static data member is not syntactically a constant evaluated constant,
21426 // but nonetheless is always required to be a constant expression, so we
21427 // can skip diagnosing.
21428 if (Decl &&
21429 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21430 Decl->isFirstDecl() && !Decl->isInline())))
21431 return false;
21432
21433 if (Stmts.empty()) {
21434 Diag(Loc, PD);
21435 return true;
21436 }
21437
21438 if (getCurFunction()) {
21439 // This queue flushes after the function is analyzed, by which time an
21440 // ignore-all-warnings region live here is gone, so sample it now. A note
21441 // is not error-class either, so this also drops the notes that accompany a
21442 // skipped warning. They arrive on their own call, out of reach of the
21443 // engine's rule that drops a note whose warning was ignored.
21444 if (Diags.getIgnoreAllWarnings() &&
21445 Diags.getDiagnosticIDs()->isWarningOrExtension(DiagID: PD.getDiagID()))
21446 return false;
21447 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21448 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21449 return true;
21450 }
21451
21452 // For non-constexpr file-scope variables with reachability context (non-empty
21453 // Stmts), build a CFG for the initializer and check whether the context in
21454 // question is reachable.
21455 if (Decl && Decl->isFileVarDecl()) {
21456 AnalysisWarnings.registerVarDeclWarning(
21457 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21458 return true;
21459 }
21460
21461 Diag(Loc, PD);
21462 return true;
21463}
21464
21465/// Emit a diagnostic that describes an effect on the run-time behavior
21466/// of the program being compiled.
21467///
21468/// This routine emits the given diagnostic when the code currently being
21469/// type-checked is "potentially evaluated", meaning that there is a
21470/// possibility that the code will actually be executable. Code in sizeof()
21471/// expressions, code used only during overload resolution, etc., are not
21472/// potentially evaluated. This routine will suppress such diagnostics or,
21473/// in the absolutely nutty case of potentially potentially evaluated
21474/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21475/// later.
21476///
21477/// This routine should be used for all diagnostics that describe the run-time
21478/// behavior of a program, such as passing a non-POD value through an ellipsis.
21479/// Failure to do so will likely result in spurious diagnostics or failures
21480/// during overload resolution or within sizeof/alignof/typeof/typeid.
21481bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21482 const PartialDiagnostic &PD) {
21483
21484 if (ExprEvalContexts.back().isDiscardedStatementContext())
21485 return false;
21486
21487 switch (ExprEvalContexts.back().Context) {
21488 case ExpressionEvaluationContext::Unevaluated:
21489 case ExpressionEvaluationContext::UnevaluatedList:
21490 case ExpressionEvaluationContext::UnevaluatedAbstract:
21491 case ExpressionEvaluationContext::DiscardedStatement:
21492 // The argument will never be evaluated, so don't complain.
21493 break;
21494
21495 case ExpressionEvaluationContext::ConstantEvaluated:
21496 case ExpressionEvaluationContext::ImmediateFunctionContext:
21497 // Relevant diagnostics should be produced by constant evaluation.
21498 break;
21499
21500 case ExpressionEvaluationContext::PotentiallyEvaluated:
21501 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21502 return DiagIfReachable(Loc, Stmts, PD);
21503 }
21504
21505 return false;
21506}
21507
21508bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21509 const PartialDiagnostic &PD) {
21510 return DiagRuntimeBehavior(
21511 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21512 PD);
21513}
21514
21515bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21516 CallExpr *CE, FunctionDecl *FD) {
21517 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21518 return false;
21519
21520 // If we're inside a decltype's expression, don't check for a valid return
21521 // type or construct temporaries until we know whether this is the last call.
21522 if (ExprEvalContexts.back().ExprContext ==
21523 ExpressionEvaluationContextRecord::EK_Decltype) {
21524 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21525 return false;
21526 }
21527
21528 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21529 FunctionDecl *FD;
21530 CallExpr *CE;
21531
21532 public:
21533 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21534 : FD(FD), CE(CE) { }
21535
21536 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21537 if (!FD) {
21538 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21539 << T << CE->getSourceRange();
21540 return;
21541 }
21542
21543 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21544 << CE->getSourceRange() << FD << T;
21545 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21546 << FD->getDeclName();
21547 }
21548 } Diagnoser(FD, CE);
21549
21550 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21551 return true;
21552
21553 return false;
21554}
21555
21556// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21557// will prevent this condition from triggering, which is what we want.
21558void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21559 SourceLocation Loc;
21560
21561 unsigned diagnostic = diag::warn_condition_is_assignment;
21562 bool IsOrAssign = false;
21563
21564 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21565 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21566 return;
21567
21568 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21569
21570 // Greylist some idioms by putting them into a warning subcategory.
21571 if (ObjCMessageExpr *ME
21572 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21573 Selector Sel = ME->getSelector();
21574
21575 // self = [<foo> init...]
21576 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21577 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21578
21579 // <foo> = [<bar> nextObject]
21580 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21581 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21582 }
21583
21584 Loc = Op->getOperatorLoc();
21585 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21586 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21587 return;
21588
21589 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21590 Loc = Op->getOperatorLoc();
21591 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21592 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21593 else {
21594 // Not an assignment.
21595 return;
21596 }
21597
21598 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21599
21600 SourceLocation Open = E->getBeginLoc();
21601 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21602 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21603 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21604 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21605
21606 if (IsOrAssign)
21607 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21608 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21609 else
21610 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21611 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21612}
21613
21614void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21615 // Don't warn if the parens came from a macro.
21616 SourceLocation parenLoc = ParenE->getBeginLoc();
21617 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21618 return;
21619 // Don't warn for dependent expressions.
21620 if (ParenE->isTypeDependent())
21621 return;
21622
21623 Expr *E = ParenE->IgnoreParens();
21624 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21625 return;
21626
21627 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21628 if (opE->getOpcode() == BO_EQ &&
21629 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21630 == Expr::MLV_Valid) {
21631 SourceLocation Loc = opE->getOperatorLoc();
21632
21633 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21634 SourceRange ParenERange = ParenE->getSourceRange();
21635 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21636 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21637 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21638 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21639 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21640 }
21641}
21642
21643ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21644 bool IsConstexpr) {
21645 DiagnoseAssignmentAsCondition(E);
21646 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21647 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21648
21649 ExprResult result = CheckPlaceholderExpr(E);
21650 if (result.isInvalid()) return ExprError();
21651 E = result.get();
21652
21653 if (!E->isTypeDependent()) {
21654 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21655 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21656
21657 if (getLangOpts().CPlusPlus)
21658 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21659
21660 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21661 if (ERes.isInvalid())
21662 return ExprError();
21663 E = ERes.get();
21664
21665 QualType T = E->getType();
21666 if (!T->isScalarType()) { // C99 6.8.4.1p1
21667 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21668 << T << E->getSourceRange();
21669 return ExprError();
21670 }
21671 CheckBoolLikeConversion(E, CC: Loc);
21672 }
21673
21674 return E;
21675}
21676
21677Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21678 Expr *SubExpr, ConditionKind CK,
21679 bool MissingOK) {
21680 // MissingOK indicates whether having no condition expression is valid
21681 // (for loop) or invalid (e.g. while loop).
21682 if (!SubExpr)
21683 return MissingOK ? ConditionResult() : ConditionError();
21684
21685 ExprResult Cond;
21686 switch (CK) {
21687 case ConditionKind::Boolean:
21688 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21689 break;
21690
21691 case ConditionKind::ConstexprIf:
21692 // Note: this might produce a FullExpr
21693 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21694 break;
21695
21696 case ConditionKind::Switch:
21697 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21698 break;
21699 }
21700 if (Cond.isInvalid()) {
21701 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21702 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21703 if (!Cond.get())
21704 return ConditionError();
21705 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21706 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21707
21708 if (!Cond.isUsable())
21709 return ConditionError();
21710
21711 return ConditionResult(*this, nullptr, Cond,
21712 CK == ConditionKind::ConstexprIf);
21713}
21714
21715namespace {
21716 /// A visitor for rebuilding a call to an __unknown_any expression
21717 /// to have an appropriate type.
21718 struct RebuildUnknownAnyFunction
21719 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21720
21721 Sema &S;
21722
21723 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21724
21725 ExprResult VisitStmt(Stmt *S) {
21726 llvm_unreachable("unexpected statement!");
21727 }
21728
21729 ExprResult VisitExpr(Expr *E) {
21730 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21731 << E->getSourceRange();
21732 return ExprError();
21733 }
21734
21735 /// Rebuild an expression which simply semantically wraps another
21736 /// expression which it shares the type and value kind of.
21737 template <class T> ExprResult rebuildSugarExpr(T *E) {
21738 ExprResult SubResult = Visit(S: E->getSubExpr());
21739 if (SubResult.isInvalid()) return ExprError();
21740
21741 Expr *SubExpr = SubResult.get();
21742 E->setSubExpr(SubExpr);
21743 E->setType(SubExpr->getType());
21744 E->setValueKind(SubExpr->getValueKind());
21745 assert(E->getObjectKind() == OK_Ordinary);
21746 return E;
21747 }
21748
21749 ExprResult VisitParenExpr(ParenExpr *E) {
21750 return rebuildSugarExpr(E);
21751 }
21752
21753 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21754 return rebuildSugarExpr(E);
21755 }
21756
21757 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21758 ExprResult SubResult = Visit(S: E->getSubExpr());
21759 if (SubResult.isInvalid()) return ExprError();
21760
21761 Expr *SubExpr = SubResult.get();
21762 E->setSubExpr(SubExpr);
21763 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21764 assert(E->isPRValue());
21765 assert(E->getObjectKind() == OK_Ordinary);
21766 return E;
21767 }
21768
21769 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21770 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21771
21772 E->setType(VD->getType());
21773
21774 assert(E->isPRValue());
21775 if (S.getLangOpts().CPlusPlus &&
21776 !(isa<CXXMethodDecl>(Val: VD) &&
21777 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21778 E->setValueKind(VK_LValue);
21779
21780 return E;
21781 }
21782
21783 ExprResult VisitMemberExpr(MemberExpr *E) {
21784 return resolveDecl(E, VD: E->getMemberDecl());
21785 }
21786
21787 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21788 return resolveDecl(E, VD: E->getDecl());
21789 }
21790 };
21791}
21792
21793/// Given a function expression of unknown-any type, try to rebuild it
21794/// to have a function type.
21795static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21796 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21797 if (Result.isInvalid()) return ExprError();
21798 return S.DefaultFunctionArrayConversion(E: Result.get());
21799}
21800
21801namespace {
21802 /// A visitor for rebuilding an expression of type __unknown_anytype
21803 /// into one which resolves the type directly on the referring
21804 /// expression. Strict preservation of the original source
21805 /// structure is not a goal.
21806 struct RebuildUnknownAnyExpr
21807 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21808
21809 Sema &S;
21810
21811 /// The current destination type.
21812 QualType DestType;
21813
21814 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21815 : S(S), DestType(CastType) {}
21816
21817 ExprResult VisitStmt(Stmt *S) {
21818 llvm_unreachable("unexpected statement!");
21819 }
21820
21821 ExprResult VisitExpr(Expr *E) {
21822 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21823 << E->getSourceRange();
21824 return ExprError();
21825 }
21826
21827 ExprResult VisitCallExpr(CallExpr *E);
21828 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21829
21830 /// Rebuild an expression which simply semantically wraps another
21831 /// expression which it shares the type and value kind of.
21832 template <class T> ExprResult rebuildSugarExpr(T *E) {
21833 ExprResult SubResult = Visit(S: E->getSubExpr());
21834 if (SubResult.isInvalid()) return ExprError();
21835 Expr *SubExpr = SubResult.get();
21836 E->setSubExpr(SubExpr);
21837 E->setType(SubExpr->getType());
21838 E->setValueKind(SubExpr->getValueKind());
21839 assert(E->getObjectKind() == OK_Ordinary);
21840 return E;
21841 }
21842
21843 ExprResult VisitParenExpr(ParenExpr *E) {
21844 return rebuildSugarExpr(E);
21845 }
21846
21847 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21848 return rebuildSugarExpr(E);
21849 }
21850
21851 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21852 const PointerType *Ptr = DestType->getAs<PointerType>();
21853 if (!Ptr) {
21854 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21855 << E->getSourceRange();
21856 return ExprError();
21857 }
21858
21859 if (isa<CallExpr>(Val: E->getSubExpr())) {
21860 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21861 << E->getSourceRange();
21862 return ExprError();
21863 }
21864
21865 assert(E->isPRValue());
21866 assert(E->getObjectKind() == OK_Ordinary);
21867 E->setType(DestType);
21868
21869 // Build the sub-expression as if it were an object of the pointee type.
21870 DestType = Ptr->getPointeeType();
21871 ExprResult SubResult = Visit(S: E->getSubExpr());
21872 if (SubResult.isInvalid()) return ExprError();
21873 E->setSubExpr(SubResult.get());
21874 return E;
21875 }
21876
21877 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21878
21879 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21880
21881 ExprResult VisitMemberExpr(MemberExpr *E) {
21882 return resolveDecl(E, VD: E->getMemberDecl());
21883 }
21884
21885 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21886 return resolveDecl(E, VD: E->getDecl());
21887 }
21888 };
21889}
21890
21891/// Rebuilds a call expression which yielded __unknown_anytype.
21892ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21893 Expr *CalleeExpr = E->getCallee();
21894
21895 enum FnKind {
21896 FK_MemberFunction,
21897 FK_FunctionPointer,
21898 FK_BlockPointer
21899 };
21900
21901 FnKind Kind;
21902 QualType CalleeType = CalleeExpr->getType();
21903 if (CalleeType == S.Context.BoundMemberTy) {
21904 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21905 Kind = FK_MemberFunction;
21906 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21907 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21908 CalleeType = Ptr->getPointeeType();
21909 Kind = FK_FunctionPointer;
21910 } else {
21911 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21912 Kind = FK_BlockPointer;
21913 }
21914 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21915
21916 // Verify that this is a legal result type of a function.
21917 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21918 DestType->isFunctionType()) {
21919 unsigned diagID = diag::err_func_returning_array_function;
21920 if (Kind == FK_BlockPointer)
21921 diagID = diag::err_block_returning_array_function;
21922
21923 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21924 << DestType->isFunctionType() << DestType;
21925 return ExprError();
21926 }
21927
21928 // Otherwise, go ahead and set DestType as the call's result.
21929 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21930 E->setValueKind(Expr::getValueKindForType(T: DestType));
21931 assert(E->getObjectKind() == OK_Ordinary);
21932
21933 // Rebuild the function type, replacing the result type with DestType.
21934 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21935 if (Proto) {
21936 // __unknown_anytype(...) is a special case used by the debugger when
21937 // it has no idea what a function's signature is.
21938 //
21939 // We want to build this call essentially under the K&R
21940 // unprototyped rules, but making a FunctionNoProtoType in C++
21941 // would foul up all sorts of assumptions. However, we cannot
21942 // simply pass all arguments as variadic arguments, nor can we
21943 // portably just call the function under a non-variadic type; see
21944 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21945 // However, it turns out that in practice it is generally safe to
21946 // call a function declared as "A foo(B,C,D);" under the prototype
21947 // "A foo(B,C,D,...);". The only known exception is with the
21948 // Windows ABI, where any variadic function is implicitly cdecl
21949 // regardless of its normal CC. Therefore we change the parameter
21950 // types to match the types of the arguments.
21951 //
21952 // This is a hack, but it is far superior to moving the
21953 // corresponding target-specific code from IR-gen to Sema/AST.
21954
21955 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21956 SmallVector<QualType, 8> ArgTypes;
21957 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21958 ArgTypes.reserve(N: E->getNumArgs());
21959 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21960 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21961 }
21962 ParamTypes = ArgTypes;
21963 }
21964 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21965 EPI: Proto->getExtProtoInfo());
21966 } else {
21967 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21968 Info: FnType->getExtInfo());
21969 }
21970
21971 // Rebuild the appropriate pointer-to-function type.
21972 switch (Kind) {
21973 case FK_MemberFunction:
21974 // Nothing to do.
21975 break;
21976
21977 case FK_FunctionPointer:
21978 DestType = S.Context.getPointerType(T: DestType);
21979 break;
21980
21981 case FK_BlockPointer:
21982 DestType = S.Context.getBlockPointerType(T: DestType);
21983 break;
21984 }
21985
21986 // Finally, we can recurse.
21987 ExprResult CalleeResult = Visit(S: CalleeExpr);
21988 if (!CalleeResult.isUsable()) return ExprError();
21989 E->setCallee(CalleeResult.get());
21990
21991 // Bind a temporary if necessary.
21992 return S.MaybeBindToTemporary(E);
21993}
21994
21995ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21996 // Verify that this is a legal result type of a call.
21997 if (DestType->isArrayType() || DestType->isFunctionType()) {
21998 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21999 << DestType->isFunctionType() << DestType;
22000 return ExprError();
22001 }
22002
22003 // Rewrite the method result type if available.
22004 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
22005 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
22006 Method->setReturnType(DestType);
22007 }
22008
22009 // Change the type of the message.
22010 E->setType(DestType.getNonReferenceType());
22011 E->setValueKind(Expr::getValueKindForType(T: DestType));
22012
22013 return S.MaybeBindToTemporary(E);
22014}
22015
22016ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
22017 // The only case we should ever see here is a function-to-pointer decay.
22018 if (E->getCastKind() == CK_FunctionToPointerDecay) {
22019 assert(E->isPRValue());
22020 assert(E->getObjectKind() == OK_Ordinary);
22021
22022 E->setType(DestType);
22023
22024 // Rebuild the sub-expression as the pointee (function) type.
22025 DestType = DestType->castAs<PointerType>()->getPointeeType();
22026
22027 ExprResult Result = Visit(S: E->getSubExpr());
22028 if (!Result.isUsable()) return ExprError();
22029
22030 E->setSubExpr(Result.get());
22031 return E;
22032 } else if (E->getCastKind() == CK_LValueToRValue) {
22033 assert(E->isPRValue());
22034 assert(E->getObjectKind() == OK_Ordinary);
22035
22036 assert(isa<BlockPointerType>(E->getType()));
22037
22038 E->setType(DestType);
22039
22040 // The sub-expression has to be a lvalue reference, so rebuild it as such.
22041 DestType = S.Context.getLValueReferenceType(T: DestType);
22042
22043 ExprResult Result = Visit(S: E->getSubExpr());
22044 if (!Result.isUsable()) return ExprError();
22045
22046 E->setSubExpr(Result.get());
22047 return E;
22048 } else {
22049 llvm_unreachable("Unhandled cast type!");
22050 }
22051}
22052
22053ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
22054 ExprValueKind ValueKind = VK_LValue;
22055 QualType Type = DestType;
22056
22057 // We know how to make this work for certain kinds of decls:
22058
22059 // - functions
22060 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
22061 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
22062 DestType = Ptr->getPointeeType();
22063 ExprResult Result = resolveDecl(E, VD);
22064 if (Result.isInvalid()) return ExprError();
22065 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
22066 VK: VK_PRValue);
22067 }
22068
22069 if (!Type->isFunctionType()) {
22070 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
22071 << VD << E->getSourceRange();
22072 return ExprError();
22073 }
22074 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
22075 // We must match the FunctionDecl's type to the hack introduced in
22076 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
22077 // type. See the lengthy commentary in that routine.
22078 QualType FDT = FD->getType();
22079 const FunctionType *FnType = FDT->castAs<FunctionType>();
22080 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
22081 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
22082 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
22083 SourceLocation Loc = FD->getLocation();
22084 FunctionDecl *NewFD = FunctionDecl::Create(
22085 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
22086 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
22087 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
22088 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
22089 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
22090
22091 if (FD->getQualifier())
22092 NewFD->setQualifierInfo(FD->getQualifierLoc());
22093
22094 SmallVector<ParmVarDecl*, 16> Params;
22095 for (const auto &AI : FT->param_types()) {
22096 ParmVarDecl *Param =
22097 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
22098 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
22099 Params.push_back(Elt: Param);
22100 }
22101 NewFD->setParams(Params);
22102 DRE->setDecl(NewFD);
22103 VD = DRE->getDecl();
22104 }
22105 }
22106
22107 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
22108 if (MD->isInstance()) {
22109 ValueKind = VK_PRValue;
22110 Type = S.Context.BoundMemberTy;
22111 }
22112
22113 // Function references aren't l-values in C.
22114 if (!S.getLangOpts().CPlusPlus)
22115 ValueKind = VK_PRValue;
22116
22117 // - variables
22118 } else if (isa<VarDecl>(Val: VD)) {
22119 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22120 Type = RefTy->getPointeeType();
22121 } else if (Type->isFunctionType()) {
22122 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
22123 << VD << E->getSourceRange();
22124 return ExprError();
22125 }
22126
22127 // - nothing else
22128 } else {
22129 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
22130 << VD << E->getSourceRange();
22131 return ExprError();
22132 }
22133
22134 // Modifying the declaration like this is friendly to IR-gen but
22135 // also really dangerous.
22136 VD->setType(DestType);
22137 E->setType(Type);
22138 E->setValueKind(ValueKind);
22139 return E;
22140}
22141
22142ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
22143 Expr *CastExpr, CastKind &CastKind,
22144 ExprValueKind &VK, CXXCastPath &Path) {
22145 // The type we're casting to must be either void or complete.
22146 if (!CastType->isVoidType() &&
22147 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
22148 DiagID: diag::err_typecheck_cast_to_incomplete))
22149 return ExprError();
22150
22151 // Rewrite the casted expression from scratch.
22152 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
22153 if (!result.isUsable()) return ExprError();
22154
22155 CastExpr = result.get();
22156 VK = CastExpr->getValueKind();
22157 CastKind = CK_NoOp;
22158
22159 return CastExpr;
22160}
22161
22162ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
22163 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
22164}
22165
22166ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
22167 Expr *arg, QualType &paramType) {
22168 // If the syntactic form of the argument is not an explicit cast of
22169 // any sort, just do default argument promotion.
22170 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
22171 if (!castArg) {
22172 ExprResult result = DefaultArgumentPromotion(E: arg);
22173 if (result.isInvalid()) return ExprError();
22174 paramType = result.get()->getType();
22175 return result;
22176 }
22177
22178 // Otherwise, use the type that was written in the explicit cast.
22179 assert(!arg->hasPlaceholderType());
22180 paramType = castArg->getTypeAsWritten();
22181
22182 // Copy-initialize a parameter of that type.
22183 InitializedEntity entity =
22184 InitializedEntity::InitializeParameter(Context, Type: paramType,
22185 /*consumed*/ Consumed: false);
22186 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
22187}
22188
22189static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
22190 Expr *orig = E;
22191 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22192 while (true) {
22193 E = E->IgnoreParenImpCasts();
22194 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
22195 E = call->getCallee();
22196 diagID = diag::err_uncasted_call_of_unknown_any;
22197 } else {
22198 break;
22199 }
22200 }
22201
22202 SourceLocation loc;
22203 NamedDecl *d;
22204 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
22205 loc = ref->getLocation();
22206 d = ref->getDecl();
22207 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
22208 loc = mem->getMemberLoc();
22209 d = mem->getMemberDecl();
22210 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
22211 diagID = diag::err_uncasted_call_of_unknown_any;
22212 loc = msg->getSelectorStartLoc();
22213 d = msg->getMethodDecl();
22214 if (!d) {
22215 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
22216 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22217 << orig->getSourceRange();
22218 return ExprError();
22219 }
22220 } else {
22221 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
22222 << E->getSourceRange();
22223 return ExprError();
22224 }
22225
22226 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
22227
22228 // Never recoverable.
22229 return ExprError();
22230}
22231
22232ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
22233 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22234 if (!placeholderType) return E;
22235
22236 switch (placeholderType->getKind()) {
22237 case BuiltinType::UnresolvedTemplate: {
22238 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
22239 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22240 // There's only one FoundDecl for UnresolvedTemplate type. See
22241 // BuildTemplateIdExpr.
22242 NamedDecl *Temp = *ULE->decls_begin();
22243 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
22244
22245 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22246 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22247 // as it models only the unqualified-id case, where this case can clearly be
22248 // qualified. Thus we can't just qualify an assumed template.
22249 TemplateName TN;
22250 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
22251 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
22252 Template: TemplateName(TD));
22253 else
22254 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
22255
22256 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
22257 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22258 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
22259 << IsTypeAliasTemplateDecl;
22260
22261 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22262 bool HasAnyDependentTA = false;
22263 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22264 HasAnyDependentTA |= Arg.getArgument().isDependent();
22265 TAL.addArgument(Loc: Arg);
22266 }
22267
22268 QualType TST;
22269 {
22270 SFINAETrap Trap(*this);
22271 TST = CheckTemplateIdType(
22272 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
22273 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22274 }
22275 if (TST.isNull())
22276 TST = Context.getTemplateSpecializationType(
22277 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
22278 /*CanonicalArgs=*/{},
22279 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22280 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
22281 T: TST);
22282 }
22283
22284 // Overloaded expressions.
22285 case BuiltinType::Overload: {
22286 // Try to resolve a single function template specialization.
22287 // This is obligatory.
22288 ExprResult Result = E;
22289 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
22290 return Result;
22291
22292 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22293 // leaves Result unchanged on failure.
22294 Result = E;
22295 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
22296 return Result;
22297
22298 // If that failed, try to recover with a call.
22299 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
22300 /*complain*/ ForceComplain: true);
22301 return Result;
22302 }
22303
22304 // Bound member functions.
22305 case BuiltinType::BoundMember: {
22306 ExprResult result = E;
22307 const Expr *BME = E->IgnoreParens();
22308 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
22309 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22310 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
22311 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22312 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
22313 if (ME->getMemberNameInfo().getName().getNameKind() ==
22314 DeclarationName::CXXDestructorName)
22315 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22316 }
22317 tryToRecoverWithCall(E&: result, PD,
22318 /*complain*/ ForceComplain: true);
22319 return result;
22320 }
22321
22322 // ARC unbridged casts.
22323 case BuiltinType::ARCUnbridgedCast: {
22324 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
22325 ObjC().diagnoseARCUnbridgedCast(e: realCast);
22326 return realCast;
22327 }
22328
22329 // Expressions of unknown type.
22330 case BuiltinType::UnknownAny:
22331 return diagnoseUnknownAnyExpr(S&: *this, E);
22332
22333 // Pseudo-objects.
22334 case BuiltinType::PseudoObject:
22335 return PseudoObject().checkRValue(E);
22336
22337 case BuiltinType::BuiltinFn: {
22338 // Accept __noop without parens by implicitly converting it to a call expr.
22339 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
22340 if (DRE) {
22341 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
22342 unsigned BuiltinID = FD->getBuiltinID();
22343 if (BuiltinID == Builtin::BI__noop) {
22344 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
22345 CK: CK_BuiltinFnToFnPtr)
22346 .get();
22347 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
22348 VK: VK_PRValue, RParenLoc: SourceLocation(),
22349 FPFeatures: FPOptionsOverride());
22350 }
22351
22352 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
22353 // Any use of these other than a direct call is ill-formed as of C++20,
22354 // because they are not addressable functions. In earlier language
22355 // modes, warn and force an instantiation of the real body.
22356 Diag(Loc: E->getBeginLoc(),
22357 DiagID: getLangOpts().CPlusPlus20
22358 ? diag::err_use_of_unaddressable_function
22359 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22360 if (FD->isImplicitlyInstantiable()) {
22361 // Require a definition here because a normal attempt at
22362 // instantiation for a builtin will be ignored, and we won't try
22363 // again later. We assume that the definition of the template
22364 // precedes this use.
22365 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
22366 /*Recursive=*/false,
22367 /*DefinitionRequired=*/true,
22368 /*AtEndOfTU=*/false);
22369 }
22370 // Produce a properly-typed reference to the function.
22371 CXXScopeSpec SS;
22372 SS.Adopt(Other: DRE->getQualifierLoc());
22373 TemplateArgumentListInfo TemplateArgs;
22374 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22375 return BuildDeclRefExpr(
22376 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22377 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22378 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22379 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22380 }
22381 }
22382
22383 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22384 return ExprError();
22385 }
22386
22387 case BuiltinType::IncompleteMatrixIdx: {
22388 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22389 // At this point, we know there was no second [] to complete the operator.
22390 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22391 if (getLangOpts().HLSL) {
22392 return CreateBuiltinMatrixSingleSubscriptExpr(
22393 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22394 }
22395 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22396 return ExprError();
22397 }
22398
22399 // Expressions of unknown type.
22400 case BuiltinType::ArraySection:
22401 // If we've already diagnosed something on the array section type, we
22402 // shouldn't need to do any further diagnostic here.
22403 if (!E->containsErrors())
22404 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22405 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22406 return ExprError();
22407
22408 // Expressions of unknown type.
22409 case BuiltinType::OMPArrayShaping:
22410 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22411
22412 case BuiltinType::OMPIterator:
22413 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22414
22415 // Everything else should be impossible.
22416#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22417 case BuiltinType::Id:
22418#include "clang/Basic/OpenCLImageTypes.def"
22419#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22420 case BuiltinType::Id:
22421#include "clang/Basic/OpenCLExtensionTypes.def"
22422#define SVE_TYPE(Name, Id, SingletonId) \
22423 case BuiltinType::Id:
22424#include "clang/Basic/AArch64ACLETypes.def"
22425#define PPC_VECTOR_TYPE(Name, Id, Size) \
22426 case BuiltinType::Id:
22427#include "clang/Basic/PPCTypes.def"
22428#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22429#include "clang/Basic/RISCVVTypes.def"
22430#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22431#include "clang/Basic/WebAssemblyReferenceTypes.def"
22432#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22433#include "clang/Basic/AMDGPUTypes.def"
22434#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22435#include "clang/Basic/HLSLIntangibleTypes.def"
22436#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22437#include "clang/Basic/HLSLPackedTypes.def"
22438#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22439#include "clang/Basic/SPIRVTypes.def"
22440#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22441#define PLACEHOLDER_TYPE(Id, SingletonId)
22442#include "clang/AST/BuiltinTypes.def"
22443 break;
22444 }
22445
22446 llvm_unreachable("invalid placeholder type!");
22447}
22448
22449bool Sema::CheckCaseExpression(Expr *E) {
22450 if (E->isTypeDependent())
22451 return true;
22452 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22453 return E->getType()->isIntegralOrEnumerationType();
22454 return false;
22455}
22456
22457ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22458 ArrayRef<Expr *> SubExprs, QualType T) {
22459 if (!Context.getLangOpts().RecoveryAST)
22460 return ExprError();
22461
22462 if (isSFINAEContext())
22463 return ExprError();
22464
22465 if (T.isNull() || T->isUndeducedType() ||
22466 !Context.getLangOpts().RecoveryASTType)
22467 // We don't know the concrete type, fallback to dependent type.
22468 T = Context.DependentTy;
22469
22470 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22471}
22472