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/Builtins.h"
37#include "clang/Basic/DiagnosticSema.h"
38#include "clang/Basic/PartialDiagnostic.h"
39#include "clang/Basic/SourceManager.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/TypeTraits.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/SemaARM.h"
57#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaFixItUtils.h"
59#include "clang/Sema/SemaHLSL.h"
60#include "clang/Sema/SemaObjC.h"
61#include "clang/Sema/SemaOpenMP.h"
62#include "clang/Sema/SemaPseudoObject.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/STLExtras.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/Support/ConvertUTF.h"
67#include "llvm/Support/SaveAndRestore.h"
68#include "llvm/Support/TimeProfiler.h"
69#include "llvm/Support/TypeSize.h"
70#include <limits>
71#include <optional>
72
73using namespace clang;
74using namespace sema;
75
76bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
77 // See if this is an auto-typed variable whose initializer we are parsing.
78 if (ParsingInitForAutoVars.count(Ptr: D))
79 return false;
80
81 // See if this is a deleted function.
82 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
83 if (FD->isDeleted())
84 return false;
85
86 // If the function has a deduced return type, and we can't deduce it,
87 // then we can't use it either.
88 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
89 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
90 return false;
91
92 // See if this is an aligned allocation/deallocation function that is
93 // unavailable.
94 if (TreatUnavailableAsInvalid &&
95 isUnavailableAlignedAllocationFunction(FD: *FD))
96 return false;
97 }
98
99 // See if this function is unavailable.
100 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
101 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
102 return false;
103
104 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
105 return false;
106
107 return true;
108}
109
110static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
111 // Warn if this is used but marked unused.
112 if (const auto *A = D->getAttr<UnusedAttr>()) {
113 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
114 // should diagnose them.
115 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
116 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
117 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
118 if (DC && !DC->hasAttr<UnusedAttr>())
119 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
120 }
121 }
122}
123
124void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
125 assert(Decl && Decl->isDeleted());
126
127 if (Decl->isDefaulted()) {
128 // If the method was explicitly defaulted, point at that declaration.
129 if (!Decl->isImplicit())
130 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
131
132 // Try to diagnose why this special member function was implicitly
133 // deleted. This might fail, if that reason no longer applies.
134 DiagnoseDeletedDefaultedFunction(FD: Decl);
135 return;
136 }
137
138 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
139 if (Ctor && Ctor->isInheritingConstructor())
140 return NoteDeletedInheritingConstructor(CD: Ctor);
141
142 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
143 << Decl << 1;
144}
145
146/// Determine whether a FunctionDecl was ever declared with an
147/// explicit storage class.
148static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
149 for (auto *I : D->redecls()) {
150 if (I->getStorageClass() != SC_None)
151 return true;
152 }
153 return false;
154}
155
156/// Check whether we're in an extern inline function and referring to a
157/// variable or function with internal linkage (C11 6.7.4p3).
158///
159/// This is only a warning because we used to silently accept this code, but
160/// in many cases it will not behave correctly. This is not enabled in C++ mode
161/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
162/// and so while there may still be user mistakes, most of the time we can't
163/// prove that there are errors.
164static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
165 const NamedDecl *D,
166 SourceLocation Loc) {
167 // This is disabled under C++; there are too many ways for this to fire in
168 // contexts where the warning is a false positive, or where it is technically
169 // correct but benign.
170 //
171 // WG14 N3622 which removed the constraint entirely in C2y. It is left
172 // enabled in earlier language modes because this is a constraint in those
173 // language modes. But in C2y mode, we still want to issue the "incompatible
174 // with previous standards" diagnostic, too.
175 if (S.getLangOpts().CPlusPlus)
176 return;
177
178 // Check if this is an inlined function or method.
179 FunctionDecl *Current = S.getCurFunctionDecl();
180 if (!Current)
181 return;
182 if (!Current->isInlined())
183 return;
184 if (!Current->isExternallyVisible())
185 return;
186
187 // Check if the decl has internal linkage.
188 if (D->getFormalLinkage() != Linkage::Internal)
189 return;
190
191 // Downgrade from ExtWarn to Extension if
192 // (1) the supposedly external inline function is in the main file,
193 // and probably won't be included anywhere else.
194 // (2) the thing we're referencing is a pure function.
195 // (3) the thing we're referencing is another inline function.
196 // This last can give us false negatives, but it's better than warning on
197 // wrappers for simple C library functions.
198 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
199 unsigned DiagID;
200 if (S.getLangOpts().C2y)
201 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
202 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
203 S.getSourceManager().isInMainFile(Loc))
204 DiagID = diag::ext_internal_in_extern_inline_quiet;
205 else
206 DiagID = diag::ext_internal_in_extern_inline;
207
208 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
209 S.MaybeSuggestAddingStaticToDecl(D: Current);
210 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
211 << D;
212}
213
214void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
215 const FunctionDecl *First = Cur->getFirstDecl();
216
217 // Suggest "static" on the function, if possible.
218 if (!hasAnyExplicitStorageClass(D: First)) {
219 SourceLocation DeclBegin = First->getSourceRange().getBegin();
220 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
221 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
222 }
223}
224
225bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
226 const ObjCInterfaceDecl *UnknownObjCClass,
227 bool ObjCPropertyAccess,
228 bool AvoidPartialAvailabilityChecks,
229 ObjCInterfaceDecl *ClassReceiver,
230 bool SkipTrailingRequiresClause) {
231 SourceLocation Loc = Locs.front();
232 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
233 // If there were any diagnostics suppressed by template argument deduction,
234 // emit them now.
235 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
236 if (Pos != SuppressedDiagnostics.end()) {
237 for (const auto &[DiagLoc, PD] : Pos->second) {
238 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
239 PD.Emit(DB: Builder);
240 }
241 // Clear out the list of suppressed diagnostics, so that we don't emit
242 // them again for this specialization. However, we don't obsolete this
243 // entry from the table, because we want to avoid ever emitting these
244 // diagnostics again.
245 Pos->second.clear();
246 }
247
248 // C++ [basic.start.main]p3:
249 // The function 'main' shall not be used within a program.
250 if (cast<FunctionDecl>(Val: D)->isMain())
251 Diag(Loc, DiagID: diag::ext_main_used);
252
253 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
254 }
255
256 // See if this is an auto-typed variable whose initializer we are parsing.
257 if (ParsingInitForAutoVars.count(Ptr: D)) {
258 if (isa<BindingDecl>(Val: D)) {
259 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
260 << D->getDeclName();
261 } else {
262 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
263 << diag::ParsingInitFor::Var << D->getDeclName()
264 << cast<VarDecl>(Val: D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, DiagID: diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
282 NoteDeletedFunction(Decl: FD);
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
317 return true;
318
319 }
320
321 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
322 Concept && CheckConceptUseInDefinition(Concept, Loc))
323 return true;
324
325 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
326 // Lambdas are only default-constructible or assignable in C++2a onwards.
327 if (MD->getParent()->isLambda() &&
328 ((isa<CXXConstructorDecl>(Val: MD) &&
329 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
330 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
331 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
332 << !isa<CXXConstructorDecl>(Val: MD);
333 }
334 }
335
336 auto getReferencedObjCProp = [](const NamedDecl *D) ->
337 const ObjCPropertyDecl * {
338 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
339 return MD->findPropertyDecl();
340 return nullptr;
341 };
342 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
343 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
344 return true;
345 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
346 return true;
347 }
348
349 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
350 // Only the variables omp_in and omp_out are allowed in the combiner.
351 // Only the variables omp_priv and omp_orig are allowed in the
352 // initializer-clause.
353 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
354 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
355 isa<VarDecl>(Val: D)) {
356 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
357 << getCurFunction()->HasOMPDeclareReductionCombiner;
358 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
359 return true;
360 }
361
362 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
363 // List-items in map clauses on this construct may only refer to the declared
364 // variable var and entities that could be referenced by a procedure defined
365 // at the same location.
366 // [OpenMP 5.2] Also allow iterator declared variables.
367 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
368 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
369 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
370 << OpenMP().getOpenMPDeclareMapperVarName();
371 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
372 return true;
373 }
374
375 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
376 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
377 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
378 return true;
379 }
380
381 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
382 AvoidPartialAvailabilityChecks, ClassReceiver);
383
384 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
385
386 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
387
388 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
389 if (getLangOpts().getFPEvalMethod() !=
390 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
391 PP.getLastFPEvalPragmaLocation().isValid() &&
392 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
393 Diag(Loc: D->getLocation(),
394 DiagID: diag::err_type_available_only_in_default_eval_method)
395 << D->getName();
396 }
397
398 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
399 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
400
401 if (LangOpts.SYCLIsDevice ||
402 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
403 if (!Context.getTargetInfo().isTLSSupported())
404 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
405 if (VD->getTLSKind() != VarDecl::TLS_None)
406 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
407 }
408
409 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
410 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
411
412 return false;
413}
414
415void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
416 ArrayRef<Expr *> Args) {
417 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
418 if (!Attr)
419 return;
420
421 // The number of formal parameters of the declaration.
422 unsigned NumFormalParams;
423
424 // The kind of declaration. This is also an index into a %select in
425 // the diagnostic.
426 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
427
428 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
429 NumFormalParams = MD->param_size();
430 CalleeKind = CK_Method;
431 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
432 NumFormalParams = FD->param_size();
433 CalleeKind = CK_Function;
434 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
435 QualType Ty = VD->getType();
436 const FunctionType *Fn = nullptr;
437 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
438 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
439 if (!Fn)
440 return;
441 CalleeKind = CK_Function;
442 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
443 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
444 CalleeKind = CK_Block;
445 } else {
446 return;
447 }
448
449 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
450 NumFormalParams = proto->getNumParams();
451 else
452 NumFormalParams = 0;
453 } else {
454 return;
455 }
456
457 // "NullPos" is the number of formal parameters at the end which
458 // effectively count as part of the variadic arguments. This is
459 // useful if you would prefer to not have *any* formal parameters,
460 // but the language forces you to have at least one.
461 unsigned NullPos = Attr->getNullPos();
462 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
463 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
464
465 // The number of arguments which should follow the sentinel.
466 unsigned NumArgsAfterSentinel = Attr->getSentinel();
467
468 // If there aren't enough arguments for all the formal parameters,
469 // the sentinel, and the args after the sentinel, complain.
470 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
471 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
472 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
473 return;
474 }
475
476 // Otherwise, find the sentinel expression.
477 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
478 if (!SentinelExpr)
479 return;
480 if (SentinelExpr->isValueDependent())
481 return;
482 if (Context.isSentinelNullExpr(E: SentinelExpr))
483 return;
484
485 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
486 // or 'NULL' if those are actually defined in the context. Only use
487 // 'nil' for ObjC methods, where it's much more likely that the
488 // variadic arguments form a list of object pointers.
489 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
490 std::string NullValue;
491 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
492 NullValue = "nil";
493 else if (getLangOpts().CPlusPlus11)
494 NullValue = "nullptr";
495 else if (PP.isMacroDefined(Id: "NULL"))
496 NullValue = "NULL";
497 else
498 NullValue = "(void*) 0";
499
500 if (MissingNilLoc.isInvalid())
501 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
502 else
503 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
504 << int(CalleeKind)
505 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
506 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
507 << int(CalleeKind) << Attr->getRange();
508}
509
510SourceRange Sema::getExprRange(Expr *E) const {
511 return E ? E->getSourceRange() : SourceRange();
512}
513
514//===----------------------------------------------------------------------===//
515// Standard Promotions and Conversions
516//===----------------------------------------------------------------------===//
517
518/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
519ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
520 // Handle any placeholder expressions which made it here.
521 if (E->hasPlaceholderType()) {
522 ExprResult result = CheckPlaceholderExpr(E);
523 if (result.isInvalid()) return ExprError();
524 E = result.get();
525 }
526
527 QualType Ty = E->getType();
528 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
529
530 if (Ty->isFunctionType()) {
531 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
532 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
533 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
534 return ExprError();
535
536 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
537 CK: CK_FunctionToPointerDecay).get();
538 } else if (Ty->isArrayType()) {
539 // In C90 mode, arrays only promote to pointers if the array expression is
540 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
541 // type 'array of type' is converted to an expression that has type 'pointer
542 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
543 // that has type 'array of type' ...". The relevant change is "an lvalue"
544 // (C90) to "an expression" (C99).
545 //
546 // C++ 4.2p1:
547 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
548 // T" can be converted to an rvalue of type "pointer to T".
549 //
550 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
551 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
552 CK: CK_ArrayToPointerDecay);
553 if (Res.isInvalid())
554 return ExprError();
555 E = Res.get();
556 }
557 }
558 return E;
559}
560
561static void CheckForNullPointerDereference(Sema &S, Expr *E) {
562 // Check to see if we are dereferencing a null pointer. If so,
563 // and if not volatile-qualified, this is undefined behavior that the
564 // optimizer will delete, so warn about it. People sometimes try to use this
565 // to get a deterministic trap and are surprised by clang's behavior. This
566 // only handles the pattern "*null", which is a very syntactic check.
567 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
568 if (UO && UO->getOpcode() == UO_Deref &&
569 UO->getSubExpr()->getType()->isPointerType()) {
570 const LangAS AS =
571 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
572 if ((!isTargetAddressSpace(AS) ||
573 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
574 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
575 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
576 !UO->getType().isVolatileQualified()) {
577 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
578 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
579 << UO->getSubExpr()->getSourceRange());
580 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
581 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
582 }
583 }
584}
585
586static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
587 SourceLocation AssignLoc,
588 const Expr* RHS) {
589 const ObjCIvarDecl *IV = OIRE->getDecl();
590 if (!IV)
591 return;
592
593 DeclarationName MemberName = IV->getDeclName();
594 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
595 if (!Member || !Member->isStr(Str: "isa"))
596 return;
597
598 const Expr *Base = OIRE->getBase();
599 QualType BaseType = Base->getType();
600 if (OIRE->isArrow())
601 BaseType = BaseType->getPointeeType();
602 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
603 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
604 ObjCInterfaceDecl *ClassDeclared = nullptr;
605 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
606 if (!ClassDeclared->getSuperClass()
607 && (*ClassDeclared->ivar_begin()) == IV) {
608 if (RHS) {
609 NamedDecl *ObjectSetClass =
610 S.LookupSingleName(S: S.TUScope,
611 Name: &S.Context.Idents.get(Name: "object_setClass"),
612 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
613 if (ObjectSetClass) {
614 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
615 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
616 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
617 Code: "object_setClass(")
618 << FixItHint::CreateReplacement(
619 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
620 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
621 }
622 else
623 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
624 } else {
625 NamedDecl *ObjectGetClass =
626 S.LookupSingleName(S: S.TUScope,
627 Name: &S.Context.Idents.get(Name: "object_getClass"),
628 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
629 if (ObjectGetClass)
630 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
631 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
632 Code: "object_getClass(")
633 << FixItHint::CreateReplacement(
634 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
635 else
636 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
637 }
638 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
639 }
640 }
641}
642
643ExprResult Sema::DefaultLvalueConversion(Expr *E) {
644 // Handle any placeholder expressions which made it here.
645 if (E->hasPlaceholderType()) {
646 ExprResult result = CheckPlaceholderExpr(E);
647 if (result.isInvalid()) return ExprError();
648 E = result.get();
649 }
650
651 // C++ [conv.lval]p1:
652 // A glvalue of a non-function, non-array type T can be
653 // converted to a prvalue.
654 if (!E->isGLValue()) return E;
655
656 QualType T = E->getType();
657 assert(!T.isNull() && "r-value conversion on typeless expression?");
658
659 // lvalue-to-rvalue conversion cannot be applied to types that decay to
660 // pointers (i.e. function or array types).
661 if (T->canDecayToPointerType())
662 return E;
663
664 // We don't want to throw lvalue-to-rvalue casts on top of
665 // expressions of certain types in C++.
666 if (getLangOpts().CPlusPlus) {
667 if (T == Context.OverloadTy || T->isRecordType() ||
668 (T->isDependentType() && !T->isAnyPointerType() &&
669 !T->isMemberPointerType()))
670 return E;
671 }
672
673 // The C standard is actually really unclear on this point, and
674 // DR106 tells us what the result should be but not why. It's
675 // generally best to say that void types just doesn't undergo
676 // lvalue-to-rvalue at all. Note that expressions of unqualified
677 // 'void' type are never l-values, but qualified void can be.
678 if (T->isVoidType())
679 return E;
680
681 // OpenCL usually rejects direct accesses to values of 'half' type.
682 if (getLangOpts().OpenCL &&
683 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
684 T->isHalfType()) {
685 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
686 << 0 << T;
687 return ExprError();
688 }
689
690 CheckForNullPointerDereference(S&: *this, E);
691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
692 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
693 Name: &Context.Idents.get(Name: "object_getClass"),
694 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
695 if (ObjectGetClass)
696 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
697 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
698 << FixItHint::CreateReplacement(
699 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
700 else
701 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
702 }
703 else if (const ObjCIvarRefExpr *OIRE =
704 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
705 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
706
707 // C++ [conv.lval]p1:
708 // [...] If T is a non-class type, the type of the prvalue is the
709 // cv-unqualified version of T. Otherwise, the type of the
710 // rvalue is T.
711 //
712 // C99 6.3.2.1p2:
713 // If the lvalue has qualified type, the value has the unqualified
714 // version of the type of the lvalue; otherwise, the value has the
715 // type of the lvalue.
716 if (T.hasQualifiers())
717 T = T.getUnqualifiedType();
718
719 // Under the MS ABI, lock down the inheritance model now.
720 if (T->isMemberPointerType() &&
721 Context.getTargetInfo().getCXXABI().isMicrosoft())
722 (void)isCompleteType(Loc: E->getExprLoc(), T);
723
724 ExprResult Res = CheckLValueToRValueConversionOperand(E);
725 if (Res.isInvalid())
726 return Res;
727 E = Res.get();
728
729 // Loading a __weak object implicitly retains the value, so we need a cleanup to
730 // balance that.
731 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
732 Cleanup.setExprNeedsCleanups(true);
733
734 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
735 Cleanup.setExprNeedsCleanups(true);
736
737 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
738 return ExprError();
739
740 // C++ [conv.lval]p3:
741 // If T is cv std::nullptr_t, the result is a null pointer constant.
742 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
743 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
744 FPO: CurFPFeatureOverrides());
745
746 // C11 6.3.2.1p2:
747 // ... if the lvalue has atomic type, the value has the non-atomic version
748 // of the type of the lvalue ...
749 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
750 T = Atomic->getValueType().getUnqualifiedType();
751 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
752 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
753 }
754
755 return Res;
756}
757
758ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
759 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
760 if (Res.isInvalid())
761 return ExprError();
762 Res = DefaultLvalueConversion(E: Res.get());
763 if (Res.isInvalid())
764 return ExprError();
765 return Res;
766}
767
768ExprResult Sema::CallExprUnaryConversions(Expr *E) {
769 QualType Ty = E->getType();
770 ExprResult Res = E;
771 // Only do implicit cast for a function type, but not for a pointer
772 // to function type.
773 if (Ty->isFunctionType()) {
774 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
775 CK: CK_FunctionToPointerDecay);
776 if (Res.isInvalid())
777 return ExprError();
778 }
779 Res = DefaultLvalueConversion(E: Res.get());
780 if (Res.isInvalid())
781 return ExprError();
782 return Res.get();
783}
784
785/// UsualUnaryFPConversions - Promotes floating-point types according to the
786/// current language semantics.
787ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
788 QualType Ty = E->getType();
789 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
790
791 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
792 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
793 (getLangOpts().getFPEvalMethod() !=
794 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
795 PP.getLastFPEvalPragmaLocation().isValid())) {
796 switch (EvalMethod) {
797 default:
798 llvm_unreachable("Unrecognized float evaluation method");
799 break;
800 case LangOptions::FEM_UnsetOnCommandLine:
801 llvm_unreachable("Float evaluation method should be set by now");
802 break;
803 case LangOptions::FEM_Double:
804 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
805 // Widen the expression to double.
806 return Ty->isComplexType()
807 ? ImpCastExprToType(E,
808 Type: Context.getComplexType(T: Context.DoubleTy),
809 CK: CK_FloatingComplexCast)
810 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
811 break;
812 case LangOptions::FEM_Extended:
813 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
814 // Widen the expression to long double.
815 return Ty->isComplexType()
816 ? ImpCastExprToType(
817 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
818 CK: CK_FloatingComplexCast)
819 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
820 CK: CK_FloatingCast);
821 break;
822 }
823 }
824
825 // Half FP have to be promoted to float unless it is natively supported
826 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
827 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
828
829 return E;
830}
831
832/// UsualUnaryConversions - Performs various conversions that are common to most
833/// operators (C99 6.3). The conversions of array and function types are
834/// sometimes suppressed. For example, the array->pointer conversion doesn't
835/// apply if the array is an argument to the sizeof or address (&) operators.
836/// In these instances, this routine should *not* be called.
837ExprResult Sema::UsualUnaryConversions(Expr *E) {
838 // First, convert to an r-value.
839 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
840 if (Res.isInvalid())
841 return ExprError();
842
843 // Promote floating-point types.
844 Res = UsualUnaryFPConversions(E: Res.get());
845 if (Res.isInvalid())
846 return ExprError();
847 E = Res.get();
848
849 QualType Ty = E->getType();
850 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
851
852 // Try to perform integral promotions if the object has a theoretically
853 // promotable type.
854 if (Ty->isIntegralOrUnscopedEnumerationType()) {
855 // C99 6.3.1.1p2:
856 //
857 // The following may be used in an expression wherever an int or
858 // unsigned int may be used:
859 // - an object or expression with an integer type whose integer
860 // conversion rank is less than or equal to the rank of int
861 // and unsigned int.
862 // - A bit-field of type _Bool, int, signed int, or unsigned int.
863 //
864 // If an int can represent all values of the original type, the
865 // value is converted to an int; otherwise, it is converted to an
866 // unsigned int. These are called the integer promotions. All
867 // other types are unchanged by the integer promotions.
868
869 QualType PTy = Context.isPromotableBitField(E);
870 if (!PTy.isNull()) {
871 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
872 return E;
873 }
874 if (Context.isPromotableIntegerType(T: Ty)) {
875 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
876 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
877 return E;
878 }
879 }
880 return E;
881}
882
883/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
884/// do not have a prototype. Arguments that have type float or __fp16
885/// are promoted to double. All other argument types are converted by
886/// UsualUnaryConversions().
887ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
888 QualType Ty = E->getType();
889 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
890
891 ExprResult Res = UsualUnaryConversions(E);
892 if (Res.isInvalid())
893 return ExprError();
894 E = Res.get();
895
896 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
897 // promote to double.
898 // Note that default argument promotion applies only to float (and
899 // half/fp16); it does not apply to _Float16.
900 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
901 if (BTy && (BTy->getKind() == BuiltinType::Half ||
902 BTy->getKind() == BuiltinType::Float)) {
903 if (getLangOpts().OpenCL &&
904 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
905 if (BTy->getKind() == BuiltinType::Half) {
906 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
907 }
908 } else {
909 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
910 }
911 }
912 if (BTy &&
913 getLangOpts().getExtendIntArgs() ==
914 LangOptions::ExtendArgsKind::ExtendTo64 &&
915 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
916 Context.getTypeSizeInChars(T: BTy) <
917 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
918 E = (Ty->isUnsignedIntegerType())
919 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
920 .get()
921 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
922 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
923 "Unexpected typesize for LongLongTy");
924 }
925
926 // C++ performs lvalue-to-rvalue conversion as a default argument
927 // promotion, even on class types, but note:
928 // C++11 [conv.lval]p2:
929 // When an lvalue-to-rvalue conversion occurs in an unevaluated
930 // operand or a subexpression thereof the value contained in the
931 // referenced object is not accessed. Otherwise, if the glvalue
932 // has a class type, the conversion copy-initializes a temporary
933 // of type T from the glvalue and the result of the conversion
934 // is a prvalue for the temporary.
935 // FIXME: add some way to gate this entire thing for correctness in
936 // potentially potentially evaluated contexts.
937 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
938 ExprResult Temp = PerformCopyInitialization(
939 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
940 EqualLoc: E->getExprLoc(), Init: E);
941 if (Temp.isInvalid())
942 return ExprError();
943 E = Temp.get();
944 }
945
946 // C++ [expr.call]p7, per CWG722:
947 // An argument that has (possibly cv-qualified) type std::nullptr_t is
948 // converted to void* ([conv.ptr]).
949 // (This does not apply to C23 nullptr)
950 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
951 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
952
953 return E;
954}
955
956VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
957 if (Ty->isIncompleteType()) {
958 // C++11 [expr.call]p7:
959 // After these conversions, if the argument does not have arithmetic,
960 // enumeration, pointer, pointer to member, or class type, the program
961 // is ill-formed.
962 //
963 // Since we've already performed null pointer conversion, array-to-pointer
964 // decay and function-to-pointer decay, the only such type in C++ is cv
965 // void. This also handles initializer lists as variadic arguments.
966 if (Ty->isVoidType())
967 return VarArgKind::Invalid;
968
969 if (Ty->isObjCObjectType())
970 return VarArgKind::Invalid;
971 return VarArgKind::Valid;
972 }
973
974 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
975 return VarArgKind::Invalid;
976
977 if (Context.getTargetInfo().getTriple().isWasm() &&
978 Ty.isWebAssemblyReferenceType()) {
979 return VarArgKind::Invalid;
980 }
981
982 if (Ty.isCXX98PODType(Context))
983 return VarArgKind::Valid;
984
985 // C++11 [expr.call]p7:
986 // Passing a potentially-evaluated argument of class type (Clause 9)
987 // having a non-trivial copy constructor, a non-trivial move constructor,
988 // or a non-trivial destructor, with no corresponding parameter,
989 // is conditionally-supported with implementation-defined semantics.
990 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
991 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
992 if (!Record->hasNonTrivialCopyConstructor() &&
993 !Record->hasNonTrivialMoveConstructor() &&
994 !Record->hasNonTrivialDestructor())
995 return VarArgKind::ValidInCXX11;
996
997 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
998 return VarArgKind::Valid;
999
1000 if (Ty->isObjCObjectType())
1001 return VarArgKind::Invalid;
1002
1003 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1004 return VarArgKind::Valid;
1005
1006 if (getLangOpts().MSVCCompat)
1007 return VarArgKind::MSVCUndefined;
1008
1009 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1010 return VarArgKind::Valid;
1011
1012 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1013 // permitted to reject them. We should consider doing so.
1014 return VarArgKind::Undefined;
1015}
1016
1017void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1018 // Don't allow one to pass an Objective-C interface to a vararg.
1019 const QualType &Ty = E->getType();
1020 VarArgKind VAK = isValidVarArgType(Ty);
1021
1022 // Complain about passing non-POD types through varargs.
1023 switch (VAK) {
1024 case VarArgKind::ValidInCXX11:
1025 DiagRuntimeBehavior(
1026 Loc: E->getBeginLoc(), Statement: nullptr,
1027 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1028 [[fallthrough]];
1029 case VarArgKind::Valid:
1030 if (Ty->isRecordType()) {
1031 // This is unlikely to be what the user intended. If the class has a
1032 // 'c_str' member function, the user probably meant to call that.
1033 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1034 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1035 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1036 }
1037 break;
1038
1039 case VarArgKind::Undefined:
1040 case VarArgKind::MSVCUndefined:
1041 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1042 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1043 << getLangOpts().CPlusPlus11 << Ty << CT);
1044 break;
1045
1046 case VarArgKind::Invalid:
1047 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1048 Diag(Loc: E->getBeginLoc(),
1049 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1050 << Ty << CT;
1051 else if (Ty->isObjCObjectType())
1052 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1053 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1054 << Ty << CT);
1055 else
1056 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1057 << isa<InitListExpr>(Val: E) << Ty << CT;
1058 break;
1059 }
1060}
1061
1062ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1063 FunctionDecl *FDecl) {
1064 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1065 // Strip the unbridged-cast placeholder expression off, if applicable.
1066 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1067 (CT == VariadicCallType::Method ||
1068 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1069 E = ObjC().stripARCUnbridgedCast(e: E);
1070
1071 // Otherwise, do normal placeholder checking.
1072 } else {
1073 ExprResult ExprRes = CheckPlaceholderExpr(E);
1074 if (ExprRes.isInvalid())
1075 return ExprError();
1076 E = ExprRes.get();
1077 }
1078 }
1079
1080 ExprResult ExprRes = DefaultArgumentPromotion(E);
1081 if (ExprRes.isInvalid())
1082 return ExprError();
1083
1084 // Copy blocks to the heap.
1085 if (ExprRes.get()->getType()->isBlockPointerType())
1086 maybeExtendBlockObject(E&: ExprRes);
1087
1088 E = ExprRes.get();
1089
1090 // Diagnostics regarding non-POD argument types are
1091 // emitted along with format string checking in Sema::CheckFunctionCall().
1092 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1093 // Turn this into a trap.
1094 CXXScopeSpec SS;
1095 SourceLocation TemplateKWLoc;
1096 UnqualifiedId Name;
1097 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1098 IdLoc: E->getBeginLoc());
1099 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1100 /*HasTrailingLParen=*/true,
1101 /*IsAddressOfOperand=*/false);
1102 if (TrapFn.isInvalid())
1103 return ExprError();
1104
1105 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1106 RParenLoc: E->getEndLoc());
1107 if (Call.isInvalid())
1108 return ExprError();
1109
1110 ExprResult Comma =
1111 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1112 if (Comma.isInvalid())
1113 return ExprError();
1114 return Comma.get();
1115 }
1116
1117 if (!getLangOpts().CPlusPlus &&
1118 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1119 DiagID: diag::err_call_incomplete_argument))
1120 return ExprError();
1121
1122 return E;
1123}
1124
1125/// Convert complex integers to complex floats and real integers to
1126/// real floats as required for complex arithmetic. Helper function of
1127/// UsualArithmeticConversions()
1128///
1129/// \return false if the integer expression is an integer type and is
1130/// successfully converted to the (complex) float type.
1131static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1132 ExprResult &ComplexExpr,
1133 QualType IntTy,
1134 QualType ComplexTy,
1135 bool SkipCast) {
1136 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1137 if (SkipCast) return false;
1138 if (IntTy->isIntegerType()) {
1139 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1140 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1141 } else {
1142 assert(IntTy->isComplexIntegerType());
1143 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1144 CK: CK_IntegralComplexToFloatingComplex);
1145 }
1146 return false;
1147}
1148
1149// This handles complex/complex, complex/float, or float/complex.
1150// When both operands are complex, the shorter operand is converted to the
1151// type of the longer, and that is the type of the result. This corresponds
1152// to what is done when combining two real floating-point operands.
1153// The fun begins when size promotion occur across type domains.
1154// From H&S 6.3.4: When one operand is complex and the other is a real
1155// floating-point type, the less precise type is converted, within it's
1156// real or complex domain, to the precision of the other type. For example,
1157// when combining a "long double" with a "double _Complex", the
1158// "double _Complex" is promoted to "long double _Complex".
1159static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1160 QualType ShorterType,
1161 QualType LongerType,
1162 bool PromotePrecision) {
1163 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1164 QualType Result =
1165 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1166
1167 if (PromotePrecision) {
1168 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1169 Shorter =
1170 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1171 } else {
1172 if (LongerIsComplex)
1173 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1174 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1175 }
1176 }
1177 return Result;
1178}
1179
1180/// Handle arithmetic conversion with complex types. Helper function of
1181/// UsualArithmeticConversions()
1182static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1183 ExprResult &RHS, QualType LHSType,
1184 QualType RHSType, bool IsCompAssign) {
1185 // Handle (complex) integer types.
1186 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1187 /*SkipCast=*/false))
1188 return LHSType;
1189 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1190 /*SkipCast=*/IsCompAssign))
1191 return RHSType;
1192
1193 // Compute the rank of the two types, regardless of whether they are complex.
1194 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1195 if (Order < 0)
1196 // Promote the precision of the LHS if not an assignment.
1197 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1198 /*PromotePrecision=*/!IsCompAssign);
1199 // Promote the precision of the RHS unless it is already the same as the LHS.
1200 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1201 /*PromotePrecision=*/Order > 0);
1202}
1203
1204/// Handle arithmetic conversion from integer to float. Helper function
1205/// of UsualArithmeticConversions()
1206static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1207 ExprResult &IntExpr,
1208 QualType FloatTy, QualType IntTy,
1209 bool ConvertFloat, bool ConvertInt) {
1210 if (IntTy->isIntegerType()) {
1211 if (ConvertInt)
1212 // Convert intExpr to the lhs floating point type.
1213 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1214 CK: CK_IntegralToFloating);
1215 return FloatTy;
1216 }
1217
1218 // Convert both sides to the appropriate complex float.
1219 assert(IntTy->isComplexIntegerType());
1220 QualType result = S.Context.getComplexType(T: FloatTy);
1221
1222 // _Complex int -> _Complex float
1223 if (ConvertInt)
1224 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1225 CK: CK_IntegralComplexToFloatingComplex);
1226
1227 // float -> _Complex float
1228 if (ConvertFloat)
1229 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1230 CK: CK_FloatingRealToComplex);
1231
1232 return result;
1233}
1234
1235/// Handle arithmethic conversion with floating point types. Helper
1236/// function of UsualArithmeticConversions()
1237static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1238 ExprResult &RHS, QualType LHSType,
1239 QualType RHSType, bool IsCompAssign) {
1240 bool LHSFloat = LHSType->isRealFloatingType();
1241 bool RHSFloat = RHSType->isRealFloatingType();
1242
1243 // N1169 4.1.4: If one of the operands has a floating type and the other
1244 // operand has a fixed-point type, the fixed-point operand
1245 // is converted to the floating type [...]
1246 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1247 if (LHSFloat)
1248 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1249 else if (!IsCompAssign)
1250 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1251 return LHSFloat ? LHSType : RHSType;
1252 }
1253
1254 // If we have two real floating types, convert the smaller operand
1255 // to the bigger result.
1256 if (LHSFloat && RHSFloat) {
1257 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1258 if (order > 0) {
1259 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1260 return LHSType;
1261 }
1262
1263 assert(order < 0 && "illegal float comparison");
1264 if (!IsCompAssign)
1265 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1266 return RHSType;
1267 }
1268
1269 if (LHSFloat) {
1270 // Half FP has to be promoted to float unless it is natively supported
1271 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1272 LHSType = S.Context.FloatTy;
1273
1274 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1275 /*ConvertFloat=*/!IsCompAssign,
1276 /*ConvertInt=*/ true);
1277 }
1278 assert(RHSFloat);
1279 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1280 /*ConvertFloat=*/ true,
1281 /*ConvertInt=*/!IsCompAssign);
1282}
1283
1284/// Diagnose attempts to convert between __float128, __ibm128 and
1285/// long double if there is no support for such conversion.
1286/// Helper function of UsualArithmeticConversions().
1287static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1288 QualType RHSType) {
1289 // No issue if either is not a floating point type.
1290 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1291 return false;
1292
1293 // No issue if both have the same 128-bit float semantics.
1294 auto *LHSComplex = LHSType->getAs<ComplexType>();
1295 auto *RHSComplex = RHSType->getAs<ComplexType>();
1296
1297 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1298 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1299
1300 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1301 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1302
1303 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1304 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1305 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1306 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1307 return false;
1308
1309 return true;
1310}
1311
1312typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1313
1314namespace {
1315/// These helper callbacks are placed in an anonymous namespace to
1316/// permit their use as function template parameters.
1317ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1318 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1319}
1320
1321ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1322 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1323 CK: CK_IntegralComplexCast);
1324}
1325}
1326
1327/// Handle integer arithmetic conversions. Helper function of
1328/// UsualArithmeticConversions()
1329template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1330static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1331 ExprResult &RHS, QualType LHSType,
1332 QualType RHSType, bool IsCompAssign) {
1333 // The rules for this case are in C99 6.3.1.8
1334 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1335 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1336 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1337 if (LHSSigned == RHSSigned) {
1338 // Same signedness; use the higher-ranked type
1339 if (order >= 0) {
1340 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1341 return LHSType;
1342 } else if (!IsCompAssign)
1343 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1344 return RHSType;
1345 } else if (order != (LHSSigned ? 1 : -1)) {
1346 // The unsigned type has greater than or equal rank to the
1347 // signed type, so use the unsigned type
1348 if (RHSSigned) {
1349 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1350 return LHSType;
1351 } else if (!IsCompAssign)
1352 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1353 return RHSType;
1354 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1355 // The two types are different widths; if we are here, that
1356 // means the signed type is larger than the unsigned type, so
1357 // use the signed type.
1358 if (LHSSigned) {
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 {
1365 // The signed type is higher-ranked than the unsigned type,
1366 // but isn't actually any bigger (like unsigned int and long
1367 // on most 32-bit systems). Use the unsigned type corresponding
1368 // to the signed type.
1369 QualType result =
1370 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1371 RHS = (*doRHSCast)(S, RHS.get(), result);
1372 if (!IsCompAssign)
1373 LHS = (*doLHSCast)(S, LHS.get(), result);
1374 return result;
1375 }
1376}
1377
1378/// Handle conversions with GCC complex int extension. Helper function
1379/// of UsualArithmeticConversions()
1380static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1381 ExprResult &RHS, QualType LHSType,
1382 QualType RHSType,
1383 bool IsCompAssign) {
1384 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1385 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1386
1387 if (LHSComplexInt && RHSComplexInt) {
1388 QualType LHSEltType = LHSComplexInt->getElementType();
1389 QualType RHSEltType = RHSComplexInt->getElementType();
1390 QualType ScalarType =
1391 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1392 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1393
1394 return S.Context.getComplexType(T: ScalarType);
1395 }
1396
1397 if (LHSComplexInt) {
1398 QualType LHSEltType = LHSComplexInt->getElementType();
1399 QualType ScalarType =
1400 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1401 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1402 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1403 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1404 CK: CK_IntegralRealToComplex);
1405
1406 return ComplexType;
1407 }
1408
1409 assert(RHSComplexInt);
1410
1411 QualType RHSEltType = RHSComplexInt->getElementType();
1412 QualType ScalarType =
1413 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1414 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1415 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1416
1417 if (!IsCompAssign)
1418 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1419 CK: CK_IntegralRealToComplex);
1420 return ComplexType;
1421}
1422
1423static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1424 ExprResult &RHS,
1425 QualType LHSType,
1426 QualType RHSType,
1427 bool IsCompAssign) {
1428
1429 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1430 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1431
1432 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1433 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1434
1435 bool LHSHasTrap =
1436 LhsOBT && LhsOBT->getBehaviorKind() ==
1437 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1438 bool RHSHasTrap =
1439 RhsOBT && RhsOBT->getBehaviorKind() ==
1440 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1441 bool LHSHasWrap =
1442 LhsOBT && LhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1444 bool RHSHasWrap =
1445 RhsOBT && RhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1447
1448 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1449 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1450
1451 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1452 if (LHSHasTrap || RHSHasTrap)
1453 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1454 else if (LHSHasWrap || RHSHasWrap)
1455 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1456
1457 QualType LHSConvType = LHSUnderlyingType;
1458 QualType RHSConvType = RHSUnderlyingType;
1459 if (DominantBehavior) {
1460 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1461 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1462 Wrapped: LHSUnderlyingType);
1463 else
1464 LHSConvType = LHSType;
1465
1466 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1467 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1468 Wrapped: RHSUnderlyingType);
1469 else
1470 RHSConvType = RHSType;
1471 }
1472
1473 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1474 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1475}
1476
1477/// Return the rank of a given fixed point or integer type. The value itself
1478/// doesn't matter, but the values must be increasing with proper increasing
1479/// rank as described in N1169 4.1.1.
1480static unsigned GetFixedPointRank(QualType Ty) {
1481 const auto *BTy = Ty->getAs<BuiltinType>();
1482 assert(BTy && "Expected a builtin type.");
1483
1484 switch (BTy->getKind()) {
1485 case BuiltinType::ShortFract:
1486 case BuiltinType::UShortFract:
1487 case BuiltinType::SatShortFract:
1488 case BuiltinType::SatUShortFract:
1489 return 1;
1490 case BuiltinType::Fract:
1491 case BuiltinType::UFract:
1492 case BuiltinType::SatFract:
1493 case BuiltinType::SatUFract:
1494 return 2;
1495 case BuiltinType::LongFract:
1496 case BuiltinType::ULongFract:
1497 case BuiltinType::SatLongFract:
1498 case BuiltinType::SatULongFract:
1499 return 3;
1500 case BuiltinType::ShortAccum:
1501 case BuiltinType::UShortAccum:
1502 case BuiltinType::SatShortAccum:
1503 case BuiltinType::SatUShortAccum:
1504 return 4;
1505 case BuiltinType::Accum:
1506 case BuiltinType::UAccum:
1507 case BuiltinType::SatAccum:
1508 case BuiltinType::SatUAccum:
1509 return 5;
1510 case BuiltinType::LongAccum:
1511 case BuiltinType::ULongAccum:
1512 case BuiltinType::SatLongAccum:
1513 case BuiltinType::SatULongAccum:
1514 return 6;
1515 default:
1516 if (BTy->isInteger())
1517 return 0;
1518 llvm_unreachable("Unexpected fixed point or integer type");
1519 }
1520}
1521
1522/// handleFixedPointConversion - Fixed point operations between fixed
1523/// point types and integers or other fixed point types do not fall under
1524/// usual arithmetic conversion since these conversions could result in loss
1525/// of precsision (N1169 4.1.4). These operations should be calculated with
1526/// the full precision of their result type (N1169 4.1.6.2.1).
1527static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1528 QualType RHSTy) {
1529 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1530 "Expected at least one of the operands to be a fixed point type");
1531 assert((LHSTy->isFixedPointOrIntegerType() ||
1532 RHSTy->isFixedPointOrIntegerType()) &&
1533 "Special fixed point arithmetic operation conversions are only "
1534 "applied to ints or other fixed point types");
1535
1536 // If one operand has signed fixed-point type and the other operand has
1537 // unsigned fixed-point type, then the unsigned fixed-point operand is
1538 // converted to its corresponding signed fixed-point type and the resulting
1539 // type is the type of the converted operand.
1540 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1541 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1542 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1543 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1544
1545 // The result type is the type with the highest rank, whereby a fixed-point
1546 // conversion rank is always greater than an integer conversion rank; if the
1547 // type of either of the operands is a saturating fixedpoint type, the result
1548 // type shall be the saturating fixed-point type corresponding to the type
1549 // with the highest rank; the resulting value is converted (taking into
1550 // account rounding and overflow) to the precision of the resulting type.
1551 // Same ranks between signed and unsigned types are resolved earlier, so both
1552 // types are either signed or both unsigned at this point.
1553 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1554 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1555
1556 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1557
1558 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1559 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1560
1561 return ResultTy;
1562}
1563
1564/// Check that the usual arithmetic conversions can be performed on this pair of
1565/// expressions that might be of enumeration type.
1566void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1567 SourceLocation Loc,
1568 ArithConvKind ACK) {
1569 // C++2a [expr.arith.conv]p1:
1570 // If one operand is of enumeration type and the other operand is of a
1571 // different enumeration type or a floating-point type, this behavior is
1572 // deprecated ([depr.arith.conv.enum]).
1573 //
1574 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1575 // Eventually we will presumably reject these cases (in C++23 onwards?).
1576 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1577 R = RHS->getEnumCoercedType(Ctx: Context);
1578 bool LEnum = L->isUnscopedEnumerationType(),
1579 REnum = R->isUnscopedEnumerationType();
1580 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1581 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1582 (REnum && L->isFloatingType())) {
1583 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1584 : getLangOpts().CPlusPlus20
1585 ? diag::warn_arith_conv_enum_float_cxx20
1586 : diag::warn_arith_conv_enum_float)
1587 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1588 << L << R;
1589 } else if (!IsCompAssign && LEnum && REnum &&
1590 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1591 unsigned DiagID;
1592 // In C++ 26, usual arithmetic conversions between 2 different enum types
1593 // are ill-formed.
1594 if (getLangOpts().CPlusPlus26)
1595 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1596 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1597 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1598 // If either enumeration type is unnamed, it's less likely that the
1599 // user cares about this, but this situation is still deprecated in
1600 // C++2a. Use a different warning group.
1601 DiagID = getLangOpts().CPlusPlus20
1602 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1603 : diag::warn_arith_conv_mixed_anon_enum_types;
1604 } else if (ACK == ArithConvKind::Conditional) {
1605 // Conditional expressions are separated out because they have
1606 // historically had a different warning flag.
1607 DiagID = getLangOpts().CPlusPlus20
1608 ? diag::warn_conditional_mixed_enum_types_cxx20
1609 : diag::warn_conditional_mixed_enum_types;
1610 } else if (ACK == ArithConvKind::Comparison) {
1611 // Comparison expressions are separated out because they have
1612 // historically had a different warning flag.
1613 DiagID = getLangOpts().CPlusPlus20
1614 ? diag::warn_comparison_mixed_enum_types_cxx20
1615 : diag::warn_comparison_mixed_enum_types;
1616 } else {
1617 DiagID = getLangOpts().CPlusPlus20
1618 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1619 : diag::warn_arith_conv_mixed_enum_types;
1620 }
1621 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1622 << (int)ACK << L << R;
1623 }
1624}
1625
1626static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1627 Expr *RHS, SourceLocation Loc,
1628 ArithConvKind ACK) {
1629 QualType LHSType = LHS->getType().getUnqualifiedType();
1630 QualType RHSType = RHS->getType().getUnqualifiedType();
1631
1632 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1633 !RHSType->isUnicodeCharacterType())
1634 return;
1635
1636 if (ACK == ArithConvKind::Comparison) {
1637 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1638 return;
1639
1640 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1641 if (T->isChar8Type())
1642 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1643 if (T->isChar16Type())
1644 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1645 assert(T->isChar32Type());
1646 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1647 };
1648
1649 Expr::EvalResult LHSRes, RHSRes;
1650 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1651 AllowSideEffects: Expr::SE_AllowSideEffects,
1652 InConstantContext: SemaRef.isConstantEvaluatedContext());
1653 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1654 AllowSideEffects: Expr::SE_AllowSideEffects,
1655 InConstantContext: SemaRef.isConstantEvaluatedContext());
1656
1657 // Don't warn if the one known value is a representable
1658 // in the type of both expressions.
1659 if (LHSSuccess != RHSuccess) {
1660 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1661 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1662 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1663 return;
1664 }
1665
1666 if (!LHSSuccess || !RHSuccess) {
1667 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1668 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1669 << RHSType;
1670 return;
1671 }
1672
1673 llvm::APSInt LHSValue(32);
1674 LHSValue = LHSRes.Val.getInt();
1675 llvm::APSInt RHSValue(32);
1676 RHSValue = RHSRes.Val.getInt();
1677
1678 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1679 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1680 if (LHSSafe && RHSSafe)
1681 return;
1682
1683 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1684 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1685 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1686 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1687 return;
1688 }
1689
1690 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1691 return;
1692
1693 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1694 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1695 << RHSType;
1696}
1697
1698/// UsualArithmeticConversions - Performs various conversions that are common to
1699/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1700/// routine returns the first non-arithmetic type found. The client is
1701/// responsible for emitting appropriate error diagnostics.
1702QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1703 SourceLocation Loc,
1704 ArithConvKind ACK) {
1705
1706 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1707
1708 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1709
1710 if (ACK != ArithConvKind::CompAssign) {
1711 LHS = UsualUnaryConversions(E: LHS.get());
1712 if (LHS.isInvalid())
1713 return QualType();
1714 }
1715
1716 RHS = UsualUnaryConversions(E: RHS.get());
1717 if (RHS.isInvalid())
1718 return QualType();
1719
1720 // For conversion purposes, we ignore any qualifiers.
1721 // For example, "const float" and "float" are equivalent.
1722 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1723 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1724
1725 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1726 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1727 LHSType = AtomicLHS->getValueType();
1728
1729 // If both types are identical, no conversion is needed.
1730 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1731 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1732
1733 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1734 // The caller can deal with this (e.g. pointer + int).
1735 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1736 return QualType();
1737
1738 // Apply unary and bitfield promotions to the LHS's type.
1739 QualType LHSUnpromotedType = LHSType;
1740 if (Context.isPromotableIntegerType(T: LHSType))
1741 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1742 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1743 if (!LHSBitfieldPromoteTy.isNull())
1744 LHSType = LHSBitfieldPromoteTy;
1745 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1746 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1747
1748 // If both types are identical, no conversion is needed.
1749 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1750 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1751
1752 // At this point, we have two different arithmetic types.
1753
1754 // Diagnose attempts to convert between __ibm128, __float128 and long double
1755 // where such conversions currently can't be handled.
1756 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1757 return QualType();
1758
1759 // Handle complex types first (C99 6.3.1.8p1).
1760 if (LHSType->isComplexType() || RHSType->isComplexType())
1761 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1762 IsCompAssign: ACK == ArithConvKind::CompAssign);
1763
1764 // Now handle "real" floating types (i.e. float, double, long double).
1765 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1766 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1767 IsCompAssign: ACK == ArithConvKind::CompAssign);
1768
1769 // Handle GCC complex int extension.
1770 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1771 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1772 IsCompAssign: ACK == ArithConvKind::CompAssign);
1773
1774 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1775 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1776
1777 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1778 return handleOverflowBehaviorTypeConversion(
1779 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1780
1781 // Finally, we have two differing integer types.
1782 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1783 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1784}
1785
1786//===----------------------------------------------------------------------===//
1787// Semantic Analysis for various Expression Types
1788//===----------------------------------------------------------------------===//
1789
1790
1791ExprResult Sema::ActOnGenericSelectionExpr(
1792 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1793 bool PredicateIsExpr, void *ControllingExprOrType,
1794 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1795 unsigned NumAssocs = ArgTypes.size();
1796 assert(NumAssocs == ArgExprs.size());
1797
1798 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1799 for (unsigned i = 0; i < NumAssocs; ++i) {
1800 if (ArgTypes[i])
1801 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1802 else
1803 Types[i] = nullptr;
1804 }
1805
1806 // If we have a controlling type, we need to convert it from a parsed type
1807 // into a semantic type and then pass that along.
1808 if (!PredicateIsExpr) {
1809 TypeSourceInfo *ControllingType;
1810 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1811 TInfo: &ControllingType);
1812 assert(ControllingType && "couldn't get the type out of the parser");
1813 ControllingExprOrType = ControllingType;
1814 }
1815
1816 ExprResult ER = CreateGenericSelectionExpr(
1817 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1818 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1819 delete [] Types;
1820 return ER;
1821}
1822
1823// Helper function to determine type compatibility for C _Generic expressions.
1824// Multiple compatible types within the same _Generic expression is ambiguous
1825// and not valid.
1826static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1827 QualType U) {
1828 // Try to handle special types like OverflowBehaviorTypes
1829 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1830 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1831
1832 if (TOBT || UOBT) {
1833 if (TOBT && UOBT) {
1834 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1835 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1836 T2: UOBT->getUnderlyingType());
1837 return false;
1838 }
1839 return false;
1840 }
1841
1842 // We're dealing with types that don't require special handling.
1843 return Ctx.typesAreCompatible(T1: T, T2: U);
1844}
1845
1846ExprResult Sema::CreateGenericSelectionExpr(
1847 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1848 bool PredicateIsExpr, void *ControllingExprOrType,
1849 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1850 unsigned NumAssocs = Types.size();
1851 assert(NumAssocs == Exprs.size());
1852 assert(ControllingExprOrType &&
1853 "Must have either a controlling expression or a controlling type");
1854
1855 Expr *ControllingExpr = nullptr;
1856 TypeSourceInfo *ControllingType = nullptr;
1857 if (PredicateIsExpr) {
1858 // Decay and strip qualifiers for the controlling expression type, and
1859 // handle placeholder type replacement. See committee discussion from WG14
1860 // DR423.
1861 EnterExpressionEvaluationContext Unevaluated(
1862 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1863 ExprResult R = DefaultFunctionArrayLvalueConversion(
1864 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1865 if (R.isInvalid())
1866 return ExprError();
1867 ControllingExpr = R.get();
1868 } else {
1869 // The extension form uses the type directly rather than converting it.
1870 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1871 if (!ControllingType)
1872 return ExprError();
1873 }
1874
1875 bool TypeErrorFound = false,
1876 IsResultDependent = ControllingExpr
1877 ? ControllingExpr->isTypeDependent()
1878 : ControllingType->getType()->isDependentType(),
1879 ContainsUnexpandedParameterPack =
1880 ControllingExpr
1881 ? ControllingExpr->containsUnexpandedParameterPack()
1882 : ControllingType->getType()->containsUnexpandedParameterPack();
1883
1884 // The controlling expression is an unevaluated operand, so side effects are
1885 // likely unintended.
1886 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1887 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1888 Diag(Loc: ControllingExpr->getExprLoc(),
1889 DiagID: diag::warn_side_effects_unevaluated_context);
1890
1891 for (unsigned i = 0; i < NumAssocs; ++i) {
1892 if (Exprs[i]->containsUnexpandedParameterPack())
1893 ContainsUnexpandedParameterPack = true;
1894
1895 if (Types[i]) {
1896 if (Types[i]->getType()->containsUnexpandedParameterPack())
1897 ContainsUnexpandedParameterPack = true;
1898
1899 if (Types[i]->getType()->isDependentType()) {
1900 IsResultDependent = true;
1901 } else {
1902 // We relax the restriction on use of incomplete types and non-object
1903 // types with the type-based extension of _Generic. Allowing incomplete
1904 // objects means those can be used as "tags" for a type-safe way to map
1905 // to a value. Similarly, matching on function types rather than
1906 // function pointer types can be useful. However, the restriction on VM
1907 // types makes sense to retain as there are open questions about how
1908 // the selection can be made at compile time.
1909 //
1910 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1911 // complete object type other than a variably modified type."
1912 // C2y removed the requirement that an expression form must
1913 // use a complete type, though it's still as-if the type has undergone
1914 // lvalue conversion. We support this as an extension in C23 and
1915 // earlier because GCC does so.
1916 unsigned D = 0;
1917 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1918 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1919 : diag::ext_assoc_type_incomplete;
1920 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1921 D = diag::err_assoc_type_nonobject;
1922 else if (Types[i]->getType()->isVariablyModifiedType())
1923 D = diag::err_assoc_type_variably_modified;
1924 else if (ControllingExpr) {
1925 // Because the controlling expression undergoes lvalue conversion,
1926 // array conversion, and function conversion, an association which is
1927 // of array type, function type, or is qualified can never be
1928 // reached. We will warn about this so users are less surprised by
1929 // the unreachable association. However, we don't have to handle
1930 // function types; that's not an object type, so it's handled above.
1931 //
1932 // The logic is somewhat different for C++ because C++ has different
1933 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1934 // If T is a non-class type, the type of the prvalue is the cv-
1935 // unqualified version of T. Otherwise, the type of the prvalue is T.
1936 // The result of these rules is that all qualified types in an
1937 // association in C are unreachable, and in C++, only qualified non-
1938 // class types are unreachable.
1939 //
1940 // NB: this does not apply when the first operand is a type rather
1941 // than an expression, because the type form does not undergo
1942 // conversion.
1943 unsigned Reason = 0;
1944 QualType QT = Types[i]->getType();
1945 if (QT->isArrayType())
1946 Reason = 1;
1947 else if (QT.hasQualifiers() &&
1948 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1949 Reason = 2;
1950
1951 if (Reason)
1952 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1953 DiagID: diag::warn_unreachable_association)
1954 << QT << (Reason - 1);
1955 }
1956
1957 if (D != 0) {
1958 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1959 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1960 if (getDiagnostics().getDiagnosticLevel(
1961 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1962 DiagnosticsEngine::Error)
1963 TypeErrorFound = true;
1964 }
1965
1966 // C11 6.5.1.1p2 "No two generic associations in the same generic
1967 // selection shall specify compatible types."
1968 for (unsigned j = i+1; j < NumAssocs; ++j)
1969 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1970 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1971 U: Types[j]->getType())) {
1972 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1973 DiagID: diag::err_assoc_compatible_types)
1974 << Types[j]->getTypeLoc().getSourceRange()
1975 << Types[j]->getType()
1976 << Types[i]->getType();
1977 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1978 DiagID: diag::note_compat_assoc)
1979 << Types[i]->getTypeLoc().getSourceRange()
1980 << Types[i]->getType();
1981 TypeErrorFound = true;
1982 }
1983 }
1984 }
1985 }
1986 if (TypeErrorFound)
1987 return ExprError();
1988
1989 // If we determined that the generic selection is result-dependent, don't
1990 // try to compute the result expression.
1991 if (IsResultDependent) {
1992 if (ControllingExpr)
1993 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
1994 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1995 ContainsUnexpandedParameterPack);
1996 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1997 AssocExprs: Exprs, DefaultLoc, RParenLoc,
1998 ContainsUnexpandedParameterPack);
1999 }
2000
2001 SmallVector<unsigned, 1> CompatIndices;
2002 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2003 // Look at the canonical type of the controlling expression in case it was a
2004 // deduced type like __auto_type. However, when issuing diagnostics, use the
2005 // type the user wrote in source rather than the canonical one.
2006 for (unsigned i = 0; i < NumAssocs; ++i) {
2007 if (!Types[i])
2008 DefaultIndex = i;
2009 else {
2010 bool Compatible;
2011 QualType ControllingQT =
2012 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2013 : ControllingType->getType().getCanonicalType();
2014 QualType AssocQT = Types[i]->getType();
2015
2016 Compatible =
2017 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2018
2019 if (Compatible)
2020 CompatIndices.push_back(Elt: i);
2021 }
2022 }
2023
2024 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2025 TypeSourceInfo *ControllingType) {
2026 // We strip parens here because the controlling expression is typically
2027 // parenthesized in macro definitions.
2028 if (ControllingExpr)
2029 ControllingExpr = ControllingExpr->IgnoreParens();
2030
2031 SourceRange SR = ControllingExpr
2032 ? ControllingExpr->getSourceRange()
2033 : ControllingType->getTypeLoc().getSourceRange();
2034 QualType QT = ControllingExpr ? ControllingExpr->getType()
2035 : ControllingType->getType();
2036
2037 return std::make_pair(x&: SR, y&: QT);
2038 };
2039
2040 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2041 // type compatible with at most one of the types named in its generic
2042 // association list."
2043 if (CompatIndices.size() > 1) {
2044 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2045 SourceRange SR = P.first;
2046 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2047 << SR << P.second << (unsigned)CompatIndices.size();
2048 for (unsigned I : CompatIndices) {
2049 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2050 DiagID: diag::note_compat_assoc)
2051 << Types[I]->getTypeLoc().getSourceRange()
2052 << Types[I]->getType();
2053 }
2054 return ExprError();
2055 }
2056
2057 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2058 // its controlling expression shall have type compatible with exactly one of
2059 // the types named in its generic association list."
2060 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2061 CompatIndices.size() == 0) {
2062 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2063 SourceRange SR = P.first;
2064 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2065 return ExprError();
2066 }
2067
2068 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2069 // type name that is compatible with the type of the controlling expression,
2070 // then the result expression of the generic selection is the expression
2071 // in that generic association. Otherwise, the result expression of the
2072 // generic selection is the expression in the default generic association."
2073 unsigned ResultIndex =
2074 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2075
2076 if (ControllingExpr) {
2077 return GenericSelectionExpr::Create(
2078 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2079 ContainsUnexpandedParameterPack, ResultIndex);
2080 }
2081 return GenericSelectionExpr::Create(
2082 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2083 ContainsUnexpandedParameterPack, ResultIndex);
2084}
2085
2086static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2087 switch (Kind) {
2088 default:
2089 llvm_unreachable("unexpected TokenKind");
2090 case tok::kw___func__:
2091 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2092 case tok::kw___FUNCTION__:
2093 return PredefinedIdentKind::Function;
2094 case tok::kw___FUNCDNAME__:
2095 return PredefinedIdentKind::FuncDName; // [MS]
2096 case tok::kw___FUNCSIG__:
2097 return PredefinedIdentKind::FuncSig; // [MS]
2098 case tok::kw_L__FUNCTION__:
2099 return PredefinedIdentKind::LFunction; // [MS]
2100 case tok::kw_L__FUNCSIG__:
2101 return PredefinedIdentKind::LFuncSig; // [MS]
2102 case tok::kw___PRETTY_FUNCTION__:
2103 return PredefinedIdentKind::PrettyFunction; // [GNU]
2104 }
2105}
2106
2107/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2108/// to determine the value of a PredefinedExpr. This can be either a
2109/// block, lambda, captured statement, function, otherwise a nullptr.
2110static Decl *getPredefinedExprDecl(DeclContext *DC) {
2111 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2112 DC = DC->getParent();
2113 return cast_or_null<Decl>(Val: DC);
2114}
2115
2116/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2117/// location of the token and the offset of the ud-suffix within it.
2118static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2119 unsigned Offset) {
2120 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2121 LangOpts: S.getLangOpts());
2122}
2123
2124/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2125/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2126static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2127 IdentifierInfo *UDSuffix,
2128 SourceLocation UDSuffixLoc,
2129 ArrayRef<Expr*> Args,
2130 SourceLocation LitEndLoc) {
2131 assert(Args.size() <= 2 && "too many arguments for literal operator");
2132
2133 QualType ArgTy[2];
2134 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2135 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2136 if (ArgTy[ArgIdx]->isArrayType())
2137 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2138 }
2139
2140 DeclarationName OpName =
2141 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2142 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2143 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2144
2145 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2146 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2147 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2148 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2149 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2150 return ExprError();
2151
2152 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2153}
2154
2155ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2156 // StringToks needs backing storage as it doesn't hold array elements itself
2157 std::vector<Token> ExpandedToks;
2158 if (getLangOpts().MicrosoftExt)
2159 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2160
2161 StringLiteralParser Literal(StringToks, PP,
2162 StringLiteralEvalMethod::Unevaluated);
2163 if (Literal.hadError)
2164 return ExprError();
2165
2166 SmallVector<SourceLocation, 4> StringTokLocs;
2167 for (const Token &Tok : StringToks)
2168 StringTokLocs.push_back(Elt: Tok.getLocation());
2169
2170 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2171 Kind: StringLiteralKind::Unevaluated,
2172 Pascal: false, Ty: {}, Locs: StringTokLocs);
2173
2174 if (!Literal.getUDSuffix().empty()) {
2175 SourceLocation UDSuffixLoc =
2176 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2177 Offset: Literal.getUDSuffixOffset());
2178 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2179 }
2180
2181 return Lit;
2182}
2183
2184std::vector<Token>
2185Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2186 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2187 // local macros that expand to string literals that may be concatenated.
2188 // These macros are expanded here (in Sema), because StringLiteralParser
2189 // (in Lex) doesn't know the enclosing function (because it hasn't been
2190 // parsed yet).
2191 assert(getLangOpts().MicrosoftExt);
2192
2193 // Note: Although function local macros are defined only inside functions,
2194 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2195 // expansion of macros into empty string literals without additional checks.
2196 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2197 if (!CurrentDecl)
2198 CurrentDecl = Context.getTranslationUnitDecl();
2199
2200 std::vector<Token> ExpandedToks;
2201 ExpandedToks.reserve(n: Toks.size());
2202 for (const Token &Tok : Toks) {
2203 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2204 assert(tok::isStringLiteral(Tok.getKind()));
2205 ExpandedToks.emplace_back(args: Tok);
2206 continue;
2207 }
2208 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2209 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2210 // Stringify predefined expression
2211 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2212 << Tok.getKind();
2213 SmallString<64> Str;
2214 llvm::raw_svector_ostream OS(Str);
2215 Token &Exp = ExpandedToks.emplace_back();
2216 Exp.startToken();
2217 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2218 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2219 OS << 'L';
2220 Exp.setKind(tok::wide_string_literal);
2221 } else {
2222 Exp.setKind(tok::string_literal);
2223 }
2224 OS << '"'
2225 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2226 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2227 << '"';
2228 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2229 }
2230 return ExpandedToks;
2231}
2232
2233ExprResult
2234Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2235 assert(!StringToks.empty() && "Must have at least one string!");
2236
2237 // StringToks needs backing storage as it doesn't hold array elements itself
2238 std::vector<Token> ExpandedToks;
2239 if (getLangOpts().MicrosoftExt)
2240 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2241
2242 StringLiteralParser Literal(StringToks, PP);
2243 if (Literal.hadError)
2244 return ExprError();
2245
2246 SmallVector<SourceLocation, 4> StringTokLocs;
2247 for (const Token &Tok : StringToks)
2248 StringTokLocs.push_back(Elt: Tok.getLocation());
2249
2250 QualType CharTy = Context.CharTy;
2251 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2252 if (Literal.isWide()) {
2253 CharTy = Context.getWideCharType();
2254 Kind = StringLiteralKind::Wide;
2255 } else if (Literal.isUTF8()) {
2256 if (getLangOpts().Char8)
2257 CharTy = Context.Char8Ty;
2258 else if (getLangOpts().C23)
2259 CharTy = Context.UnsignedCharTy;
2260 Kind = StringLiteralKind::UTF8;
2261 } else if (Literal.isUTF16()) {
2262 CharTy = Context.Char16Ty;
2263 Kind = StringLiteralKind::UTF16;
2264 } else if (Literal.isUTF32()) {
2265 CharTy = Context.Char32Ty;
2266 Kind = StringLiteralKind::UTF32;
2267 } else if (Literal.isPascal()) {
2268 CharTy = Context.UnsignedCharTy;
2269 }
2270
2271 // Warn on u8 string literals before C++20 and C23, whose type
2272 // was an array of char before but becomes an array of char8_t.
2273 // In C++20, it cannot be used where a pointer to char is expected.
2274 // In C23, it might have an unexpected value if char was signed.
2275 if (Kind == StringLiteralKind::UTF8 &&
2276 (getLangOpts().CPlusPlus
2277 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2278 : !getLangOpts().C23)) {
2279 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2280 ? diag::warn_cxx20_compat_utf8_string
2281 : diag::warn_c23_compat_utf8_string);
2282
2283 // Create removals for all 'u8' prefixes in the string literal(s). This
2284 // ensures C++20/C23 compatibility (but may change the program behavior when
2285 // built by non-Clang compilers for which the execution character set is
2286 // not always UTF-8).
2287 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2288 SourceLocation RemovalDiagLoc;
2289 for (const Token &Tok : StringToks) {
2290 if (Tok.getKind() == tok::utf8_string_literal) {
2291 if (RemovalDiagLoc.isInvalid())
2292 RemovalDiagLoc = Tok.getLocation();
2293 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2294 B: Tok.getLocation(),
2295 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2296 SM: getSourceManager(), LangOpts: getLangOpts())));
2297 }
2298 }
2299 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2300 }
2301
2302 QualType StrTy =
2303 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2304
2305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2306 StringLiteral *Lit = StringLiteral::Create(
2307 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2308 if (Literal.getUDSuffix().empty())
2309 return Lit;
2310
2311 // We're building a user-defined literal.
2312 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2313 SourceLocation UDSuffixLoc =
2314 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2315 Offset: Literal.getUDSuffixOffset());
2316
2317 // Make sure we're allowed user-defined literals here.
2318 if (!UDLScope)
2319 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2320
2321 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2322 // operator "" X (str, len)
2323 QualType SizeType = Context.getSizeType();
2324
2325 DeclarationName OpName =
2326 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2327 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2328 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2329
2330 QualType ArgTy[] = {
2331 Context.getArrayDecayedType(T: StrTy), SizeType
2332 };
2333
2334 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2335 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2336 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2337 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2338 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2339
2340 case LOLR_Cooked: {
2341 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2342 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2343 l: StringTokLocs[0]);
2344 Expr *Args[] = { Lit, LenArg };
2345
2346 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2347 }
2348
2349 case LOLR_Template: {
2350 TemplateArgumentListInfo ExplicitArgs;
2351 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2352 TemplateArgumentLocInfo ArgInfo(Lit);
2353 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2354 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2355 ExplicitTemplateArgs: &ExplicitArgs);
2356 }
2357
2358 case LOLR_StringTemplatePack: {
2359 TemplateArgumentListInfo ExplicitArgs;
2360
2361 unsigned CharBits = Context.getIntWidth(T: CharTy);
2362 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2363 llvm::APSInt Value(CharBits, CharIsUnsigned);
2364
2365 TemplateArgument TypeArg(CharTy);
2366 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2367 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2368
2369 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2370 Value = Lit->getCodeUnit(i: I);
2371 TemplateArgument Arg(Context, Value, CharTy);
2372 TemplateArgumentLocInfo ArgInfo;
2373 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2374 }
2375 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2376 ExplicitTemplateArgs: &ExplicitArgs);
2377 }
2378 case LOLR_Raw:
2379 case LOLR_ErrorNoDiagnostic:
2380 llvm_unreachable("unexpected literal operator lookup result");
2381 case LOLR_Error:
2382 return ExprError();
2383 }
2384 llvm_unreachable("unexpected literal operator lookup result");
2385}
2386
2387DeclRefExpr *
2388Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2389 SourceLocation Loc,
2390 const CXXScopeSpec *SS) {
2391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2393}
2394
2395DeclRefExpr *
2396Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2397 const DeclarationNameInfo &NameInfo,
2398 const CXXScopeSpec *SS, NamedDecl *FoundD,
2399 SourceLocation TemplateKWLoc,
2400 const TemplateArgumentListInfo *TemplateArgs) {
2401 NestedNameSpecifierLoc NNS =
2402 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2403 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2404 TemplateArgs);
2405}
2406
2407// CUDA/HIP: Check whether a captured reference variable is referencing a
2408// host variable in a device or host device lambda.
2409static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2410 VarDecl *VD) {
2411 if (!S.getLangOpts().CUDA || !VD->hasInit())
2412 return false;
2413 assert(VD->getType()->isReferenceType());
2414
2415 // Check whether the reference variable is referencing a host variable.
2416 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2417 if (!DRE)
2418 return false;
2419 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2420 if (!Referee || !Referee->hasGlobalStorage() ||
2421 Referee->hasAttr<CUDADeviceAttr>())
2422 return false;
2423
2424 // Check whether the current function is a device or host device lambda.
2425 // Check whether the reference variable is a capture by getDeclContext()
2426 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2427 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2428 if (MD && MD->getParent()->isLambda() &&
2429 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2430 VD->getDeclContext() != MD)
2431 return true;
2432
2433 return false;
2434}
2435
2436NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2437 // A declaration named in an unevaluated operand never constitutes an odr-use.
2438 if (isUnevaluatedContext())
2439 return NOUR_Unevaluated;
2440
2441 // C++2a [basic.def.odr]p4:
2442 // A variable x whose name appears as a potentially-evaluated expression e
2443 // is odr-used by e unless [...] x is a reference that is usable in
2444 // constant expressions.
2445 // CUDA/HIP:
2446 // If a reference variable referencing a host variable is captured in a
2447 // device or host device lambda, the value of the referee must be copied
2448 // to the capture and the reference variable must be treated as odr-use
2449 // since the value of the referee is not known at compile time and must
2450 // be loaded from the captured.
2451 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2452 if (VD->getType()->isReferenceType() &&
2453 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2454 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2455 VD->isUsableInConstantExpressions(C: Context))
2456 return NOUR_Constant;
2457 }
2458
2459 // All remaining non-variable cases constitute an odr-use. For variables, we
2460 // need to wait and see how the expression is used.
2461 return NOUR_None;
2462}
2463
2464DeclRefExpr *
2465Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2466 const DeclarationNameInfo &NameInfo,
2467 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2468 SourceLocation TemplateKWLoc,
2469 const TemplateArgumentListInfo *TemplateArgs) {
2470 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2471 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2472
2473 DeclRefExpr *E = DeclRefExpr::Create(
2474 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2475 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2476 MarkDeclRefReferenced(E);
2477
2478 // C++ [except.spec]p17:
2479 // An exception-specification is considered to be needed when:
2480 // - in an expression, the function is the unique lookup result or
2481 // the selected member of a set of overloaded functions.
2482 //
2483 // We delay doing this until after we've built the function reference and
2484 // marked it as used so that:
2485 // a) if the function is defaulted, we get errors from defining it before /
2486 // instead of errors from computing its exception specification, and
2487 // b) if the function is a defaulted comparison, we can use the body we
2488 // build when defining it as input to the exception specification
2489 // computation rather than computing a new body.
2490 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2491 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2492 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2493 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2494 }
2495 }
2496
2497 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2498 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2499 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2500 getCurFunction()->recordUseOfWeak(E);
2501
2502 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2503 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2504 FD = IFD->getAnonField();
2505 if (FD) {
2506 UnusedPrivateFields.remove(X: FD);
2507 // Just in case we're building an illegal pointer-to-member.
2508 if (FD->isBitField())
2509 E->setObjectKind(OK_BitField);
2510 }
2511
2512 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2513 // designates a bit-field.
2514 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2515 if (const auto *BE = BD->getBinding())
2516 E->setObjectKind(BE->getObjectKind());
2517
2518 return E;
2519}
2520
2521void
2522Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2523 TemplateArgumentListInfo &Buffer,
2524 DeclarationNameInfo &NameInfo,
2525 const TemplateArgumentListInfo *&TemplateArgs) {
2526 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2527 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2528 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2529
2530 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2531 Id.TemplateId->NumArgs);
2532 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2533
2534 TemplateName TName = Id.TemplateId->Template.get();
2535 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2536 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2537 TemplateArgs = &Buffer;
2538 } else {
2539 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2540 TemplateArgs = nullptr;
2541 }
2542}
2543
2544bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2545 // During a default argument instantiation the CurContext points
2546 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2547 // function parameter list, hence add an explicit check.
2548 bool isDefaultArgument =
2549 !CodeSynthesisContexts.empty() &&
2550 CodeSynthesisContexts.back().Kind ==
2551 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2552 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2553 bool isInstance = CurMethod && CurMethod->isInstance() &&
2554 R.getNamingClass() == CurMethod->getParent() &&
2555 !isDefaultArgument;
2556
2557 // There are two ways we can find a class-scope declaration during template
2558 // instantiation that we did not find in the template definition: if it is a
2559 // member of a dependent base class, or if it is declared after the point of
2560 // use in the same class. Distinguish these by comparing the class in which
2561 // the member was found to the naming class of the lookup.
2562 unsigned DiagID = diag::err_found_in_dependent_base;
2563 unsigned NoteID = diag::note_member_declared_at;
2564 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2565 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2566 : diag::err_found_later_in_class;
2567 } else if (getLangOpts().MSVCCompat) {
2568 DiagID = diag::ext_found_in_dependent_base;
2569 NoteID = diag::note_dependent_member_use;
2570 }
2571
2572 if (isInstance) {
2573 // Give a code modification hint to insert 'this->'.
2574 Diag(Loc: R.getNameLoc(), DiagID)
2575 << R.getLookupName()
2576 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2577 CheckCXXThisCapture(Loc: R.getNameLoc());
2578 } else {
2579 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2580 // they're not shadowed).
2581 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2582 }
2583
2584 for (const NamedDecl *D : R)
2585 Diag(Loc: D->getLocation(), DiagID: NoteID);
2586
2587 // Return true if we are inside a default argument instantiation
2588 // and the found name refers to an instance member function, otherwise
2589 // the caller will try to create an implicit member call and this is wrong
2590 // for default arguments.
2591 //
2592 // FIXME: Is this special case necessary? We could allow the caller to
2593 // diagnose this.
2594 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2595 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2596 return true;
2597 }
2598
2599 // Tell the callee to try to recover.
2600 return false;
2601}
2602
2603bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2604 CorrectionCandidateCallback &CCC,
2605 TemplateArgumentListInfo *ExplicitTemplateArgs,
2606 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2607 DeclarationName Name = R.getLookupName();
2608 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2609
2610 unsigned diagnostic = diag::err_undeclared_var_use;
2611 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2612 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2613 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2614 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2615 diagnostic = diag::err_undeclared_use;
2616 diagnostic_suggest = diag::err_undeclared_use_suggest;
2617 }
2618
2619 // If the original lookup was an unqualified lookup, fake an
2620 // unqualified lookup. This is useful when (for example) the
2621 // original lookup would not have found something because it was a
2622 // dependent name.
2623 DeclContext *DC =
2624 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2625 while (DC) {
2626 if (isa<CXXRecordDecl>(Val: DC)) {
2627 if (ExplicitTemplateArgs) {
2628 if (LookupTemplateName(
2629 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2630 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2631 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2632 return true;
2633 } else {
2634 LookupQualifiedName(R, LookupCtx: DC);
2635 }
2636
2637 if (!R.empty()) {
2638 // Don't give errors about ambiguities in this lookup.
2639 R.suppressDiagnostics();
2640
2641 // If there's a best viable function among the results, only mention
2642 // that one in the notes.
2643 OverloadCandidateSet Candidates(R.getNameLoc(),
2644 OverloadCandidateSet::CSK_Normal);
2645 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2646 OverloadCandidateSet::iterator Best;
2647 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2648 OR_Success) {
2649 R.clear();
2650 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2651 R.resolveKind();
2652 }
2653
2654 return DiagnoseDependentMemberLookup(R);
2655 }
2656
2657 R.clear();
2658 }
2659
2660 DC = DC->getLookupParent();
2661 }
2662
2663 // We didn't find anything, so try to correct for a typo.
2664 TypoCorrection Corrected;
2665 if (S && (Corrected =
2666 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2667 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2668 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2669 bool DroppedSpecifier =
2670 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2671 R.setLookupName(Corrected.getCorrection());
2672
2673 bool AcceptableWithRecovery = false;
2674 bool AcceptableWithoutRecovery = false;
2675 NamedDecl *ND = Corrected.getFoundDecl();
2676 if (ND) {
2677 if (Corrected.isOverloaded()) {
2678 OverloadCandidateSet OCS(R.getNameLoc(),
2679 OverloadCandidateSet::CSK_Normal);
2680 OverloadCandidateSet::iterator Best;
2681 for (NamedDecl *CD : Corrected) {
2682 if (FunctionTemplateDecl *FTD =
2683 dyn_cast<FunctionTemplateDecl>(Val: CD))
2684 AddTemplateOverloadCandidate(
2685 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2686 Args, CandidateSet&: OCS);
2687 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2688 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2689 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2690 Args, CandidateSet&: OCS);
2691 }
2692 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2693 case OR_Success:
2694 ND = Best->FoundDecl;
2695 Corrected.setCorrectionDecl(ND);
2696 break;
2697 default:
2698 // FIXME: Arbitrarily pick the first declaration for the note.
2699 Corrected.setCorrectionDecl(ND);
2700 break;
2701 }
2702 }
2703 R.addDecl(D: ND);
2704 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2705 CXXRecordDecl *Record =
2706 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2707 if (!Record)
2708 Record = cast<CXXRecordDecl>(
2709 Val: ND->getDeclContext()->getRedeclContext());
2710 R.setNamingClass(Record);
2711 }
2712
2713 auto *UnderlyingND = ND->getUnderlyingDecl();
2714 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2715 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2716 // FIXME: If we ended up with a typo for a type name or
2717 // Objective-C class name, we're in trouble because the parser
2718 // is in the wrong place to recover. Suggest the typo
2719 // correction, but don't make it a fix-it since we're not going
2720 // to recover well anyway.
2721 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2722 getAsTypeTemplateDecl(D: UnderlyingND) ||
2723 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2724 } else {
2725 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2726 // because we aren't able to recover.
2727 AcceptableWithoutRecovery = true;
2728 }
2729
2730 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2731 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2732 ? diag::note_implicit_param_decl
2733 : diag::note_previous_decl;
2734 if (SS.isEmpty())
2735 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2736 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2737 else
2738 diagnoseTypo(Correction: Corrected,
2739 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2740 << Name << computeDeclContext(SS, EnteringContext: false)
2741 << DroppedSpecifier << NameRange,
2742 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2743
2744 if (Corrected.WillReplaceSpecifier()) {
2745 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2746 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2747 SS.MakeTrivial(Context, Qualifier: NNS,
2748 R: NNS ? NameRange.getBegin() : SourceRange());
2749 }
2750
2751 // Tell the callee whether to try to recover.
2752 return !AcceptableWithRecovery;
2753 }
2754 }
2755 R.clear();
2756
2757 // Emit a special diagnostic for failed member lookups.
2758 // FIXME: computing the declaration context might fail here (?)
2759 if (!SS.isEmpty()) {
2760 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2761 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2762 return true;
2763 }
2764
2765 // Give up, we can't recover.
2766 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2767 return true;
2768}
2769
2770/// In Microsoft mode, if we are inside a template class whose parent class has
2771/// dependent base classes, and we can't resolve an unqualified identifier, then
2772/// assume the identifier is a member of a dependent base class. We can only
2773/// recover successfully in static methods, instance methods, and other contexts
2774/// where 'this' is available. This doesn't precisely match MSVC's
2775/// instantiation model, but it's close enough.
2776static Expr *
2777recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2778 DeclarationNameInfo &NameInfo,
2779 SourceLocation TemplateKWLoc,
2780 const TemplateArgumentListInfo *TemplateArgs) {
2781 // Only try to recover from lookup into dependent bases in static methods or
2782 // contexts where 'this' is available.
2783 QualType ThisType = S.getCurrentThisType();
2784 const CXXRecordDecl *RD = nullptr;
2785 if (!ThisType.isNull())
2786 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2787 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2788 RD = MD->getParent();
2789 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2790 return nullptr;
2791
2792 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2793 // is available, suggest inserting 'this->' as a fixit.
2794 SourceLocation Loc = NameInfo.getLoc();
2795 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2796 DB << NameInfo.getName() << RD;
2797
2798 if (!ThisType.isNull()) {
2799 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2800 return CXXDependentScopeMemberExpr::Create(
2801 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2802 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2803 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2804 }
2805
2806 // Synthesize a fake NNS that points to the derived class. This will
2807 // perform name lookup during template instantiation.
2808 CXXScopeSpec SS;
2809 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2810 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2811 return DependentScopeDeclRefExpr::Create(
2812 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2813 TemplateArgs);
2814}
2815
2816ExprResult
2817Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2818 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2819 bool HasTrailingLParen, bool IsAddressOfOperand,
2820 CorrectionCandidateCallback *CCC,
2821 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2822 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2823 "cannot be direct & operand and have a trailing lparen");
2824 if (SS.isInvalid())
2825 return ExprError();
2826
2827 TemplateArgumentListInfo TemplateArgsBuffer;
2828
2829 // Decompose the UnqualifiedId into the following data.
2830 DeclarationNameInfo NameInfo;
2831 const TemplateArgumentListInfo *TemplateArgs;
2832 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2833
2834 DeclarationName Name = NameInfo.getName();
2835 IdentifierInfo *II = Name.getAsIdentifierInfo();
2836 SourceLocation NameLoc = NameInfo.getLoc();
2837
2838 if (II && II->isEditorPlaceholder()) {
2839 // FIXME: When typed placeholders are supported we can create a typed
2840 // placeholder expression node.
2841 return ExprError();
2842 }
2843
2844 // This specially handles arguments of attributes appertains to a type of C
2845 // struct field such that the name lookup within a struct finds the member
2846 // name, which is not the case for other contexts in C.
2847 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2848 // See if this is reference to a field of struct.
2849 LookupResult R(*this, NameInfo, LookupMemberName);
2850 // LookupName handles a name lookup from within anonymous struct.
2851 if (LookupName(R, S)) {
2852 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2853 QualType type = VD->getType().getNonReferenceType();
2854 // This will eventually be translated into MemberExpr upon
2855 // the use of instantiated struct fields.
2856 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2857 }
2858 }
2859 }
2860
2861 // Perform the required lookup.
2862 LookupResult R(*this, NameInfo,
2863 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2864 ? LookupObjCImplicitSelfParam
2865 : LookupOrdinaryName);
2866 if (TemplateKWLoc.isValid() || TemplateArgs) {
2867 // Lookup the template name again to correctly establish the context in
2868 // which it was found. This is really unfortunate as we already did the
2869 // lookup to determine that it was a template name in the first place. If
2870 // this becomes a performance hit, we can work harder to preserve those
2871 // results until we get here but it's likely not worth it.
2872 AssumedTemplateKind AssumedTemplate;
2873 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2874 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2875 ATK: &AssumedTemplate))
2876 return ExprError();
2877
2878 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2879 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2880 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2881 } else {
2882 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2883 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2884 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2885
2886 // If the result might be in a dependent base class, this is a dependent
2887 // id-expression.
2888 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2890 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2891
2892 // If this reference is in an Objective-C method, then we need to do
2893 // some special Objective-C lookup, too.
2894 if (IvarLookupFollowUp) {
2895 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2896 if (E.isInvalid())
2897 return ExprError();
2898
2899 if (Expr *Ex = E.getAs<Expr>())
2900 return Ex;
2901 }
2902 }
2903
2904 if (R.isAmbiguous())
2905 return ExprError();
2906
2907 // This could be an implicitly declared function reference if the language
2908 // mode allows it as a feature.
2909 if (R.empty() && HasTrailingLParen && II &&
2910 getLangOpts().implicitFunctionsAllowed()) {
2911 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2912 if (D) R.addDecl(D);
2913 }
2914
2915 // Determine whether this name might be a candidate for
2916 // argument-dependent lookup.
2917 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2918
2919 if (R.empty() && !ADL) {
2920 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2921 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2922 TemplateKWLoc, TemplateArgs))
2923 return E;
2924 }
2925
2926 // Don't diagnose an empty lookup for inline assembly.
2927 if (IsInlineAsmIdentifier)
2928 return ExprError();
2929
2930 // If this name wasn't predeclared and if this is not a function
2931 // call, diagnose the problem.
2932 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2933 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2934 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2935 "Typo correction callback misconfigured");
2936 if (CCC) {
2937 // Make sure the callback knows what the typo being diagnosed is.
2938 CCC->setTypoName(II);
2939 if (SS.isValid())
2940 CCC->setTypoNNS(SS.getScopeRep());
2941 }
2942 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2943 // a template name, but we happen to have always already looked up the name
2944 // before we get here if it must be a template name.
2945 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2946 Args: {}, LookupCtx: nullptr))
2947 return ExprError();
2948
2949 assert(!R.empty() &&
2950 "DiagnoseEmptyLookup returned false but added no results");
2951
2952 // If we found an Objective-C instance variable, let
2953 // LookupInObjCMethod build the appropriate expression to
2954 // reference the ivar.
2955 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2956 R.clear();
2957 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2958 // In a hopelessly buggy code, Objective-C instance variable
2959 // lookup fails and no expression will be built to reference it.
2960 if (!E.isInvalid() && !E.get())
2961 return ExprError();
2962 return E;
2963 }
2964 }
2965
2966 // This is guaranteed from this point on.
2967 assert(!R.empty() || ADL);
2968
2969 // Check whether this might be a C++ implicit instance member access.
2970 // C++ [class.mfct.non-static]p3:
2971 // When an id-expression that is not part of a class member access
2972 // syntax and not used to form a pointer to member is used in the
2973 // body of a non-static member function of class X, if name lookup
2974 // resolves the name in the id-expression to a non-static non-type
2975 // member of some class C, the id-expression is transformed into a
2976 // class member access expression using (*this) as the
2977 // postfix-expression to the left of the . operator.
2978 //
2979 // But we don't actually need to do this for '&' operands if R
2980 // resolved to a function or overloaded function set, because the
2981 // expression is ill-formed if it actually works out to be a
2982 // non-static member function:
2983 //
2984 // C++ [expr.ref]p4:
2985 // Otherwise, if E1.E2 refers to a non-static member function. . .
2986 // [t]he expression can be used only as the left-hand operand of a
2987 // member function call.
2988 //
2989 // There are other safeguards against such uses, but it's important
2990 // to get this right here so that we don't end up making a
2991 // spuriously dependent expression if we're inside a dependent
2992 // instance method.
2993 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2994 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2995 S);
2996
2997 if (TemplateArgs || TemplateKWLoc.isValid()) {
2998
2999 // In C++1y, if this is a variable template id, then check it
3000 // in BuildTemplateIdExpr().
3001 // The single lookup result must be a variable template declaration.
3002 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3003 (Id.TemplateId->Kind == TNK_Var_template ||
3004 Id.TemplateId->Kind == TNK_Concept_template)) {
3005 assert(R.getAsSingle<TemplateDecl>() &&
3006 "There should only be one declaration found.");
3007 }
3008
3009 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3010 }
3011
3012 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3013}
3014
3015ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3016 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3017 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3018 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3019 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3020
3021 if (R.isAmbiguous())
3022 return ExprError();
3023
3024 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3025 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3026 NameInfo, /*TemplateArgs=*/nullptr);
3027
3028 if (R.empty()) {
3029 // Don't diagnose problems with invalid record decl, the secondary no_member
3030 // diagnostic during template instantiation is likely bogus, e.g. if a class
3031 // is invalid because it's derived from an invalid base class, then missing
3032 // members were likely supposed to be inherited.
3033 DeclContext *DC = computeDeclContext(SS);
3034 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3035 if (CD->isInvalidDecl() || CD->isBeingDefined())
3036 return ExprError();
3037 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3038 << NameInfo.getName() << DC << SS.getRange();
3039 return ExprError();
3040 }
3041
3042 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3043 QualType ET;
3044 TypeLocBuilder TLB;
3045 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3046 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3047 Qualifier: SS.getScopeRep(), TD: TagD,
3048 /*OwnsTag=*/false);
3049 auto TL = TLB.push<TagTypeLoc>(T: ET);
3050 TL.setElaboratedKeywordLoc(SourceLocation());
3051 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3052 TL.setNameLoc(NameInfo.getLoc());
3053 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3054 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3055 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3056 TLB.push<TypedefTypeLoc>(T: ET).set(
3057 /*ElaboratedKeywordLoc=*/SourceLocation(),
3058 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3059 } else {
3060 // FIXME: What else can appear here?
3061 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3062 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3063 assert(SS.isEmpty());
3064 }
3065
3066 // Diagnose a missing typename if this resolved unambiguously to a type in
3067 // a dependent context. If we can recover with a type, downgrade this to
3068 // a warning in Microsoft compatibility mode.
3069 unsigned DiagID = diag::err_typename_missing;
3070 if (RecoveryTSI && getLangOpts().MSVCCompat)
3071 DiagID = diag::ext_typename_missing;
3072 SourceLocation Loc = SS.getBeginLoc();
3073 auto D = Diag(Loc, DiagID);
3074 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3075
3076 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3077 // context.
3078 if (!RecoveryTSI)
3079 return ExprError();
3080
3081 // Only issue the fixit if we're prepared to recover.
3082 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3083
3084 // Recover by pretending this was an elaborated type.
3085 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3086
3087 return ExprEmpty();
3088 }
3089
3090 // If necessary, build an implicit class member access.
3091 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3092 return BuildPossibleImplicitMemberExpr(SS,
3093 /*TemplateKWLoc=*/SourceLocation(),
3094 R, /*TemplateArgs=*/nullptr,
3095 /*S=*/nullptr);
3096
3097 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3098}
3099
3100ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3101 NestedNameSpecifier Qualifier,
3102 NamedDecl *FoundDecl,
3103 NamedDecl *Member) {
3104 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3105 if (!RD)
3106 return From;
3107
3108 QualType DestRecordType;
3109 QualType DestType;
3110 QualType FromRecordType;
3111 QualType FromType = From->getType();
3112 bool PointerConversions = false;
3113 if (isa<FieldDecl>(Val: Member)) {
3114 DestRecordType = Context.getCanonicalTagType(TD: RD);
3115 auto FromPtrType = FromType->getAs<PointerType>();
3116 DestRecordType = Context.getAddrSpaceQualType(
3117 T: DestRecordType, AddressSpace: FromPtrType
3118 ? FromType->getPointeeType().getAddressSpace()
3119 : FromType.getAddressSpace());
3120
3121 if (FromPtrType) {
3122 DestType = Context.getPointerType(T: DestRecordType);
3123 FromRecordType = FromPtrType->getPointeeType();
3124 PointerConversions = true;
3125 } else {
3126 DestType = DestRecordType;
3127 FromRecordType = FromType;
3128 }
3129 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3130 if (!Method->isImplicitObjectMemberFunction())
3131 return From;
3132
3133 DestType = Method->getThisType().getNonReferenceType();
3134 DestRecordType = Method->getFunctionObjectParameterType();
3135
3136 if (FromType->getAs<PointerType>()) {
3137 FromRecordType = FromType->getPointeeType();
3138 PointerConversions = true;
3139 } else {
3140 FromRecordType = FromType;
3141 DestType = DestRecordType;
3142 }
3143
3144 LangAS FromAS = FromRecordType.getAddressSpace();
3145 LangAS DestAS = DestRecordType.getAddressSpace();
3146 if (FromAS != DestAS) {
3147 QualType FromRecordTypeWithoutAS =
3148 Context.removeAddrSpaceQualType(T: FromRecordType);
3149 QualType FromTypeWithDestAS =
3150 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3151 if (PointerConversions)
3152 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3153 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3154 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3155 .get();
3156 }
3157 } else {
3158 // No conversion necessary.
3159 return From;
3160 }
3161
3162 if (DestType->isDependentType() || FromType->isDependentType())
3163 return From;
3164
3165 // If the unqualified types are the same, no conversion is necessary.
3166 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3167 return From;
3168
3169 SourceRange FromRange = From->getSourceRange();
3170 SourceLocation FromLoc = FromRange.getBegin();
3171
3172 ExprValueKind VK = From->getValueKind();
3173
3174 // C++ [class.member.lookup]p8:
3175 // [...] Ambiguities can often be resolved by qualifying a name with its
3176 // class name.
3177 //
3178 // If the member was a qualified name and the qualified referred to a
3179 // specific base subobject type, we'll cast to that intermediate type
3180 // first and then to the object in which the member is declared. That allows
3181 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3182 //
3183 // class Base { public: int x; };
3184 // class Derived1 : public Base { };
3185 // class Derived2 : public Base { };
3186 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3187 //
3188 // void VeryDerived::f() {
3189 // x = 17; // error: ambiguous base subobjects
3190 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3191 // }
3192 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3193 QualType QType = QualType(Qualifier.getAsType(), 0);
3194 assert(QType->isRecordType() && "lookup done with non-record type");
3195
3196 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3197
3198 // In C++98, the qualifier type doesn't actually have to be a base
3199 // type of the object type, in which case we just ignore it.
3200 // Otherwise build the appropriate casts.
3201 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3202 CXXCastPath BasePath;
3203 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3204 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3205 return ExprError();
3206
3207 if (PointerConversions)
3208 QType = Context.getPointerType(T: QType);
3209 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3210 VK, BasePath: &BasePath).get();
3211
3212 FromType = QType;
3213 FromRecordType = QRecordType;
3214
3215 // If the qualifier type was the same as the destination type,
3216 // we're done.
3217 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3218 return From;
3219 }
3220 }
3221
3222 CXXCastPath BasePath;
3223 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3224 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3225 /*IgnoreAccess=*/true))
3226 return ExprError();
3227
3228 // Propagate qualifiers to base subobjects as per:
3229 // C++ [basic.type.qualifier]p1.2:
3230 // A volatile object is [...] a subobject of a volatile object.
3231 Qualifiers FromTypeQuals = FromType.getQualifiers();
3232 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3233 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3234
3235 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3236 BasePath: &BasePath);
3237}
3238
3239bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3240 const LookupResult &R,
3241 bool HasTrailingLParen) {
3242 // Only when used directly as the postfix-expression of a call.
3243 if (!HasTrailingLParen)
3244 return false;
3245
3246 // Never if a scope specifier was provided.
3247 if (SS.isNotEmpty())
3248 return false;
3249
3250 // Only in C++ or ObjC++.
3251 if (!getLangOpts().CPlusPlus)
3252 return false;
3253
3254 // Turn off ADL when we find certain kinds of declarations during
3255 // normal lookup:
3256 for (const NamedDecl *D : R) {
3257 // C++0x [basic.lookup.argdep]p3:
3258 // -- a declaration of a class member
3259 // Since using decls preserve this property, we check this on the
3260 // original decl.
3261 if (D->isCXXClassMember())
3262 return false;
3263
3264 // C++0x [basic.lookup.argdep]p3:
3265 // -- a block-scope function declaration that is not a
3266 // using-declaration
3267 // NOTE: we also trigger this for function templates (in fact, we
3268 // don't check the decl type at all, since all other decl types
3269 // turn off ADL anyway).
3270 if (isa<UsingShadowDecl>(Val: D))
3271 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3272 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3273 return false;
3274
3275 // C++0x [basic.lookup.argdep]p3:
3276 // -- a declaration that is neither a function or a function
3277 // template
3278 // And also for builtin functions.
3279 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3280 // But also builtin functions.
3281 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3282 return false;
3283 } else if (!isa<FunctionTemplateDecl>(Val: D))
3284 return false;
3285 }
3286
3287 return true;
3288}
3289
3290
3291/// Diagnoses obvious problems with the use of the given declaration
3292/// as an expression. This is only actually called for lookups that
3293/// were not overloaded, and it doesn't promise that the declaration
3294/// will in fact be used.
3295static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3296 bool AcceptInvalid) {
3297 if (D->isInvalidDecl() && !AcceptInvalid)
3298 return true;
3299
3300 if (isa<TypedefNameDecl>(Val: D)) {
3301 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3302 return true;
3303 }
3304
3305 if (isa<ObjCInterfaceDecl>(Val: D)) {
3306 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3307 return true;
3308 }
3309
3310 if (isa<NamespaceDecl>(Val: D)) {
3311 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3312 return true;
3313 }
3314
3315 return false;
3316}
3317
3318// Certain multiversion types should be treated as overloaded even when there is
3319// only one result.
3320static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3321 assert(R.isSingleResult() && "Expected only a single result");
3322 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3323 return FD &&
3324 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3325}
3326
3327ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3328 LookupResult &R, bool NeedsADL,
3329 bool AcceptInvalidDecl) {
3330 // If this is a single, fully-resolved result and we don't need ADL,
3331 // just build an ordinary singleton decl ref.
3332 if (!NeedsADL && R.isSingleResult() &&
3333 !R.getAsSingle<FunctionTemplateDecl>() &&
3334 !ShouldLookupResultBeMultiVersionOverload(R))
3335 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3336 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3337 AcceptInvalidDecl);
3338
3339 // We only need to check the declaration if there's exactly one
3340 // result, because in the overloaded case the results can only be
3341 // functions and function templates.
3342 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3343 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3344 AcceptInvalid: AcceptInvalidDecl))
3345 return ExprError();
3346
3347 // Otherwise, just build an unresolved lookup expression. Suppress
3348 // any lookup-related diagnostics; we'll hash these out later, when
3349 // we've picked a target.
3350 R.suppressDiagnostics();
3351
3352 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3353 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3354 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3356
3357 return ULE;
3358}
3359
3360ExprResult Sema::BuildDeclarationNameExpr(
3361 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3362 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3363 bool AcceptInvalidDecl) {
3364 assert(D && "Cannot refer to a NULL declaration");
3365 assert(!isa<FunctionTemplateDecl>(D) &&
3366 "Cannot refer unambiguously to a function template");
3367
3368 SourceLocation Loc = NameInfo.getLoc();
3369 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3370 // Recovery from invalid cases (e.g. D is an invalid Decl).
3371 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3372 // diagnostics, as invalid decls use int as a fallback type.
3373 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3374 }
3375
3376 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3377 // Specifically diagnose references to class templates that are missing
3378 // a template argument list.
3379 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3380 return ExprError();
3381 }
3382
3383 // Make sure that we're referring to a value.
3384 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3385 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3386 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3387 return ExprError();
3388 }
3389
3390 // Check whether this declaration can be used. Note that we suppress
3391 // this check when we're going to perform argument-dependent lookup
3392 // on this function name, because this might not be the function
3393 // that overload resolution actually selects.
3394 if (DiagnoseUseOfDecl(D, Locs: Loc))
3395 return ExprError();
3396
3397 auto *VD = cast<ValueDecl>(Val: D);
3398
3399 // Only create DeclRefExpr's for valid Decl's.
3400 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3401 return ExprError();
3402
3403 // Handle members of anonymous structs and unions. If we got here,
3404 // and the reference is to a class member indirect field, then this
3405 // must be the subject of a pointer-to-member expression.
3406 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3407 IndirectField && !IndirectField->isCXXClassMember())
3408 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3409 indirectField: IndirectField);
3410
3411 QualType type = VD->getType();
3412 if (type.isNull())
3413 return ExprError();
3414 ExprValueKind valueKind = VK_PRValue;
3415
3416 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3417 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3418 // is expanded by some outer '...' in the context of the use.
3419 type = type.getNonPackExpansionType();
3420
3421 switch (D->getKind()) {
3422 // Ignore all the non-ValueDecl kinds.
3423#define ABSTRACT_DECL(kind)
3424#define VALUE(type, base)
3425#define DECL(type, base) case Decl::type:
3426#include "clang/AST/DeclNodes.inc"
3427 llvm_unreachable("invalid value decl kind");
3428
3429 // These shouldn't make it here.
3430 case Decl::ObjCAtDefsField:
3431 llvm_unreachable("forming non-member reference to ivar?");
3432
3433 // Enum constants are always r-values and never references.
3434 // Unresolved using declarations are dependent.
3435 case Decl::EnumConstant:
3436 case Decl::UnresolvedUsingValue:
3437 case Decl::OMPDeclareReduction:
3438 case Decl::OMPDeclareMapper:
3439 valueKind = VK_PRValue;
3440 break;
3441
3442 // Fields and indirect fields that got here must be for
3443 // pointer-to-member expressions; we just call them l-values for
3444 // internal consistency, because this subexpression doesn't really
3445 // exist in the high-level semantics.
3446 case Decl::Field:
3447 case Decl::IndirectField:
3448 case Decl::ObjCIvar:
3449 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3450 "building reference to field in C?");
3451
3452 // These can't have reference type in well-formed programs, but
3453 // for internal consistency we do this anyway.
3454 type = type.getNonReferenceType();
3455 valueKind = VK_LValue;
3456 break;
3457
3458 // Non-type template parameters are either l-values or r-values
3459 // depending on the type.
3460 case Decl::NonTypeTemplateParm: {
3461 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3462 type = reftype->getPointeeType();
3463 valueKind = VK_LValue; // even if the parameter is an r-value reference
3464 break;
3465 }
3466
3467 // [expr.prim.id.unqual]p2:
3468 // If the entity is a template parameter object for a template
3469 // parameter of type T, the type of the expression is const T.
3470 // [...] The expression is an lvalue if the entity is a [...] template
3471 // parameter object.
3472 if (type->isRecordType()) {
3473 type = type.getUnqualifiedType().withConst();
3474 valueKind = VK_LValue;
3475 break;
3476 }
3477
3478 // For non-references, we need to strip qualifiers just in case
3479 // the template parameter was declared as 'const int' or whatever.
3480 valueKind = VK_PRValue;
3481 type = type.getUnqualifiedType();
3482 break;
3483 }
3484
3485 case Decl::Var:
3486 case Decl::VarTemplateSpecialization:
3487 case Decl::VarTemplatePartialSpecialization:
3488 case Decl::Decomposition:
3489 case Decl::Binding:
3490 case Decl::OMPCapturedExpr:
3491 // In C, "extern void blah;" is valid and is an r-value.
3492 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3493 type->isVoidType()) {
3494 valueKind = VK_PRValue;
3495 break;
3496 }
3497 [[fallthrough]];
3498
3499 case Decl::ImplicitParam:
3500 case Decl::ParmVar: {
3501 // These are always l-values.
3502 valueKind = VK_LValue;
3503 type = type.getNonReferenceType();
3504
3505 // FIXME: Does the addition of const really only apply in
3506 // potentially-evaluated contexts? Since the variable isn't actually
3507 // captured in an unevaluated context, it seems that the answer is no.
3508 if (!isUnevaluatedContext()) {
3509 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3510 if (!CapturedType.isNull())
3511 type = CapturedType;
3512 }
3513 break;
3514 }
3515
3516 case Decl::Function: {
3517 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3518 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3519 type = Context.BuiltinFnTy;
3520 valueKind = VK_PRValue;
3521 break;
3522 }
3523 }
3524
3525 const FunctionType *fty = type->castAs<FunctionType>();
3526
3527 // If we're referring to a function with an __unknown_anytype
3528 // result type, make the entire expression __unknown_anytype.
3529 if (fty->getReturnType() == Context.UnknownAnyTy) {
3530 type = Context.UnknownAnyTy;
3531 valueKind = VK_PRValue;
3532 break;
3533 }
3534
3535 // Functions are l-values in C++.
3536 if (getLangOpts().CPlusPlus) {
3537 valueKind = VK_LValue;
3538 break;
3539 }
3540
3541 // C99 DR 316 says that, if a function type comes from a
3542 // function definition (without a prototype), that type is only
3543 // used for checking compatibility. Therefore, when referencing
3544 // the function, we pretend that we don't have the full function
3545 // type.
3546 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3547 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3548 Info: fty->getExtInfo());
3549
3550 // Functions are r-values in C.
3551 valueKind = VK_PRValue;
3552 break;
3553 }
3554
3555 case Decl::CXXDeductionGuide:
3556 llvm_unreachable("building reference to deduction guide");
3557
3558 case Decl::MSProperty:
3559 case Decl::MSGuid:
3560 case Decl::TemplateParamObject:
3561 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3562 // capture in OpenMP, or duplicated between host and device?
3563 valueKind = VK_LValue;
3564 break;
3565
3566 case Decl::UnnamedGlobalConstant:
3567 valueKind = VK_LValue;
3568 break;
3569
3570 case Decl::CXXMethod:
3571 // If we're referring to a method with an __unknown_anytype
3572 // result type, make the entire expression __unknown_anytype.
3573 // This should only be possible with a type written directly.
3574 if (const FunctionProtoType *proto =
3575 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3576 if (proto->getReturnType() == Context.UnknownAnyTy) {
3577 type = Context.UnknownAnyTy;
3578 valueKind = VK_PRValue;
3579 break;
3580 }
3581
3582 // C++ methods are l-values if static, r-values if non-static.
3583 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3584 valueKind = VK_LValue;
3585 break;
3586 }
3587 [[fallthrough]];
3588
3589 case Decl::CXXConversion:
3590 case Decl::CXXDestructor:
3591 case Decl::CXXConstructor:
3592 valueKind = VK_PRValue;
3593 break;
3594 }
3595
3596 auto *E =
3597 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3598 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3599 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3600 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3601 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3602 // diagnostics).
3603 if (VD->isInvalidDecl() && E)
3604 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3605 return E;
3606}
3607
3608static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3609 SmallString<32> &Target) {
3610 Target.resize(N: CharByteWidth * (Source.size() + 1));
3611 char *ResultPtr = &Target[0];
3612 const llvm::UTF8 *ErrorPtr;
3613 bool success =
3614 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3615 (void)success;
3616 assert(success);
3617 Target.resize(N: ResultPtr - &Target[0]);
3618}
3619
3620ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3621 PredefinedIdentKind IK) {
3622 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3623 if (!currentDecl) {
3624 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3625 currentDecl = Context.getTranslationUnitDecl();
3626 }
3627
3628 QualType ResTy;
3629 StringLiteral *SL = nullptr;
3630 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3631 ResTy = Context.DependentTy;
3632 else {
3633 // Pre-defined identifiers are of type char[x], where x is the length of
3634 // the string.
3635 bool ForceElaboratedPrinting =
3636 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3637 auto Str =
3638 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3639 unsigned Length = Str.length();
3640
3641 llvm::APInt LengthI(32, Length + 1);
3642 if (IK == PredefinedIdentKind::LFunction ||
3643 IK == PredefinedIdentKind::LFuncSig) {
3644 ResTy =
3645 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3646 SmallString<32> RawChars;
3647 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3648 Source: Str, Target&: RawChars);
3649 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3650 ASM: ArraySizeModifier::Normal,
3651 /*IndexTypeQuals*/ 0);
3652 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3653 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3654 } else {
3655 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3656 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3657 ASM: ArraySizeModifier::Normal,
3658 /*IndexTypeQuals*/ 0);
3659 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3660 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3661 }
3662 }
3663
3664 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3665 SL);
3666}
3667
3668ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3669 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3670}
3671
3672ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3673 SmallString<16> CharBuffer;
3674 bool Invalid = false;
3675 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3676 if (Invalid)
3677 return ExprError();
3678
3679 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3680 PP, Tok.getKind());
3681 if (Literal.hadError())
3682 return ExprError();
3683
3684 QualType Ty;
3685 if (Literal.isWide())
3686 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3687 else if (Literal.isUTF8() && getLangOpts().C23)
3688 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3689 else if (Literal.isUTF8() && getLangOpts().Char8)
3690 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3691 else if (Literal.isUTF16())
3692 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3693 else if (Literal.isUTF32())
3694 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3695 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3696 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3697 else
3698 Ty = Context.CharTy; // 'x' -> char in C++;
3699 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3700
3701 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3702 if (Literal.isWide())
3703 Kind = CharacterLiteralKind::Wide;
3704 else if (Literal.isUTF16())
3705 Kind = CharacterLiteralKind::UTF16;
3706 else if (Literal.isUTF32())
3707 Kind = CharacterLiteralKind::UTF32;
3708 else if (Literal.isUTF8())
3709 Kind = CharacterLiteralKind::UTF8;
3710
3711 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3712 Tok.getLocation());
3713
3714 if (Literal.getUDSuffix().empty())
3715 return Lit;
3716
3717 // We're building a user-defined literal.
3718 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3719 SourceLocation UDSuffixLoc =
3720 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3721
3722 // Make sure we're allowed user-defined literals here.
3723 if (!UDLScope)
3724 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3725
3726 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3727 // operator "" X (ch)
3728 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3729 Args: Lit, LitEndLoc: Tok.getLocation());
3730}
3731
3732ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3733 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3734 return IntegerLiteral::Create(C: Context,
3735 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3736 type: Context.IntTy, l: Loc);
3737}
3738
3739static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3740 QualType Ty, SourceLocation Loc) {
3741 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3742
3743 using llvm::APFloat;
3744 APFloat Val(Format);
3745
3746 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3747 if (RM == llvm::RoundingMode::Dynamic)
3748 RM = llvm::RoundingMode::NearestTiesToEven;
3749 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3750
3751 // Overflow is always an error, but underflow is only an error if
3752 // we underflowed to zero (APFloat reports denormals as underflow).
3753 if ((result & APFloat::opOverflow) ||
3754 ((result & APFloat::opUnderflow) && Val.isZero())) {
3755 unsigned diagnostic;
3756 SmallString<20> buffer;
3757 if (result & APFloat::opOverflow) {
3758 diagnostic = diag::warn_float_overflow;
3759 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3760 } else {
3761 diagnostic = diag::warn_float_underflow;
3762 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3763 }
3764
3765 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3766 }
3767
3768 bool isExact = (result == APFloat::opOK);
3769 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3770}
3771
3772bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3773 assert(E && "Invalid expression");
3774
3775 if (E->isValueDependent())
3776 return false;
3777
3778 QualType QT = E->getType();
3779 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3780 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3781 return true;
3782 }
3783
3784 llvm::APSInt ValueAPS;
3785 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3786
3787 if (R.isInvalid())
3788 return true;
3789
3790 // GCC allows the value of unroll count to be 0.
3791 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3792 // "The values of 0 and 1 block any unrolling of the loop."
3793 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3794 // '#pragma unroll' cases.
3795 bool ValueIsPositive =
3796 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3797 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3798 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3799 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3800 return true;
3801 }
3802
3803 return false;
3804}
3805
3806ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3807 // Fast path for a single digit (which is quite common). A single digit
3808 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3809 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3810 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3811 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3812 }
3813
3814 SmallString<128> SpellingBuffer;
3815 // NumericLiteralParser wants to overread by one character. Add padding to
3816 // the buffer in case the token is copied to the buffer. If getSpelling()
3817 // returns a StringRef to the memory buffer, it should have a null char at
3818 // the EOF, so it is also safe.
3819 SpellingBuffer.resize(N: Tok.getLength() + 1);
3820
3821 // Get the spelling of the token, which eliminates trigraphs, etc.
3822 bool Invalid = false;
3823 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3824 if (Invalid)
3825 return ExprError();
3826
3827 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3828 PP.getSourceManager(), PP.getLangOpts(),
3829 PP.getTargetInfo(), PP.getDiagnostics());
3830 if (Literal.hadError)
3831 return ExprError();
3832
3833 if (Literal.hasUDSuffix()) {
3834 // We're building a user-defined literal.
3835 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3836 SourceLocation UDSuffixLoc =
3837 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3838
3839 // Make sure we're allowed user-defined literals here.
3840 if (!UDLScope)
3841 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3842
3843 QualType CookedTy;
3844 if (Literal.isFloatingLiteral()) {
3845 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3846 // long double, the literal is treated as a call of the form
3847 // operator "" X (f L)
3848 CookedTy = Context.LongDoubleTy;
3849 } else {
3850 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3851 // unsigned long long, the literal is treated as a call of the form
3852 // operator "" X (n ULL)
3853 CookedTy = Context.UnsignedLongLongTy;
3854 }
3855
3856 DeclarationName OpName =
3857 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3858 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3859 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3860
3861 SourceLocation TokLoc = Tok.getLocation();
3862
3863 // Perform literal operator lookup to determine if we're building a raw
3864 // literal or a cooked one.
3865 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3866 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3867 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3868 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3869 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3870 case LOLR_ErrorNoDiagnostic:
3871 // Lookup failure for imaginary constants isn't fatal, there's still the
3872 // GNU extension producing _Complex types.
3873 break;
3874 case LOLR_Error:
3875 return ExprError();
3876 case LOLR_Cooked: {
3877 Expr *Lit;
3878 if (Literal.isFloatingLiteral()) {
3879 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3880 } else {
3881 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3882 if (Literal.GetIntegerValue(Val&: ResultVal))
3883 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3884 << /* Unsigned */ 1;
3885 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3886 l: Tok.getLocation());
3887 }
3888 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3889 }
3890
3891 case LOLR_Raw: {
3892 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3893 // literal is treated as a call of the form
3894 // operator "" X ("n")
3895 unsigned Length = Literal.getUDSuffixOffset();
3896 QualType StrTy = Context.getConstantArrayType(
3897 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3898 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3899 Expr *Lit =
3900 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3901 Kind: StringLiteralKind::Ordinary,
3902 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3903 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3904 }
3905
3906 case LOLR_Template: {
3907 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3908 // template), L is treated as a call fo the form
3909 // operator "" X <'c1', 'c2', ... 'ck'>()
3910 // where n is the source character sequence c1 c2 ... ck.
3911 TemplateArgumentListInfo ExplicitArgs;
3912 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3913 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3914 llvm::APSInt Value(CharBits, CharIsUnsigned);
3915 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3916 Value = TokSpelling[I];
3917 TemplateArgument Arg(Context, Value, Context.CharTy);
3918 TemplateArgumentLocInfo ArgInfo;
3919 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3920 }
3921 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3922 }
3923 case LOLR_StringTemplatePack:
3924 llvm_unreachable("unexpected literal operator lookup result");
3925 }
3926 }
3927
3928 Expr *Res;
3929
3930 if (Literal.isFixedPointLiteral()) {
3931 QualType Ty;
3932
3933 if (Literal.isAccum) {
3934 if (Literal.isHalf) {
3935 Ty = Context.ShortAccumTy;
3936 } else if (Literal.isLong) {
3937 Ty = Context.LongAccumTy;
3938 } else {
3939 Ty = Context.AccumTy;
3940 }
3941 } else if (Literal.isFract) {
3942 if (Literal.isHalf) {
3943 Ty = Context.ShortFractTy;
3944 } else if (Literal.isLong) {
3945 Ty = Context.LongFractTy;
3946 } else {
3947 Ty = Context.FractTy;
3948 }
3949 }
3950
3951 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3952
3953 bool isSigned = !Literal.isUnsigned;
3954 unsigned scale = Context.getFixedPointScale(Ty);
3955 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3956
3957 llvm::APInt Val(bit_width, 0, isSigned);
3958 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3959 bool ValIsZero = Val.isZero() && !Overflowed;
3960
3961 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3962 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3963 // Clause 6.4.4 - The value of a constant shall be in the range of
3964 // representable values for its type, with exception for constants of a
3965 // fract type with a value of exactly 1; such a constant shall denote
3966 // the maximal value for the type.
3967 --Val;
3968 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3969 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3970
3971 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3972 l: Tok.getLocation(), Scale: scale);
3973 } else if (Literal.isFloatingLiteral()) {
3974 QualType Ty;
3975 if (Literal.isHalf){
3976 if (getLangOpts().HLSL ||
3977 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
3978 Ty = Context.HalfTy;
3979 else {
3980 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
3981 return ExprError();
3982 }
3983 } else if (Literal.isFloat)
3984 Ty = Context.FloatTy;
3985 else if (Literal.isLong)
3986 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3987 else if (Literal.isFloat16)
3988 Ty = Context.Float16Ty;
3989 else if (Literal.isFloat128)
3990 Ty = Context.Float128Ty;
3991 else if (getLangOpts().HLSL)
3992 Ty = Context.FloatTy;
3993 else
3994 Ty = Context.DoubleTy;
3995
3996 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
3997
3998 if (Ty == Context.DoubleTy) {
3999 if (getLangOpts().SinglePrecisionConstants) {
4000 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4001 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4002 }
4003 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4004 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4005 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4006 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4007 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4008 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4009 }
4010 }
4011 } else if (!Literal.isIntegerLiteral()) {
4012 return ExprError();
4013 } else {
4014 QualType Ty;
4015
4016 // 'z/uz' literals are a C++23 feature.
4017 if (Literal.isSizeT)
4018 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4019 ? getLangOpts().CPlusPlus23
4020 ? diag::warn_cxx20_compat_size_t_suffix
4021 : diag::ext_cxx23_size_t_suffix
4022 : diag::err_cxx23_size_t_suffix);
4023
4024 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4025 // but we do not currently support the suffix in C++ mode because it's not
4026 // entirely clear whether WG21 will prefer this suffix to return a library
4027 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4028 // literals are a C++ extension.
4029 if (Literal.isBitInt)
4030 PP.Diag(Loc: Tok.getLocation(),
4031 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4032 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4033 : diag::ext_c23_bitint_suffix);
4034
4035 // Get the value in the widest-possible width. What is "widest" depends on
4036 // whether the literal is a bit-precise integer or not. For a bit-precise
4037 // integer type, try to scan the source to determine how many bits are
4038 // needed to represent the value. This may seem a bit expensive, but trying
4039 // to get the integer value from an overly-wide APInt is *extremely*
4040 // expensive, so the naive approach of assuming
4041 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4042 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4043 if (Literal.isBitInt)
4044 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4045 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4046 if (Literal.MicrosoftInteger) {
4047 if (Literal.MicrosoftInteger == 128 &&
4048 !Context.getTargetInfo().hasInt128Type())
4049 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4050 << Literal.isUnsigned;
4051 BitsNeeded = Literal.MicrosoftInteger;
4052 }
4053
4054 llvm::APInt ResultVal(BitsNeeded, 0);
4055
4056 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4057 // If this value didn't fit into uintmax_t, error and force to ull.
4058 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4059 << /* Unsigned */ 1;
4060 Ty = Context.UnsignedLongLongTy;
4061 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4062 "long long is not intmax_t?");
4063 } else {
4064 // If this value fits into a ULL, try to figure out what else it fits into
4065 // according to the rules of C99 6.4.4.1p5.
4066
4067 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4068 // be an unsigned int.
4069 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4070
4071 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4072 // suffix for portability of code with C++, but both `l` and `ll` are
4073 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4074 // same.
4075 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4076 Literal.isLong = true;
4077 Literal.isLongLong = false;
4078 }
4079
4080 // Check from smallest to largest, picking the smallest type we can.
4081 unsigned Width = 0;
4082
4083 // Microsoft specific integer suffixes are explicitly sized.
4084 if (Literal.MicrosoftInteger) {
4085 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4086 Width = 8;
4087 Ty = Context.CharTy;
4088 } else {
4089 Width = Literal.MicrosoftInteger;
4090 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4091 /*Signed=*/!Literal.isUnsigned);
4092 }
4093 }
4094
4095 // Bit-precise integer literals are automagically-sized based on the
4096 // width required by the literal.
4097 if (Literal.isBitInt) {
4098 // The signed version has one more bit for the sign value. There are no
4099 // zero-width bit-precise integers, even if the literal value is 0.
4100 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4101 (Literal.isUnsigned ? 0u : 1u);
4102
4103 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4104 // and reset the type to the largest supported width.
4105 unsigned int MaxBitIntWidth =
4106 Context.getTargetInfo().getMaxBitIntWidth();
4107 if (Width > MaxBitIntWidth) {
4108 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4109 << Literal.isUnsigned;
4110 Width = MaxBitIntWidth;
4111 }
4112
4113 // Reset the result value to the smaller APInt and select the correct
4114 // type to be used. Note, we zext even for signed values because the
4115 // literal itself is always an unsigned value (a preceeding - is a
4116 // unary operator, not part of the literal).
4117 ResultVal = ResultVal.zextOrTrunc(width: Width);
4118 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4119 }
4120
4121 // Check C++23 size_t literals.
4122 if (Literal.isSizeT) {
4123 assert(!Literal.MicrosoftInteger &&
4124 "size_t literals can't be Microsoft literals");
4125 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4126 T: Context.getTargetInfo().getSizeType());
4127
4128 // Does it fit in size_t?
4129 if (ResultVal.isIntN(N: SizeTSize)) {
4130 // Does it fit in ssize_t?
4131 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4132 Ty = Context.getSignedSizeType();
4133 else if (AllowUnsigned)
4134 Ty = Context.getSizeType();
4135 Width = SizeTSize;
4136 }
4137 }
4138
4139 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4140 !Literal.isSizeT) {
4141 // Are int/unsigned possibilities?
4142 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4143
4144 // Does it fit in a unsigned int?
4145 if (ResultVal.isIntN(N: IntSize)) {
4146 // Does it fit in a signed int?
4147 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4148 Ty = Context.IntTy;
4149 else if (AllowUnsigned)
4150 Ty = Context.UnsignedIntTy;
4151 Width = IntSize;
4152 }
4153 }
4154
4155 // Are long/unsigned long possibilities?
4156 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4157 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4158
4159 // Does it fit in a unsigned long?
4160 if (ResultVal.isIntN(N: LongSize)) {
4161 // Does it fit in a signed long?
4162 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4163 Ty = Context.LongTy;
4164 else if (AllowUnsigned)
4165 Ty = Context.UnsignedLongTy;
4166 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4167 // is compatible.
4168 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4169 const unsigned LongLongSize =
4170 Context.getTargetInfo().getLongLongWidth();
4171 Diag(Loc: Tok.getLocation(),
4172 DiagID: getLangOpts().CPlusPlus
4173 ? Literal.isLong
4174 ? diag::warn_old_implicitly_unsigned_long_cxx
4175 : /*C++98 UB*/ diag::
4176 ext_old_implicitly_unsigned_long_cxx
4177 : diag::warn_old_implicitly_unsigned_long)
4178 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4179 : /*will be ill-formed*/ 1);
4180 Ty = Context.UnsignedLongTy;
4181 }
4182 Width = LongSize;
4183 }
4184 }
4185
4186 // Check long long if needed.
4187 if (Ty.isNull() && !Literal.isSizeT) {
4188 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4189
4190 // Does it fit in a unsigned long long?
4191 if (ResultVal.isIntN(N: LongLongSize)) {
4192 // Does it fit in a signed long long?
4193 // To be compatible with MSVC, hex integer literals ending with the
4194 // LL or i64 suffix are always signed in Microsoft mode.
4195 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4196 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4197 Ty = Context.LongLongTy;
4198 else if (AllowUnsigned)
4199 Ty = Context.UnsignedLongLongTy;
4200 Width = LongLongSize;
4201
4202 // 'long long' is a C99 or C++11 feature, whether the literal
4203 // explicitly specified 'long long' or we needed the extra width.
4204 if (getLangOpts().CPlusPlus)
4205 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4206 ? diag::warn_cxx98_compat_longlong
4207 : diag::ext_cxx11_longlong);
4208 else if (!getLangOpts().C99)
4209 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4210 }
4211 }
4212
4213 // If we still couldn't decide a type, we either have 'size_t' literal
4214 // that is out of range, or a decimal literal that does not fit in a
4215 // signed long long and has no U suffix.
4216 if (Ty.isNull()) {
4217 if (Literal.isSizeT)
4218 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4219 << Literal.isUnsigned;
4220 else
4221 Diag(Loc: Tok.getLocation(),
4222 DiagID: diag::ext_integer_literal_too_large_for_signed);
4223 Ty = Context.UnsignedLongLongTy;
4224 Width = Context.getTargetInfo().getLongLongWidth();
4225 }
4226
4227 if (ResultVal.getBitWidth() != Width)
4228 ResultVal = ResultVal.trunc(width: Width);
4229 }
4230 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4231 }
4232
4233 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4234 if (Literal.isImaginary) {
4235 Res = new (Context) ImaginaryLiteral(Res,
4236 Context.getComplexType(T: Res->getType()));
4237
4238 // In C++, this is a GNU extension. In C, it's a C2y extension.
4239 unsigned DiagId;
4240 if (getLangOpts().CPlusPlus)
4241 DiagId = diag::ext_gnu_imaginary_constant;
4242 else if (getLangOpts().C2y)
4243 DiagId = diag::warn_c23_compat_imaginary_constant;
4244 else
4245 DiagId = diag::ext_c2y_imaginary_constant;
4246 Diag(Loc: Tok.getLocation(), DiagID: DiagId);
4247 }
4248 return Res;
4249}
4250
4251ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4252 assert(E && "ActOnParenExpr() missing expr");
4253 QualType ExprTy = E->getType();
4254 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4255 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4256 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4257 return new (Context) ParenExpr(L, R, E);
4258}
4259
4260static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4261 SourceLocation Loc,
4262 SourceRange ArgRange) {
4263 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4264 // scalar or vector data type argument..."
4265 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4266 // type (C99 6.2.5p18) or void.
4267 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4268 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4269 << T << ArgRange;
4270 return true;
4271 }
4272
4273 assert((T->isVoidType() || !T->isIncompleteType()) &&
4274 "Scalar types should always be complete");
4275 return false;
4276}
4277
4278static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4279 SourceLocation Loc,
4280 SourceRange ArgRange) {
4281 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4282 if (!T->isVectorType() && !T->isSizelessVectorType())
4283 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4284 << ""
4285 << "__builtin_vectorelements" << T << ArgRange;
4286
4287 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4288 if (T->isSVESizelessBuiltinType()) {
4289 llvm::StringMap<bool> CallerFeatureMap;
4290 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4291 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4292 }
4293 }
4294
4295 return false;
4296}
4297
4298static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4299 SourceLocation Loc,
4300 SourceRange ArgRange) {
4301 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4302 return true;
4303
4304 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4305 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4306 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4307 return true;
4308 }
4309
4310 return false;
4311}
4312
4313static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4314 SourceLocation Loc,
4315 SourceRange ArgRange,
4316 UnaryExprOrTypeTrait TraitKind) {
4317 // Invalid types must be hard errors for SFINAE in C++.
4318 if (S.LangOpts.CPlusPlus)
4319 return true;
4320
4321 // C99 6.5.3.4p1:
4322 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4323 TraitKind == UETT_PreferredAlignOf) {
4324
4325 // sizeof(function)/alignof(function) is allowed as an extension.
4326 if (T->isFunctionType()) {
4327 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4328 << getTraitSpelling(T: TraitKind) << ArgRange;
4329 return false;
4330 }
4331
4332 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4333 // this is an error (OpenCL v1.1 s6.3.k)
4334 if (T->isVoidType()) {
4335 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4336 : diag::ext_sizeof_alignof_void_type;
4337 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4338 return false;
4339 }
4340 }
4341 return true;
4342}
4343
4344static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4345 SourceLocation Loc,
4346 SourceRange ArgRange,
4347 UnaryExprOrTypeTrait TraitKind) {
4348 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4349 // runtime doesn't allow it.
4350 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4351 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4352 << T << (TraitKind == UETT_SizeOf)
4353 << ArgRange;
4354 return true;
4355 }
4356
4357 return false;
4358}
4359
4360/// Check whether E is a pointer from a decayed array type (the decayed
4361/// pointer type is equal to T) and emit a warning if it is.
4362static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4363 const Expr *E) {
4364 // Don't warn if the operation changed the type.
4365 if (T != E->getType())
4366 return;
4367
4368 // Now look for array decays.
4369 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4370 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4371 return;
4372
4373 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4374 << ICE->getType()
4375 << ICE->getSubExpr()->getType();
4376}
4377
4378bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4379 UnaryExprOrTypeTrait ExprKind) {
4380 QualType ExprTy = E->getType();
4381 assert(!ExprTy->isReferenceType());
4382
4383 bool IsUnevaluatedOperand =
4384 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4385 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4386 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4387 if (IsUnevaluatedOperand) {
4388 ExprResult Result = CheckUnevaluatedOperand(E);
4389 if (Result.isInvalid())
4390 return true;
4391 E = Result.get();
4392 }
4393
4394 // The operand for sizeof and alignof is in an unevaluated expression context,
4395 // so side effects could result in unintended consequences.
4396 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4397 // used to build SFINAE gadgets.
4398 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4399 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4400 !E->isInstantiationDependent() &&
4401 !E->getType()->isVariableArrayType() &&
4402 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4403 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4404
4405 if (ExprKind == UETT_VecStep)
4406 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4407 ArgRange: E->getSourceRange());
4408
4409 if (ExprKind == UETT_VectorElements)
4410 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4411 ArgRange: E->getSourceRange());
4412
4413 // Explicitly list some types as extensions.
4414 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4415 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4416 return false;
4417
4418 // WebAssembly tables are always illegal operands to unary expressions and
4419 // type traits.
4420 if (Context.getTargetInfo().getTriple().isWasm() &&
4421 E->getType()->isWebAssemblyTableType()) {
4422 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4423 << getTraitSpelling(T: ExprKind);
4424 return true;
4425 }
4426
4427 // 'alignof' applied to an expression only requires the base element type of
4428 // the expression to be complete. 'sizeof' requires the expression's type to
4429 // be complete (and will attempt to complete it if it's an array of unknown
4430 // bound).
4431 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4432 if (RequireCompleteSizedType(
4433 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4434 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4435 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4436 return true;
4437 } else {
4438 if (RequireCompleteSizedExprType(
4439 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4440 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4441 return true;
4442 }
4443
4444 // Completing the expression's type may have changed it.
4445 ExprTy = E->getType();
4446 assert(!ExprTy->isReferenceType());
4447
4448 if (ExprTy->isFunctionType()) {
4449 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4450 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4451 return true;
4452 }
4453
4454 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4455 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4456 return true;
4457
4458 if (ExprKind == UETT_CountOf) {
4459 // The type has to be an array type. We already checked for incomplete
4460 // types above.
4461 QualType ExprType = E->IgnoreParens()->getType();
4462 if (!ExprType->isArrayType()) {
4463 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4464 return true;
4465 }
4466 // FIXME: warn on _Countof on an array parameter. Not warning on it
4467 // currently because there are papers in WG14 about array types which do
4468 // not decay that could impact this behavior, so we want to see if anything
4469 // changes here before coming up with a warning group for _Countof-related
4470 // diagnostics.
4471 }
4472
4473 if (ExprKind == UETT_SizeOf) {
4474 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4475 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4476 QualType OType = PVD->getOriginalType();
4477 QualType Type = PVD->getType();
4478 if (Type->isPointerType() && OType->isArrayType()) {
4479 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4480 << Type << OType;
4481 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4482 }
4483 }
4484 }
4485
4486 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4487 // decays into a pointer and returns an unintended result. This is most
4488 // likely a typo for "sizeof(array) op x".
4489 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4490 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4491 E: BO->getLHS());
4492 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4493 E: BO->getRHS());
4494 }
4495 }
4496
4497 return false;
4498}
4499
4500static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4501 // Cannot know anything else if the expression is dependent.
4502 if (E->isTypeDependent())
4503 return false;
4504
4505 if (E->getObjectKind() == OK_BitField) {
4506 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4507 << 1 << E->getSourceRange();
4508 return true;
4509 }
4510
4511 ValueDecl *D = nullptr;
4512 Expr *Inner = E->IgnoreParens();
4513 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4514 D = DRE->getDecl();
4515 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4516 D = ME->getMemberDecl();
4517 }
4518
4519 // If it's a field, require the containing struct to have a
4520 // complete definition so that we can compute the layout.
4521 //
4522 // This can happen in C++11 onwards, either by naming the member
4523 // in a way that is not transformed into a member access expression
4524 // (in an unevaluated operand, for instance), or by naming the member
4525 // in a trailing-return-type.
4526 //
4527 // For the record, since __alignof__ on expressions is a GCC
4528 // extension, GCC seems to permit this but always gives the
4529 // nonsensical answer 0.
4530 //
4531 // We don't really need the layout here --- we could instead just
4532 // directly check for all the appropriate alignment-lowing
4533 // attributes --- but that would require duplicating a lot of
4534 // logic that just isn't worth duplicating for such a marginal
4535 // use-case.
4536 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4537 // Fast path this check, since we at least know the record has a
4538 // definition if we can find a member of it.
4539 if (!FD->getParent()->isCompleteDefinition()) {
4540 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4541 << E->getSourceRange();
4542 return true;
4543 }
4544
4545 // Otherwise, if it's a field, and the field doesn't have
4546 // reference type, then it must have a complete type (or be a
4547 // flexible array member, which we explicitly want to
4548 // white-list anyway), which makes the following checks trivial.
4549 if (!FD->getType()->isReferenceType())
4550 return false;
4551 }
4552
4553 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4554}
4555
4556bool Sema::CheckVecStepExpr(Expr *E) {
4557 E = E->IgnoreParens();
4558
4559 // Cannot know anything else if the expression is dependent.
4560 if (E->isTypeDependent())
4561 return false;
4562
4563 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4564}
4565
4566static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4567 CapturingScopeInfo *CSI) {
4568 assert(T->isVariablyModifiedType());
4569 assert(CSI != nullptr);
4570
4571 // We're going to walk down into the type and look for VLA expressions.
4572 do {
4573 const Type *Ty = T.getTypePtr();
4574 switch (Ty->getTypeClass()) {
4575#define TYPE(Class, Base)
4576#define ABSTRACT_TYPE(Class, Base)
4577#define NON_CANONICAL_TYPE(Class, Base)
4578#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4579#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4580#include "clang/AST/TypeNodes.inc"
4581 T = QualType();
4582 break;
4583 // These types are never variably-modified.
4584 case Type::Builtin:
4585 case Type::Complex:
4586 case Type::Vector:
4587 case Type::ExtVector:
4588 case Type::ConstantMatrix:
4589 case Type::Record:
4590 case Type::Enum:
4591 case Type::TemplateSpecialization:
4592 case Type::ObjCObject:
4593 case Type::ObjCInterface:
4594 case Type::ObjCObjectPointer:
4595 case Type::ObjCTypeParam:
4596 case Type::Pipe:
4597 case Type::BitInt:
4598 case Type::HLSLInlineSpirv:
4599 llvm_unreachable("type class is never variably-modified!");
4600 case Type::Adjusted:
4601 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4602 break;
4603 case Type::Decayed:
4604 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4605 break;
4606 case Type::ArrayParameter:
4607 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4608 break;
4609 case Type::Pointer:
4610 T = cast<PointerType>(Val: Ty)->getPointeeType();
4611 break;
4612 case Type::BlockPointer:
4613 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4614 break;
4615 case Type::LValueReference:
4616 case Type::RValueReference:
4617 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4618 break;
4619 case Type::MemberPointer:
4620 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4621 break;
4622 case Type::ConstantArray:
4623 case Type::IncompleteArray:
4624 // Losing element qualification here is fine.
4625 T = cast<ArrayType>(Val: Ty)->getElementType();
4626 break;
4627 case Type::VariableArray: {
4628 // Losing element qualification here is fine.
4629 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4630
4631 // Unknown size indication requires no size computation.
4632 // Otherwise, evaluate and record it.
4633 auto Size = VAT->getSizeExpr();
4634 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4635 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4636 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4637
4638 T = VAT->getElementType();
4639 break;
4640 }
4641 case Type::FunctionProto:
4642 case Type::FunctionNoProto:
4643 T = cast<FunctionType>(Val: Ty)->getReturnType();
4644 break;
4645 case Type::Paren:
4646 case Type::TypeOf:
4647 case Type::UnaryTransform:
4648 case Type::Attributed:
4649 case Type::BTFTagAttributed:
4650 case Type::OverflowBehavior:
4651 case Type::HLSLAttributedResource:
4652 case Type::SubstTemplateTypeParm:
4653 case Type::MacroQualified:
4654 case Type::CountAttributed:
4655 // Keep walking after single level desugaring.
4656 T = T.getSingleStepDesugaredType(Context);
4657 break;
4658 case Type::Typedef:
4659 T = cast<TypedefType>(Val: Ty)->desugar();
4660 break;
4661 case Type::Decltype:
4662 T = cast<DecltypeType>(Val: Ty)->desugar();
4663 break;
4664 case Type::PackIndexing:
4665 T = cast<PackIndexingType>(Val: Ty)->desugar();
4666 break;
4667 case Type::Using:
4668 T = cast<UsingType>(Val: Ty)->desugar();
4669 break;
4670 case Type::Auto:
4671 case Type::DeducedTemplateSpecialization:
4672 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4673 break;
4674 case Type::TypeOfExpr:
4675 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4676 break;
4677 case Type::Atomic:
4678 T = cast<AtomicType>(Val: Ty)->getValueType();
4679 break;
4680 case Type::PredefinedSugar:
4681 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4682 break;
4683 }
4684 } while (!T.isNull() && T->isVariablyModifiedType());
4685}
4686
4687bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4688 SourceLocation OpLoc,
4689 SourceRange ExprRange,
4690 UnaryExprOrTypeTrait ExprKind,
4691 StringRef KWName) {
4692 if (ExprType->isDependentType())
4693 return false;
4694
4695 // C++ [expr.sizeof]p2:
4696 // When applied to a reference or a reference type, the result
4697 // is the size of the referenced type.
4698 // C++11 [expr.alignof]p3:
4699 // When alignof is applied to a reference type, the result
4700 // shall be the alignment of the referenced type.
4701 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4702 ExprType = Ref->getPointeeType();
4703
4704 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4705 // When alignof or _Alignof is applied to an array type, the result
4706 // is the alignment of the element type.
4707 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4708 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4709 // If the trait is 'alignof' in C before C2y, the ability to apply the
4710 // trait to an incomplete array is an extension.
4711 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4712 ExprType->isIncompleteArrayType())
4713 Diag(Loc: OpLoc, DiagID: getLangOpts().C2y
4714 ? diag::warn_c2y_compat_alignof_incomplete_array
4715 : diag::ext_c2y_alignof_incomplete_array);
4716 ExprType = Context.getBaseElementType(QT: ExprType);
4717 }
4718
4719 if (ExprKind == UETT_VecStep)
4720 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4721
4722 if (ExprKind == UETT_VectorElements)
4723 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4724 ArgRange: ExprRange);
4725
4726 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4727 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4728 ArgRange: ExprRange);
4729
4730 // Explicitly list some types as extensions.
4731 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4732 TraitKind: ExprKind))
4733 return false;
4734
4735 if (RequireCompleteSizedType(
4736 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4737 Args: KWName, Args: ExprRange))
4738 return true;
4739
4740 if (ExprType->isFunctionType()) {
4741 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4742 return true;
4743 }
4744
4745 if (ExprKind == UETT_CountOf) {
4746 // The type has to be an array type. We already checked for incomplete
4747 // types above.
4748 if (!ExprType->isArrayType()) {
4749 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4750 return true;
4751 }
4752 }
4753
4754 // WebAssembly tables are always illegal operands to unary expressions and
4755 // type traits.
4756 if (Context.getTargetInfo().getTriple().isWasm() &&
4757 ExprType->isWebAssemblyTableType()) {
4758 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4759 << getTraitSpelling(T: ExprKind);
4760 return true;
4761 }
4762
4763 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4764 TraitKind: ExprKind))
4765 return true;
4766
4767 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4768 if (auto *TT = ExprType->getAs<TypedefType>()) {
4769 for (auto I = FunctionScopes.rbegin(),
4770 E = std::prev(x: FunctionScopes.rend());
4771 I != E; ++I) {
4772 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4773 if (CSI == nullptr)
4774 break;
4775 DeclContext *DC = nullptr;
4776 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4777 DC = LSI->CallOperator;
4778 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4779 DC = CRSI->TheCapturedDecl;
4780 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4781 DC = BSI->TheDecl;
4782 if (DC) {
4783 if (DC->containsDecl(D: TT->getDecl()))
4784 break;
4785 captureVariablyModifiedType(Context, T: ExprType, CSI);
4786 }
4787 }
4788 }
4789 }
4790
4791 return false;
4792}
4793
4794ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4795 SourceLocation OpLoc,
4796 UnaryExprOrTypeTrait ExprKind,
4797 SourceRange R) {
4798 if (!TInfo)
4799 return ExprError();
4800
4801 QualType T = TInfo->getType();
4802
4803 if (!T->isDependentType() &&
4804 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4805 KWName: getTraitSpelling(T: ExprKind)))
4806 return ExprError();
4807
4808 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4809 // properly deal with VLAs in nested calls of sizeof and typeof.
4810 if (currentEvaluationContext().isUnevaluated() &&
4811 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4812 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4813 TInfo->getType()->isVariablyModifiedType())
4814 TInfo = TransformToPotentiallyEvaluated(TInfo);
4815
4816 // It's possible that the transformation above failed.
4817 if (!TInfo)
4818 return ExprError();
4819
4820 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4821 return new (Context) UnaryExprOrTypeTraitExpr(
4822 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4823}
4824
4825ExprResult
4826Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4827 UnaryExprOrTypeTrait ExprKind) {
4828 ExprResult PE = CheckPlaceholderExpr(E);
4829 if (PE.isInvalid())
4830 return ExprError();
4831
4832 E = PE.get();
4833
4834 // Verify that the operand is valid.
4835 bool isInvalid = false;
4836 if (E->isTypeDependent()) {
4837 // Delay type-checking for type-dependent expressions.
4838 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4839 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4840 } else if (ExprKind == UETT_VecStep) {
4841 isInvalid = CheckVecStepExpr(E);
4842 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4843 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4844 isInvalid = true;
4845 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4846 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4847 isInvalid = true;
4848 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4849 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4850 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4851 }
4852
4853 if (isInvalid)
4854 return ExprError();
4855
4856 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4857 E->getType()->isVariableArrayType()) {
4858 PE = TransformToPotentiallyEvaluated(E);
4859 if (PE.isInvalid()) return ExprError();
4860 E = PE.get();
4861 }
4862
4863 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4864 return new (Context) UnaryExprOrTypeTraitExpr(
4865 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4866}
4867
4868ExprResult
4869Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4870 UnaryExprOrTypeTrait ExprKind, bool IsType,
4871 void *TyOrEx, SourceRange ArgRange) {
4872 // If error parsing type, ignore.
4873 if (!TyOrEx) return ExprError();
4874
4875 if (IsType) {
4876 TypeSourceInfo *TInfo;
4877 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4878 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4879 }
4880
4881 Expr *ArgEx = (Expr *)TyOrEx;
4882 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4883 return Result;
4884}
4885
4886bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4887 SourceLocation OpLoc, SourceRange R) {
4888 if (!TInfo)
4889 return true;
4890 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4891 ExprKind: UETT_AlignOf, KWName);
4892}
4893
4894bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4895 SourceLocation OpLoc, SourceRange R) {
4896 TypeSourceInfo *TInfo;
4897 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4898 TInfo: &TInfo);
4899 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4900}
4901
4902static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4903 bool IsReal) {
4904 if (V.get()->isTypeDependent())
4905 return S.Context.DependentTy;
4906
4907 // _Real and _Imag are only l-values for normal l-values.
4908 if (V.get()->getObjectKind() != OK_Ordinary) {
4909 V = S.DefaultLvalueConversion(E: V.get());
4910 if (V.isInvalid())
4911 return QualType();
4912 }
4913
4914 // These operators return the element type of a complex type.
4915 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4916 return CT->getElementType();
4917
4918 // Otherwise they pass through real integer and floating point types here.
4919 if (V.get()->getType()->isArithmeticType())
4920 return V.get()->getType();
4921
4922 // Test for placeholders.
4923 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4924 if (PR.isInvalid()) return QualType();
4925 if (PR.get() != V.get()) {
4926 V = PR;
4927 return CheckRealImagOperand(S, V, Loc, IsReal);
4928 }
4929
4930 // Reject anything else.
4931 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4932 << (IsReal ? "__real" : "__imag");
4933 return QualType();
4934}
4935
4936
4937
4938ExprResult
4939Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4940 tok::TokenKind Kind, Expr *Input) {
4941 UnaryOperatorKind Opc;
4942 switch (Kind) {
4943 default: llvm_unreachable("Unknown unary op!");
4944 case tok::plusplus: Opc = UO_PostInc; break;
4945 case tok::minusminus: Opc = UO_PostDec; break;
4946 }
4947
4948 // Since this might is a postfix expression, get rid of ParenListExprs.
4949 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4950 if (Result.isInvalid()) return ExprError();
4951 Input = Result.get();
4952
4953 return BuildUnaryOp(S, OpLoc, Opc, Input);
4954}
4955
4956/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4957///
4958/// \return true on error
4959static bool checkArithmeticOnObjCPointer(Sema &S,
4960 SourceLocation opLoc,
4961 Expr *op) {
4962 assert(op->getType()->isObjCObjectPointerType());
4963 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4964 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4965 return false;
4966
4967 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4968 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4969 << op->getSourceRange();
4970 return true;
4971}
4972
4973static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4974 auto *BaseNoParens = Base->IgnoreParens();
4975 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4976 return MSProp->getPropertyDecl()->getType()->isArrayType();
4977 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4978}
4979
4980// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4981// Typically this is DependentTy, but can sometimes be more precise.
4982//
4983// There are cases when we could determine a non-dependent type:
4984// - LHS and RHS may have non-dependent types despite being type-dependent
4985// (e.g. unbounded array static members of the current instantiation)
4986// - one may be a dependent-sized array with known element type
4987// - one may be a dependent-typed valid index (enum in current instantiation)
4988//
4989// We *always* return a dependent type, in such cases it is DependentTy.
4990// This avoids creating type-dependent expressions with non-dependent types.
4991// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4992static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4993 const ASTContext &Ctx) {
4994 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4995 QualType LTy = LHS->getType(), RTy = RHS->getType();
4996 QualType Result = Ctx.DependentTy;
4997 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4998 if (const PointerType *PT = LTy->getAs<PointerType>())
4999 Result = PT->getPointeeType();
5000 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5001 Result = AT->getElementType();
5002 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5003 if (const PointerType *PT = RTy->getAs<PointerType>())
5004 Result = PT->getPointeeType();
5005 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5006 Result = AT->getElementType();
5007 }
5008 // Ensure we return a dependent type.
5009 return Result->isDependentType() ? Result : Ctx.DependentTy;
5010}
5011
5012ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5013 SourceLocation lbLoc,
5014 MultiExprArg ArgExprs,
5015 SourceLocation rbLoc) {
5016
5017 if (base && !base->getType().isNull() &&
5018 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5019 auto *AS = cast<ArraySectionExpr>(Val: base);
5020 if (AS->isOMPArraySection())
5021 return OpenMP().ActOnOMPArraySectionExpr(
5022 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5023 /*Length*/ nullptr,
5024 /*Stride=*/nullptr, RBLoc: rbLoc);
5025
5026 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5027 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5028 RBLoc: rbLoc);
5029 }
5030
5031 // Since this might be a postfix expression, get rid of ParenListExprs.
5032 if (isa<ParenListExpr>(Val: base)) {
5033 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5034 if (result.isInvalid())
5035 return ExprError();
5036 base = result.get();
5037 }
5038
5039 // Check if base and idx form a MatrixSubscriptExpr.
5040 //
5041 // Helper to check for comma expressions, which are not allowed as indices for
5042 // matrix subscript expressions.
5043 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5044 if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) {
5045 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5046 << SourceRange(base->getBeginLoc(), rbLoc);
5047 return true;
5048 }
5049 return false;
5050 };
5051 // The matrix subscript operator ([][])is considered a single operator.
5052 // Separating the index expressions by parenthesis is not allowed.
5053 if (base && !base->getType().isNull() &&
5054 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5055 !isa<MatrixSubscriptExpr>(Val: base)) {
5056 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5057 << SourceRange(base->getBeginLoc(), rbLoc);
5058 return ExprError();
5059 }
5060 // If the base is a MatrixSubscriptExpr, try to create a new
5061 // MatrixSubscriptExpr.
5062 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5063 if (matSubscriptE) {
5064 assert(ArgExprs.size() == 1);
5065 if (CheckAndReportCommaError(ArgExprs.front()))
5066 return ExprError();
5067
5068 assert(matSubscriptE->isIncomplete() &&
5069 "base has to be an incomplete matrix subscript");
5070 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5071 RowIdx: matSubscriptE->getRowIdx(),
5072 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5073 }
5074 if (base->getType()->isWebAssemblyTableType()) {
5075 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5076 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5077 return ExprError();
5078 }
5079
5080 CheckInvalidBuiltinCountedByRef(E: base,
5081 K: BuiltinCountedByRefKind::ArraySubscript);
5082
5083 // Handle any non-overload placeholder types in the base and index
5084 // expressions. We can't handle overloads here because the other
5085 // operand might be an overloadable type, in which case the overload
5086 // resolution for the operator overload should get the first crack
5087 // at the overload.
5088 bool IsMSPropertySubscript = false;
5089 if (base->getType()->isNonOverloadPlaceholderType()) {
5090 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5091 if (!IsMSPropertySubscript) {
5092 ExprResult result = CheckPlaceholderExpr(E: base);
5093 if (result.isInvalid())
5094 return ExprError();
5095 base = result.get();
5096 }
5097 }
5098
5099 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5100 if (base->getType()->isMatrixType()) {
5101 assert(ArgExprs.size() == 1);
5102 if (CheckAndReportCommaError(ArgExprs.front()))
5103 return ExprError();
5104
5105 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5106 RBLoc: rbLoc);
5107 }
5108
5109 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5110 Expr *idx = ArgExprs[0];
5111 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5112 (isa<CXXOperatorCallExpr>(Val: idx) &&
5113 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5114 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5115 << SourceRange(base->getBeginLoc(), rbLoc);
5116 }
5117 }
5118
5119 if (ArgExprs.size() == 1 &&
5120 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5121 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5122 if (result.isInvalid())
5123 return ExprError();
5124 ArgExprs[0] = result.get();
5125 } else {
5126 if (CheckArgsForPlaceholders(args: ArgExprs))
5127 return ExprError();
5128 }
5129
5130 // Build an unanalyzed expression if either operand is type-dependent.
5131 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5132 (base->isTypeDependent() ||
5133 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5134 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5135 return new (Context) ArraySubscriptExpr(
5136 base, ArgExprs.front(),
5137 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5138 VK_LValue, OK_Ordinary, rbLoc);
5139 }
5140
5141 // MSDN, property (C++)
5142 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5143 // This attribute can also be used in the declaration of an empty array in a
5144 // class or structure definition. For example:
5145 // __declspec(property(get=GetX, put=PutX)) int x[];
5146 // The above statement indicates that x[] can be used with one or more array
5147 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5148 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5149 if (IsMSPropertySubscript) {
5150 assert(ArgExprs.size() == 1);
5151 // Build MS property subscript expression if base is MS property reference
5152 // or MS property subscript.
5153 return new (Context)
5154 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5155 VK_LValue, OK_Ordinary, rbLoc);
5156 }
5157
5158 // Use C++ overloaded-operator rules if either operand has record
5159 // type. The spec says to do this if either type is *overloadable*,
5160 // but enum types can't declare subscript operators or conversion
5161 // operators, so there's nothing interesting for overload resolution
5162 // to do if there aren't any record types involved.
5163 //
5164 // ObjC pointers have their own subscripting logic that is not tied
5165 // to overload resolution and so should not take this path.
5166 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5167 ((base->getType()->isRecordType() ||
5168 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5169 ArgExprs[0]->getType()->isRecordType())))) {
5170 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5171 }
5172
5173 ExprResult Res =
5174 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5175
5176 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5177 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5178
5179 return Res;
5180}
5181
5182ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5183 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5184 InitializationKind Kind =
5185 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5186 InitializationSequence InitSeq(*this, Entity, Kind, E);
5187 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5188}
5189
5190ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5191 Expr *RowIdx,
5192 SourceLocation RBLoc) {
5193 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5194 if (BaseR.isInvalid())
5195 return BaseR;
5196 Base = BaseR.get();
5197
5198 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5199 if (RowR.isInvalid())
5200 return RowR;
5201 RowIdx = RowR.get();
5202
5203 // Build an unanalyzed expression if any of the operands is type-dependent.
5204 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5205 return new (Context)
5206 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5207
5208 // Check that IndexExpr is an integer expression. If it is a constant
5209 // expression, check that it is less than Dim (= the number of elements in the
5210 // corresponding dimension).
5211 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5212 bool IsColumnIdx) -> Expr * {
5213 if (!IndexExpr->getType()->isIntegerType() &&
5214 !IndexExpr->isTypeDependent()) {
5215 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5216 << IsColumnIdx;
5217 return nullptr;
5218 }
5219
5220 if (std::optional<llvm::APSInt> Idx =
5221 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5222 if ((*Idx < 0 || *Idx >= Dim)) {
5223 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5224 << IsColumnIdx << Dim;
5225 return nullptr;
5226 }
5227 }
5228
5229 ExprResult ConvExpr = IndexExpr;
5230 assert(!ConvExpr.isInvalid() &&
5231 "should be able to convert any integer type to size type");
5232 return ConvExpr.get();
5233 };
5234
5235 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5236 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5237 if (!RowIdx)
5238 return ExprError();
5239
5240 QualType RowVecQT =
5241 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5242
5243 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5244}
5245
5246ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5247 Expr *ColumnIdx,
5248 SourceLocation RBLoc) {
5249 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5250 if (BaseR.isInvalid())
5251 return BaseR;
5252 Base = BaseR.get();
5253
5254 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5255 if (RowR.isInvalid())
5256 return RowR;
5257 RowIdx = RowR.get();
5258
5259 if (!ColumnIdx)
5260 return new (Context) MatrixSubscriptExpr(
5261 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5262
5263 // Build an unanalyzed expression if any of the operands is type-dependent.
5264 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5265 ColumnIdx->isTypeDependent())
5266 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5267 Context.DependentTy, RBLoc);
5268
5269 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5270 if (ColumnR.isInvalid())
5271 return ColumnR;
5272 ColumnIdx = ColumnR.get();
5273
5274 // Check that IndexExpr is an integer expression. If it is a constant
5275 // expression, check that it is less than Dim (= the number of elements in the
5276 // corresponding dimension).
5277 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5278 bool IsColumnIdx) -> Expr * {
5279 if (!IndexExpr->getType()->isIntegerType() &&
5280 !IndexExpr->isTypeDependent()) {
5281 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5282 << IsColumnIdx;
5283 return nullptr;
5284 }
5285
5286 if (std::optional<llvm::APSInt> Idx =
5287 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5288 if ((*Idx < 0 || *Idx >= Dim)) {
5289 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5290 << IsColumnIdx << Dim;
5291 return nullptr;
5292 }
5293 }
5294
5295 ExprResult ConvExpr = IndexExpr;
5296 assert(!ConvExpr.isInvalid() &&
5297 "should be able to convert any integer type to size type");
5298 return ConvExpr.get();
5299 };
5300
5301 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5302 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5303 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5304 if (!RowIdx || !ColumnIdx)
5305 return ExprError();
5306
5307 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5308 MTy->getElementType(), RBLoc);
5309}
5310
5311void Sema::CheckAddressOfNoDeref(const Expr *E) {
5312 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5313 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5314
5315 // For expressions like `&(*s).b`, the base is recorded and what should be
5316 // checked.
5317 const MemberExpr *Member = nullptr;
5318 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5319 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5320
5321 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5322}
5323
5324void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5325 if (isUnevaluatedContext())
5326 return;
5327
5328 QualType ResultTy = E->getType();
5329 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5330
5331 // Bail if the element is an array since it is not memory access.
5332 if (isa<ArrayType>(Val: ResultTy))
5333 return;
5334
5335 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5336 LastRecord.PossibleDerefs.insert(Ptr: E);
5337 return;
5338 }
5339
5340 // Check if the base type is a pointer to a member access of a struct
5341 // marked with noderef.
5342 const Expr *Base = E->getBase();
5343 QualType BaseTy = Base->getType();
5344 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5345 // Not a pointer access
5346 return;
5347
5348 const MemberExpr *Member = nullptr;
5349 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5350 Member->isArrow())
5351 Base = Member->getBase();
5352
5353 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5354 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5355 LastRecord.PossibleDerefs.insert(Ptr: E);
5356 }
5357}
5358
5359ExprResult
5360Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5361 Expr *Idx, SourceLocation RLoc) {
5362 Expr *LHSExp = Base;
5363 Expr *RHSExp = Idx;
5364
5365 ExprValueKind VK = VK_LValue;
5366 ExprObjectKind OK = OK_Ordinary;
5367
5368 // Per C++ core issue 1213, the result is an xvalue if either operand is
5369 // a non-lvalue array, and an lvalue otherwise.
5370 if (getLangOpts().CPlusPlus11) {
5371 for (auto *Op : {LHSExp, RHSExp}) {
5372 Op = Op->IgnoreImplicit();
5373 if (Op->getType()->isArrayType() && !Op->isLValue())
5374 VK = VK_XValue;
5375 }
5376 }
5377
5378 // Perform default conversions.
5379 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5380 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5381 if (Result.isInvalid())
5382 return ExprError();
5383 LHSExp = Result.get();
5384 }
5385 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5386 if (Result.isInvalid())
5387 return ExprError();
5388 RHSExp = Result.get();
5389
5390 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5391
5392 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5393 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5394 // in the subscript position. As a result, we need to derive the array base
5395 // and index from the expression types.
5396 Expr *BaseExpr, *IndexExpr;
5397 QualType ResultType;
5398 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5399 BaseExpr = LHSExp;
5400 IndexExpr = RHSExp;
5401 ResultType =
5402 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5403 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5404 BaseExpr = LHSExp;
5405 IndexExpr = RHSExp;
5406 ResultType = PTy->getPointeeType();
5407 } else if (const ObjCObjectPointerType *PTy =
5408 LHSTy->getAs<ObjCObjectPointerType>()) {
5409 BaseExpr = LHSExp;
5410 IndexExpr = RHSExp;
5411
5412 // Use custom logic if this should be the pseudo-object subscript
5413 // expression.
5414 if (!LangOpts.isSubscriptPointerArithmetic())
5415 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5416 getterMethod: nullptr, setterMethod: nullptr);
5417
5418 ResultType = PTy->getPointeeType();
5419 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5420 // Handle the uncommon case of "123[Ptr]".
5421 BaseExpr = RHSExp;
5422 IndexExpr = LHSExp;
5423 ResultType = PTy->getPointeeType();
5424 } else if (const ObjCObjectPointerType *PTy =
5425 RHSTy->getAs<ObjCObjectPointerType>()) {
5426 // Handle the uncommon case of "123[Ptr]".
5427 BaseExpr = RHSExp;
5428 IndexExpr = LHSExp;
5429 ResultType = PTy->getPointeeType();
5430 if (!LangOpts.isSubscriptPointerArithmetic()) {
5431 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5432 << ResultType << BaseExpr->getSourceRange();
5433 return ExprError();
5434 }
5435 } else if (LHSTy->isSubscriptableVectorType()) {
5436 if (LHSTy->isBuiltinType() &&
5437 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5438 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5439 if (BTy->isSVEBool())
5440 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5441 << LHSExp->getSourceRange()
5442 << RHSExp->getSourceRange());
5443 ResultType = BTy->getSveEltType(Ctx: Context);
5444 } else {
5445 const VectorType *VTy = LHSTy->getAs<VectorType>();
5446 ResultType = VTy->getElementType();
5447 }
5448 BaseExpr = LHSExp; // vectors: V[123]
5449 IndexExpr = RHSExp;
5450 // We apply C++ DR1213 to vector subscripting too.
5451 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5452 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5453 if (Materialized.isInvalid())
5454 return ExprError();
5455 LHSExp = Materialized.get();
5456 }
5457 VK = LHSExp->getValueKind();
5458 if (VK != VK_PRValue)
5459 OK = OK_VectorComponent;
5460
5461 QualType BaseType = BaseExpr->getType();
5462 Qualifiers BaseQuals = BaseType.getQualifiers();
5463 Qualifiers MemberQuals = ResultType.getQualifiers();
5464 Qualifiers Combined = BaseQuals + MemberQuals;
5465 if (Combined != MemberQuals)
5466 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5467 } else if (LHSTy->isArrayType()) {
5468 // If we see an array that wasn't promoted by
5469 // DefaultFunctionArrayLvalueConversion, it must be an array that
5470 // wasn't promoted because of the C90 rule that doesn't
5471 // allow promoting non-lvalue arrays. Warn, then
5472 // force the promotion here.
5473 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5474 << LHSExp->getSourceRange();
5475 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5476 CK: CK_ArrayToPointerDecay).get();
5477 LHSTy = LHSExp->getType();
5478
5479 BaseExpr = LHSExp;
5480 IndexExpr = RHSExp;
5481 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5482 } else if (RHSTy->isArrayType()) {
5483 // Same as previous, except for 123[f().a] case
5484 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5485 << RHSExp->getSourceRange();
5486 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5487 CK: CK_ArrayToPointerDecay).get();
5488 RHSTy = RHSExp->getType();
5489
5490 BaseExpr = RHSExp;
5491 IndexExpr = LHSExp;
5492 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5493 } else {
5494 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5495 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5496 }
5497 // C99 6.5.2.1p1
5498 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5499 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5500 << IndexExpr->getSourceRange());
5501
5502 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5503 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5504 !IndexExpr->isTypeDependent()) {
5505 std::optional<llvm::APSInt> IntegerContantExpr =
5506 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5507 if (!IntegerContantExpr.has_value() ||
5508 IntegerContantExpr.value().isNegative())
5509 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5510 }
5511
5512 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5513 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5514 // type. Note that Functions are not objects, and that (in C99 parlance)
5515 // incomplete types are not object types.
5516 if (ResultType->isFunctionType()) {
5517 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5518 << ResultType << BaseExpr->getSourceRange();
5519 return ExprError();
5520 }
5521
5522 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5523 // GNU extension: subscripting on pointer to void
5524 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5525 << BaseExpr->getSourceRange();
5526
5527 // C forbids expressions of unqualified void type from being l-values.
5528 // See IsCForbiddenLValueType.
5529 if (!ResultType.hasQualifiers())
5530 VK = VK_PRValue;
5531 } else if (!ResultType->isDependentType() &&
5532 !ResultType.isWebAssemblyReferenceType() &&
5533 RequireCompleteSizedType(
5534 Loc: LLoc, T: ResultType,
5535 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5536 return ExprError();
5537
5538 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5539 !ResultType.isCForbiddenLValueType());
5540
5541 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5542 FunctionScopes.size() > 1) {
5543 if (auto *TT =
5544 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5545 for (auto I = FunctionScopes.rbegin(),
5546 E = std::prev(x: FunctionScopes.rend());
5547 I != E; ++I) {
5548 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5549 if (CSI == nullptr)
5550 break;
5551 DeclContext *DC = nullptr;
5552 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5553 DC = LSI->CallOperator;
5554 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5555 DC = CRSI->TheCapturedDecl;
5556 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5557 DC = BSI->TheDecl;
5558 if (DC) {
5559 if (DC->containsDecl(D: TT->getDecl()))
5560 break;
5561 captureVariablyModifiedType(
5562 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5563 }
5564 }
5565 }
5566 }
5567
5568 return new (Context)
5569 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5570}
5571
5572bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5573 ParmVarDecl *Param, Expr *RewrittenInit,
5574 bool SkipImmediateInvocations) {
5575 if (Param->hasUnparsedDefaultArg()) {
5576 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5577 // If we've already cleared out the location for the default argument,
5578 // that means we're parsing it right now.
5579 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5580 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5581 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5582 Param->setInvalidDecl();
5583 return true;
5584 }
5585
5586 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5587 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5588 Diag(Loc: UnparsedDefaultArgLocs[Param],
5589 DiagID: diag::note_default_argument_declared_here);
5590 return true;
5591 }
5592
5593 if (Param->hasUninstantiatedDefaultArg()) {
5594 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5595 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5596 return true;
5597 }
5598
5599 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5600 assert(Init && "default argument but no initializer?");
5601
5602 // If the default expression creates temporaries, we need to
5603 // push them to the current stack of expression temporaries so they'll
5604 // be properly destroyed.
5605 // FIXME: We should really be rebuilding the default argument with new
5606 // bound temporaries; see the comment in PR5810.
5607 // We don't need to do that with block decls, though, because
5608 // blocks in default argument expression can never capture anything.
5609 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5610 // Set the "needs cleanups" bit regardless of whether there are
5611 // any explicit objects.
5612 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5613 // Append all the objects to the cleanup list. Right now, this
5614 // should always be a no-op, because blocks in default argument
5615 // expressions should never be able to capture anything.
5616 assert(!InitWithCleanup->getNumObjects() &&
5617 "default argument expression has capturing blocks?");
5618 }
5619 // C++ [expr.const]p15.1:
5620 // An expression or conversion is in an immediate function context if it is
5621 // potentially evaluated and [...] its innermost enclosing non-block scope
5622 // is a function parameter scope of an immediate function.
5623 EnterExpressionEvaluationContext EvalContext(
5624 *this,
5625 FD->isImmediateFunction()
5626 ? ExpressionEvaluationContext::ImmediateFunctionContext
5627 : ExpressionEvaluationContext::PotentiallyEvaluated,
5628 Param);
5629 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5630 SkipImmediateInvocations;
5631 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5632 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5633 });
5634 return false;
5635}
5636
5637struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5638 const ASTContext &Context;
5639 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5640 ShouldVisitImplicitCode = true;
5641 }
5642
5643 bool HasImmediateCalls = false;
5644
5645 bool VisitCallExpr(CallExpr *E) override {
5646 if (const FunctionDecl *FD = E->getDirectCallee())
5647 HasImmediateCalls |= FD->isImmediateFunction();
5648 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5649 }
5650
5651 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5652 if (const FunctionDecl *FD = E->getConstructor())
5653 HasImmediateCalls |= FD->isImmediateFunction();
5654 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5655 }
5656
5657 // SourceLocExpr are not immediate invocations
5658 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5659 // need to be rebuilt so that they refer to the correct SourceLocation and
5660 // DeclContext.
5661 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5662 HasImmediateCalls = true;
5663 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5664 }
5665
5666 // A nested lambda might have parameters with immediate invocations
5667 // in their default arguments.
5668 // The compound statement is not visited (as it does not constitute a
5669 // subexpression).
5670 // FIXME: We should consider visiting and transforming captures
5671 // with init expressions.
5672 bool VisitLambdaExpr(LambdaExpr *E) override {
5673 return VisitCXXMethodDecl(D: E->getCallOperator());
5674 }
5675
5676 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5677 return TraverseStmt(S: E->getExpr());
5678 }
5679
5680 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5681 return TraverseStmt(S: E->getExpr());
5682 }
5683};
5684
5685struct EnsureImmediateInvocationInDefaultArgs
5686 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5687 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5688 : TreeTransform(SemaRef) {}
5689
5690 bool AlwaysRebuild() { return true; }
5691
5692 // Lambda can only have immediate invocations in the default
5693 // args of their parameters, which is transformed upon calling the closure.
5694 // The body is not a subexpression, so we have nothing to do.
5695 // FIXME: Immediate calls in capture initializers should be transformed.
5696 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5697 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5698
5699 // Make sure we don't rebuild the this pointer as it would
5700 // cause it to incorrectly point it to the outermost class
5701 // in the case of nested struct initialization.
5702 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5703
5704 // Rewrite to source location to refer to the context in which they are used.
5705 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5706 DeclContext *DC = E->getParentContext();
5707 if (DC == SemaRef.CurContext)
5708 return E;
5709
5710 // FIXME: During instantiation, because the rebuild of defaults arguments
5711 // is not always done in the context of the template instantiator,
5712 // we run the risk of producing a dependent source location
5713 // that would never be rebuilt.
5714 // This usually happens during overload resolution, or in contexts
5715 // where the value of the source location does not matter.
5716 // However, we should find a better way to deal with source location
5717 // of function templates.
5718 if (!SemaRef.CurrentInstantiationScope ||
5719 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5720 DC = SemaRef.CurContext;
5721
5722 return getDerived().RebuildSourceLocExpr(
5723 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5724 }
5725};
5726
5727ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5728 FunctionDecl *FD, ParmVarDecl *Param,
5729 Expr *Init) {
5730 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5731
5732 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5733 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5734 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5735 InitializationContext =
5736 OutermostDeclarationWithDelayedImmediateInvocations();
5737 if (!InitializationContext.has_value())
5738 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5739
5740 if (!Init && !Param->hasUnparsedDefaultArg()) {
5741 // Mark that we are replacing a default argument first.
5742 // If we are instantiating a template we won't have to
5743 // retransform immediate calls.
5744 // C++ [expr.const]p15.1:
5745 // An expression or conversion is in an immediate function context if it
5746 // is potentially evaluated and [...] its innermost enclosing non-block
5747 // scope is a function parameter scope of an immediate function.
5748 EnterExpressionEvaluationContext EvalContext(
5749 *this,
5750 FD->isImmediateFunction()
5751 ? ExpressionEvaluationContext::ImmediateFunctionContext
5752 : ExpressionEvaluationContext::PotentiallyEvaluated,
5753 Param);
5754
5755 if (Param->hasUninstantiatedDefaultArg()) {
5756 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5757 return ExprError();
5758 }
5759 // CWG2631
5760 // An immediate invocation that is not evaluated where it appears is
5761 // evaluated and checked for whether it is a constant expression at the
5762 // point where the enclosing initializer is used in a function call.
5763 ImmediateCallVisitor V(getASTContext());
5764 if (!NestedDefaultChecking)
5765 V.TraverseDecl(D: Param);
5766
5767 // Rewrite the call argument that was created from the corresponding
5768 // parameter's default argument.
5769 if (V.HasImmediateCalls ||
5770 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5771 if (V.HasImmediateCalls)
5772 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5773 CallLoc, Param, CurContext};
5774 // Pass down lifetime extending flag, and collect temporaries in
5775 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5776 currentEvaluationContext().InLifetimeExtendingContext =
5777 parentEvaluationContext().InLifetimeExtendingContext;
5778 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5779 ExprResult Res;
5780 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5781 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5782 /*NotCopy=*/NotCopyInit: false);
5783 });
5784 if (Res.isInvalid())
5785 return ExprError();
5786 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5787 EqualLoc: Res.get()->getBeginLoc());
5788 if (Res.isInvalid())
5789 return ExprError();
5790 Init = Res.get();
5791 }
5792 }
5793
5794 if (CheckCXXDefaultArgExpr(
5795 CallLoc, FD, Param, RewrittenInit: Init,
5796 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5797 return ExprError();
5798
5799 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5800 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5801}
5802
5803static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5804 FieldDecl *Field) {
5805 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5806 return Pattern;
5807 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5808 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5809 DeclContext::lookup_result Lookup =
5810 ClassPattern->lookup(Name: Field->getDeclName());
5811 auto Rng = llvm::make_filter_range(
5812 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5813 if (Rng.empty())
5814 return nullptr;
5815 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5816 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5817 // && "Duplicated instantiation pattern for field decl");
5818 return cast<FieldDecl>(Val: *Rng.begin());
5819}
5820
5821ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5822 assert(Field->hasInClassInitializer());
5823
5824 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5825
5826 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5827
5828 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5829 InitializationContext =
5830 OutermostDeclarationWithDelayedImmediateInvocations();
5831 if (!InitializationContext.has_value())
5832 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5833
5834 Expr *Init = nullptr;
5835
5836 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5837 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5838 EnterExpressionEvaluationContext EvalContext(
5839 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5840
5841 if (!Field->getInClassInitializer()) {
5842 // Maybe we haven't instantiated the in-class initializer. Go check the
5843 // pattern FieldDecl to see if it has one.
5844 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5845 FieldDecl *Pattern =
5846 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5847 assert(Pattern && "We must have set the Pattern!");
5848 if (!Pattern->hasInClassInitializer() ||
5849 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5850 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5851 Field->setInvalidDecl();
5852 return ExprError();
5853 }
5854 }
5855 }
5856
5857 // CWG2631
5858 // An immediate invocation that is not evaluated where it appears is
5859 // evaluated and checked for whether it is a constant expression at the
5860 // point where the enclosing initializer is used in a [...] a constructor
5861 // definition, or an aggregate initialization.
5862 ImmediateCallVisitor V(getASTContext());
5863 if (!NestedDefaultChecking)
5864 V.TraverseDecl(D: Field);
5865
5866 // CWG1815
5867 // Support lifetime extension of temporary created by aggregate
5868 // initialization using a default member initializer. We should rebuild
5869 // the initializer in a lifetime extension context if the initializer
5870 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5871 // extension code recurses into the default initializer and does lifetime
5872 // extension when warranted.
5873 bool ContainsAnyTemporaries =
5874 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5875 if (Field->getInClassInitializer() &&
5876 !Field->getInClassInitializer()->containsErrors() &&
5877 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5878 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5879 CurContext};
5880 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5881 NestedDefaultChecking;
5882 // Pass down lifetime extending flag, and collect temporaries in
5883 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5884 currentEvaluationContext().InLifetimeExtendingContext =
5885 parentEvaluationContext().InLifetimeExtendingContext;
5886 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5887 ExprResult Res;
5888 runWithSufficientStackSpace(Loc, Fn: [&] {
5889 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5890 /*CXXDirectInit=*/NotCopyInit: false);
5891 });
5892 if (!Res.isInvalid())
5893 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5894 if (Res.isInvalid()) {
5895 Field->setInvalidDecl();
5896 return ExprError();
5897 }
5898 Init = Res.get();
5899 }
5900
5901 if (Field->getInClassInitializer()) {
5902 Expr *E = Init ? Init : Field->getInClassInitializer();
5903 if (!NestedDefaultChecking)
5904 runWithSufficientStackSpace(Loc, Fn: [&] {
5905 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5906 });
5907 if (isInLifetimeExtendingContext())
5908 DiscardCleanupsInEvaluationContext();
5909 // C++11 [class.base.init]p7:
5910 // The initialization of each base and member constitutes a
5911 // full-expression.
5912 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5913 if (Res.isInvalid()) {
5914 Field->setInvalidDecl();
5915 return ExprError();
5916 }
5917 Init = Res.get();
5918
5919 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5920 Field, UsedContext: InitializationContext->Context,
5921 RewrittenInitExpr: Init);
5922 }
5923
5924 // DR1351:
5925 // If the brace-or-equal-initializer of a non-static data member
5926 // invokes a defaulted default constructor of its class or of an
5927 // enclosing class in a potentially evaluated subexpression, the
5928 // program is ill-formed.
5929 //
5930 // This resolution is unworkable: the exception specification of the
5931 // default constructor can be needed in an unevaluated context, in
5932 // particular, in the operand of a noexcept-expression, and we can be
5933 // unable to compute an exception specification for an enclosed class.
5934 //
5935 // Any attempt to resolve the exception specification of a defaulted default
5936 // constructor before the initializer is lexically complete will ultimately
5937 // come here at which point we can diagnose it.
5938 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5939 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5940 << OutermostClass << Field;
5941 Diag(Loc: Field->getEndLoc(),
5942 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5943 // Recover by marking the field invalid, unless we're in a SFINAE context.
5944 if (!isSFINAEContext())
5945 Field->setInvalidDecl();
5946 return ExprError();
5947}
5948
5949VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5950 const FunctionProtoType *Proto,
5951 Expr *Fn) {
5952 if (Proto && Proto->isVariadic()) {
5953 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
5954 return VariadicCallType::Constructor;
5955 else if (Fn && Fn->getType()->isBlockPointerType())
5956 return VariadicCallType::Block;
5957 else if (FDecl) {
5958 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
5959 if (Method->isInstance())
5960 return VariadicCallType::Method;
5961 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5962 return VariadicCallType::Method;
5963 return VariadicCallType::Function;
5964 }
5965 return VariadicCallType::DoesNotApply;
5966}
5967
5968namespace {
5969class FunctionCallCCC final : public FunctionCallFilterCCC {
5970public:
5971 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5972 unsigned NumArgs, MemberExpr *ME)
5973 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5974 FunctionName(FuncName) {}
5975
5976 bool ValidateCandidate(const TypoCorrection &candidate) override {
5977 if (!candidate.getCorrectionSpecifier() ||
5978 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5979 return false;
5980 }
5981
5982 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5983 }
5984
5985 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5986 return std::make_unique<FunctionCallCCC>(args&: *this);
5987 }
5988
5989private:
5990 const IdentifierInfo *const FunctionName;
5991};
5992}
5993
5994static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5995 FunctionDecl *FDecl,
5996 ArrayRef<Expr *> Args) {
5997 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
5998 DeclarationName FuncName = FDecl->getDeclName();
5999 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6000
6001 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6002 if (TypoCorrection Corrected = S.CorrectTypo(
6003 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6004 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6005 Mode: CorrectTypoKind::ErrorRecovery)) {
6006 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6007 if (Corrected.isOverloaded()) {
6008 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6009 OverloadCandidateSet::iterator Best;
6010 for (NamedDecl *CD : Corrected) {
6011 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6012 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6013 CandidateSet&: OCS);
6014 }
6015 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6016 case OR_Success:
6017 ND = Best->FoundDecl;
6018 Corrected.setCorrectionDecl(ND);
6019 break;
6020 default:
6021 break;
6022 }
6023 }
6024 ND = ND->getUnderlyingDecl();
6025 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6026 return Corrected;
6027 }
6028 }
6029 return TypoCorrection();
6030}
6031
6032// [C++26][[expr.unary.op]/p4
6033// A pointer to member is only formed when an explicit &
6034// is used and its operand is a qualified-id not enclosed in parentheses.
6035static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6036 if (!isa<ParenExpr>(Val: Fn))
6037 return false;
6038
6039 Fn = Fn->IgnoreParens();
6040
6041 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6042 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6043 return false;
6044 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6045 return DRE->hasQualifier();
6046 }
6047 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6048 return bool(OVL->getQualifier());
6049 return false;
6050}
6051
6052bool
6053Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6054 FunctionDecl *FDecl,
6055 const FunctionProtoType *Proto,
6056 ArrayRef<Expr *> Args,
6057 SourceLocation RParenLoc,
6058 bool IsExecConfig) {
6059 // Bail out early if calling a builtin with custom typechecking.
6060 if (FDecl)
6061 if (unsigned ID = FDecl->getBuiltinID())
6062 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6063 return false;
6064
6065 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6066 // assignment, to the types of the corresponding parameter, ...
6067
6068 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6069 bool HasExplicitObjectParameter =
6070 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6071 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6072 unsigned NumParams = Proto->getNumParams();
6073 bool Invalid = false;
6074 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6075 unsigned FnKind = Fn->getType()->isBlockPointerType()
6076 ? 1 /* block */
6077 : (IsExecConfig ? 3 /* kernel function (exec config) */
6078 : 0 /* function */);
6079
6080 // If too few arguments are available (and we don't have default
6081 // arguments for the remaining parameters), don't make the call.
6082 if (Args.size() < NumParams) {
6083 if (Args.size() < MinArgs) {
6084 TypoCorrection TC;
6085 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6086 unsigned diag_id =
6087 MinArgs == NumParams && !Proto->isVariadic()
6088 ? diag::err_typecheck_call_too_few_args_suggest
6089 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6090 diagnoseTypo(
6091 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6092 << FnKind << MinArgs - ExplicitObjectParameterOffset
6093 << static_cast<unsigned>(Args.size()) -
6094 ExplicitObjectParameterOffset
6095 << HasExplicitObjectParameter << TC.getCorrectionRange());
6096 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6097 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6098 ->getDeclName())
6099 Diag(Loc: RParenLoc,
6100 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6101 ? diag::err_typecheck_call_too_few_args_one
6102 : diag::err_typecheck_call_too_few_args_at_least_one)
6103 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6104 << HasExplicitObjectParameter << Fn->getSourceRange();
6105 else
6106 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6107 ? diag::err_typecheck_call_too_few_args
6108 : diag::err_typecheck_call_too_few_args_at_least)
6109 << FnKind << MinArgs - ExplicitObjectParameterOffset
6110 << static_cast<unsigned>(Args.size()) -
6111 ExplicitObjectParameterOffset
6112 << HasExplicitObjectParameter << Fn->getSourceRange();
6113
6114 // Emit the location of the prototype.
6115 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6116 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6117 << FDecl << FDecl->getParametersSourceRange();
6118
6119 return true;
6120 }
6121 // We reserve space for the default arguments when we create
6122 // the call expression, before calling ConvertArgumentsForCall.
6123 assert((Call->getNumArgs() == NumParams) &&
6124 "We should have reserved space for the default arguments before!");
6125 }
6126
6127 // If too many are passed and not variadic, error on the extras and drop
6128 // them.
6129 if (Args.size() > NumParams) {
6130 if (!Proto->isVariadic()) {
6131 TypoCorrection TC;
6132 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6133 unsigned diag_id =
6134 MinArgs == NumParams && !Proto->isVariadic()
6135 ? diag::err_typecheck_call_too_many_args_suggest
6136 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6137 diagnoseTypo(
6138 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6139 << FnKind << NumParams - ExplicitObjectParameterOffset
6140 << static_cast<unsigned>(Args.size()) -
6141 ExplicitObjectParameterOffset
6142 << HasExplicitObjectParameter << TC.getCorrectionRange());
6143 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6144 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6145 ->getDeclName())
6146 Diag(Loc: Args[NumParams]->getBeginLoc(),
6147 DiagID: MinArgs == NumParams
6148 ? diag::err_typecheck_call_too_many_args_one
6149 : diag::err_typecheck_call_too_many_args_at_most_one)
6150 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6151 << static_cast<unsigned>(Args.size()) -
6152 ExplicitObjectParameterOffset
6153 << HasExplicitObjectParameter << Fn->getSourceRange()
6154 << SourceRange(Args[NumParams]->getBeginLoc(),
6155 Args.back()->getEndLoc());
6156 else
6157 Diag(Loc: Args[NumParams]->getBeginLoc(),
6158 DiagID: MinArgs == NumParams
6159 ? diag::err_typecheck_call_too_many_args
6160 : diag::err_typecheck_call_too_many_args_at_most)
6161 << FnKind << NumParams - ExplicitObjectParameterOffset
6162 << static_cast<unsigned>(Args.size()) -
6163 ExplicitObjectParameterOffset
6164 << HasExplicitObjectParameter << Fn->getSourceRange()
6165 << SourceRange(Args[NumParams]->getBeginLoc(),
6166 Args.back()->getEndLoc());
6167
6168 // Emit the location of the prototype.
6169 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6170 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6171 << FDecl << FDecl->getParametersSourceRange();
6172
6173 // This deletes the extra arguments.
6174 Call->shrinkNumArgs(NewNumArgs: NumParams);
6175 return true;
6176 }
6177 }
6178 SmallVector<Expr *, 8> AllArgs;
6179 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6180
6181 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6182 AllArgs, CallType);
6183 if (Invalid)
6184 return true;
6185 unsigned TotalNumArgs = AllArgs.size();
6186 for (unsigned i = 0; i < TotalNumArgs; ++i)
6187 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6188
6189 Call->computeDependence();
6190 return false;
6191}
6192
6193bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6194 const FunctionProtoType *Proto,
6195 unsigned FirstParam, ArrayRef<Expr *> Args,
6196 SmallVectorImpl<Expr *> &AllArgs,
6197 VariadicCallType CallType, bool AllowExplicit,
6198 bool IsListInitialization) {
6199 unsigned NumParams = Proto->getNumParams();
6200 bool Invalid = false;
6201 size_t ArgIx = 0;
6202 // Continue to check argument types (even if we have too few/many args).
6203 for (unsigned i = FirstParam; i < NumParams; i++) {
6204 QualType ProtoArgType = Proto->getParamType(i);
6205
6206 Expr *Arg;
6207 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6208 if (ArgIx < Args.size()) {
6209 Arg = Args[ArgIx++];
6210
6211 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6212 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6213 return true;
6214
6215 // Strip the unbridged-cast placeholder expression off, if applicable.
6216 bool CFAudited = false;
6217 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6218 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6219 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6220 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6221 else if (getLangOpts().ObjCAutoRefCount &&
6222 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6223 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6224 CFAudited = true;
6225
6226 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6227 ProtoArgType->isBlockPointerType())
6228 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6229 BE->getBlockDecl()->setDoesNotEscape();
6230 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6231 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6232 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6233 if (ArgExpr.isInvalid())
6234 return true;
6235 Arg = ArgExpr.getAs<Expr>();
6236 }
6237
6238 InitializedEntity Entity =
6239 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6240 Type: ProtoArgType)
6241 : InitializedEntity::InitializeParameter(
6242 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6243
6244 // Remember that parameter belongs to a CF audited API.
6245 if (CFAudited)
6246 Entity.setParameterCFAudited();
6247
6248 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6249 // function boundaries is a common oversight.
6250 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6251 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6252 bool isPedantic =
6253 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6254 Diag(Loc: Arg->getExprLoc(),
6255 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6256 : diag::warn_obt_discarded_at_function_boundary)
6257 << Arg->getType() << ProtoArgType;
6258 }
6259
6260 ExprResult ArgE = PerformCopyInitialization(
6261 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6262 if (ArgE.isInvalid())
6263 return true;
6264
6265 Arg = ArgE.getAs<Expr>();
6266 } else {
6267 assert(Param && "can't use default arguments without a known callee");
6268
6269 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6270 if (ArgExpr.isInvalid())
6271 return true;
6272
6273 Arg = ArgExpr.getAs<Expr>();
6274 }
6275
6276 // Check for array bounds violations for each argument to the call. This
6277 // check only triggers warnings when the argument isn't a more complex Expr
6278 // with its own checking, such as a BinaryOperator.
6279 CheckArrayAccess(E: Arg);
6280
6281 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6282 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6283
6284 AllArgs.push_back(Elt: Arg);
6285 }
6286
6287 // If this is a variadic call, handle args passed through "...".
6288 if (CallType != VariadicCallType::DoesNotApply) {
6289 // Assume that extern "C" functions with variadic arguments that
6290 // return __unknown_anytype aren't *really* variadic.
6291 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6292 FDecl->isExternC()) {
6293 for (Expr *A : Args.slice(N: ArgIx)) {
6294 QualType paramType; // ignored
6295 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6296 Invalid |= arg.isInvalid();
6297 AllArgs.push_back(Elt: arg.get());
6298 }
6299
6300 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6301 } else {
6302 for (Expr *A : Args.slice(N: ArgIx)) {
6303 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6304 Invalid |= Arg.isInvalid();
6305 AllArgs.push_back(Elt: Arg.get());
6306 }
6307 }
6308
6309 // Check for array bounds violations.
6310 for (Expr *A : Args.slice(N: ArgIx))
6311 CheckArrayAccess(E: A);
6312 }
6313 return Invalid;
6314}
6315
6316static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6317 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6318 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6319 TL = DTL.getOriginalLoc();
6320 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6321 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6322 << ATL.getLocalSourceRange();
6323}
6324
6325void
6326Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6327 ParmVarDecl *Param,
6328 const Expr *ArgExpr) {
6329 // Static array parameters are not supported in C++.
6330 if (!Param || getLangOpts().CPlusPlus)
6331 return;
6332
6333 QualType OrigTy = Param->getOriginalType();
6334
6335 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6336 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6337 return;
6338
6339 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6340 NPC: Expr::NPC_NeverValueDependent)) {
6341 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6342 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6343 return;
6344 }
6345
6346 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6347 if (!CAT)
6348 return;
6349
6350 const ConstantArrayType *ArgCAT =
6351 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6352 if (!ArgCAT)
6353 return;
6354
6355 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6356 T2: ArgCAT->getElementType())) {
6357 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6358 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6359 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6360 << (unsigned)CAT->getZExtSize() << 0;
6361 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6362 }
6363 return;
6364 }
6365
6366 std::optional<CharUnits> ArgSize =
6367 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6368 std::optional<CharUnits> ParmSize =
6369 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6370 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6371 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6372 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6373 << (unsigned)ParmSize->getQuantity() << 1;
6374 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6375 }
6376}
6377
6378/// Given a function expression of unknown-any type, try to rebuild it
6379/// to have a function type.
6380static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6381
6382/// Is the given type a placeholder that we need to lower out
6383/// immediately during argument processing?
6384static bool isPlaceholderToRemoveAsArg(QualType type) {
6385 // Placeholders are never sugared.
6386 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6387 if (!placeholder) return false;
6388
6389 switch (placeholder->getKind()) {
6390 // Ignore all the non-placeholder types.
6391#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6392 case BuiltinType::Id:
6393#include "clang/Basic/OpenCLImageTypes.def"
6394#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6395 case BuiltinType::Id:
6396#include "clang/Basic/OpenCLExtensionTypes.def"
6397 // In practice we'll never use this, since all SVE types are sugared
6398 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6399#define SVE_TYPE(Name, Id, SingletonId) \
6400 case BuiltinType::Id:
6401#include "clang/Basic/AArch64ACLETypes.def"
6402#define PPC_VECTOR_TYPE(Name, Id, Size) \
6403 case BuiltinType::Id:
6404#include "clang/Basic/PPCTypes.def"
6405#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6406#include "clang/Basic/RISCVVTypes.def"
6407#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6408#include "clang/Basic/WebAssemblyReferenceTypes.def"
6409#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6410#include "clang/Basic/AMDGPUTypes.def"
6411#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6412#include "clang/Basic/HLSLIntangibleTypes.def"
6413#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6414#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6415#include "clang/AST/BuiltinTypes.def"
6416 return false;
6417
6418 case BuiltinType::UnresolvedTemplate:
6419 // We cannot lower out overload sets; they might validly be resolved
6420 // by the call machinery.
6421 case BuiltinType::Overload:
6422 return false;
6423
6424 // Unbridged casts in ARC can be handled in some call positions and
6425 // should be left in place.
6426 case BuiltinType::ARCUnbridgedCast:
6427 return false;
6428
6429 // Pseudo-objects should be converted as soon as possible.
6430 case BuiltinType::PseudoObject:
6431 return true;
6432
6433 // The debugger mode could theoretically but currently does not try
6434 // to resolve unknown-typed arguments based on known parameter types.
6435 case BuiltinType::UnknownAny:
6436 return true;
6437
6438 // These are always invalid as call arguments and should be reported.
6439 case BuiltinType::BoundMember:
6440 case BuiltinType::BuiltinFn:
6441 case BuiltinType::IncompleteMatrixIdx:
6442 case BuiltinType::ArraySection:
6443 case BuiltinType::OMPArrayShaping:
6444 case BuiltinType::OMPIterator:
6445 return true;
6446
6447 }
6448 llvm_unreachable("bad builtin type kind");
6449}
6450
6451bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6452 // Apply this processing to all the arguments at once instead of
6453 // dying at the first failure.
6454 bool hasInvalid = false;
6455 for (size_t i = 0, e = args.size(); i != e; i++) {
6456 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6457 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6458 if (result.isInvalid()) hasInvalid = true;
6459 else args[i] = result.get();
6460 }
6461 }
6462 return hasInvalid;
6463}
6464
6465/// If a builtin function has a pointer argument with no explicit address
6466/// space, then it should be able to accept a pointer to any address
6467/// space as input. In order to do this, we need to replace the
6468/// standard builtin declaration with one that uses the same address space
6469/// as the call.
6470///
6471/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6472/// it does not contain any pointer arguments without
6473/// an address space qualifer. Otherwise the rewritten
6474/// FunctionDecl is returned.
6475/// TODO: Handle pointer return types.
6476static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6477 FunctionDecl *FDecl,
6478 MultiExprArg ArgExprs) {
6479
6480 QualType DeclType = FDecl->getType();
6481 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6482
6483 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6484 ArgExprs.size() < FT->getNumParams())
6485 return nullptr;
6486
6487 bool NeedsNewDecl = false;
6488 unsigned i = 0;
6489 SmallVector<QualType, 8> OverloadParams;
6490
6491 {
6492 // The lvalue conversions in this loop are only for type resolution and
6493 // don't actually occur.
6494 EnterExpressionEvaluationContext Unevaluated(
6495 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6496 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6497
6498 for (QualType ParamType : FT->param_types()) {
6499
6500 // Convert array arguments to pointer to simplify type lookup.
6501 ExprResult ArgRes =
6502 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6503 if (ArgRes.isInvalid())
6504 return nullptr;
6505 Expr *Arg = ArgRes.get();
6506 QualType ArgType = Arg->getType();
6507 if (!ParamType->isPointerType() ||
6508 ParamType->getPointeeType().hasAddressSpace() ||
6509 !ArgType->isPointerType() ||
6510 !ArgType->getPointeeType().hasAddressSpace() ||
6511 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6512 OverloadParams.push_back(Elt: ParamType);
6513 continue;
6514 }
6515
6516 QualType PointeeType = ParamType->getPointeeType();
6517 NeedsNewDecl = true;
6518 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6519
6520 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6521 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6522 }
6523 }
6524
6525 if (!NeedsNewDecl)
6526 return nullptr;
6527
6528 FunctionProtoType::ExtProtoInfo EPI;
6529 EPI.Variadic = FT->isVariadic();
6530 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6531 Args: OverloadParams, EPI);
6532 DeclContext *Parent = FDecl->getParent();
6533 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6534 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6535 N: FDecl->getIdentifier(), T: OverloadTy,
6536 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6537 isInlineSpecified: false,
6538 /*hasPrototype=*/hasWrittenPrototype: true);
6539 SmallVector<ParmVarDecl*, 16> Params;
6540 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6541 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6542 QualType ParamType = FT->getParamType(i);
6543 ParmVarDecl *Parm =
6544 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6545 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6546 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6547 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6548 Params.push_back(Elt: Parm);
6549 }
6550 OverloadDecl->setParams(Params);
6551 // We cannot merge host/device attributes of redeclarations. They have to
6552 // be consistent when created.
6553 if (Sema->LangOpts.CUDA) {
6554 if (FDecl->hasAttr<CUDAHostAttr>())
6555 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6556 if (FDecl->hasAttr<CUDADeviceAttr>())
6557 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6558 }
6559 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6560 return OverloadDecl;
6561}
6562
6563static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6564 FunctionDecl *Callee,
6565 MultiExprArg ArgExprs) {
6566 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6567 // similar attributes) really don't like it when functions are called with an
6568 // invalid number of args.
6569 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6570 /*PartialOverloading=*/false) &&
6571 !Callee->isVariadic())
6572 return;
6573 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6574 return;
6575
6576 if (const EnableIfAttr *Attr =
6577 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6578 S.Diag(Loc: Fn->getBeginLoc(),
6579 DiagID: isa<CXXMethodDecl>(Val: Callee)
6580 ? diag::err_ovl_no_viable_member_function_in_call
6581 : diag::err_ovl_no_viable_function_in_call)
6582 << Callee << Callee->getSourceRange();
6583 S.Diag(Loc: Callee->getLocation(),
6584 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6585 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6586 return;
6587 }
6588}
6589
6590static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6591 const UnresolvedMemberExpr *const UME, Sema &S) {
6592
6593 const auto GetFunctionLevelDCIfCXXClass =
6594 [](Sema &S) -> const CXXRecordDecl * {
6595 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6596 if (!DC || !DC->getParent())
6597 return nullptr;
6598
6599 // If the call to some member function was made from within a member
6600 // function body 'M' return return 'M's parent.
6601 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6602 return MD->getParent()->getCanonicalDecl();
6603 // else the call was made from within a default member initializer of a
6604 // class, so return the class.
6605 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6606 return RD->getCanonicalDecl();
6607 return nullptr;
6608 };
6609 // If our DeclContext is neither a member function nor a class (in the
6610 // case of a lambda in a default member initializer), we can't have an
6611 // enclosing 'this'.
6612
6613 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6614 if (!CurParentClass)
6615 return false;
6616
6617 // The naming class for implicit member functions call is the class in which
6618 // name lookup starts.
6619 const CXXRecordDecl *const NamingClass =
6620 UME->getNamingClass()->getCanonicalDecl();
6621 assert(NamingClass && "Must have naming class even for implicit access");
6622
6623 // If the unresolved member functions were found in a 'naming class' that is
6624 // related (either the same or derived from) to the class that contains the
6625 // member function that itself contained the implicit member access.
6626
6627 return CurParentClass == NamingClass ||
6628 CurParentClass->isDerivedFrom(Base: NamingClass);
6629}
6630
6631static void
6632tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6633 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6634
6635 if (!UME)
6636 return;
6637
6638 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6639 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6640 // already been captured, or if this is an implicit member function call (if
6641 // it isn't, an attempt to capture 'this' should already have been made).
6642 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6643 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6644 return;
6645
6646 // Check if the naming class in which the unresolved members were found is
6647 // related (same as or is a base of) to the enclosing class.
6648
6649 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6650 return;
6651
6652
6653 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6654 // If the enclosing function is not dependent, then this lambda is
6655 // capture ready, so if we can capture this, do so.
6656 if (!EnclosingFunctionCtx->isDependentContext()) {
6657 // If the current lambda and all enclosing lambdas can capture 'this' -
6658 // then go ahead and capture 'this' (since our unresolved overload set
6659 // contains at least one non-static member function).
6660 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6661 S.CheckCXXThisCapture(Loc: CallLoc);
6662 } else if (S.CurContext->isDependentContext()) {
6663 // ... since this is an implicit member reference, that might potentially
6664 // involve a 'this' capture, mark 'this' for potential capture in
6665 // enclosing lambdas.
6666 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6667 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6668 }
6669}
6670
6671// Once a call is fully resolved, warn for unqualified calls to specific
6672// C++ standard functions, like move and forward.
6673static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6674 const CallExpr *Call) {
6675 // We are only checking unary move and forward so exit early here.
6676 if (Call->getNumArgs() != 1)
6677 return;
6678
6679 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6680 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6681 return;
6682 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6683 if (!DRE || !DRE->getLocation().isValid())
6684 return;
6685
6686 if (DRE->getQualifier())
6687 return;
6688
6689 const FunctionDecl *FD = Call->getDirectCallee();
6690 if (!FD)
6691 return;
6692
6693 // Only warn for some functions deemed more frequent or problematic.
6694 unsigned BuiltinID = FD->getBuiltinID();
6695 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6696 return;
6697
6698 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6699 << FD->getQualifiedNameAsString()
6700 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6701}
6702
6703ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6704 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6705 Expr *ExecConfig) {
6706 ExprResult Call =
6707 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6708 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6709 if (Call.isInvalid())
6710 return Call;
6711
6712 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6713 // language modes.
6714 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6715 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6716 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6717 << ULE->getName();
6718 }
6719
6720 if (LangOpts.OpenMP)
6721 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6722 ExecConfig);
6723 if (LangOpts.CPlusPlus) {
6724 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6725 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6726
6727 // If we previously found that the id-expression of this call refers to a
6728 // consteval function but the call is dependent, we should not treat is an
6729 // an invalid immediate call.
6730 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6731 DRE && Call.get()->isValueDependent()) {
6732 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6733 }
6734 }
6735 return Call;
6736}
6737
6738// Any type that could be used to form a callable expression
6739static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6740 QualType T = E->getType();
6741 if (T->isDependentType())
6742 return true;
6743
6744 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6745 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6746 T->isFunctionType() || T->isFunctionReferenceType() ||
6747 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6748 T->isBlockPointerType() || T->isRecordType())
6749 return true;
6750
6751 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6752 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6753}
6754
6755ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6756 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6757 Expr *ExecConfig, bool IsExecConfig,
6758 bool AllowRecovery) {
6759 // Since this might be a postfix expression, get rid of ParenListExprs.
6760 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6761 if (Result.isInvalid()) return ExprError();
6762 Fn = Result.get();
6763
6764 if (CheckArgsForPlaceholders(args: ArgExprs))
6765 return ExprError();
6766
6767 // The result of __builtin_counted_by_ref cannot be used as a function
6768 // argument. It allows leaking and modification of bounds safety information.
6769 for (const Expr *Arg : ArgExprs)
6770 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6771 K: BuiltinCountedByRefKind::FunctionArg))
6772 return ExprError();
6773
6774 if (getLangOpts().CPlusPlus) {
6775 // If this is a pseudo-destructor expression, build the call immediately.
6776 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6777 if (!ArgExprs.empty()) {
6778 // Pseudo-destructor calls should not have any arguments.
6779 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6780 << FixItHint::CreateRemoval(
6781 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6782 ArgExprs.back()->getEndLoc()));
6783 }
6784
6785 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6786 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6787 }
6788 if (Fn->getType() == Context.PseudoObjectTy) {
6789 ExprResult result = CheckPlaceholderExpr(E: Fn);
6790 if (result.isInvalid()) return ExprError();
6791 Fn = result.get();
6792 }
6793
6794 // Determine whether this is a dependent call inside a C++ template,
6795 // in which case we won't do any semantic analysis now.
6796 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6797 if (ExecConfig) {
6798 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6799 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6800 Ty: Context.DependentTy, VK: VK_PRValue,
6801 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6802 } else {
6803
6804 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6805 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6806 CallLoc: Fn->getBeginLoc());
6807
6808 // If the type of the function itself is not dependent
6809 // check that it is a reasonable as a function, as type deduction
6810 // later assume the CallExpr has a sensible TYPE.
6811 if (!MayBeFunctionType(Context, E: Fn))
6812 return ExprError(
6813 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6814 << Fn->getType() << Fn->getSourceRange());
6815
6816 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6817 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6818 }
6819 }
6820
6821 // Determine whether this is a call to an object (C++ [over.call.object]).
6822 if (Fn->getType()->isRecordType())
6823 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6824 RParenLoc);
6825
6826 if (Fn->getType() == Context.UnknownAnyTy) {
6827 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6828 if (result.isInvalid()) return ExprError();
6829 Fn = result.get();
6830 }
6831
6832 if (Fn->getType() == Context.BoundMemberTy) {
6833 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6834 RParenLoc, ExecConfig, IsExecConfig,
6835 AllowRecovery);
6836 }
6837 }
6838
6839 // Check for overloaded calls. This can happen even in C due to extensions.
6840 if (Fn->getType() == Context.OverloadTy) {
6841 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6842
6843 // We aren't supposed to apply this logic if there's an '&' involved.
6844 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6845 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6846 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6847 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6848 OverloadExpr *ovl = find.Expression;
6849 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6850 return BuildOverloadedCallExpr(
6851 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6852 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6853 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6854 RParenLoc, ExecConfig, IsExecConfig,
6855 AllowRecovery);
6856 }
6857 }
6858
6859 // If we're directly calling a function, get the appropriate declaration.
6860 if (Fn->getType() == Context.UnknownAnyTy) {
6861 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6862 if (result.isInvalid()) return ExprError();
6863 Fn = result.get();
6864 }
6865
6866 Expr *NakedFn = Fn->IgnoreParens();
6867
6868 bool CallingNDeclIndirectly = false;
6869 NamedDecl *NDecl = nullptr;
6870 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6871 if (UnOp->getOpcode() == UO_AddrOf) {
6872 CallingNDeclIndirectly = true;
6873 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6874 }
6875 }
6876
6877 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6878 NDecl = DRE->getDecl();
6879
6880 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6881 if (FDecl && FDecl->getBuiltinID()) {
6882 // Rewrite the function decl for this builtin by replacing parameters
6883 // with no explicit address space with the address space of the arguments
6884 // in ArgExprs.
6885 if ((FDecl =
6886 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6887 NDecl = FDecl;
6888 Fn = DeclRefExpr::Create(
6889 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6890 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
6891 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6892 }
6893 }
6894 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6895 NDecl = ME->getMemberDecl();
6896
6897 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6898 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6899 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6900 return ExprError();
6901
6902 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6903
6904 // If this expression is a call to a builtin function in HIP compilation,
6905 // allow a pointer-type argument to default address space to be passed as a
6906 // pointer-type parameter to a non-default address space. If Arg is declared
6907 // in the default address space and Param is declared in a non-default
6908 // address space, perform an implicit address space cast to the parameter
6909 // type.
6910 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6911 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6912 ++Idx) {
6913 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
6914 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6915 !ArgExprs[Idx]->getType()->isPointerType())
6916 continue;
6917
6918 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6919 auto ArgTy = ArgExprs[Idx]->getType();
6920 auto ArgPtTy = ArgTy->getPointeeType();
6921 auto ArgAS = ArgPtTy.getAddressSpace();
6922
6923 // Add address space cast if target address spaces are different
6924 bool NeedImplicitASC =
6925 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6926 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6927 // or from specific AS which has target AS matching that of Param.
6928 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
6929 if (!NeedImplicitASC)
6930 continue;
6931
6932 // First, ensure that the Arg is an RValue.
6933 if (ArgExprs[Idx]->isGLValue()) {
6934 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
6935 if (Res.isInvalid())
6936 return ExprError();
6937 ArgExprs[Idx] = Res.get();
6938 }
6939
6940 // Construct a new arg type with address space of Param
6941 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6942 ArgPtQuals.setAddressSpace(ParamAS);
6943 auto NewArgPtTy =
6944 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
6945 auto NewArgTy =
6946 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
6947 Qs: ArgTy.getQualifiers());
6948
6949 // Finally perform an implicit address space cast
6950 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
6951 CK: CK_AddressSpaceConversion)
6952 .get();
6953 }
6954 }
6955 }
6956
6957 if (Context.isDependenceAllowed() &&
6958 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
6959 assert(!getLangOpts().CPlusPlus);
6960 assert((Fn->containsErrors() ||
6961 llvm::any_of(ArgExprs,
6962 [](clang::Expr *E) { return E->containsErrors(); })) &&
6963 "should only occur in error-recovery path.");
6964 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6965 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6966 }
6967 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
6968 Config: ExecConfig, IsExecConfig);
6969}
6970
6971Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6972 MultiExprArg CallArgs) {
6973 std::string Name = Context.BuiltinInfo.getName(ID: Id);
6974 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6975 Sema::LookupOrdinaryName);
6976 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
6977
6978 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6979 assert(BuiltInDecl && "failed to find builtin declaration");
6980
6981 ExprResult DeclRef =
6982 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
6983 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6984
6985 ExprResult Call =
6986 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
6987
6988 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6989 return Call.get();
6990}
6991
6992ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6993 SourceLocation BuiltinLoc,
6994 SourceLocation RParenLoc) {
6995 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
6996 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
6997}
6998
6999ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7000 SourceLocation BuiltinLoc,
7001 SourceLocation RParenLoc) {
7002 ExprValueKind VK = VK_PRValue;
7003 ExprObjectKind OK = OK_Ordinary;
7004 QualType SrcTy = E->getType();
7005 if (!SrcTy->isDependentType() &&
7006 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7007 return ExprError(
7008 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7009 << DestTy << SrcTy << E->getSourceRange());
7010 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7011}
7012
7013ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7014 SourceLocation BuiltinLoc,
7015 SourceLocation RParenLoc) {
7016 TypeSourceInfo *TInfo;
7017 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7018 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7019}
7020
7021ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7022 SourceLocation LParenLoc,
7023 ArrayRef<Expr *> Args,
7024 SourceLocation RParenLoc, Expr *Config,
7025 bool IsExecConfig, ADLCallKind UsesADL) {
7026 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7027 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7028
7029 auto IsSJLJ = [&] {
7030 switch (BuiltinID) {
7031 case Builtin::BI__builtin_longjmp:
7032 case Builtin::BI__builtin_setjmp:
7033 case Builtin::BI__sigsetjmp:
7034 case Builtin::BI_longjmp:
7035 case Builtin::BI_setjmp:
7036 case Builtin::BIlongjmp:
7037 case Builtin::BIsetjmp:
7038 case Builtin::BIsiglongjmp:
7039 case Builtin::BIsigsetjmp:
7040 return true;
7041 default:
7042 return false;
7043 }
7044 };
7045
7046 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7047 if (!CurrentDefer.empty() && IsSJLJ()) {
7048 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7049 // for more than just blocks (e.g. lambdas, nested classes...).
7050 Scope *DeferParent = CurrentDefer.back().first;
7051 Scope *Block = CurScope->getBlockParent();
7052 if (DeferParent->Contains(rhs: *CurScope) &&
7053 (!Block || !DeferParent->Contains(rhs: *Block)))
7054 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7055 }
7056
7057 // Functions with 'interrupt' attribute cannot be called directly.
7058 if (FDecl) {
7059 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7060 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7061 return ExprError();
7062 }
7063 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7064 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7065 return ExprError();
7066 }
7067 }
7068
7069 // X86 interrupt handlers may only call routines with attribute
7070 // no_caller_saved_registers since there is no efficient way to
7071 // save and restore the non-GPR state.
7072 if (auto *Caller = getCurFunctionDecl()) {
7073 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7074 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7075 const TargetInfo &TI = Context.getTargetInfo();
7076 bool HasNonGPRRegisters =
7077 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7078 if (HasNonGPRRegisters &&
7079 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7080 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7081 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7082 if (FDecl)
7083 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7084 }
7085 }
7086 }
7087
7088 // Extract the return type from the builtin function pointer type.
7089 QualType ResultTy;
7090 if (BuiltinID)
7091 ResultTy = FDecl->getCallResultType();
7092 else
7093 ResultTy = Context.BoolTy;
7094
7095 // Promote the function operand.
7096 // We special-case function promotion here because we only allow promoting
7097 // builtin functions to function pointers in the callee of a call.
7098 ExprResult Result;
7099 if (BuiltinID &&
7100 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7101 // FIXME Several builtins still have setType in
7102 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7103 // Builtins.td to ensure they are correct before removing setType calls.
7104 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7105 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7106 } else
7107 Result = CallExprUnaryConversions(E: Fn);
7108 if (Result.isInvalid())
7109 return ExprError();
7110 Fn = Result.get();
7111
7112 // Check for a valid function type, but only if it is not a builtin which
7113 // requires custom type checking. These will be handled by
7114 // CheckBuiltinFunctionCall below just after creation of the call expression.
7115 const FunctionType *FuncT = nullptr;
7116 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7117 retry:
7118 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7119 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7120 // have type pointer to function".
7121 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7122 if (!FuncT)
7123 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7124 << Fn->getType() << Fn->getSourceRange());
7125 } else if (const BlockPointerType *BPT =
7126 Fn->getType()->getAs<BlockPointerType>()) {
7127 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7128 } else {
7129 // Handle calls to expressions of unknown-any type.
7130 if (Fn->getType() == Context.UnknownAnyTy) {
7131 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7132 if (rewrite.isInvalid())
7133 return ExprError();
7134 Fn = rewrite.get();
7135 goto retry;
7136 }
7137
7138 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7139 << Fn->getType() << Fn->getSourceRange());
7140 }
7141 }
7142
7143 // Get the number of parameters in the function prototype, if any.
7144 // We will allocate space for max(Args.size(), NumParams) arguments
7145 // in the call expression.
7146 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7147 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7148
7149 CallExpr *TheCall;
7150 if (Config) {
7151 assert(UsesADL == ADLCallKind::NotADL &&
7152 "CUDAKernelCallExpr should not use ADL");
7153 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7154 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7155 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7156 } else {
7157 TheCall =
7158 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7159 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7160 }
7161
7162 // Bail out early if calling a builtin with custom type checking.
7163 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7164 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7165 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7166 E = CheckForImmediateInvocation(E, Decl: FDecl);
7167 return E;
7168 }
7169
7170 if (getLangOpts().CUDA) {
7171 if (Config) {
7172 // CUDA: Kernel calls must be to global functions
7173 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7174 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7175 << FDecl << Fn->getSourceRange());
7176
7177 // CUDA: Kernel function must have 'void' return type
7178 if (!FuncT->getReturnType()->isVoidType() &&
7179 !FuncT->getReturnType()->getAs<AutoType>() &&
7180 !FuncT->getReturnType()->isInstantiationDependentType())
7181 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7182 << Fn->getType() << Fn->getSourceRange());
7183 } else {
7184 // CUDA: Calls to global functions must be configured
7185 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7186 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7187 << FDecl << Fn->getSourceRange());
7188 }
7189 }
7190
7191 // Check for a valid return type
7192 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7193 FD: FDecl))
7194 return ExprError();
7195
7196 // We know the result type of the call, set it.
7197 TheCall->setType(FuncT->getCallResultType(Context));
7198 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7199
7200 // WebAssembly tables can't be used as arguments.
7201 if (Context.getTargetInfo().getTriple().isWasm()) {
7202 for (const Expr *Arg : Args) {
7203 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7204 return ExprError(Diag(Loc: Arg->getExprLoc(),
7205 DiagID: diag::err_wasm_table_as_function_parameter));
7206 }
7207 }
7208 }
7209
7210 if (Proto) {
7211 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7212 IsExecConfig))
7213 return ExprError();
7214 } else {
7215 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7216
7217 if (FDecl) {
7218 // Check if we have too few/too many template arguments, based
7219 // on our knowledge of the function definition.
7220 const FunctionDecl *Def = nullptr;
7221 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7222 Proto = Def->getType()->getAs<FunctionProtoType>();
7223 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7224 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7225 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7226 }
7227
7228 // If the function we're calling isn't a function prototype, but we have
7229 // a function prototype from a prior declaratiom, use that prototype.
7230 if (!FDecl->hasPrototype())
7231 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7232 }
7233
7234 // If we still haven't found a prototype to use but there are arguments to
7235 // the call, diagnose this as calling a function without a prototype.
7236 // However, if we found a function declaration, check to see if
7237 // -Wdeprecated-non-prototype was disabled where the function was declared.
7238 // If so, we will silence the diagnostic here on the assumption that this
7239 // interface is intentional and the user knows what they're doing. We will
7240 // also silence the diagnostic if there is a function declaration but it
7241 // was implicitly defined (the user already gets diagnostics about the
7242 // creation of the implicit function declaration, so the additional warning
7243 // is not helpful).
7244 if (!Proto && !Args.empty() &&
7245 (!FDecl || (!FDecl->isImplicit() &&
7246 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7247 Loc: FDecl->getLocation()))))
7248 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7249 << (FDecl != nullptr) << FDecl;
7250
7251 // Promote the arguments (C99 6.5.2.2p6).
7252 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7253 Expr *Arg = Args[i];
7254
7255 if (Proto && i < Proto->getNumParams()) {
7256 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7257 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7258 ExprResult ArgE =
7259 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7260 if (ArgE.isInvalid())
7261 return true;
7262
7263 Arg = ArgE.getAs<Expr>();
7264
7265 } else {
7266 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7267
7268 if (ArgE.isInvalid())
7269 return true;
7270
7271 Arg = ArgE.getAs<Expr>();
7272 }
7273
7274 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7275 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7276 return ExprError();
7277
7278 TheCall->setArg(Arg: i, ArgExpr: Arg);
7279 }
7280 TheCall->computeDependence();
7281 }
7282
7283 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7284 if (Method->isImplicitObjectMemberFunction())
7285 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7286 << Fn->getSourceRange() << 0);
7287
7288 // Check for sentinels
7289 if (NDecl)
7290 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7291
7292 // Warn for unions passing across security boundary (CMSE).
7293 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7294 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7295 if (const auto *RT =
7296 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7297 if (RT->getDecl()->isOrContainsUnion())
7298 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7299 << 0 << i;
7300 }
7301 }
7302 }
7303
7304 // Do special checking on direct calls to functions.
7305 if (FDecl) {
7306 if (CheckFunctionCall(FDecl, TheCall, Proto))
7307 return ExprError();
7308
7309 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7310
7311 if (BuiltinID)
7312 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7313 } else if (NDecl) {
7314 if (CheckPointerCall(NDecl, TheCall, Proto))
7315 return ExprError();
7316 } else {
7317 if (CheckOtherCall(TheCall, Proto))
7318 return ExprError();
7319 }
7320
7321 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7322}
7323
7324ExprResult
7325Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7326 SourceLocation RParenLoc, Expr *InitExpr) {
7327 assert(Ty && "ActOnCompoundLiteral(): missing type");
7328 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7329
7330 TypeSourceInfo *TInfo;
7331 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7332 if (!TInfo)
7333 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7334
7335 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7336}
7337
7338ExprResult
7339Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7340 SourceLocation RParenLoc, Expr *LiteralExpr) {
7341 QualType literalType = TInfo->getType();
7342
7343 if (literalType->isArrayType()) {
7344 if (RequireCompleteSizedType(
7345 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7346 DiagID: diag::err_array_incomplete_or_sizeless_type,
7347 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7348 return ExprError();
7349 if (literalType->isVariableArrayType()) {
7350 // C23 6.7.10p4: An entity of variable length array type shall not be
7351 // initialized except by an empty initializer.
7352 //
7353 // The C extension warnings are issued from ParseBraceInitializer() and
7354 // do not need to be issued here. However, we continue to issue an error
7355 // in the case there are initializers or we are compiling C++. We allow
7356 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7357 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7358 // FIXME: should we allow this construct in C++ when it makes sense to do
7359 // so?
7360 //
7361 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7362 // shall specify an object type or an array of unknown size, but not a
7363 // variable length array type. This seems odd, as it allows 'int a[size] =
7364 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7365 // says, this is what's implemented here for C (except for the extension
7366 // that permits constant foldable size arrays)
7367
7368 auto diagID = LangOpts.CPlusPlus
7369 ? diag::err_variable_object_no_init
7370 : diag::err_compound_literal_with_vla_type;
7371 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7372 FailedFoldDiagID: diagID))
7373 return ExprError();
7374 }
7375 } else if (!literalType->isDependentType() &&
7376 RequireCompleteType(Loc: LParenLoc, T: literalType,
7377 DiagID: diag::err_typecheck_decl_incomplete_type,
7378 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7379 return ExprError();
7380
7381 InitializedEntity Entity
7382 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7383 InitializationKind Kind
7384 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7385 TypeRange: SourceRange(LParenLoc, RParenLoc),
7386 /*InitList=*/true);
7387 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7388 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7389 ResultType: &literalType);
7390 if (Result.isInvalid())
7391 return ExprError();
7392 LiteralExpr = Result.get();
7393
7394 // We treat the compound literal as being at file scope if it's not in a
7395 // function or method body, or within the function's prototype scope. This
7396 // means the following compound literal is not at file scope:
7397 // void func(char *para[(int [1]){ 0 }[0]);
7398 const Scope *S = getCurScope();
7399 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7400 !S->isInCFunctionScope() &&
7401 (!S || !S->isFunctionPrototypeScope());
7402
7403 // In C, compound literals are l-values for some reason.
7404 // For GCC compatibility, in C++, file-scope array compound literals with
7405 // constant initializers are also l-values, and compound literals are
7406 // otherwise prvalues.
7407 //
7408 // (GCC also treats C++ list-initialized file-scope array prvalues with
7409 // constant initializers as l-values, but that's non-conforming, so we don't
7410 // follow it there.)
7411 //
7412 // FIXME: It would be better to handle the lvalue cases as materializing and
7413 // lifetime-extending a temporary object, but our materialized temporaries
7414 // representation only supports lifetime extension from a variable, not "out
7415 // of thin air".
7416 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7417 // is bound to the result of applying array-to-pointer decay to the compound
7418 // literal.
7419 // FIXME: GCC supports compound literals of reference type, which should
7420 // obviously have a value kind derived from the kind of reference involved.
7421 ExprValueKind VK =
7422 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7423 ? VK_PRValue
7424 : VK_LValue;
7425
7426 // C99 6.5.2.5
7427 // "If the compound literal occurs outside the body of a function, the
7428 // initializer list shall consist of constant expressions."
7429 if (IsFileScope)
7430 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7431 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7432 Expr *Init = ILE->getInit(Init: i);
7433 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7434 !Init->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false)) {
7435 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7436 << Init->getSourceBitField();
7437 return ExprError();
7438 }
7439
7440 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7441 }
7442
7443 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7444 LiteralExpr, IsFileScope);
7445 if (IsFileScope) {
7446 if (!LiteralExpr->isTypeDependent() &&
7447 !LiteralExpr->isValueDependent() &&
7448 !literalType->isDependentType()) // C99 6.5.2.5p3
7449 if (CheckForConstantInitializer(Init: LiteralExpr))
7450 return ExprError();
7451 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7452 literalType.getAddressSpace() != LangAS::Default) {
7453 // Embedded-C extensions to C99 6.5.2.5:
7454 // "If the compound literal occurs inside the body of a function, the
7455 // type name shall not be qualified by an address-space qualifier."
7456 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7457 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7458 return ExprError();
7459 }
7460
7461 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7462 // Compound literals that have automatic storage duration are destroyed at
7463 // the end of the scope in C; in C++, they're just temporaries.
7464
7465 // Emit diagnostics if it is or contains a C union type that is non-trivial
7466 // to destruct.
7467 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7468 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7469 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7470 NonTrivialKind: NTCUK_Destruct);
7471
7472 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7473 if (literalType.isDestructedType()) {
7474 Cleanup.setExprNeedsCleanups(true);
7475 ExprCleanupObjects.push_back(Elt: E);
7476 getCurFunction()->setHasBranchProtectedScope();
7477 }
7478 }
7479
7480 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7481 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7482 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7483 Loc: E->getInitializer()->getExprLoc());
7484
7485 return MaybeBindToTemporary(E);
7486}
7487
7488ExprResult
7489Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7490 SourceLocation RBraceLoc) {
7491 // Only produce each kind of designated initialization diagnostic once.
7492 SourceLocation FirstDesignator;
7493 bool DiagnosedArrayDesignator = false;
7494 bool DiagnosedNestedDesignator = false;
7495 bool DiagnosedMixedDesignator = false;
7496
7497 // Check that any designated initializers are syntactically valid in the
7498 // current language mode.
7499 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7500 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7501 if (FirstDesignator.isInvalid())
7502 FirstDesignator = DIE->getBeginLoc();
7503
7504 if (!getLangOpts().CPlusPlus)
7505 break;
7506
7507 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7508 DiagnosedNestedDesignator = true;
7509 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7510 << DIE->getDesignatorsSourceRange();
7511 }
7512
7513 for (auto &Desig : DIE->designators()) {
7514 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7515 DiagnosedArrayDesignator = true;
7516 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7517 << Desig.getSourceRange();
7518 }
7519 }
7520
7521 if (!DiagnosedMixedDesignator &&
7522 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7523 DiagnosedMixedDesignator = true;
7524 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7525 << DIE->getSourceRange();
7526 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7527 << InitArgList[0]->getSourceRange();
7528 }
7529 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7530 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7531 DiagnosedMixedDesignator = true;
7532 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7533 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7534 << DIE->getSourceRange();
7535 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7536 << InitArgList[I]->getSourceRange();
7537 }
7538 }
7539
7540 if (FirstDesignator.isValid()) {
7541 // Only diagnose designated initiaization as a C++20 extension if we didn't
7542 // already diagnose use of (non-C++20) C99 designator syntax.
7543 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7544 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7545 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7546 ? diag::warn_cxx17_compat_designated_init
7547 : diag::ext_cxx_designated_init);
7548 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7549 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7550 }
7551 }
7552
7553 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7554}
7555
7556ExprResult
7557Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7558 SourceLocation RBraceLoc) {
7559 // Semantic analysis for initializers is done by ActOnDeclarator() and
7560 // CheckInitializer() - it requires knowledge of the object being initialized.
7561
7562 // Immediately handle non-overload placeholders. Overloads can be
7563 // resolved contextually, but everything else here can't.
7564 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7565 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7566 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7567
7568 // Ignore failures; dropping the entire initializer list because
7569 // of one failure would be terrible for indexing/etc.
7570 if (result.isInvalid()) continue;
7571
7572 InitArgList[I] = result.get();
7573 }
7574 }
7575
7576 InitListExpr *E =
7577 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7578 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7579 return E;
7580}
7581
7582void Sema::maybeExtendBlockObject(ExprResult &E) {
7583 assert(E.get()->getType()->isBlockPointerType());
7584 assert(E.get()->isPRValue());
7585
7586 // Only do this in an r-value context.
7587 if (!getLangOpts().ObjCAutoRefCount) return;
7588
7589 E = ImplicitCastExpr::Create(
7590 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7591 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7592 Cleanup.setExprNeedsCleanups(true);
7593}
7594
7595CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7596 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7597 // Also, callers should have filtered out the invalid cases with
7598 // pointers. Everything else should be possible.
7599
7600 QualType SrcTy = Src.get()->getType();
7601 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7602 return CK_NoOp;
7603
7604 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7605 case Type::STK_MemberPointer:
7606 llvm_unreachable("member pointer type in C");
7607
7608 case Type::STK_CPointer:
7609 case Type::STK_BlockPointer:
7610 case Type::STK_ObjCObjectPointer:
7611 switch (DestTy->getScalarTypeKind()) {
7612 case Type::STK_CPointer: {
7613 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7614 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7615 if (SrcAS != DestAS)
7616 return CK_AddressSpaceConversion;
7617 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7618 return CK_NoOp;
7619 return CK_BitCast;
7620 }
7621 case Type::STK_BlockPointer:
7622 return (SrcKind == Type::STK_BlockPointer
7623 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7624 case Type::STK_ObjCObjectPointer:
7625 if (SrcKind == Type::STK_ObjCObjectPointer)
7626 return CK_BitCast;
7627 if (SrcKind == Type::STK_CPointer)
7628 return CK_CPointerToObjCPointerCast;
7629 maybeExtendBlockObject(E&: Src);
7630 return CK_BlockPointerToObjCPointerCast;
7631 case Type::STK_Bool:
7632 return CK_PointerToBoolean;
7633 case Type::STK_Integral:
7634 return CK_PointerToIntegral;
7635 case Type::STK_Floating:
7636 case Type::STK_FloatingComplex:
7637 case Type::STK_IntegralComplex:
7638 case Type::STK_MemberPointer:
7639 case Type::STK_FixedPoint:
7640 llvm_unreachable("illegal cast from pointer");
7641 }
7642 llvm_unreachable("Should have returned before this");
7643
7644 case Type::STK_FixedPoint:
7645 switch (DestTy->getScalarTypeKind()) {
7646 case Type::STK_FixedPoint:
7647 return CK_FixedPointCast;
7648 case Type::STK_Bool:
7649 return CK_FixedPointToBoolean;
7650 case Type::STK_Integral:
7651 return CK_FixedPointToIntegral;
7652 case Type::STK_Floating:
7653 return CK_FixedPointToFloating;
7654 case Type::STK_IntegralComplex:
7655 case Type::STK_FloatingComplex:
7656 Diag(Loc: Src.get()->getExprLoc(),
7657 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7658 << DestTy;
7659 return CK_IntegralCast;
7660 case Type::STK_CPointer:
7661 case Type::STK_ObjCObjectPointer:
7662 case Type::STK_BlockPointer:
7663 case Type::STK_MemberPointer:
7664 llvm_unreachable("illegal cast to pointer type");
7665 }
7666 llvm_unreachable("Should have returned before this");
7667
7668 case Type::STK_Bool: // casting from bool is like casting from an integer
7669 case Type::STK_Integral:
7670 switch (DestTy->getScalarTypeKind()) {
7671 case Type::STK_CPointer:
7672 case Type::STK_ObjCObjectPointer:
7673 case Type::STK_BlockPointer:
7674 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7675 NPC: Expr::NPC_ValueDependentIsNull))
7676 return CK_NullToPointer;
7677 return CK_IntegralToPointer;
7678 case Type::STK_Bool:
7679 return CK_IntegralToBoolean;
7680 case Type::STK_Integral:
7681 return CK_IntegralCast;
7682 case Type::STK_Floating:
7683 return CK_IntegralToFloating;
7684 case Type::STK_IntegralComplex:
7685 Src = ImpCastExprToType(E: Src.get(),
7686 Type: DestTy->castAs<ComplexType>()->getElementType(),
7687 CK: CK_IntegralCast);
7688 return CK_IntegralRealToComplex;
7689 case Type::STK_FloatingComplex:
7690 Src = ImpCastExprToType(E: Src.get(),
7691 Type: DestTy->castAs<ComplexType>()->getElementType(),
7692 CK: CK_IntegralToFloating);
7693 return CK_FloatingRealToComplex;
7694 case Type::STK_MemberPointer:
7695 llvm_unreachable("member pointer type in C");
7696 case Type::STK_FixedPoint:
7697 return CK_IntegralToFixedPoint;
7698 }
7699 llvm_unreachable("Should have returned before this");
7700
7701 case Type::STK_Floating:
7702 switch (DestTy->getScalarTypeKind()) {
7703 case Type::STK_Floating:
7704 return CK_FloatingCast;
7705 case Type::STK_Bool:
7706 return CK_FloatingToBoolean;
7707 case Type::STK_Integral:
7708 return CK_FloatingToIntegral;
7709 case Type::STK_FloatingComplex:
7710 Src = ImpCastExprToType(E: Src.get(),
7711 Type: DestTy->castAs<ComplexType>()->getElementType(),
7712 CK: CK_FloatingCast);
7713 return CK_FloatingRealToComplex;
7714 case Type::STK_IntegralComplex:
7715 Src = ImpCastExprToType(E: Src.get(),
7716 Type: DestTy->castAs<ComplexType>()->getElementType(),
7717 CK: CK_FloatingToIntegral);
7718 return CK_IntegralRealToComplex;
7719 case Type::STK_CPointer:
7720 case Type::STK_ObjCObjectPointer:
7721 case Type::STK_BlockPointer:
7722 llvm_unreachable("valid float->pointer cast?");
7723 case Type::STK_MemberPointer:
7724 llvm_unreachable("member pointer type in C");
7725 case Type::STK_FixedPoint:
7726 return CK_FloatingToFixedPoint;
7727 }
7728 llvm_unreachable("Should have returned before this");
7729
7730 case Type::STK_FloatingComplex:
7731 switch (DestTy->getScalarTypeKind()) {
7732 case Type::STK_FloatingComplex:
7733 return CK_FloatingComplexCast;
7734 case Type::STK_IntegralComplex:
7735 return CK_FloatingComplexToIntegralComplex;
7736 case Type::STK_Floating: {
7737 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7738 if (Context.hasSameType(T1: ET, T2: DestTy))
7739 return CK_FloatingComplexToReal;
7740 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7741 return CK_FloatingCast;
7742 }
7743 case Type::STK_Bool:
7744 return CK_FloatingComplexToBoolean;
7745 case Type::STK_Integral:
7746 Src = ImpCastExprToType(E: Src.get(),
7747 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7748 CK: CK_FloatingComplexToReal);
7749 return CK_FloatingToIntegral;
7750 case Type::STK_CPointer:
7751 case Type::STK_ObjCObjectPointer:
7752 case Type::STK_BlockPointer:
7753 llvm_unreachable("valid complex float->pointer cast?");
7754 case Type::STK_MemberPointer:
7755 llvm_unreachable("member pointer type in C");
7756 case Type::STK_FixedPoint:
7757 Diag(Loc: Src.get()->getExprLoc(),
7758 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7759 << SrcTy;
7760 return CK_IntegralCast;
7761 }
7762 llvm_unreachable("Should have returned before this");
7763
7764 case Type::STK_IntegralComplex:
7765 switch (DestTy->getScalarTypeKind()) {
7766 case Type::STK_FloatingComplex:
7767 return CK_IntegralComplexToFloatingComplex;
7768 case Type::STK_IntegralComplex:
7769 return CK_IntegralComplexCast;
7770 case Type::STK_Integral: {
7771 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7772 if (Context.hasSameType(T1: ET, T2: DestTy))
7773 return CK_IntegralComplexToReal;
7774 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7775 return CK_IntegralCast;
7776 }
7777 case Type::STK_Bool:
7778 return CK_IntegralComplexToBoolean;
7779 case Type::STK_Floating:
7780 Src = ImpCastExprToType(E: Src.get(),
7781 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7782 CK: CK_IntegralComplexToReal);
7783 return CK_IntegralToFloating;
7784 case Type::STK_CPointer:
7785 case Type::STK_ObjCObjectPointer:
7786 case Type::STK_BlockPointer:
7787 llvm_unreachable("valid complex int->pointer cast?");
7788 case Type::STK_MemberPointer:
7789 llvm_unreachable("member pointer type in C");
7790 case Type::STK_FixedPoint:
7791 Diag(Loc: Src.get()->getExprLoc(),
7792 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7793 << SrcTy;
7794 return CK_IntegralCast;
7795 }
7796 llvm_unreachable("Should have returned before this");
7797 }
7798
7799 llvm_unreachable("Unhandled scalar cast");
7800}
7801
7802static bool breakDownVectorType(QualType type, uint64_t &len,
7803 QualType &eltType) {
7804 // Vectors are simple.
7805 if (const VectorType *vecType = type->getAs<VectorType>()) {
7806 len = vecType->getNumElements();
7807 eltType = vecType->getElementType();
7808 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7809 return true;
7810 }
7811
7812 // We allow lax conversion to and from non-vector types, but only if
7813 // they're real types (i.e. non-complex, non-pointer scalar types).
7814 if (!type->isRealType()) return false;
7815
7816 len = 1;
7817 eltType = type;
7818 return true;
7819}
7820
7821bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7822 assert(srcTy->isVectorType() || destTy->isVectorType());
7823
7824 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7825 if (!FirstType->isSVESizelessBuiltinType())
7826 return false;
7827
7828 const auto *VecTy = SecondType->getAs<VectorType>();
7829 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7830 };
7831
7832 return ValidScalableConversion(srcTy, destTy) ||
7833 ValidScalableConversion(destTy, srcTy);
7834}
7835
7836bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7837 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7838 return false;
7839
7840 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7841 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7842
7843 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7844 matSrcType->getNumColumns() == matDestType->getNumColumns();
7845}
7846
7847bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7848 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7849
7850 uint64_t SrcLen, DestLen;
7851 QualType SrcEltTy, DestEltTy;
7852 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7853 return false;
7854 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7855 return false;
7856
7857 // ASTContext::getTypeSize will return the size rounded up to a
7858 // power of 2, so instead of using that, we need to use the raw
7859 // element size multiplied by the element count.
7860 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7861 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7862
7863 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7864}
7865
7866bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7867 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7868 "expected at least one type to be a vector here");
7869
7870 bool IsSrcTyAltivec =
7871 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7872 VectorKind::AltiVecVector) ||
7873 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7874 VectorKind::AltiVecBool) ||
7875 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7876 VectorKind::AltiVecPixel));
7877
7878 bool IsDestTyAltivec = DestTy->isVectorType() &&
7879 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7880 VectorKind::AltiVecVector) ||
7881 (DestTy->castAs<VectorType>()->getVectorKind() ==
7882 VectorKind::AltiVecBool) ||
7883 (DestTy->castAs<VectorType>()->getVectorKind() ==
7884 VectorKind::AltiVecPixel));
7885
7886 return (IsSrcTyAltivec || IsDestTyAltivec);
7887}
7888
7889bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7890 assert(destTy->isVectorType() || srcTy->isVectorType());
7891
7892 // Disallow lax conversions between scalars and ExtVectors (these
7893 // conversions are allowed for other vector types because common headers
7894 // depend on them). Most scalar OP ExtVector cases are handled by the
7895 // splat path anyway, which does what we want (convert, not bitcast).
7896 // What this rules out for ExtVectors is crazy things like char4*float.
7897 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7898 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7899
7900 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
7901}
7902
7903bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7904 assert(destTy->isVectorType() || srcTy->isVectorType());
7905
7906 switch (Context.getLangOpts().getLaxVectorConversions()) {
7907 case LangOptions::LaxVectorConversionKind::None:
7908 return false;
7909
7910 case LangOptions::LaxVectorConversionKind::Integer:
7911 if (!srcTy->isIntegralOrEnumerationType()) {
7912 auto *Vec = srcTy->getAs<VectorType>();
7913 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7914 return false;
7915 }
7916 if (!destTy->isIntegralOrEnumerationType()) {
7917 auto *Vec = destTy->getAs<VectorType>();
7918 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7919 return false;
7920 }
7921 // OK, integer (vector) -> integer (vector) bitcast.
7922 break;
7923
7924 case LangOptions::LaxVectorConversionKind::All:
7925 break;
7926 }
7927
7928 return areLaxCompatibleVectorTypes(srcTy, destTy);
7929}
7930
7931bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7932 CastKind &Kind) {
7933 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7934 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
7935 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
7936 << DestTy << SrcTy << R;
7937 }
7938 } else if (SrcTy->isMatrixType()) {
7939 return Diag(Loc: R.getBegin(),
7940 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7941 << SrcTy << DestTy << R;
7942 } else if (DestTy->isMatrixType()) {
7943 return Diag(Loc: R.getBegin(),
7944 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7945 << DestTy << SrcTy << R;
7946 }
7947
7948 Kind = CK_MatrixCast;
7949 return false;
7950}
7951
7952bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7953 CastKind &Kind) {
7954 assert(VectorTy->isVectorType() && "Not a vector type!");
7955
7956 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
7957 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
7958 return Diag(Loc: R.getBegin(),
7959 DiagID: Ty->isVectorType() ?
7960 diag::err_invalid_conversion_between_vectors :
7961 diag::err_invalid_conversion_between_vector_and_integer)
7962 << VectorTy << Ty << R;
7963 } else
7964 return Diag(Loc: R.getBegin(),
7965 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
7966 << VectorTy << Ty << R;
7967
7968 Kind = CK_BitCast;
7969 return false;
7970}
7971
7972ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7973 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7974
7975 if (DestElemTy == SplattedExpr->getType())
7976 return SplattedExpr;
7977
7978 assert(DestElemTy->isFloatingType() ||
7979 DestElemTy->isIntegralOrEnumerationType());
7980
7981 CastKind CK;
7982 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7983 // OpenCL requires that we convert `true` boolean expressions to -1, but
7984 // only when splatting vectors.
7985 if (DestElemTy->isFloatingType()) {
7986 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7987 // in two steps: boolean to signed integral, then to floating.
7988 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
7989 CK: CK_BooleanToSignedIntegral);
7990 SplattedExpr = CastExprRes.get();
7991 CK = CK_IntegralToFloating;
7992 } else {
7993 CK = CK_BooleanToSignedIntegral;
7994 }
7995 } else {
7996 ExprResult CastExprRes = SplattedExpr;
7997 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
7998 if (CastExprRes.isInvalid())
7999 return ExprError();
8000 SplattedExpr = CastExprRes.get();
8001 }
8002 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8003}
8004
8005ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8006 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8007
8008 if (DestElemTy == SplattedExpr->getType())
8009 return SplattedExpr;
8010
8011 assert(DestElemTy->isFloatingType() ||
8012 DestElemTy->isIntegralOrEnumerationType());
8013
8014 ExprResult CastExprRes = SplattedExpr;
8015 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8016 if (CastExprRes.isInvalid())
8017 return ExprError();
8018 SplattedExpr = CastExprRes.get();
8019
8020 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8021}
8022
8023ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8024 Expr *CastExpr, CastKind &Kind) {
8025 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8026
8027 QualType SrcTy = CastExpr->getType();
8028
8029 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8030 // an ExtVectorType.
8031 // In OpenCL, casts between vectors of different types are not allowed.
8032 // (See OpenCL 6.2).
8033 if (SrcTy->isVectorType()) {
8034 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8035 (getLangOpts().OpenCL &&
8036 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8037 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8038 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8039 << DestTy << SrcTy << R;
8040 return ExprError();
8041 }
8042 Kind = CK_BitCast;
8043 return CastExpr;
8044 }
8045
8046 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8047 // conversion will take place first from scalar to elt type, and then
8048 // splat from elt type to vector.
8049 if (SrcTy->isPointerType())
8050 return Diag(Loc: R.getBegin(),
8051 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8052 << DestTy << SrcTy << R;
8053
8054 Kind = CK_VectorSplat;
8055 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8056}
8057
8058/// Check that a call to alloc_size function specifies sufficient space for the
8059/// destination type.
8060static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8061 const Expr *E) {
8062 QualType SourceType = E->getType();
8063 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8064 DestType == SourceType)
8065 return;
8066
8067 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8068 if (!CE)
8069 return;
8070
8071 // Find the total size allocated by the function call.
8072 if (!CE->getCalleeAllocSizeAttr())
8073 return;
8074 std::optional<llvm::APInt> AllocSize =
8075 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8076 // Allocations of size zero are permitted as a special case. They are usually
8077 // done intentionally.
8078 if (!AllocSize || AllocSize->isZero())
8079 return;
8080 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8081
8082 QualType TargetType = DestType->getPointeeType();
8083 // Find the destination size. As a special case function types have size of
8084 // one byte to match the sizeof operator behavior.
8085 auto LhsSize = TargetType->isFunctionType()
8086 ? CharUnits::One()
8087 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8088 if (LhsSize && Size < LhsSize)
8089 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8090 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8091}
8092
8093ExprResult
8094Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8095 Declarator &D, ParsedType &Ty,
8096 SourceLocation RParenLoc, Expr *CastExpr) {
8097 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8098 "ActOnCastExpr(): missing type or expr");
8099
8100 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8101 if (D.isInvalidType())
8102 return ExprError();
8103
8104 if (getLangOpts().CPlusPlus) {
8105 // Check that there are no default arguments (C++ only).
8106 CheckExtraCXXDefaultArguments(D);
8107 }
8108
8109 checkUnusedDeclAttributes(D);
8110
8111 QualType castType = castTInfo->getType();
8112 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8113
8114 bool isVectorLiteral = false;
8115
8116 // Check for an altivec or OpenCL literal,
8117 // i.e. all the elements are integer constants.
8118 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8119 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8120 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8121 && castType->isVectorType() && (PE || PLE)) {
8122 if (PLE && PLE->getNumExprs() == 0) {
8123 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8124 return ExprError();
8125 }
8126 if (PE || PLE->getNumExprs() == 1) {
8127 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8128 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8129 isVectorLiteral = true;
8130 }
8131 else
8132 isVectorLiteral = true;
8133 }
8134
8135 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8136 // then handle it as such.
8137 if (isVectorLiteral)
8138 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8139
8140 // If the Expr being casted is a ParenListExpr, handle it specially.
8141 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8142 // sequence of BinOp comma operators.
8143 if (isa<ParenListExpr>(Val: CastExpr)) {
8144 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8145 if (Result.isInvalid()) return ExprError();
8146 CastExpr = Result.get();
8147 }
8148
8149 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8150 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8151
8152 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8153
8154 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8155
8156 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8157
8158 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8159
8160 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8161}
8162
8163ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8164 SourceLocation RParenLoc, Expr *E,
8165 TypeSourceInfo *TInfo) {
8166 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8167 "Expected paren or paren list expression");
8168
8169 Expr **exprs;
8170 unsigned numExprs;
8171 Expr *subExpr;
8172 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8173 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8174 LiteralLParenLoc = PE->getLParenLoc();
8175 LiteralRParenLoc = PE->getRParenLoc();
8176 exprs = PE->getExprs();
8177 numExprs = PE->getNumExprs();
8178 } else { // isa<ParenExpr> by assertion at function entrance
8179 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8180 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8181 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8182 exprs = &subExpr;
8183 numExprs = 1;
8184 }
8185
8186 QualType Ty = TInfo->getType();
8187 assert(Ty->isVectorType() && "Expected vector type");
8188
8189 SmallVector<Expr *, 8> initExprs;
8190 const VectorType *VTy = Ty->castAs<VectorType>();
8191 unsigned numElems = VTy->getNumElements();
8192
8193 // '(...)' form of vector initialization in AltiVec: the number of
8194 // initializers must be one or must match the size of the vector.
8195 // If a single value is specified in the initializer then it will be
8196 // replicated to all the components of the vector
8197 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8198 SrcTy: VTy->getElementType()))
8199 return ExprError();
8200 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8201 // The number of initializers must be one or must match the size of the
8202 // vector. If a single value is specified in the initializer then it will
8203 // be replicated to all the components of the vector
8204 if (numExprs == 1) {
8205 QualType ElemTy = VTy->getElementType();
8206 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8207 if (Literal.isInvalid())
8208 return ExprError();
8209 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8210 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8211 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8212 }
8213 else if (numExprs < numElems) {
8214 Diag(Loc: E->getExprLoc(),
8215 DiagID: diag::err_incorrect_number_of_vector_initializers);
8216 return ExprError();
8217 }
8218 else
8219 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8220 }
8221 else {
8222 // For OpenCL, when the number of initializers is a single value,
8223 // it will be replicated to all components of the vector.
8224 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8225 numExprs == 1) {
8226 QualType SrcTy = exprs[0]->getType();
8227 if (!SrcTy->isArithmeticType()) {
8228 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8229 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8230 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8231 return ExprError();
8232 }
8233 QualType ElemTy = VTy->getElementType();
8234 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8235 if (Literal.isInvalid())
8236 return ExprError();
8237 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8238 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8239 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8240 }
8241
8242 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8243 }
8244 // FIXME: This means that pretty-printing the final AST will produce curly
8245 // braces instead of the original commas.
8246 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8247 initExprs, LiteralRParenLoc);
8248 initE->setType(Ty);
8249 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8250}
8251
8252ExprResult
8253Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8254 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8255 if (!E)
8256 return OrigExpr;
8257
8258 ExprResult Result(E->getExpr(Init: 0));
8259
8260 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8261 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8262 RHSExpr: E->getExpr(Init: i));
8263
8264 if (Result.isInvalid()) return ExprError();
8265
8266 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8267}
8268
8269ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8270 SourceLocation R,
8271 MultiExprArg Val) {
8272 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8273}
8274
8275ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8276 unsigned NumUserSpecifiedExprs,
8277 SourceLocation InitLoc,
8278 SourceLocation LParenLoc,
8279 SourceLocation RParenLoc) {
8280 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8281 InitLoc, LParenLoc, RParenLoc);
8282}
8283
8284bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8285 SourceLocation QuestionLoc) {
8286 const Expr *NullExpr = LHSExpr;
8287 const Expr *NonPointerExpr = RHSExpr;
8288 Expr::NullPointerConstantKind NullKind =
8289 NullExpr->isNullPointerConstant(Ctx&: Context,
8290 NPC: Expr::NPC_ValueDependentIsNotNull);
8291
8292 if (NullKind == Expr::NPCK_NotNull) {
8293 NullExpr = RHSExpr;
8294 NonPointerExpr = LHSExpr;
8295 NullKind =
8296 NullExpr->isNullPointerConstant(Ctx&: Context,
8297 NPC: Expr::NPC_ValueDependentIsNotNull);
8298 }
8299
8300 if (NullKind == Expr::NPCK_NotNull)
8301 return false;
8302
8303 if (NullKind == Expr::NPCK_ZeroExpression)
8304 return false;
8305
8306 if (NullKind == Expr::NPCK_ZeroLiteral) {
8307 // In this case, check to make sure that we got here from a "NULL"
8308 // string in the source code.
8309 NullExpr = NullExpr->IgnoreParenImpCasts();
8310 SourceLocation loc = NullExpr->getExprLoc();
8311 if (!findMacroSpelling(loc, name: "NULL"))
8312 return false;
8313 }
8314
8315 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8316 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8317 << NonPointerExpr->getType() << DiagType
8318 << NonPointerExpr->getSourceRange();
8319 return true;
8320}
8321
8322/// Return false if the condition expression is valid, true otherwise.
8323static bool checkCondition(Sema &S, const Expr *Cond,
8324 SourceLocation QuestionLoc) {
8325 QualType CondTy = Cond->getType();
8326
8327 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8328 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8329 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8330 << CondTy << Cond->getSourceRange();
8331 return true;
8332 }
8333
8334 // C99 6.5.15p2
8335 if (CondTy->isScalarType()) return false;
8336
8337 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8338 << CondTy << Cond->getSourceRange();
8339 return true;
8340}
8341
8342/// Return false if the NullExpr can be promoted to PointerTy,
8343/// true otherwise.
8344static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8345 QualType PointerTy) {
8346 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8347 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8348 NPC: Expr::NPC_ValueDependentIsNull))
8349 return true;
8350
8351 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8352 return false;
8353}
8354
8355/// Checks compatibility between two pointers and return the resulting
8356/// type.
8357static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8358 ExprResult &RHS,
8359 SourceLocation Loc) {
8360 QualType LHSTy = LHS.get()->getType();
8361 QualType RHSTy = RHS.get()->getType();
8362
8363 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8364 // Two identical pointers types are always compatible.
8365 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8366 }
8367
8368 QualType lhptee, rhptee;
8369
8370 // Get the pointee types.
8371 bool IsBlockPointer = false;
8372 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8373 lhptee = LHSBTy->getPointeeType();
8374 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8375 IsBlockPointer = true;
8376 } else {
8377 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8378 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8379 }
8380
8381 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8382 // differently qualified versions of compatible types, the result type is
8383 // a pointer to an appropriately qualified version of the composite
8384 // type.
8385
8386 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8387 // clause doesn't make sense for our extensions. E.g. address space 2 should
8388 // be incompatible with address space 3: they may live on different devices or
8389 // anything.
8390 Qualifiers lhQual = lhptee.getQualifiers();
8391 Qualifiers rhQual = rhptee.getQualifiers();
8392
8393 LangAS ResultAddrSpace = LangAS::Default;
8394 LangAS LAddrSpace = lhQual.getAddressSpace();
8395 LangAS RAddrSpace = rhQual.getAddressSpace();
8396
8397 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8398 // spaces is disallowed.
8399 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8400 ResultAddrSpace = LAddrSpace;
8401 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8402 ResultAddrSpace = RAddrSpace;
8403 else {
8404 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8405 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8406 << RHS.get()->getSourceRange();
8407 return QualType();
8408 }
8409
8410 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8411 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8412 lhQual.removeCVRQualifiers();
8413 rhQual.removeCVRQualifiers();
8414
8415 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8416 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8417 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8418 << RHS.get()->getSourceRange();
8419 return QualType();
8420 }
8421
8422 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8423 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8424 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8425 // qual types are compatible iff
8426 // * corresponded types are compatible
8427 // * CVR qualifiers are equal
8428 // * address spaces are equal
8429 // Thus for conditional operator we merge CVR and address space unqualified
8430 // pointees and if there is a composite type we return a pointer to it with
8431 // merged qualifiers.
8432 LHSCastKind =
8433 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8434 RHSCastKind =
8435 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8436 lhQual.removeAddressSpace();
8437 rhQual.removeAddressSpace();
8438
8439 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8440 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8441
8442 QualType CompositeTy = S.Context.mergeTypes(
8443 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8444 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8445
8446 if (CompositeTy.isNull()) {
8447 // In this situation, we assume void* type. No especially good
8448 // reason, but this is what gcc does, and we do have to pick
8449 // to get a consistent AST.
8450 QualType incompatTy;
8451 incompatTy = S.Context.getPointerType(
8452 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8453 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8454 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8455
8456 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8457 // for casts between types with incompatible address space qualifiers.
8458 // For the following code the compiler produces casts between global and
8459 // local address spaces of the corresponded innermost pointees:
8460 // local int *global *a;
8461 // global int *global *b;
8462 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8463 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8464 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8465 << RHS.get()->getSourceRange();
8466
8467 return incompatTy;
8468 }
8469
8470 // The pointer types are compatible.
8471 // In case of OpenCL ResultTy should have the address space qualifier
8472 // which is a superset of address spaces of both the 2nd and the 3rd
8473 // operands of the conditional operator.
8474 QualType ResultTy = [&, ResultAddrSpace]() {
8475 if (S.getLangOpts().OpenCL) {
8476 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8477 CompositeQuals.setAddressSpace(ResultAddrSpace);
8478 return S.Context
8479 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8480 .withCVRQualifiers(CVR: MergedCVRQual);
8481 }
8482 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8483 }();
8484 if (IsBlockPointer)
8485 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8486 else
8487 ResultTy = S.Context.getPointerType(T: ResultTy);
8488
8489 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8490 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8491 return ResultTy;
8492}
8493
8494/// Return the resulting type when the operands are both block pointers.
8495static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8496 ExprResult &LHS,
8497 ExprResult &RHS,
8498 SourceLocation Loc) {
8499 QualType LHSTy = LHS.get()->getType();
8500 QualType RHSTy = RHS.get()->getType();
8501
8502 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8503 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8504 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8505 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8506 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8507 return destType;
8508 }
8509 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8510 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8511 << RHS.get()->getSourceRange();
8512 return QualType();
8513 }
8514
8515 // We have 2 block pointer types.
8516 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8517}
8518
8519/// Return the resulting type when the operands are both pointers.
8520static QualType
8521checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8522 ExprResult &RHS,
8523 SourceLocation Loc) {
8524 // get the pointer types
8525 QualType LHSTy = LHS.get()->getType();
8526 QualType RHSTy = RHS.get()->getType();
8527
8528 // get the "pointed to" types
8529 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8530 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8531
8532 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8533 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8534 // Figure out necessary qualifiers (C99 6.5.15p6)
8535 QualType destPointee
8536 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8537 QualType destType = S.Context.getPointerType(T: destPointee);
8538 // Add qualifiers if necessary.
8539 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8540 // Promote to void*.
8541 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8542 return destType;
8543 }
8544 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8545 QualType destPointee
8546 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8547 QualType destType = S.Context.getPointerType(T: destPointee);
8548 // Add qualifiers if necessary.
8549 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8550 // Promote to void*.
8551 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8552 return destType;
8553 }
8554
8555 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8556}
8557
8558/// Return false if the first expression is not an integer and the second
8559/// expression is not a pointer, true otherwise.
8560static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8561 Expr* PointerExpr, SourceLocation Loc,
8562 bool IsIntFirstExpr) {
8563 if (!PointerExpr->getType()->isPointerType() ||
8564 !Int.get()->getType()->isIntegerType())
8565 return false;
8566
8567 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8568 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8569
8570 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8571 << Expr1->getType() << Expr2->getType()
8572 << Expr1->getSourceRange() << Expr2->getSourceRange();
8573 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8574 CK: CK_IntegralToPointer);
8575 return true;
8576}
8577
8578/// Simple conversion between integer and floating point types.
8579///
8580/// Used when handling the OpenCL conditional operator where the
8581/// condition is a vector while the other operands are scalar.
8582///
8583/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8584/// types are either integer or floating type. Between the two
8585/// operands, the type with the higher rank is defined as the "result
8586/// type". The other operand needs to be promoted to the same type. No
8587/// other type promotion is allowed. We cannot use
8588/// UsualArithmeticConversions() for this purpose, since it always
8589/// promotes promotable types.
8590static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8591 ExprResult &RHS,
8592 SourceLocation QuestionLoc) {
8593 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8594 if (LHS.isInvalid())
8595 return QualType();
8596 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8597 if (RHS.isInvalid())
8598 return QualType();
8599
8600 // For conversion purposes, we ignore any qualifiers.
8601 // For example, "const float" and "float" are equivalent.
8602 QualType LHSType =
8603 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8604 QualType RHSType =
8605 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8606
8607 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8608 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8609 << LHSType << LHS.get()->getSourceRange();
8610 return QualType();
8611 }
8612
8613 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8614 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8615 << RHSType << RHS.get()->getSourceRange();
8616 return QualType();
8617 }
8618
8619 // If both types are identical, no conversion is needed.
8620 if (LHSType == RHSType)
8621 return LHSType;
8622
8623 // Now handle "real" floating types (i.e. float, double, long double).
8624 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8625 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8626 /*IsCompAssign = */ false);
8627
8628 // Finally, we have two differing integer types.
8629 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8630 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8631}
8632
8633/// Convert scalar operands to a vector that matches the
8634/// condition in length.
8635///
8636/// Used when handling the OpenCL conditional operator where the
8637/// condition is a vector while the other operands are scalar.
8638///
8639/// We first compute the "result type" for the scalar operands
8640/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8641/// into a vector of that type where the length matches the condition
8642/// vector type. s6.11.6 requires that the element types of the result
8643/// and the condition must have the same number of bits.
8644static QualType
8645OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8646 QualType CondTy, SourceLocation QuestionLoc) {
8647 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8648 if (ResTy.isNull()) return QualType();
8649
8650 const VectorType *CV = CondTy->getAs<VectorType>();
8651 assert(CV);
8652
8653 // Determine the vector result type
8654 unsigned NumElements = CV->getNumElements();
8655 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8656
8657 // Ensure that all types have the same number of bits
8658 if (S.Context.getTypeSize(T: CV->getElementType())
8659 != S.Context.getTypeSize(T: ResTy)) {
8660 // Since VectorTy is created internally, it does not pretty print
8661 // with an OpenCL name. Instead, we just print a description.
8662 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8663 SmallString<64> Str;
8664 llvm::raw_svector_ostream OS(Str);
8665 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8666 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8667 << CondTy << OS.str();
8668 return QualType();
8669 }
8670
8671 // Convert operands to the vector result type
8672 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8673 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8674
8675 return VectorTy;
8676}
8677
8678/// Return false if this is a valid OpenCL condition vector
8679static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8680 SourceLocation QuestionLoc) {
8681 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8682 // integral type.
8683 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8684 assert(CondTy);
8685 QualType EleTy = CondTy->getElementType();
8686 if (EleTy->isIntegerType()) return false;
8687
8688 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8689 << Cond->getType() << Cond->getSourceRange();
8690 return true;
8691}
8692
8693/// Return false if the vector condition type and the vector
8694/// result type are compatible.
8695///
8696/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8697/// number of elements, and their element types have the same number
8698/// of bits.
8699static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8700 SourceLocation QuestionLoc) {
8701 const VectorType *CV = CondTy->getAs<VectorType>();
8702 const VectorType *RV = VecResTy->getAs<VectorType>();
8703 assert(CV && RV);
8704
8705 if (CV->getNumElements() != RV->getNumElements()) {
8706 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8707 << CondTy << VecResTy;
8708 return true;
8709 }
8710
8711 QualType CVE = CV->getElementType();
8712 QualType RVE = RV->getElementType();
8713
8714 // Boolean vectors are permitted outside of OpenCL mode.
8715 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8716 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8717 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8718 << CondTy << VecResTy;
8719 return true;
8720 }
8721
8722 return false;
8723}
8724
8725/// Return the resulting type for the conditional operator in
8726/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8727/// s6.3.i) when the condition is a vector type.
8728static QualType
8729OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8730 ExprResult &LHS, ExprResult &RHS,
8731 SourceLocation QuestionLoc) {
8732 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8733 if (Cond.isInvalid())
8734 return QualType();
8735 QualType CondTy = Cond.get()->getType();
8736
8737 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8738 return QualType();
8739
8740 // If either operand is a vector then find the vector type of the
8741 // result as specified in OpenCL v1.1 s6.3.i.
8742 if (LHS.get()->getType()->isVectorType() ||
8743 RHS.get()->getType()->isVectorType()) {
8744 bool IsBoolVecLang =
8745 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8746 QualType VecResTy =
8747 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8748 /*isCompAssign*/ IsCompAssign: false,
8749 /*AllowBothBool*/ true,
8750 /*AllowBoolConversions*/ AllowBoolConversion: false,
8751 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8752 /*ReportInvalid*/ true);
8753 if (VecResTy.isNull())
8754 return QualType();
8755 // The result type must match the condition type as specified in
8756 // OpenCL v1.1 s6.11.6.
8757 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8758 return QualType();
8759 return VecResTy;
8760 }
8761
8762 // Both operands are scalar.
8763 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8764}
8765
8766/// Return true if the Expr is block type
8767static bool checkBlockType(Sema &S, const Expr *E) {
8768 if (E->getType()->isBlockPointerType()) {
8769 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8770 return true;
8771 }
8772
8773 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8774 QualType Ty = CE->getCallee()->getType();
8775 if (Ty->isBlockPointerType()) {
8776 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8777 return true;
8778 }
8779 }
8780 return false;
8781}
8782
8783/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8784/// In that case, LHS = cond.
8785/// C99 6.5.15
8786QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8787 ExprResult &RHS, ExprValueKind &VK,
8788 ExprObjectKind &OK,
8789 SourceLocation QuestionLoc) {
8790
8791 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8792 if (!LHSResult.isUsable()) return QualType();
8793 LHS = LHSResult;
8794
8795 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8796 if (!RHSResult.isUsable()) return QualType();
8797 RHS = RHSResult;
8798
8799 // C++ is sufficiently different to merit its own checker.
8800 if (getLangOpts().CPlusPlus)
8801 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8802
8803 VK = VK_PRValue;
8804 OK = OK_Ordinary;
8805
8806 if (Context.isDependenceAllowed() &&
8807 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8808 RHS.get()->isTypeDependent())) {
8809 assert(!getLangOpts().CPlusPlus);
8810 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8811 RHS.get()->containsErrors()) &&
8812 "should only occur in error-recovery path.");
8813 return Context.DependentTy;
8814 }
8815
8816 // The OpenCL operator with a vector condition is sufficiently
8817 // different to merit its own checker.
8818 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8819 Cond.get()->getType()->isExtVectorType())
8820 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8821
8822 // First, check the condition.
8823 Cond = UsualUnaryConversions(E: Cond.get());
8824 if (Cond.isInvalid())
8825 return QualType();
8826 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8827 return QualType();
8828
8829 // Handle vectors.
8830 if (LHS.get()->getType()->isVectorType() ||
8831 RHS.get()->getType()->isVectorType())
8832 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8833 /*AllowBothBool*/ true,
8834 /*AllowBoolConversions*/ AllowBoolConversion: false,
8835 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8836 /*ReportInvalid*/ true);
8837
8838 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8839 ACK: ArithConvKind::Conditional);
8840 if (LHS.isInvalid() || RHS.isInvalid())
8841 return QualType();
8842
8843 // WebAssembly tables are not allowed as conditional LHS or RHS.
8844 QualType LHSTy = LHS.get()->getType();
8845 QualType RHSTy = RHS.get()->getType();
8846 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8847 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8849 return QualType();
8850 }
8851
8852 // Diagnose attempts to convert between __ibm128, __float128 and long double
8853 // where such conversions currently can't be handled.
8854 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8855 Diag(Loc: QuestionLoc,
8856 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8858 return QualType();
8859 }
8860
8861 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8862 // selection operator (?:).
8863 if (getLangOpts().OpenCL &&
8864 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8865 return QualType();
8866 }
8867
8868 // If both operands have arithmetic type, do the usual arithmetic conversions
8869 // to find a common type: C99 6.5.15p3,5.
8870 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8871 // Disallow invalid arithmetic conversions, such as those between bit-
8872 // precise integers types of different sizes, or between a bit-precise
8873 // integer and another type.
8874 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8875 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8876 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8877 << RHS.get()->getSourceRange();
8878 return QualType();
8879 }
8880
8881 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8882 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8883
8884 return ResTy;
8885 }
8886
8887 // If both operands are the same structure or union type, the result is that
8888 // type.
8889 // FIXME: Type of conditional expression must be complete in C mode.
8890 if (LHSTy->isRecordType() &&
8891 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
8892 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8893 Y: RHSTy.getUnqualifiedType());
8894
8895 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8896 // The following || allows only one side to be void (a GCC-ism).
8897 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8898 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8899 // UsualArithmeticConversions already handled the case where both sides
8900 // are the same type.
8901 } else if (RHSTy->isVoidType()) {
8902 ResTy = RHSTy;
8903 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8904 << RHS.get()->getSourceRange();
8905 } else {
8906 ResTy = LHSTy;
8907 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8908 << LHS.get()->getSourceRange();
8909 }
8910 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8911 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
8912 return ResTy;
8913 }
8914
8915 // C23 6.5.15p7:
8916 // ... if both the second and third operands have nullptr_t type, the
8917 // result also has that type.
8918 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
8919 return ResTy;
8920
8921 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8922 // the type of the other operand."
8923 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
8924 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
8925
8926 // All objective-c pointer type analysis is done here.
8927 QualType compositeType =
8928 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8929 if (LHS.isInvalid() || RHS.isInvalid())
8930 return QualType();
8931 if (!compositeType.isNull())
8932 return compositeType;
8933
8934
8935 // Handle block pointer types.
8936 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8937 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
8938 Loc: QuestionLoc);
8939
8940 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8941 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8942 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
8943 Loc: QuestionLoc);
8944
8945 // GCC compatibility: soften pointer/integer mismatch. Note that
8946 // null pointers have been filtered out by this point.
8947 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
8948 /*IsIntFirstExpr=*/true))
8949 return RHSTy;
8950 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
8951 /*IsIntFirstExpr=*/false))
8952 return LHSTy;
8953
8954 // Emit a better diagnostic if one of the expressions is a null pointer
8955 // constant and the other is not a pointer type. In this case, the user most
8956 // likely forgot to take the address of the other expression.
8957 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
8958 return QualType();
8959
8960 // Finally, if the LHS and RHS types are canonically the same type, we can
8961 // use the common sugared type.
8962 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
8963 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8964
8965 // Otherwise, the operands are not compatible.
8966 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8967 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8968 << RHS.get()->getSourceRange();
8969 return QualType();
8970}
8971
8972/// SuggestParentheses - Emit a note with a fixit hint that wraps
8973/// ParenRange in parentheses.
8974static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8975 const PartialDiagnostic &Note,
8976 SourceRange ParenRange) {
8977 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
8978 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8979 EndLoc.isValid()) {
8980 Self.Diag(Loc, PD: Note)
8981 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
8982 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
8983 } else {
8984 // We can't display the parentheses, so just show the bare note.
8985 Self.Diag(Loc, PD: Note) << ParenRange;
8986 }
8987}
8988
8989static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8990 return BinaryOperator::isAdditiveOp(Opc) ||
8991 BinaryOperator::isMultiplicativeOp(Opc) ||
8992 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8993 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8994 // not any of the logical operators. Bitwise-xor is commonly used as a
8995 // logical-xor because there is no logical-xor operator. The logical
8996 // operators, including uses of xor, have a high false positive rate for
8997 // precedence warnings.
8998}
8999
9000/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9001/// expression, either using a built-in or overloaded operator,
9002/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9003/// expression.
9004static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9005 const Expr **RHSExprs) {
9006 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9007 E = E->IgnoreImpCasts();
9008 E = E->IgnoreConversionOperatorSingleStep();
9009 E = E->IgnoreImpCasts();
9010 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9011 E = MTE->getSubExpr();
9012 E = E->IgnoreImpCasts();
9013 }
9014
9015 // Built-in binary operator.
9016 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9017 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9018 *Opcode = OP->getOpcode();
9019 *RHSExprs = OP->getRHS();
9020 return true;
9021 }
9022
9023 // Overloaded operator.
9024 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9025 if (Call->getNumArgs() != 2)
9026 return false;
9027
9028 // Make sure this is really a binary operator that is safe to pass into
9029 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9030 OverloadedOperatorKind OO = Call->getOperator();
9031 if (OO < OO_Plus || OO > OO_Arrow ||
9032 OO == OO_PlusPlus || OO == OO_MinusMinus)
9033 return false;
9034
9035 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9036 if (IsArithmeticOp(Opc: OpKind)) {
9037 *Opcode = OpKind;
9038 *RHSExprs = Call->getArg(Arg: 1);
9039 return true;
9040 }
9041 }
9042
9043 return false;
9044}
9045
9046/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9047/// or is a logical expression such as (x==y) which has int type, but is
9048/// commonly interpreted as boolean.
9049static bool ExprLooksBoolean(const Expr *E) {
9050 E = E->IgnoreParenImpCasts();
9051
9052 if (E->getType()->isBooleanType())
9053 return true;
9054 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9055 return OP->isComparisonOp() || OP->isLogicalOp();
9056 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9057 return OP->getOpcode() == UO_LNot;
9058 if (E->getType()->isPointerType())
9059 return true;
9060 // FIXME: What about overloaded operator calls returning "unspecified boolean
9061 // type"s (commonly pointer-to-members)?
9062
9063 return false;
9064}
9065
9066/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9067/// and binary operator are mixed in a way that suggests the programmer assumed
9068/// the conditional operator has higher precedence, for example:
9069/// "int x = a + someBinaryCondition ? 1 : 2".
9070static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9071 Expr *Condition, const Expr *LHSExpr,
9072 const Expr *RHSExpr) {
9073 BinaryOperatorKind CondOpcode;
9074 const Expr *CondRHS;
9075
9076 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9077 return;
9078 if (!ExprLooksBoolean(E: CondRHS))
9079 return;
9080
9081 // The condition is an arithmetic binary expression, with a right-
9082 // hand side that looks boolean, so warn.
9083
9084 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9085 ? diag::warn_precedence_bitwise_conditional
9086 : diag::warn_precedence_conditional;
9087
9088 Self.Diag(Loc: OpLoc, DiagID)
9089 << Condition->getSourceRange()
9090 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9091
9092 SuggestParentheses(
9093 Self, Loc: OpLoc,
9094 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9095 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9096 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9097
9098 SuggestParentheses(Self, Loc: OpLoc,
9099 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9100 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9101}
9102
9103/// Compute the nullability of a conditional expression.
9104static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9105 QualType LHSTy, QualType RHSTy,
9106 ASTContext &Ctx) {
9107 if (!ResTy->isAnyPointerType())
9108 return ResTy;
9109
9110 auto GetNullability = [](QualType Ty) {
9111 std::optional<NullabilityKind> Kind = Ty->getNullability();
9112 if (Kind) {
9113 // For our purposes, treat _Nullable_result as _Nullable.
9114 if (*Kind == NullabilityKind::NullableResult)
9115 return NullabilityKind::Nullable;
9116 return *Kind;
9117 }
9118 return NullabilityKind::Unspecified;
9119 };
9120
9121 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9122 NullabilityKind MergedKind;
9123
9124 // Compute nullability of a binary conditional expression.
9125 if (IsBin) {
9126 if (LHSKind == NullabilityKind::NonNull)
9127 MergedKind = NullabilityKind::NonNull;
9128 else
9129 MergedKind = RHSKind;
9130 // Compute nullability of a normal conditional expression.
9131 } else {
9132 if (LHSKind == NullabilityKind::Nullable ||
9133 RHSKind == NullabilityKind::Nullable)
9134 MergedKind = NullabilityKind::Nullable;
9135 else if (LHSKind == NullabilityKind::NonNull)
9136 MergedKind = RHSKind;
9137 else if (RHSKind == NullabilityKind::NonNull)
9138 MergedKind = LHSKind;
9139 else
9140 MergedKind = NullabilityKind::Unspecified;
9141 }
9142
9143 // Return if ResTy already has the correct nullability.
9144 if (GetNullability(ResTy) == MergedKind)
9145 return ResTy;
9146
9147 // Strip all nullability from ResTy.
9148 while (ResTy->getNullability())
9149 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9150
9151 // Create a new AttributedType with the new nullability kind.
9152 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9153}
9154
9155ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9156 SourceLocation ColonLoc,
9157 Expr *CondExpr, Expr *LHSExpr,
9158 Expr *RHSExpr) {
9159 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9160 // was the condition.
9161 OpaqueValueExpr *opaqueValue = nullptr;
9162 Expr *commonExpr = nullptr;
9163 if (!LHSExpr) {
9164 commonExpr = CondExpr;
9165 // Lower out placeholder types first. This is important so that we don't
9166 // try to capture a placeholder. This happens in few cases in C++; such
9167 // as Objective-C++'s dictionary subscripting syntax.
9168 if (commonExpr->hasPlaceholderType()) {
9169 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9170 if (!result.isUsable()) return ExprError();
9171 commonExpr = result.get();
9172 }
9173 // We usually want to apply unary conversions *before* saving, except
9174 // in the special case of a C++ l-value conditional.
9175 if (!(getLangOpts().CPlusPlus
9176 && !commonExpr->isTypeDependent()
9177 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9178 && commonExpr->isGLValue()
9179 && commonExpr->isOrdinaryOrBitFieldObject()
9180 && RHSExpr->isOrdinaryOrBitFieldObject()
9181 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9182 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9183 if (commonRes.isInvalid())
9184 return ExprError();
9185 commonExpr = commonRes.get();
9186 }
9187
9188 // If the common expression is a class or array prvalue, materialize it
9189 // so that we can safely refer to it multiple times.
9190 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9191 commonExpr->getType()->isArrayType())) {
9192 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9193 if (MatExpr.isInvalid())
9194 return ExprError();
9195 commonExpr = MatExpr.get();
9196 }
9197
9198 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9199 commonExpr->getType(),
9200 commonExpr->getValueKind(),
9201 commonExpr->getObjectKind(),
9202 commonExpr);
9203 LHSExpr = CondExpr = opaqueValue;
9204 }
9205
9206 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9207 ExprValueKind VK = VK_PRValue;
9208 ExprObjectKind OK = OK_Ordinary;
9209 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9210 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9211 VK, OK, QuestionLoc);
9212 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9213 RHS.isInvalid())
9214 return ExprError();
9215
9216 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9217 RHSExpr: RHS.get());
9218
9219 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9220
9221 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9222 Ctx&: Context);
9223
9224 if (!commonExpr)
9225 return new (Context)
9226 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9227 RHS.get(), result, VK, OK);
9228
9229 return new (Context) BinaryConditionalOperator(
9230 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9231 ColonLoc, result, VK, OK);
9232}
9233
9234bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9235 unsigned FromAttributes = 0, ToAttributes = 0;
9236 if (const auto *FromFn =
9237 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9238 FromAttributes =
9239 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9240 if (const auto *ToFn =
9241 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9242 ToAttributes =
9243 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9244
9245 return FromAttributes != ToAttributes;
9246}
9247
9248// checkPointerTypesForAssignment - This is a very tricky routine (despite
9249// being closely modeled after the C99 spec:-). The odd characteristic of this
9250// routine is it effectively iqnores the qualifiers on the top level pointee.
9251// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9252// FIXME: add a couple examples in this comment.
9253static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9254 QualType LHSType,
9255 QualType RHSType,
9256 SourceLocation Loc) {
9257 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9258 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9259
9260 // get the "pointed to" type (ignoring qualifiers at the top level)
9261 const Type *lhptee, *rhptee;
9262 Qualifiers lhq, rhq;
9263 std::tie(args&: lhptee, args&: lhq) =
9264 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9265 std::tie(args&: rhptee, args&: rhq) =
9266 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9267
9268 AssignConvertType ConvTy = AssignConvertType::Compatible;
9269
9270 // C99 6.5.16.1p1: This following citation is common to constraints
9271 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9272 // qualifiers of the type *pointed to* by the right;
9273
9274 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9275 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9276 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9277 // Ignore lifetime for further calculation.
9278 lhq.removeObjCLifetime();
9279 rhq.removeObjCLifetime();
9280 }
9281
9282 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9283 // Treat address-space mismatches as fatal.
9284 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9285 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9286
9287 // It's okay to add or remove GC or lifetime qualifiers when converting to
9288 // and from void*.
9289 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9290 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9291 Ctx: S.getASTContext()) &&
9292 (lhptee->isVoidType() || rhptee->isVoidType()))
9293 ; // keep old
9294
9295 // Treat lifetime mismatches as fatal.
9296 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9297 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9298
9299 // Treat pointer-auth mismatches as fatal.
9300 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9301 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9302
9303 // For GCC/MS compatibility, other qualifier mismatches are treated
9304 // as still compatible in C.
9305 else
9306 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9307 }
9308
9309 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9310 // incomplete type and the other is a pointer to a qualified or unqualified
9311 // version of void...
9312 if (lhptee->isVoidType()) {
9313 if (rhptee->isIncompleteOrObjectType())
9314 return ConvTy;
9315
9316 // As an extension, we allow cast to/from void* to function pointer.
9317 assert(rhptee->isFunctionType());
9318 return AssignConvertType::FunctionVoidPointer;
9319 }
9320
9321 if (rhptee->isVoidType()) {
9322 // In C, void * to another pointer type is compatible, but we want to note
9323 // that there will be an implicit conversion happening here.
9324 if (lhptee->isIncompleteOrObjectType())
9325 return ConvTy == AssignConvertType::Compatible &&
9326 !S.getLangOpts().CPlusPlus
9327 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9328 : ConvTy;
9329
9330 // As an extension, we allow cast to/from void* to function pointer.
9331 assert(lhptee->isFunctionType());
9332 return AssignConvertType::FunctionVoidPointer;
9333 }
9334
9335 if (!S.Diags.isIgnored(
9336 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9337 Loc) &&
9338 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9339 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9340 return AssignConvertType::IncompatibleFunctionPointerStrict;
9341
9342 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9343 // unqualified versions of compatible types, ...
9344 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9345
9346 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9347 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9348 QualType LUnderlying =
9349 ltrans->isOverflowBehaviorType()
9350 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9351 : ltrans;
9352 QualType RUnderlying =
9353 rtrans->isOverflowBehaviorType()
9354 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9355 : rtrans;
9356
9357 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9358 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9359
9360 ltrans = LUnderlying;
9361 rtrans = RUnderlying;
9362 }
9363 }
9364
9365 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9366 // Check if the pointee types are compatible ignoring the sign.
9367 // We explicitly check for char so that we catch "char" vs
9368 // "unsigned char" on systems where "char" is unsigned.
9369 if (lhptee->isCharType())
9370 ltrans = S.Context.UnsignedCharTy;
9371 else if (lhptee->hasSignedIntegerRepresentation())
9372 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9373
9374 if (rhptee->isCharType())
9375 rtrans = S.Context.UnsignedCharTy;
9376 else if (rhptee->hasSignedIntegerRepresentation())
9377 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9378
9379 if (ltrans == rtrans) {
9380 // Types are compatible ignoring the sign. Qualifier incompatibility
9381 // takes priority over sign incompatibility because the sign
9382 // warning can be disabled.
9383 if (!S.IsAssignConvertCompatible(ConvTy))
9384 return ConvTy;
9385
9386 return AssignConvertType::IncompatiblePointerSign;
9387 }
9388
9389 // If we are a multi-level pointer, it's possible that our issue is simply
9390 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9391 // the eventual target type is the same and the pointers have the same
9392 // level of indirection, this must be the issue.
9393 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9394 do {
9395 std::tie(args&: lhptee, args&: lhq) =
9396 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9397 std::tie(args&: rhptee, args&: rhq) =
9398 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9399
9400 // Inconsistent address spaces at this point is invalid, even if the
9401 // address spaces would be compatible.
9402 // FIXME: This doesn't catch address space mismatches for pointers of
9403 // different nesting levels, like:
9404 // __local int *** a;
9405 // int ** b = a;
9406 // It's not clear how to actually determine when such pointers are
9407 // invalidly incompatible.
9408 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9409 return AssignConvertType::
9410 IncompatibleNestedPointerAddressSpaceMismatch;
9411
9412 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9413
9414 if (lhptee == rhptee)
9415 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9416 }
9417
9418 // General pointer incompatibility takes priority over qualifiers.
9419 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9420 return AssignConvertType::IncompatibleFunctionPointer;
9421 return AssignConvertType::IncompatiblePointer;
9422 }
9423 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9424 // hasSameType, so we can skip further checks.
9425 const auto *LFT = ltrans->getAs<FunctionType>();
9426 const auto *RFT = rtrans->getAs<FunctionType>();
9427 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9428 // The invocation of IsFunctionConversion below will try to transform rtrans
9429 // to obtain an exact match for ltrans. This should not fail because of
9430 // mismatches in result type and parameter types, they were already checked
9431 // by typesAreCompatible above. So we will recreate rtrans (or where
9432 // appropriate ltrans) using the result type and parameter types from ltrans
9433 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9434 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9435 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9436 if (LFPT && RFPT) {
9437 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9438 Args: LFPT->getParamTypes(),
9439 EPI: RFPT->getExtProtoInfo());
9440 } else if (LFPT) {
9441 FunctionProtoType::ExtProtoInfo EPI;
9442 EPI.ExtInfo = RFT->getExtInfo();
9443 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9444 Args: LFPT->getParamTypes(), EPI);
9445 } else if (RFPT) {
9446 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9447 // all of its ExtProtoInfo. Transform ltrans instead.
9448 FunctionProtoType::ExtProtoInfo EPI;
9449 EPI.ExtInfo = LFT->getExtInfo();
9450 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9451 Args: RFPT->getParamTypes(), EPI);
9452 } else {
9453 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9454 Info: RFT->getExtInfo());
9455 }
9456 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9457 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9458 return AssignConvertType::IncompatibleFunctionPointer;
9459 }
9460 return ConvTy;
9461}
9462
9463/// checkBlockPointerTypesForAssignment - This routine determines whether two
9464/// block pointer types are compatible or whether a block and normal pointer
9465/// are compatible. It is more restrict than comparing two function pointer
9466// types.
9467static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9468 QualType LHSType,
9469 QualType RHSType) {
9470 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9471 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9472
9473 QualType lhptee, rhptee;
9474
9475 // get the "pointed to" type (ignoring qualifiers at the top level)
9476 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9477 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9478
9479 // In C++, the types have to match exactly.
9480 if (S.getLangOpts().CPlusPlus)
9481 return AssignConvertType::IncompatibleBlockPointer;
9482
9483 AssignConvertType ConvTy = AssignConvertType::Compatible;
9484
9485 // For blocks we enforce that qualifiers are identical.
9486 Qualifiers LQuals = lhptee.getLocalQualifiers();
9487 Qualifiers RQuals = rhptee.getLocalQualifiers();
9488 if (S.getLangOpts().OpenCL) {
9489 LQuals.removeAddressSpace();
9490 RQuals.removeAddressSpace();
9491 }
9492 if (LQuals != RQuals)
9493 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9494
9495 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9496 // assignment.
9497 // The current behavior is similar to C++ lambdas. A block might be
9498 // assigned to a variable iff its return type and parameters are compatible
9499 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9500 // an assignment. Presumably it should behave in way that a function pointer
9501 // assignment does in C, so for each parameter and return type:
9502 // * CVR and address space of LHS should be a superset of CVR and address
9503 // space of RHS.
9504 // * unqualified types should be compatible.
9505 if (S.getLangOpts().OpenCL) {
9506 if (!S.Context.typesAreBlockPointerCompatible(
9507 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9508 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9509 return AssignConvertType::IncompatibleBlockPointer;
9510 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9511 return AssignConvertType::IncompatibleBlockPointer;
9512
9513 return ConvTy;
9514}
9515
9516/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9517/// for assignment compatibility.
9518static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9519 QualType LHSType,
9520 QualType RHSType) {
9521 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9522 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9523
9524 if (LHSType->isObjCBuiltinType()) {
9525 // Class is not compatible with ObjC object pointers.
9526 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9527 !RHSType->isObjCQualifiedClassType())
9528 return AssignConvertType::IncompatiblePointer;
9529 return AssignConvertType::Compatible;
9530 }
9531 if (RHSType->isObjCBuiltinType()) {
9532 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9533 !LHSType->isObjCQualifiedClassType())
9534 return AssignConvertType::IncompatiblePointer;
9535 return AssignConvertType::Compatible;
9536 }
9537 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9538 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9539
9540 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9541 // make an exception for id<P>
9542 !LHSType->isObjCQualifiedIdType())
9543 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9544
9545 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9546 return AssignConvertType::Compatible;
9547 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9548 return AssignConvertType::IncompatibleObjCQualifiedId;
9549 return AssignConvertType::IncompatiblePointer;
9550}
9551
9552AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9553 QualType LHSType,
9554 QualType RHSType) {
9555 // Fake up an opaque expression. We don't actually care about what
9556 // cast operations are required, so if CheckAssignmentConstraints
9557 // adds casts to this they'll be wasted, but fortunately that doesn't
9558 // usually happen on valid code.
9559 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9560 ExprResult RHSPtr = &RHSExpr;
9561 CastKind K;
9562
9563 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9564}
9565
9566/// This helper function returns true if QT is a vector type that has element
9567/// type ElementType.
9568static bool isVector(QualType QT, QualType ElementType) {
9569 if (const VectorType *VT = QT->getAs<VectorType>())
9570 return VT->getElementType().getCanonicalType() == ElementType;
9571 return false;
9572}
9573
9574/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9575/// has code to accommodate several GCC extensions when type checking
9576/// pointers. Here are some objectionable examples that GCC considers warnings:
9577///
9578/// int a, *pint;
9579/// short *pshort;
9580/// struct foo *pfoo;
9581///
9582/// pint = pshort; // warning: assignment from incompatible pointer type
9583/// a = pint; // warning: assignment makes integer from pointer without a cast
9584/// pint = a; // warning: assignment makes pointer from integer without a cast
9585/// pint = pfoo; // warning: assignment from incompatible pointer type
9586///
9587/// As a result, the code for dealing with pointers is more complex than the
9588/// C99 spec dictates.
9589///
9590/// Sets 'Kind' for any result kind except Incompatible.
9591AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9592 ExprResult &RHS,
9593 CastKind &Kind,
9594 bool ConvertRHS) {
9595 QualType RHSType = RHS.get()->getType();
9596 QualType OrigLHSType = LHSType;
9597
9598 // Get canonical types. We're not formatting these types, just comparing
9599 // them.
9600 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9601 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9602
9603 // Common case: no conversion required.
9604 if (LHSType == RHSType) {
9605 Kind = CK_NoOp;
9606 return AssignConvertType::Compatible;
9607 }
9608
9609 // If the LHS has an __auto_type, there are no additional type constraints
9610 // to be worried about.
9611 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9612 if (AT->isGNUAutoType()) {
9613 Kind = CK_NoOp;
9614 return AssignConvertType::Compatible;
9615 }
9616 }
9617
9618 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9619 switch (OBTResult) {
9620 case ASTContext::OBTAssignResult::IncompatibleKinds:
9621 Kind = CK_NoOp;
9622 return AssignConvertType::IncompatibleOBTKinds;
9623 case ASTContext::OBTAssignResult::Discards:
9624 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9625 return AssignConvertType::CompatibleOBTDiscards;
9626 case ASTContext::OBTAssignResult::Compatible:
9627 case ASTContext::OBTAssignResult::NotApplicable:
9628 break;
9629 }
9630
9631 // Check for incompatible OBT types in pointer pointee types
9632 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9633 QualType LHSPointee = LHSType->getPointeeType();
9634 QualType RHSPointee = RHSType->getPointeeType();
9635 if ((LHSPointee->isOverflowBehaviorType() ||
9636 RHSPointee->isOverflowBehaviorType()) &&
9637 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9638 Kind = CK_NoOp;
9639 return AssignConvertType::IncompatibleOBTKinds;
9640 }
9641 }
9642
9643 // If we have an atomic type, try a non-atomic assignment, then just add an
9644 // atomic qualification step.
9645 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9646 AssignConvertType Result =
9647 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9648 if (!IsAssignConvertCompatible(ConvTy: Result))
9649 return Result;
9650 if (Kind != CK_NoOp && ConvertRHS)
9651 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9652 Kind = CK_NonAtomicToAtomic;
9653 return Result;
9654 }
9655
9656 // If the left-hand side is a reference type, then we are in a
9657 // (rare!) case where we've allowed the use of references in C,
9658 // e.g., as a parameter type in a built-in function. In this case,
9659 // just make sure that the type referenced is compatible with the
9660 // right-hand side type. The caller is responsible for adjusting
9661 // LHSType so that the resulting expression does not have reference
9662 // type.
9663 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9664 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9665 Kind = CK_LValueBitCast;
9666 return AssignConvertType::Compatible;
9667 }
9668 return AssignConvertType::Incompatible;
9669 }
9670
9671 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9672 // of an ExtVector type to the same ExtVector type.
9673 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9674 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9675 // Implicit conversions require the same number of elements.
9676 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9677 return AssignConvertType::Incompatible;
9678
9679 if (LHSType->isExtVectorBoolType() &&
9680 RHSExtType->getElementType()->isIntegerType()) {
9681 Kind = CK_IntegralToBoolean;
9682 return AssignConvertType::Compatible;
9683 }
9684 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9685 if (Context.getLangOpts().OpenCL &&
9686 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9687 Kind = CK_BitCast;
9688 return AssignConvertType::Compatible;
9689 }
9690 return AssignConvertType::Incompatible;
9691 }
9692 if (RHSType->isArithmeticType()) {
9693 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9694 if (ConvertRHS)
9695 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9696 Kind = CK_VectorSplat;
9697 return AssignConvertType::Compatible;
9698 }
9699 }
9700
9701 // Conversions to or from vector type.
9702 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9703 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9704 // Allow assignments of an AltiVec vector type to an equivalent GCC
9705 // vector type and vice versa
9706 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9707 Kind = CK_BitCast;
9708 return AssignConvertType::Compatible;
9709 }
9710
9711 // If we are allowing lax vector conversions, and LHS and RHS are both
9712 // vectors, the total size only needs to be the same. This is a bitcast;
9713 // no bits are changed but the result type is different.
9714 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9715 // The default for lax vector conversions with Altivec vectors will
9716 // change, so if we are converting between vector types where
9717 // at least one is an Altivec vector, emit a warning.
9718 if (Context.getTargetInfo().getTriple().isPPC() &&
9719 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9720 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9721 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9722 << RHSType << LHSType;
9723 Kind = CK_BitCast;
9724 return AssignConvertType::IncompatibleVectors;
9725 }
9726 }
9727
9728 // When the RHS comes from another lax conversion (e.g. binops between
9729 // scalars and vectors) the result is canonicalized as a vector. When the
9730 // LHS is also a vector, the lax is allowed by the condition above. Handle
9731 // the case where LHS is a scalar.
9732 if (LHSType->isScalarType()) {
9733 const VectorType *VecType = RHSType->getAs<VectorType>();
9734 if (VecType && VecType->getNumElements() == 1 &&
9735 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9736 if (Context.getTargetInfo().getTriple().isPPC() &&
9737 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9738 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9739 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9740 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9741 << RHSType << LHSType;
9742 ExprResult *VecExpr = &RHS;
9743 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9744 Kind = CK_BitCast;
9745 return AssignConvertType::Compatible;
9746 }
9747 }
9748
9749 // Allow assignments between fixed-length and sizeless SVE vectors.
9750 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9751 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9752 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9753 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9754 Kind = CK_BitCast;
9755 return AssignConvertType::Compatible;
9756 }
9757
9758 // Allow assignments between fixed-length and sizeless RVV vectors.
9759 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9760 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9761 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9762 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9763 Kind = CK_BitCast;
9764 return AssignConvertType::Compatible;
9765 }
9766 }
9767
9768 return AssignConvertType::Incompatible;
9769 }
9770
9771 // Diagnose attempts to convert between __ibm128, __float128 and long double
9772 // where such conversions currently can't be handled.
9773 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9774 return AssignConvertType::Incompatible;
9775
9776 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9777 // discards the imaginary part.
9778 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9779 !LHSType->getAs<ComplexType>())
9780 return AssignConvertType::Incompatible;
9781
9782 // Arithmetic conversions.
9783 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9784 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9785 if (ConvertRHS)
9786 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9787 return AssignConvertType::Compatible;
9788 }
9789
9790 // Conversions to normal pointers.
9791 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9792 // U* -> T*
9793 if (isa<PointerType>(Val: RHSType)) {
9794 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9795 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9796 if (AddrSpaceL != AddrSpaceR)
9797 Kind = CK_AddressSpaceConversion;
9798 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9799 Kind = CK_NoOp;
9800 else
9801 Kind = CK_BitCast;
9802 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9803 Loc: RHS.get()->getBeginLoc());
9804 }
9805
9806 // int -> T*
9807 if (RHSType->isIntegerType()) {
9808 Kind = CK_IntegralToPointer; // FIXME: null?
9809 return AssignConvertType::IntToPointer;
9810 }
9811
9812 // C pointers are not compatible with ObjC object pointers,
9813 // with two exceptions:
9814 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9815 // - conversions to void*
9816 if (LHSPointer->getPointeeType()->isVoidType()) {
9817 Kind = CK_BitCast;
9818 return AssignConvertType::Compatible;
9819 }
9820
9821 // - conversions from 'Class' to the redefinition type
9822 if (RHSType->isObjCClassType() &&
9823 Context.hasSameType(T1: LHSType,
9824 T2: Context.getObjCClassRedefinitionType())) {
9825 Kind = CK_BitCast;
9826 return AssignConvertType::Compatible;
9827 }
9828
9829 Kind = CK_BitCast;
9830 return AssignConvertType::IncompatiblePointer;
9831 }
9832
9833 // U^ -> void*
9834 if (RHSType->getAs<BlockPointerType>()) {
9835 if (LHSPointer->getPointeeType()->isVoidType()) {
9836 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9837 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9838 ->getPointeeType()
9839 .getAddressSpace();
9840 Kind =
9841 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9842 return AssignConvertType::Compatible;
9843 }
9844 }
9845
9846 return AssignConvertType::Incompatible;
9847 }
9848
9849 // Conversions to block pointers.
9850 if (isa<BlockPointerType>(Val: LHSType)) {
9851 // U^ -> T^
9852 if (RHSType->isBlockPointerType()) {
9853 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9854 ->getPointeeType()
9855 .getAddressSpace();
9856 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9857 ->getPointeeType()
9858 .getAddressSpace();
9859 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9860 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9861 }
9862
9863 // int or null -> T^
9864 if (RHSType->isIntegerType()) {
9865 Kind = CK_IntegralToPointer; // FIXME: null
9866 return AssignConvertType::IntToBlockPointer;
9867 }
9868
9869 // id -> T^
9870 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9871 Kind = CK_AnyPointerToBlockPointerCast;
9872 return AssignConvertType::Compatible;
9873 }
9874
9875 // void* -> T^
9876 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9877 if (RHSPT->getPointeeType()->isVoidType()) {
9878 Kind = CK_AnyPointerToBlockPointerCast;
9879 return AssignConvertType::Compatible;
9880 }
9881
9882 return AssignConvertType::Incompatible;
9883 }
9884
9885 // Conversions to Objective-C pointers.
9886 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
9887 // A* -> B*
9888 if (RHSType->isObjCObjectPointerType()) {
9889 Kind = CK_BitCast;
9890 AssignConvertType result =
9891 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9892 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9893 result == AssignConvertType::Compatible &&
9894 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
9895 result = AssignConvertType::IncompatibleObjCWeakRef;
9896 return result;
9897 }
9898
9899 // int or null -> A*
9900 if (RHSType->isIntegerType()) {
9901 Kind = CK_IntegralToPointer; // FIXME: null
9902 return AssignConvertType::IntToPointer;
9903 }
9904
9905 // In general, C pointers are not compatible with ObjC object pointers,
9906 // with two exceptions:
9907 if (isa<PointerType>(Val: RHSType)) {
9908 Kind = CK_CPointerToObjCPointerCast;
9909
9910 // - conversions from 'void*'
9911 if (RHSType->isVoidPointerType()) {
9912 return AssignConvertType::Compatible;
9913 }
9914
9915 // - conversions to 'Class' from its redefinition type
9916 if (LHSType->isObjCClassType() &&
9917 Context.hasSameType(T1: RHSType,
9918 T2: Context.getObjCClassRedefinitionType())) {
9919 return AssignConvertType::Compatible;
9920 }
9921
9922 return AssignConvertType::IncompatiblePointer;
9923 }
9924
9925 // Only under strict condition T^ is compatible with an Objective-C pointer.
9926 if (RHSType->isBlockPointerType() &&
9927 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
9928 if (ConvertRHS)
9929 maybeExtendBlockObject(E&: RHS);
9930 Kind = CK_BlockPointerToObjCPointerCast;
9931 return AssignConvertType::Compatible;
9932 }
9933
9934 return AssignConvertType::Incompatible;
9935 }
9936
9937 // Conversion to nullptr_t (C23 only)
9938 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9939 RHS.get()->isNullPointerConstant(Ctx&: Context,
9940 NPC: Expr::NPC_ValueDependentIsNull)) {
9941 // null -> nullptr_t
9942 Kind = CK_NullToPointer;
9943 return AssignConvertType::Compatible;
9944 }
9945
9946 // Conversions from pointers that are not covered by the above.
9947 if (isa<PointerType>(Val: RHSType)) {
9948 // T* -> _Bool
9949 if (LHSType == Context.BoolTy) {
9950 Kind = CK_PointerToBoolean;
9951 return AssignConvertType::Compatible;
9952 }
9953
9954 // T* -> int
9955 if (LHSType->isIntegerType()) {
9956 Kind = CK_PointerToIntegral;
9957 return AssignConvertType::PointerToInt;
9958 }
9959
9960 return AssignConvertType::Incompatible;
9961 }
9962
9963 // Conversions from Objective-C pointers that are not covered by the above.
9964 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9965 // T* -> _Bool
9966 if (LHSType == Context.BoolTy) {
9967 Kind = CK_PointerToBoolean;
9968 return AssignConvertType::Compatible;
9969 }
9970
9971 // T* -> int
9972 if (LHSType->isIntegerType()) {
9973 Kind = CK_PointerToIntegral;
9974 return AssignConvertType::PointerToInt;
9975 }
9976
9977 return AssignConvertType::Incompatible;
9978 }
9979
9980 // struct A -> struct B
9981 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
9982 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
9983 Kind = CK_NoOp;
9984 return AssignConvertType::Compatible;
9985 }
9986 }
9987
9988 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9989 Kind = CK_IntToOCLSampler;
9990 return AssignConvertType::Compatible;
9991 }
9992
9993 return AssignConvertType::Incompatible;
9994}
9995
9996/// Constructs a transparent union from an expression that is
9997/// used to initialize the transparent union.
9998static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9999 ExprResult &EResult, QualType UnionType,
10000 FieldDecl *Field) {
10001 // Build an initializer list that designates the appropriate member
10002 // of the transparent union.
10003 Expr *E = EResult.get();
10004 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10005 E, SourceLocation());
10006 Initializer->setType(UnionType);
10007 Initializer->setInitializedFieldInUnion(Field);
10008
10009 // Build a compound literal constructing a value of the transparent
10010 // union type from this initializer list.
10011 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10012 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10013 VK_PRValue, Initializer, false);
10014}
10015
10016AssignConvertType
10017Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10018 ExprResult &RHS) {
10019 QualType RHSType = RHS.get()->getType();
10020
10021 // If the ArgType is a Union type, we want to handle a potential
10022 // transparent_union GCC extension.
10023 const RecordType *UT = ArgType->getAsUnionType();
10024 if (!UT)
10025 return AssignConvertType::Incompatible;
10026
10027 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10028 if (!UD->hasAttr<TransparentUnionAttr>())
10029 return AssignConvertType::Incompatible;
10030
10031 // The field to initialize within the transparent union.
10032 FieldDecl *InitField = nullptr;
10033 // It's compatible if the expression matches any of the fields.
10034 for (auto *it : UD->fields()) {
10035 if (it->getType()->isPointerType()) {
10036 // If the transparent union contains a pointer type, we allow:
10037 // 1) void pointer
10038 // 2) null pointer constant
10039 if (RHSType->isPointerType())
10040 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10041 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10042 InitField = it;
10043 break;
10044 }
10045
10046 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10047 NPC: Expr::NPC_ValueDependentIsNull)) {
10048 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10049 CK: CK_NullToPointer);
10050 InitField = it;
10051 break;
10052 }
10053 }
10054
10055 CastKind Kind;
10056 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10057 AssignConvertType::Compatible) {
10058 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10059 InitField = it;
10060 break;
10061 }
10062 }
10063
10064 if (!InitField)
10065 return AssignConvertType::Incompatible;
10066
10067 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10068 return AssignConvertType::Compatible;
10069}
10070
10071AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10072 ExprResult &CallerRHS,
10073 bool Diagnose,
10074 bool DiagnoseCFAudited,
10075 bool ConvertRHS) {
10076 // We need to be able to tell the caller whether we diagnosed a problem, if
10077 // they ask us to issue diagnostics.
10078 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10079
10080 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10081 // we can't avoid *all* modifications at the moment, so we need some somewhere
10082 // to put the updated value.
10083 ExprResult LocalRHS = CallerRHS;
10084 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10085
10086 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10087 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10088 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10089 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10090 Diag(Loc: RHS.get()->getExprLoc(),
10091 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10092 << RHS.get()->getSourceRange();
10093 }
10094 }
10095 }
10096
10097 if (getLangOpts().CPlusPlus) {
10098 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10099 // C++ 5.17p3: If the left operand is not of class type, the
10100 // expression is implicitly converted (C++ 4) to the
10101 // cv-unqualified type of the left operand.
10102 QualType RHSType = RHS.get()->getType();
10103 if (Diagnose) {
10104 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10105 Action: AssignmentAction::Assigning);
10106 } else {
10107 ImplicitConversionSequence ICS =
10108 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10109 /*SuppressUserConversions=*/false,
10110 AllowExplicit: AllowedExplicit::None,
10111 /*InOverloadResolution=*/false,
10112 /*CStyle=*/false,
10113 /*AllowObjCWritebackConversion=*/false);
10114 if (ICS.isFailure())
10115 return AssignConvertType::Incompatible;
10116 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10117 ICS, Action: AssignmentAction::Assigning);
10118 }
10119 if (RHS.isInvalid())
10120 return AssignConvertType::Incompatible;
10121 AssignConvertType result = AssignConvertType::Compatible;
10122 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10123 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10124 result = AssignConvertType::IncompatibleObjCWeakRef;
10125
10126 // Check if OBT is being discarded during assignment
10127 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10128 if (RHSType->isOverflowBehaviorType() &&
10129 !LHSType->isOverflowBehaviorType()) {
10130 result = AssignConvertType::CompatibleOBTDiscards;
10131 }
10132
10133 return result;
10134 }
10135
10136 // FIXME: Currently, we fall through and treat C++ classes like C
10137 // structures.
10138 // FIXME: We also fall through for atomics; not sure what should
10139 // happen there, though.
10140 } else if (RHS.get()->getType() == Context.OverloadTy) {
10141 // As a set of extensions to C, we support overloading on functions. These
10142 // functions need to be resolved here.
10143 DeclAccessPair DAP;
10144 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10145 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10146 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10147 else
10148 return AssignConvertType::Incompatible;
10149 }
10150
10151 // This check seems unnatural, however it is necessary to ensure the proper
10152 // conversion of functions/arrays. If the conversion were done for all
10153 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10154 // expressions that suppress this implicit conversion (&, sizeof). This needs
10155 // to happen before we check for null pointer conversions because C does not
10156 // undergo the same implicit conversions as C++ does above (by the calls to
10157 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10158 // lvalue to rvalue cast before checking for null pointer constraints. This
10159 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10160 //
10161 // Suppress this for references: C++ 8.5.3p5.
10162 if (!LHSType->isReferenceType()) {
10163 // FIXME: We potentially allocate here even if ConvertRHS is false.
10164 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10165 if (RHS.isInvalid())
10166 return AssignConvertType::Incompatible;
10167 }
10168
10169 // The constraints are expressed in terms of the atomic, qualified, or
10170 // unqualified type of the LHS.
10171 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10172
10173 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10174 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10175 if ((LHSTypeAfterConversion->isPointerType() ||
10176 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10177 LHSTypeAfterConversion->isBlockPointerType()) &&
10178 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10179 RHS.get()->isNullPointerConstant(Ctx&: Context,
10180 NPC: Expr::NPC_ValueDependentIsNull))) {
10181 AssignConvertType Ret = AssignConvertType::Compatible;
10182 if (Diagnose || ConvertRHS) {
10183 CastKind Kind;
10184 CXXCastPath Path;
10185 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10186 /*IgnoreBaseAccess=*/false, Diagnose);
10187
10188 // If there is a conversion of some kind, check to see what kind of
10189 // pointer conversion happened so we can diagnose a C++ compatibility
10190 // diagnostic if the conversion is invalid. This only matters if the RHS
10191 // is some kind of void pointer. We have a carve-out when the RHS is from
10192 // a macro expansion because the use of a macro may indicate different
10193 // code between C and C++. Consider: char *s = NULL; where NULL is
10194 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10195 // C++, which is valid in C++.
10196 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10197 !RHS.get()->getBeginLoc().isMacroID()) {
10198 QualType CanRHS =
10199 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10200 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10201 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10202 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10203 Loc: RHS.get()->getExprLoc());
10204 // Anything that's not considered perfectly compatible would be
10205 // incompatible in C++.
10206 if (Ret != AssignConvertType::Compatible)
10207 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10208 }
10209 }
10210
10211 if (ConvertRHS)
10212 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10213 }
10214 return Ret;
10215 }
10216 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10217 // unqualified bool, and the right operand is a pointer or its type is
10218 // nullptr_t.
10219 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10220 RHS.get()->getType()->isNullPtrType()) {
10221 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10222 // only handles nullptr -> _Bool due to needing an extra conversion
10223 // step.
10224 // We model this by converting from nullptr -> void * and then let the
10225 // conversion from void * -> _Bool happen naturally.
10226 if (Diagnose || ConvertRHS) {
10227 CastKind Kind;
10228 CXXCastPath Path;
10229 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10230 /*IgnoreBaseAccess=*/false, Diagnose);
10231 if (ConvertRHS)
10232 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10233 BasePath: &Path);
10234 }
10235 }
10236
10237 // OpenCL queue_t type assignment.
10238 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10239 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10240 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10241 return AssignConvertType::Compatible;
10242 }
10243
10244 CastKind Kind;
10245 AssignConvertType result =
10246 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10247
10248 // If assigning a void * created by an allocation function call to some other
10249 // type, check that the allocated size is sufficient for that type.
10250 if (result != AssignConvertType::Incompatible &&
10251 RHS.get()->getType()->isVoidPointerType())
10252 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10253
10254 // C99 6.5.16.1p2: The value of the right operand is converted to the
10255 // type of the assignment expression.
10256 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10257 // so that we can use references in built-in functions even in C.
10258 // The getNonReferenceType() call makes sure that the resulting expression
10259 // does not have reference type.
10260 if (result != AssignConvertType::Incompatible &&
10261 RHS.get()->getType() != LHSType) {
10262 QualType Ty = LHSType.getNonLValueExprType(Context);
10263 Expr *E = RHS.get();
10264
10265 // Check for various Objective-C errors. If we are not reporting
10266 // diagnostics and just checking for errors, e.g., during overload
10267 // resolution, return Incompatible to indicate the failure.
10268 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10269 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10270 CCK: CheckedConversionKind::Implicit, Diagnose,
10271 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10272 if (!Diagnose)
10273 return AssignConvertType::Incompatible;
10274 }
10275 if (getLangOpts().ObjC &&
10276 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10277 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10278 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10279 if (!Diagnose)
10280 return AssignConvertType::Incompatible;
10281 // Replace the expression with a corrected version and continue so we
10282 // can find further errors.
10283 RHS = E;
10284 return AssignConvertType::Compatible;
10285 }
10286
10287 if (ConvertRHS)
10288 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10289 }
10290
10291 return result;
10292}
10293
10294namespace {
10295/// The original operand to an operator, prior to the application of the usual
10296/// arithmetic conversions and converting the arguments of a builtin operator
10297/// candidate.
10298struct OriginalOperand {
10299 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10300 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10301 Op = MTE->getSubExpr();
10302 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10303 Op = BTE->getSubExpr();
10304 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10305 Orig = ICE->getSubExprAsWritten();
10306 Conversion = ICE->getConversionFunction();
10307 }
10308 }
10309
10310 QualType getType() const { return Orig->getType(); }
10311
10312 Expr *Orig;
10313 NamedDecl *Conversion;
10314};
10315}
10316
10317QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10318 ExprResult &RHS) {
10319 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10320
10321 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10322 << OrigLHS.getType() << OrigRHS.getType()
10323 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10324
10325 // If a user-defined conversion was applied to either of the operands prior
10326 // to applying the built-in operator rules, tell the user about it.
10327 if (OrigLHS.Conversion) {
10328 Diag(Loc: OrigLHS.Conversion->getLocation(),
10329 DiagID: diag::note_typecheck_invalid_operands_converted)
10330 << 0 << LHS.get()->getType();
10331 }
10332 if (OrigRHS.Conversion) {
10333 Diag(Loc: OrigRHS.Conversion->getLocation(),
10334 DiagID: diag::note_typecheck_invalid_operands_converted)
10335 << 1 << RHS.get()->getType();
10336 }
10337
10338 return QualType();
10339}
10340
10341QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10342 ExprResult &RHS) {
10343 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10344 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10345
10346 bool LHSNatVec = LHSType->isVectorType();
10347 bool RHSNatVec = RHSType->isVectorType();
10348
10349 if (!(LHSNatVec && RHSNatVec)) {
10350 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10351 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10352 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10353 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10354 << Vector->getSourceRange();
10355 return QualType();
10356 }
10357
10358 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10359 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10360 << RHS.get()->getSourceRange();
10361
10362 return QualType();
10363}
10364
10365/// Try to convert a value of non-vector type to a vector type by converting
10366/// the type to the element type of the vector and then performing a splat.
10367/// If the language is OpenCL, we only use conversions that promote scalar
10368/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10369/// for float->int.
10370///
10371/// OpenCL V2.0 6.2.6.p2:
10372/// An error shall occur if any scalar operand type has greater rank
10373/// than the type of the vector element.
10374///
10375/// \param scalar - if non-null, actually perform the conversions
10376/// \return true if the operation fails (but without diagnosing the failure)
10377static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10378 QualType scalarTy,
10379 QualType vectorEltTy,
10380 QualType vectorTy,
10381 unsigned &DiagID) {
10382 // The conversion to apply to the scalar before splatting it,
10383 // if necessary.
10384 CastKind scalarCast = CK_NoOp;
10385
10386 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10387 scalarCast = CK_IntegralToBoolean;
10388 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10389 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10390 (scalarTy->isIntegerType() &&
10391 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10392 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10393 return true;
10394 }
10395 if (!scalarTy->isIntegralType(Ctx: S.Context))
10396 return true;
10397 scalarCast = CK_IntegralCast;
10398 } else if (vectorEltTy->isRealFloatingType()) {
10399 if (scalarTy->isRealFloatingType()) {
10400 if (S.getLangOpts().OpenCL &&
10401 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10402 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10403 return true;
10404 }
10405 scalarCast = CK_FloatingCast;
10406 }
10407 else if (scalarTy->isIntegralType(Ctx: S.Context))
10408 scalarCast = CK_IntegralToFloating;
10409 else
10410 return true;
10411 } else {
10412 return true;
10413 }
10414
10415 // Adjust scalar if desired.
10416 if (scalar) {
10417 if (scalarCast != CK_NoOp)
10418 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10419 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10420 }
10421 return false;
10422}
10423
10424/// Convert vector E to a vector with the same number of elements but different
10425/// element type.
10426static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10427 const auto *VecTy = E->getType()->getAs<VectorType>();
10428 assert(VecTy && "Expression E must be a vector");
10429 QualType NewVecTy =
10430 VecTy->isExtVectorType()
10431 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10432 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10433 VecKind: VecTy->getVectorKind());
10434
10435 // Look through the implicit cast. Return the subexpression if its type is
10436 // NewVecTy.
10437 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10438 if (ICE->getSubExpr()->getType() == NewVecTy)
10439 return ICE->getSubExpr();
10440
10441 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10442 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10443}
10444
10445/// Test if a (constant) integer Int can be casted to another integer type
10446/// IntTy without losing precision.
10447static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10448 QualType OtherIntTy) {
10449 Expr *E = Int->get();
10450 if (E->containsErrors() || E->isInstantiationDependent())
10451 return false;
10452
10453 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10454
10455 // Reject cases where the value of the Int is unknown as that would
10456 // possibly cause truncation, but accept cases where the scalar can be
10457 // demoted without loss of precision.
10458 Expr::EvalResult EVResult;
10459 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10460 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10461 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10462 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10463
10464 if (CstInt) {
10465 // If the scalar is constant and is of a higher order and has more active
10466 // bits that the vector element type, reject it.
10467 llvm::APSInt Result = EVResult.Val.getInt();
10468 unsigned NumBits = IntSigned
10469 ? (Result.isNegative() ? Result.getSignificantBits()
10470 : Result.getActiveBits())
10471 : Result.getActiveBits();
10472 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10473 return true;
10474
10475 // If the signedness of the scalar type and the vector element type
10476 // differs and the number of bits is greater than that of the vector
10477 // element reject it.
10478 return (IntSigned != OtherIntSigned &&
10479 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10480 }
10481
10482 // Reject cases where the value of the scalar is not constant and it's
10483 // order is greater than that of the vector element type.
10484 return (Order < 0);
10485}
10486
10487/// Test if a (constant) integer Int can be casted to floating point type
10488/// FloatTy without losing precision.
10489static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10490 QualType FloatTy) {
10491 if (Int->get()->containsErrors())
10492 return false;
10493
10494 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10495
10496 // Determine if the integer constant can be expressed as a floating point
10497 // number of the appropriate type.
10498 Expr::EvalResult EVResult;
10499 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10500
10501 uint64_t Bits = 0;
10502 if (CstInt) {
10503 // Reject constants that would be truncated if they were converted to
10504 // the floating point type. Test by simple to/from conversion.
10505 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10506 // could be avoided if there was a convertFromAPInt method
10507 // which could signal back if implicit truncation occurred.
10508 llvm::APSInt Result = EVResult.Val.getInt();
10509 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10510 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10511 RM: llvm::APFloat::rmTowardZero);
10512 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10513 !IntTy->hasSignedIntegerRepresentation());
10514 bool Ignored = false;
10515 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10516 IsExact: &Ignored);
10517 if (Result != ConvertBack)
10518 return true;
10519 } else {
10520 // Reject types that cannot be fully encoded into the mantissa of
10521 // the float.
10522 Bits = S.Context.getTypeSize(T: IntTy);
10523 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10524 S.Context.getFloatTypeSemantics(T: FloatTy));
10525 if (Bits > FloatPrec)
10526 return true;
10527 }
10528
10529 return false;
10530}
10531
10532/// Attempt to convert and splat Scalar into a vector whose types matches
10533/// Vector following GCC conversion rules. The rule is that implicit
10534/// conversion can occur when Scalar can be casted to match Vector's element
10535/// type without causing truncation of Scalar.
10536static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10537 ExprResult *Vector) {
10538 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10539 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10540 QualType VectorEltTy;
10541
10542 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10543 assert(!isa<ExtVectorType>(VT) &&
10544 "ExtVectorTypes should not be handled here!");
10545 VectorEltTy = VT->getElementType();
10546 } else if (VectorTy->isSveVLSBuiltinType()) {
10547 VectorEltTy =
10548 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10549 } else {
10550 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10551 }
10552
10553 // Reject cases where the vector element type or the scalar element type are
10554 // not integral or floating point types.
10555 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10556 return true;
10557
10558 // The conversion to apply to the scalar before splatting it,
10559 // if necessary.
10560 CastKind ScalarCast = CK_NoOp;
10561
10562 // Accept cases where the vector elements are integers and the scalar is
10563 // an integer.
10564 // FIXME: Notionally if the scalar was a floating point value with a precise
10565 // integral representation, we could cast it to an appropriate integer
10566 // type and then perform the rest of the checks here. GCC will perform
10567 // this conversion in some cases as determined by the input language.
10568 // We should accept it on a language independent basis.
10569 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10570 ScalarTy->isIntegralType(Ctx: S.Context) &&
10571 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10572
10573 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10574 return true;
10575
10576 ScalarCast = CK_IntegralCast;
10577 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10578 ScalarTy->isRealFloatingType()) {
10579 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10580 ScalarCast = CK_FloatingToIntegral;
10581 else
10582 return true;
10583 } else if (VectorEltTy->isRealFloatingType()) {
10584 if (ScalarTy->isRealFloatingType()) {
10585
10586 // Reject cases where the scalar type is not a constant and has a higher
10587 // Order than the vector element type.
10588 llvm::APFloat Result(0.0);
10589
10590 // Determine whether this is a constant scalar. In the event that the
10591 // value is dependent (and thus cannot be evaluated by the constant
10592 // evaluator), skip the evaluation. This will then diagnose once the
10593 // expression is instantiated.
10594 bool CstScalar = Scalar->get()->isValueDependent() ||
10595 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10596 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10597 if (!CstScalar && Order < 0)
10598 return true;
10599
10600 // If the scalar cannot be safely casted to the vector element type,
10601 // reject it.
10602 if (CstScalar) {
10603 bool Truncated = false;
10604 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10605 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10606 if (Truncated)
10607 return true;
10608 }
10609
10610 ScalarCast = CK_FloatingCast;
10611 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10612 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10613 return true;
10614
10615 ScalarCast = CK_IntegralToFloating;
10616 } else
10617 return true;
10618 } else if (ScalarTy->isEnumeralType())
10619 return true;
10620
10621 // Adjust scalar if desired.
10622 if (ScalarCast != CK_NoOp)
10623 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10624 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10625 return false;
10626}
10627
10628QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10629 SourceLocation Loc, bool IsCompAssign,
10630 bool AllowBothBool,
10631 bool AllowBoolConversions,
10632 bool AllowBoolOperation,
10633 bool ReportInvalid) {
10634 if (!IsCompAssign) {
10635 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10636 if (LHS.isInvalid())
10637 return QualType();
10638 }
10639 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10640 if (RHS.isInvalid())
10641 return QualType();
10642
10643 // For conversion purposes, we ignore any qualifiers.
10644 // For example, "const float" and "float" are equivalent.
10645 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10646 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10647
10648 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10649 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10650 assert(LHSVecType || RHSVecType);
10651
10652 if (getLangOpts().HLSL)
10653 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10654 IsCompAssign);
10655
10656 // Any operation with MFloat8 type is only possible with C intrinsics
10657 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10658 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10659 return InvalidOperands(Loc, LHS, RHS);
10660
10661 // AltiVec-style "vector bool op vector bool" combinations are allowed
10662 // for some operators but not others.
10663 if (!AllowBothBool && LHSVecType &&
10664 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10665 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10666 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10667
10668 // This operation may not be performed on boolean vectors.
10669 if (!AllowBoolOperation &&
10670 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10671 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10672
10673 // If the vector types are identical, return.
10674 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10675 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10676
10677 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10678 if (LHSVecType && RHSVecType &&
10679 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10680 if (isa<ExtVectorType>(Val: LHSVecType)) {
10681 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10682 return LHSType;
10683 }
10684
10685 if (!IsCompAssign)
10686 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10687 return RHSType;
10688 }
10689
10690 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10691 // can be mixed, with the result being the non-bool type. The non-bool
10692 // operand must have integer element type.
10693 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10694 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10695 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10696 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10697 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10698 LHSVecType->getElementType()->isIntegerType() &&
10699 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10700 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10701 return LHSType;
10702 }
10703 if (!IsCompAssign &&
10704 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10705 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10706 RHSVecType->getElementType()->isIntegerType()) {
10707 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10708 return RHSType;
10709 }
10710 }
10711
10712 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10713 // invalid since the ambiguity can affect the ABI.
10714 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10715 unsigned &SVEorRVV) {
10716 const VectorType *VecType = SecondType->getAs<VectorType>();
10717 SVEorRVV = 0;
10718 if (FirstType->isSizelessBuiltinType() && VecType) {
10719 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10720 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10721 return true;
10722 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10723 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10724 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10725 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10726 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10727 SVEorRVV = 1;
10728 return true;
10729 }
10730 }
10731
10732 return false;
10733 };
10734
10735 unsigned SVEorRVV;
10736 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10737 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10738 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10739 << SVEorRVV << LHSType << RHSType;
10740 return QualType();
10741 }
10742
10743 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10744 // invalid since the ambiguity can affect the ABI.
10745 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10746 unsigned &SVEorRVV) {
10747 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10748 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10749
10750 SVEorRVV = 0;
10751 if (FirstVecType && SecondVecType) {
10752 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10753 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10754 SecondVecType->getVectorKind() ==
10755 VectorKind::SveFixedLengthPredicate)
10756 return true;
10757 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10758 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10759 SecondVecType->getVectorKind() ==
10760 VectorKind::RVVFixedLengthMask_1 ||
10761 SecondVecType->getVectorKind() ==
10762 VectorKind::RVVFixedLengthMask_2 ||
10763 SecondVecType->getVectorKind() ==
10764 VectorKind::RVVFixedLengthMask_4) {
10765 SVEorRVV = 1;
10766 return true;
10767 }
10768 }
10769 return false;
10770 }
10771
10772 if (SecondVecType &&
10773 SecondVecType->getVectorKind() == VectorKind::Generic) {
10774 if (FirstType->isSVESizelessBuiltinType())
10775 return true;
10776 if (FirstType->isRVVSizelessBuiltinType()) {
10777 SVEorRVV = 1;
10778 return true;
10779 }
10780 }
10781
10782 return false;
10783 };
10784
10785 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10786 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10787 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10788 << SVEorRVV << LHSType << RHSType;
10789 return QualType();
10790 }
10791
10792 // If there's a vector type and a scalar, try to convert the scalar to
10793 // the vector element type and splat.
10794 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10795 if (!RHSVecType) {
10796 if (isa<ExtVectorType>(Val: LHSVecType)) {
10797 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10798 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10799 DiagID))
10800 return LHSType;
10801 } else {
10802 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10803 return LHSType;
10804 }
10805 }
10806 if (!LHSVecType) {
10807 if (isa<ExtVectorType>(Val: RHSVecType)) {
10808 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10809 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10810 vectorTy: RHSType, DiagID))
10811 return RHSType;
10812 } else {
10813 if (LHS.get()->isLValue() ||
10814 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10815 return RHSType;
10816 }
10817 }
10818
10819 // FIXME: The code below also handles conversion between vectors and
10820 // non-scalars, we should break this down into fine grained specific checks
10821 // and emit proper diagnostics.
10822 QualType VecType = LHSVecType ? LHSType : RHSType;
10823 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10824 QualType OtherType = LHSVecType ? RHSType : LHSType;
10825 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10826 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10827 if (Context.getTargetInfo().getTriple().isPPC() &&
10828 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10829 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10830 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10831 // If we're allowing lax vector conversions, only the total (data) size
10832 // needs to be the same. For non compound assignment, if one of the types is
10833 // scalar, the result is always the vector type.
10834 if (!IsCompAssign) {
10835 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10836 return VecType;
10837 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10838 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10839 // type. Note that this is already done by non-compound assignments in
10840 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10841 // <1 x T> -> T. The result is also a vector type.
10842 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10843 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10844 ExprResult *RHSExpr = &RHS;
10845 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10846 return VecType;
10847 }
10848 }
10849
10850 // Okay, the expression is invalid.
10851
10852 // If there's a non-vector, non-real operand, diagnose that.
10853 if ((!RHSVecType && !RHSType->isRealType()) ||
10854 (!LHSVecType && !LHSType->isRealType())) {
10855 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10856 << LHSType << RHSType
10857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10858 return QualType();
10859 }
10860
10861 // OpenCL V1.1 6.2.6.p1:
10862 // If the operands are of more than one vector type, then an error shall
10863 // occur. Implicit conversions between vector types are not permitted, per
10864 // section 6.2.1.
10865 if (getLangOpts().OpenCL &&
10866 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10867 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10868 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10869 << RHSType;
10870 return QualType();
10871 }
10872
10873
10874 // If there is a vector type that is not a ExtVector and a scalar, we reach
10875 // this point if scalar could not be converted to the vector's element type
10876 // without truncation.
10877 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
10878 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
10879 QualType Scalar = LHSVecType ? RHSType : LHSType;
10880 QualType Vector = LHSVecType ? LHSType : RHSType;
10881 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10882 Diag(Loc,
10883 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10884 << ScalarOrVector << Scalar << Vector;
10885
10886 return QualType();
10887 }
10888
10889 // Otherwise, use the generic diagnostic.
10890 Diag(Loc, DiagID)
10891 << LHSType << RHSType
10892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10893 return QualType();
10894}
10895
10896QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10897 SourceLocation Loc,
10898 bool IsCompAssign,
10899 ArithConvKind OperationKind) {
10900 if (!IsCompAssign) {
10901 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10902 if (LHS.isInvalid())
10903 return QualType();
10904 }
10905 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10906 if (RHS.isInvalid())
10907 return QualType();
10908
10909 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10910 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10911
10912 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10913 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10914
10915 unsigned DiagID = diag::err_typecheck_invalid_operands;
10916 if ((OperationKind == ArithConvKind::Arithmetic) &&
10917 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10918 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10919 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10920 << RHS.get()->getSourceRange();
10921 return QualType();
10922 }
10923
10924 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10925 return LHSType;
10926
10927 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10928 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10929 return LHSType;
10930 }
10931 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10932 if (LHS.get()->isLValue() ||
10933 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10934 return RHSType;
10935 }
10936
10937 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10938 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10939 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10940 << LHSType << RHSType << LHS.get()->getSourceRange()
10941 << RHS.get()->getSourceRange();
10942 return QualType();
10943 }
10944
10945 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10946 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
10947 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
10948 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
10949 << LHSType << RHSType << LHS.get()->getSourceRange()
10950 << RHS.get()->getSourceRange();
10951 return QualType();
10952 }
10953
10954 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10955 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10956 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10957 bool ScalarOrVector =
10958 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10959
10960 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10961 << ScalarOrVector << Scalar << Vector;
10962
10963 return QualType();
10964 }
10965
10966 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10967 << RHS.get()->getSourceRange();
10968 return QualType();
10969}
10970
10971// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10972// expression. These are mainly cases where the null pointer is used as an
10973// integer instead of a pointer.
10974static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10975 SourceLocation Loc, bool IsCompare) {
10976 // The canonical way to check for a GNU null is with isNullPointerConstant,
10977 // but we use a bit of a hack here for speed; this is a relatively
10978 // hot path, and isNullPointerConstant is slow.
10979 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
10980 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
10981
10982 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10983
10984 // Avoid analyzing cases where the result will either be invalid (and
10985 // diagnosed as such) or entirely valid and not something to warn about.
10986 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10987 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10988 return;
10989
10990 // Comparison operations would not make sense with a null pointer no matter
10991 // what the other expression is.
10992 if (!IsCompare) {
10993 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
10994 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10995 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10996 return;
10997 }
10998
10999 // The rest of the operations only make sense with a null pointer
11000 // if the other expression is a pointer.
11001 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11002 NonNullType->canDecayToPointerType())
11003 return;
11004
11005 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11006 << LHSNull /* LHS is NULL */ << NonNullType
11007 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11008}
11009
11010static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11011 SourceLocation OpLoc) {
11012 // If the divisor is real, then this is real/real or complex/real division.
11013 // Either way there can be no precision loss.
11014 auto *CT = DivisorTy->getAs<ComplexType>();
11015 if (!CT)
11016 return;
11017
11018 QualType ElementType = CT->getElementType().getCanonicalType();
11019 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11020 LangOptions::ComplexRangeKind::CX_Promoted;
11021 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11022 return;
11023
11024 ASTContext &Ctx = S.getASTContext();
11025 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11026 const llvm::fltSemantics &ElementTypeSemantics =
11027 Ctx.getFloatTypeSemantics(T: ElementType);
11028 const llvm::fltSemantics &HigherElementTypeSemantics =
11029 Ctx.getFloatTypeSemantics(T: HigherElementType);
11030
11031 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11032 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11033 (HigherElementType == Ctx.LongDoubleTy &&
11034 !Ctx.getTargetInfo().hasLongDoubleType())) {
11035 // Retain the location of the first use of higher precision type.
11036 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11037 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11038 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11039 if (Type == HigherElementType) {
11040 Num++;
11041 return;
11042 }
11043 }
11044 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11045 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11046 }
11047}
11048
11049static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11050 SourceLocation Loc) {
11051 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11052 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11053 if (!LUE || !RUE)
11054 return;
11055 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11056 RUE->getKind() != UETT_SizeOf)
11057 return;
11058
11059 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11060 QualType LHSTy = LHSArg->getType();
11061 QualType RHSTy;
11062
11063 if (RUE->isArgumentType())
11064 RHSTy = RUE->getArgumentType().getNonReferenceType();
11065 else
11066 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11067
11068 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11069 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11070 return;
11071
11072 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11073 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11074 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11075 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11076 << LHSArgDecl;
11077 }
11078 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11079 QualType ArrayElemTy = ArrayTy->getElementType();
11080 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11081 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11082 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11083 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11084 return;
11085 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11086 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11087 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11088 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11089 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11090 << LHSArgDecl;
11091 }
11092
11093 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11094 }
11095}
11096
11097static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11098 ExprResult &RHS,
11099 SourceLocation Loc, bool IsDiv) {
11100 // Check for division/remainder by zero.
11101 Expr::EvalResult RHSValue;
11102 if (!RHS.get()->isValueDependent() &&
11103 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11104 RHSValue.Val.getInt() == 0)
11105 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11106 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11107 << IsDiv << RHS.get()->getSourceRange());
11108}
11109
11110static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11111 const ExprResult &LHS, const ExprResult &RHS,
11112 BinaryOperatorKind Opc) {
11113 if (!LHS.isUsable() || !RHS.isUsable())
11114 return;
11115 const Expr *LHSExpr = LHS.get();
11116 const Expr *RHSExpr = RHS.get();
11117 const QualType LHSType = LHSExpr->getType();
11118 const QualType RHSType = RHSExpr->getType();
11119 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11120 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11121 if (!LHSIsScoped && !RHSIsScoped)
11122 return;
11123 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11124 return;
11125 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11126 return;
11127 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11128 return;
11129 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11130 SourceLocation BeginLoc = expr->getBeginLoc();
11131 QualType IntType = type->castAs<EnumType>()
11132 ->getDecl()
11133 ->getDefinitionOrSelf()
11134 ->getIntegerType();
11135 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11136 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11137 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11138 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11139 };
11140 if (LHSIsScoped) {
11141 DiagnosticHelper(LHSExpr, LHSType);
11142 }
11143 if (RHSIsScoped) {
11144 DiagnosticHelper(RHSExpr, RHSType);
11145 }
11146}
11147
11148QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11149 SourceLocation Loc,
11150 BinaryOperatorKind Opc) {
11151 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11152 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11153
11154 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11155
11156 QualType LHSTy = LHS.get()->getType();
11157 QualType RHSTy = RHS.get()->getType();
11158 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11159 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11160 /*AllowBothBool*/ getLangOpts().AltiVec,
11161 /*AllowBoolConversions*/ false,
11162 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11163 /*ReportInvalid*/ true);
11164 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11165 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11166 OperationKind: ArithConvKind::Arithmetic);
11167 if (!IsDiv &&
11168 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11169 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11170 // For division, only matrix-by-scalar is supported. Other combinations with
11171 // matrix types are invalid.
11172 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11173 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11174
11175 QualType compType = UsualArithmeticConversions(
11176 LHS, RHS, Loc,
11177 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11178 if (LHS.isInvalid() || RHS.isInvalid())
11179 return QualType();
11180
11181 if (compType.isNull() || !compType->isArithmeticType()) {
11182 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11183 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11184 return ResultTy;
11185 }
11186 if (IsDiv) {
11187 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11188 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11189 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11190 }
11191 return compType;
11192}
11193
11194QualType Sema::CheckRemainderOperands(
11195 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11196 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11197
11198 // Note: This check is here to simplify the double exclusions of
11199 // scalar and vector HLSL checks. No getLangOpts().HLSL
11200 // is needed since all languages exlcude doubles.
11201 if (LHS.get()->getType()->isDoubleType() ||
11202 RHS.get()->getType()->isDoubleType() ||
11203 (LHS.get()->getType()->isVectorType() && LHS.get()
11204 ->getType()
11205 ->getAs<VectorType>()
11206 ->getElementType()
11207 ->isDoubleType()) ||
11208 (RHS.get()->getType()->isVectorType() && RHS.get()
11209 ->getType()
11210 ->getAs<VectorType>()
11211 ->getElementType()
11212 ->isDoubleType()))
11213 return InvalidOperands(Loc, LHS, RHS);
11214
11215 if (LHS.get()->getType()->isVectorType() ||
11216 RHS.get()->getType()->isVectorType()) {
11217 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11218 RHS.get()->getType()->hasIntegerRepresentation()) ||
11219 (getLangOpts().HLSL &&
11220 (LHS.get()->getType()->hasFloatingRepresentation() ||
11221 RHS.get()->getType()->hasFloatingRepresentation())))
11222 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11223 /*AllowBothBool*/ getLangOpts().AltiVec,
11224 /*AllowBoolConversions*/ false,
11225 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11226 /*ReportInvalid*/ true);
11227 return InvalidOperands(Loc, LHS, RHS);
11228 }
11229
11230 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11231 RHS.get()->getType()->isSveVLSBuiltinType()) {
11232 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11233 RHS.get()->getType()->hasIntegerRepresentation())
11234 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11235 OperationKind: ArithConvKind::Arithmetic);
11236
11237 return InvalidOperands(Loc, LHS, RHS);
11238 }
11239
11240 QualType compType = UsualArithmeticConversions(
11241 LHS, RHS, Loc,
11242 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11243 if (LHS.isInvalid() || RHS.isInvalid())
11244 return QualType();
11245
11246 if (compType.isNull() ||
11247 (!compType->isIntegerType() &&
11248 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11249 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11250 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11251 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11252 return ResultTy;
11253 }
11254 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11255 return compType;
11256}
11257
11258/// Diagnose invalid arithmetic on two void pointers.
11259static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11260 Expr *LHSExpr, Expr *RHSExpr) {
11261 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11262 ? diag::err_typecheck_pointer_arith_void_type
11263 : diag::ext_gnu_void_ptr)
11264 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11265 << RHSExpr->getSourceRange();
11266}
11267
11268/// Diagnose invalid arithmetic on a void pointer.
11269static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11270 Expr *Pointer) {
11271 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11272 ? diag::err_typecheck_pointer_arith_void_type
11273 : diag::ext_gnu_void_ptr)
11274 << 0 /* one pointer */ << Pointer->getSourceRange();
11275}
11276
11277/// Diagnose invalid arithmetic on a null pointer.
11278///
11279/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11280/// idiom, which we recognize as a GNU extension.
11281///
11282static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11283 Expr *Pointer, bool IsGNUIdiom) {
11284 if (IsGNUIdiom)
11285 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11286 << Pointer->getSourceRange();
11287 else
11288 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11289 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11290}
11291
11292/// Diagnose invalid subraction on a null pointer.
11293///
11294static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11295 Expr *Pointer, bool BothNull) {
11296 // Null - null is valid in C++ [expr.add]p7
11297 if (BothNull && S.getLangOpts().CPlusPlus)
11298 return;
11299
11300 // Is this s a macro from a system header?
11301 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11302 return;
11303
11304 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11305 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11306 << S.getLangOpts().CPlusPlus
11307 << Pointer->getSourceRange());
11308}
11309
11310/// Diagnose invalid arithmetic on two function pointers.
11311static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11312 Expr *LHS, Expr *RHS) {
11313 assert(LHS->getType()->isAnyPointerType());
11314 assert(RHS->getType()->isAnyPointerType());
11315 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11316 ? diag::err_typecheck_pointer_arith_function_type
11317 : diag::ext_gnu_ptr_func_arith)
11318 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11319 // We only show the second type if it differs from the first.
11320 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11321 T2: RHS->getType())
11322 << RHS->getType()->getPointeeType()
11323 << LHS->getSourceRange() << RHS->getSourceRange();
11324}
11325
11326/// Diagnose invalid arithmetic on a function pointer.
11327static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11328 Expr *Pointer) {
11329 assert(Pointer->getType()->isAnyPointerType());
11330 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11331 ? diag::err_typecheck_pointer_arith_function_type
11332 : diag::ext_gnu_ptr_func_arith)
11333 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11334 << 0 /* one pointer, so only one type */
11335 << Pointer->getSourceRange();
11336}
11337
11338/// Emit error if Operand is incomplete pointer type
11339///
11340/// \returns True if pointer has incomplete type
11341static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11342 Expr *Operand) {
11343 QualType ResType = Operand->getType();
11344 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11345 ResType = ResAtomicType->getValueType();
11346
11347 assert(ResType->isAnyPointerType());
11348 QualType PointeeTy = ResType->getPointeeType();
11349 return S.RequireCompleteSizedType(
11350 Loc, T: PointeeTy,
11351 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11352 Args: Operand->getSourceRange());
11353}
11354
11355/// Check the validity of an arithmetic pointer operand.
11356///
11357/// If the operand has pointer type, this code will check for pointer types
11358/// which are invalid in arithmetic operations. These will be diagnosed
11359/// appropriately, including whether or not the use is supported as an
11360/// extension.
11361///
11362/// \returns True when the operand is valid to use (even if as an extension).
11363static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11364 Expr *Operand) {
11365 QualType ResType = Operand->getType();
11366 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11367 ResType = ResAtomicType->getValueType();
11368
11369 if (!ResType->isAnyPointerType()) return true;
11370
11371 QualType PointeeTy = ResType->getPointeeType();
11372 if (PointeeTy->isVoidType()) {
11373 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11374 return !S.getLangOpts().CPlusPlus;
11375 }
11376 if (PointeeTy->isFunctionType()) {
11377 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11378 return !S.getLangOpts().CPlusPlus;
11379 }
11380
11381 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11382
11383 return true;
11384}
11385
11386/// Check the validity of a binary arithmetic operation w.r.t. pointer
11387/// operands.
11388///
11389/// This routine will diagnose any invalid arithmetic on pointer operands much
11390/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11391/// for emitting a single diagnostic even for operations where both LHS and RHS
11392/// are (potentially problematic) pointers.
11393///
11394/// \returns True when the operand is valid to use (even if as an extension).
11395static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11396 Expr *LHSExpr, Expr *RHSExpr) {
11397 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11398 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11399 if (!isLHSPointer && !isRHSPointer) return true;
11400
11401 QualType LHSPointeeTy, RHSPointeeTy;
11402 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11403 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11404
11405 // if both are pointers check if operation is valid wrt address spaces
11406 if (isLHSPointer && isRHSPointer) {
11407 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11408 Ctx: S.getASTContext())) {
11409 S.Diag(Loc,
11410 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11411 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11412 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11413 return false;
11414 }
11415 }
11416
11417 // Check for arithmetic on pointers to incomplete types.
11418 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11419 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11420 if (isLHSVoidPtr || isRHSVoidPtr) {
11421 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11422 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11423 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11424
11425 return !S.getLangOpts().CPlusPlus;
11426 }
11427
11428 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11429 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11430 if (isLHSFuncPtr || isRHSFuncPtr) {
11431 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11432 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11433 Pointer: RHSExpr);
11434 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11435
11436 return !S.getLangOpts().CPlusPlus;
11437 }
11438
11439 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11440 return false;
11441 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11442 return false;
11443
11444 return true;
11445}
11446
11447/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11448/// literal.
11449static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11450 Expr *LHSExpr, Expr *RHSExpr) {
11451 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11452 Expr* IndexExpr = RHSExpr;
11453 if (!StrExpr) {
11454 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11455 IndexExpr = LHSExpr;
11456 }
11457
11458 bool IsStringPlusInt = StrExpr &&
11459 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11460 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11461 return;
11462
11463 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11464 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11465 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11466
11467 // Only print a fixit for "str" + int, not for int + "str".
11468 if (IndexExpr == RHSExpr) {
11469 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11470 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11471 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11472 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11473 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11474 } else
11475 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11476}
11477
11478/// Emit a warning when adding a char literal to a string.
11479static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11480 Expr *LHSExpr, Expr *RHSExpr) {
11481 const Expr *StringRefExpr = LHSExpr;
11482 const CharacterLiteral *CharExpr =
11483 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11484
11485 if (!CharExpr) {
11486 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11487 StringRefExpr = RHSExpr;
11488 }
11489
11490 if (!CharExpr || !StringRefExpr)
11491 return;
11492
11493 const QualType StringType = StringRefExpr->getType();
11494
11495 // Return if not a PointerType.
11496 if (!StringType->isAnyPointerType())
11497 return;
11498
11499 // Return if not a CharacterType.
11500 if (!StringType->getPointeeType()->isAnyCharacterType())
11501 return;
11502
11503 ASTContext &Ctx = Self.getASTContext();
11504 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11505
11506 const QualType CharType = CharExpr->getType();
11507 if (!CharType->isAnyCharacterType() &&
11508 CharType->isIntegerType() &&
11509 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11510 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11511 << DiagRange << Ctx.CharTy;
11512 } else {
11513 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11514 << DiagRange << CharExpr->getType();
11515 }
11516
11517 // Only print a fixit for str + char, not for char + str.
11518 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11519 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11520 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11521 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11522 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11523 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11524 } else {
11525 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11526 }
11527}
11528
11529/// Emit error when two pointers are incompatible.
11530static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11531 Expr *LHSExpr, Expr *RHSExpr) {
11532 assert(LHSExpr->getType()->isAnyPointerType());
11533 assert(RHSExpr->getType()->isAnyPointerType());
11534 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11535 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11536 << RHSExpr->getSourceRange();
11537}
11538
11539// C99 6.5.6
11540QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11541 SourceLocation Loc, BinaryOperatorKind Opc,
11542 QualType* CompLHSTy) {
11543 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11544
11545 if (LHS.get()->getType()->isVectorType() ||
11546 RHS.get()->getType()->isVectorType()) {
11547 QualType compType =
11548 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11549 /*AllowBothBool*/ getLangOpts().AltiVec,
11550 /*AllowBoolConversions*/ getLangOpts().ZVector,
11551 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11552 /*ReportInvalid*/ true);
11553 if (CompLHSTy) *CompLHSTy = compType;
11554 return compType;
11555 }
11556
11557 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11558 RHS.get()->getType()->isSveVLSBuiltinType()) {
11559 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11560 OperationKind: ArithConvKind::Arithmetic);
11561 if (CompLHSTy)
11562 *CompLHSTy = compType;
11563 return compType;
11564 }
11565
11566 if (LHS.get()->getType()->isConstantMatrixType() ||
11567 RHS.get()->getType()->isConstantMatrixType()) {
11568 QualType compType =
11569 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11570 if (CompLHSTy)
11571 *CompLHSTy = compType;
11572 return compType;
11573 }
11574
11575 QualType compType = UsualArithmeticConversions(
11576 LHS, RHS, Loc,
11577 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11578 if (LHS.isInvalid() || RHS.isInvalid())
11579 return QualType();
11580
11581 // Diagnose "string literal" '+' int and string '+' "char literal".
11582 if (Opc == BO_Add) {
11583 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11584 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11585 }
11586
11587 // handle the common case first (both operands are arithmetic).
11588 if (!compType.isNull() && compType->isArithmeticType()) {
11589 if (CompLHSTy) *CompLHSTy = compType;
11590 return compType;
11591 }
11592
11593 // Type-checking. Ultimately the pointer's going to be in PExp;
11594 // note that we bias towards the LHS being the pointer.
11595 Expr *PExp = LHS.get(), *IExp = RHS.get();
11596
11597 bool isObjCPointer;
11598 if (PExp->getType()->isPointerType()) {
11599 isObjCPointer = false;
11600 } else if (PExp->getType()->isObjCObjectPointerType()) {
11601 isObjCPointer = true;
11602 } else {
11603 std::swap(a&: PExp, b&: IExp);
11604 if (PExp->getType()->isPointerType()) {
11605 isObjCPointer = false;
11606 } else if (PExp->getType()->isObjCObjectPointerType()) {
11607 isObjCPointer = true;
11608 } else {
11609 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11610 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11611 return ResultTy;
11612 }
11613 }
11614 assert(PExp->getType()->isAnyPointerType());
11615
11616 if (!IExp->getType()->isIntegerType())
11617 return InvalidOperands(Loc, LHS, RHS);
11618
11619 // Adding to a null pointer results in undefined behavior.
11620 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11621 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11622 // In C++ adding zero to a null pointer is defined.
11623 Expr::EvalResult KnownVal;
11624 if (!getLangOpts().CPlusPlus ||
11625 (!IExp->isValueDependent() &&
11626 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11627 KnownVal.Val.getInt() != 0))) {
11628 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11629 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11630 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11631 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11632 }
11633 }
11634
11635 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11636 return QualType();
11637
11638 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11639 return QualType();
11640
11641 // Arithmetic on label addresses is normally allowed, except when we add
11642 // a ptrauth signature to the addresses.
11643 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11644 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11645 << /*addition*/ 1;
11646 return QualType();
11647 }
11648
11649 // Check array bounds for pointer arithemtic
11650 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11651
11652 if (CompLHSTy) {
11653 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11654 if (LHSTy.isNull()) {
11655 LHSTy = LHS.get()->getType();
11656 if (Context.isPromotableIntegerType(T: LHSTy))
11657 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11658 }
11659 *CompLHSTy = LHSTy;
11660 }
11661
11662 return PExp->getType();
11663}
11664
11665// C99 6.5.6
11666QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11667 SourceLocation Loc,
11668 BinaryOperatorKind Opc,
11669 QualType *CompLHSTy) {
11670 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11671
11672 if (LHS.get()->getType()->isVectorType() ||
11673 RHS.get()->getType()->isVectorType()) {
11674 QualType compType =
11675 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11676 /*AllowBothBool*/ getLangOpts().AltiVec,
11677 /*AllowBoolConversions*/ getLangOpts().ZVector,
11678 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11679 /*ReportInvalid*/ true);
11680 if (CompLHSTy) *CompLHSTy = compType;
11681 return compType;
11682 }
11683
11684 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11685 RHS.get()->getType()->isSveVLSBuiltinType()) {
11686 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11687 OperationKind: ArithConvKind::Arithmetic);
11688 if (CompLHSTy)
11689 *CompLHSTy = compType;
11690 return compType;
11691 }
11692
11693 if (LHS.get()->getType()->isConstantMatrixType() ||
11694 RHS.get()->getType()->isConstantMatrixType()) {
11695 QualType compType =
11696 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11697 if (CompLHSTy)
11698 *CompLHSTy = compType;
11699 return compType;
11700 }
11701
11702 QualType compType = UsualArithmeticConversions(
11703 LHS, RHS, Loc,
11704 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11705 if (LHS.isInvalid() || RHS.isInvalid())
11706 return QualType();
11707
11708 // Enforce type constraints: C99 6.5.6p3.
11709
11710 // Handle the common case first (both operands are arithmetic).
11711 if (!compType.isNull() && compType->isArithmeticType()) {
11712 if (CompLHSTy) *CompLHSTy = compType;
11713 return compType;
11714 }
11715
11716 // Either ptr - int or ptr - ptr.
11717 if (LHS.get()->getType()->isAnyPointerType()) {
11718 QualType lpointee = LHS.get()->getType()->getPointeeType();
11719
11720 // Diagnose bad cases where we step over interface counts.
11721 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11722 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11723 return QualType();
11724
11725 // Arithmetic on label addresses is normally allowed, except when we add
11726 // a ptrauth signature to the addresses.
11727 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11728 getLangOpts().PointerAuthIndirectGotos) {
11729 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11730 << /*subtraction*/ 0;
11731 return QualType();
11732 }
11733
11734 // The result type of a pointer-int computation is the pointer type.
11735 if (RHS.get()->getType()->isIntegerType()) {
11736 // Subtracting from a null pointer should produce a warning.
11737 // The last argument to the diagnose call says this doesn't match the
11738 // GNU int-to-pointer idiom.
11739 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11740 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11741 // In C++ adding zero to a null pointer is defined.
11742 Expr::EvalResult KnownVal;
11743 if (!getLangOpts().CPlusPlus ||
11744 (!RHS.get()->isValueDependent() &&
11745 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11746 KnownVal.Val.getInt() != 0))) {
11747 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11748 }
11749 }
11750
11751 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11752 return QualType();
11753
11754 // Check array bounds for pointer arithemtic
11755 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11756 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11757
11758 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11759 return LHS.get()->getType();
11760 }
11761
11762 // Handle pointer-pointer subtractions.
11763 if (const PointerType *RHSPTy
11764 = RHS.get()->getType()->getAs<PointerType>()) {
11765 QualType rpointee = RHSPTy->getPointeeType();
11766
11767 if (getLangOpts().CPlusPlus) {
11768 // Pointee types must be the same: C++ [expr.add]
11769 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11770 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11771 }
11772 } else {
11773 // Pointee types must be compatible C99 6.5.6p3
11774 if (!Context.typesAreCompatible(
11775 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11776 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11777 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11778 return QualType();
11779 }
11780 }
11781
11782 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11783 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11784 return QualType();
11785
11786 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11787 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11788 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11789 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11790
11791 // Subtracting nullptr or from nullptr is suspect
11792 if (LHSIsNullPtr)
11793 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11794 if (RHSIsNullPtr)
11795 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11796
11797 // The pointee type may have zero size. As an extension, a structure or
11798 // union may have zero size or an array may have zero length. In this
11799 // case subtraction does not make sense.
11800 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11801 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11802 if (ElementSize.isZero()) {
11803 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11804 << rpointee.getUnqualifiedType()
11805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11806 }
11807 }
11808
11809 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11810 return Context.getPointerDiffType();
11811 }
11812 }
11813
11814 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11815 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11816 return ResultTy;
11817}
11818
11819static bool isScopedEnumerationType(QualType T) {
11820 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11821 return ET->getDecl()->isScoped();
11822 return false;
11823}
11824
11825static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11826 SourceLocation Loc, BinaryOperatorKind Opc,
11827 QualType LHSType) {
11828 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11829 // so skip remaining warnings as we don't want to modify values within Sema.
11830 if (S.getLangOpts().OpenCL)
11831 return;
11832
11833 if (Opc == BO_Shr &&
11834 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11835 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11836
11837 // Check right/shifter operand
11838 Expr::EvalResult RHSResult;
11839 if (RHS.get()->isValueDependent() ||
11840 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11841 return;
11842 llvm::APSInt Right = RHSResult.Val.getInt();
11843
11844 if (Right.isNegative()) {
11845 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11846 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11847 << RHS.get()->getSourceRange());
11848 return;
11849 }
11850
11851 QualType LHSExprType = LHS.get()->getType();
11852 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11853 if (LHSExprType->isBitIntType())
11854 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11855 else if (LHSExprType->isFixedPointType()) {
11856 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11857 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11858 }
11859 if (Right.uge(RHS: LeftSize)) {
11860 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11861 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11862 << RHS.get()->getSourceRange());
11863 return;
11864 }
11865
11866 // FIXME: We probably need to handle fixed point types specially here.
11867 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11868 return;
11869
11870 // When left shifting an ICE which is signed, we can check for overflow which
11871 // according to C++ standards prior to C++2a has undefined behavior
11872 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11873 // more than the maximum value representable in the result type, so never
11874 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11875 // expression is still probably a bug.)
11876 Expr::EvalResult LHSResult;
11877 if (LHS.get()->isValueDependent() ||
11878 LHSType->hasUnsignedIntegerRepresentation() ||
11879 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
11880 return;
11881 llvm::APSInt Left = LHSResult.Val.getInt();
11882
11883 // Don't warn if signed overflow is defined, then all the rest of the
11884 // diagnostics will not be triggered because the behavior is defined.
11885 // Also don't warn in C++20 mode (and newer), as signed left shifts
11886 // always wrap and never overflow.
11887 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11888 return;
11889
11890 // If LHS does not have a non-negative value then, the
11891 // behavior is undefined before C++2a. Warn about it.
11892 if (Left.isNegative()) {
11893 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
11894 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
11895 << LHS.get()->getSourceRange());
11896 return;
11897 }
11898
11899 llvm::APInt ResultBits =
11900 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11901 if (ResultBits.ule(RHS: LeftSize))
11902 return;
11903 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
11904 Result = Result.shl(ShiftAmt: Right);
11905
11906 // Print the bit representation of the signed integer as an unsigned
11907 // hexadecimal number.
11908 SmallString<40> HexResult;
11909 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
11910
11911 // If we are only missing a sign bit, this is less likely to result in actual
11912 // bugs -- if the result is cast back to an unsigned type, it will have the
11913 // expected value. Thus we place this behind a different warning that can be
11914 // turned off separately if needed.
11915 if (ResultBits - 1 == LeftSize) {
11916 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
11917 << HexResult << LHSType
11918 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11919 return;
11920 }
11921
11922 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
11923 << HexResult.str() << Result.getSignificantBits() << LHSType
11924 << Left.getBitWidth() << LHS.get()->getSourceRange()
11925 << RHS.get()->getSourceRange();
11926}
11927
11928/// Return the resulting type when a vector is shifted
11929/// by a scalar or vector shift amount.
11930static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11931 SourceLocation Loc, bool IsCompAssign) {
11932 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11933 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11934 !LHS.get()->getType()->isVectorType()) {
11935 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
11936 << RHS.get()->getType() << LHS.get()->getType()
11937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11938 return QualType();
11939 }
11940
11941 if (!IsCompAssign) {
11942 LHS = S.UsualUnaryConversions(E: LHS.get());
11943 if (LHS.isInvalid()) return QualType();
11944 }
11945
11946 RHS = S.UsualUnaryConversions(E: RHS.get());
11947 if (RHS.isInvalid()) return QualType();
11948
11949 QualType LHSType = LHS.get()->getType();
11950 // Note that LHS might be a scalar because the routine calls not only in
11951 // OpenCL case.
11952 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11953 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11954
11955 // Note that RHS might not be a vector.
11956 QualType RHSType = RHS.get()->getType();
11957 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11958 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11959
11960 // Do not allow shifts for boolean vectors.
11961 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11962 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11963 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
11964 << LHS.get()->getType() << RHS.get()->getType()
11965 << LHS.get()->getSourceRange();
11966 return QualType();
11967 }
11968
11969 // The operands need to be integers.
11970 if (!LHSEleType->isIntegerType()) {
11971 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11972 << LHS.get()->getType() << LHS.get()->getSourceRange();
11973 return QualType();
11974 }
11975
11976 if (!RHSEleType->isIntegerType()) {
11977 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11978 << RHS.get()->getType() << RHS.get()->getSourceRange();
11979 return QualType();
11980 }
11981
11982 if (!LHSVecTy) {
11983 assert(RHSVecTy);
11984 if (IsCompAssign)
11985 return RHSType;
11986 if (LHSEleType != RHSEleType) {
11987 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
11988 LHSEleType = RHSEleType;
11989 }
11990 QualType VecTy =
11991 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
11992 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
11993 LHSType = VecTy;
11994 } else if (RHSVecTy) {
11995 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11996 // are applied component-wise. So if RHS is a vector, then ensure
11997 // that the number of elements is the same as LHS...
11998 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11999 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12000 << LHS.get()->getType() << RHS.get()->getType()
12001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12002 return QualType();
12003 }
12004 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12005 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12006 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12007 if (LHSBT != RHSBT &&
12008 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12009 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12010 << LHS.get()->getType() << RHS.get()->getType()
12011 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12012 }
12013 }
12014 } else {
12015 // ...else expand RHS to match the number of elements in LHS.
12016 QualType VecTy =
12017 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12018 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12019 }
12020
12021 return LHSType;
12022}
12023
12024static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12025 ExprResult &RHS, SourceLocation Loc,
12026 bool IsCompAssign) {
12027 if (!IsCompAssign) {
12028 LHS = S.UsualUnaryConversions(E: LHS.get());
12029 if (LHS.isInvalid())
12030 return QualType();
12031 }
12032
12033 RHS = S.UsualUnaryConversions(E: RHS.get());
12034 if (RHS.isInvalid())
12035 return QualType();
12036
12037 QualType LHSType = LHS.get()->getType();
12038 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12039 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12040 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12041 : LHSType;
12042
12043 // Note that RHS might not be a vector
12044 QualType RHSType = RHS.get()->getType();
12045 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12046 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12047 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12048 : RHSType;
12049
12050 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12051 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12052 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12053 << LHSType << RHSType << LHS.get()->getSourceRange();
12054 return QualType();
12055 }
12056
12057 if (!LHSEleType->isIntegerType()) {
12058 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12059 << LHS.get()->getType() << LHS.get()->getSourceRange();
12060 return QualType();
12061 }
12062
12063 if (!RHSEleType->isIntegerType()) {
12064 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12065 << RHS.get()->getType() << RHS.get()->getSourceRange();
12066 return QualType();
12067 }
12068
12069 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12070 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12071 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12072 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12073 << LHSType << RHSType << LHS.get()->getSourceRange()
12074 << RHS.get()->getSourceRange();
12075 return QualType();
12076 }
12077
12078 if (!LHSType->isSveVLSBuiltinType()) {
12079 assert(RHSType->isSveVLSBuiltinType());
12080 if (IsCompAssign)
12081 return RHSType;
12082 if (LHSEleType != RHSEleType) {
12083 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12084 LHSEleType = RHSEleType;
12085 }
12086 const llvm::ElementCount VecSize =
12087 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12088 QualType VecTy =
12089 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12090 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12091 LHSType = VecTy;
12092 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12093 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12094 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12095 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12096 << LHSType << RHSType << LHS.get()->getSourceRange()
12097 << RHS.get()->getSourceRange();
12098 return QualType();
12099 }
12100 } else {
12101 const llvm::ElementCount VecSize =
12102 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12103 if (LHSEleType != RHSEleType) {
12104 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12105 RHSEleType = LHSEleType;
12106 }
12107 QualType VecTy =
12108 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12109 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12110 }
12111
12112 return LHSType;
12113}
12114
12115// C99 6.5.7
12116QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12117 SourceLocation Loc, BinaryOperatorKind Opc,
12118 bool IsCompAssign) {
12119 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12120
12121 // Vector shifts promote their scalar inputs to vector type.
12122 if (LHS.get()->getType()->isVectorType() ||
12123 RHS.get()->getType()->isVectorType()) {
12124 if (LangOpts.ZVector) {
12125 // The shift operators for the z vector extensions work basically
12126 // like general shifts, except that neither the LHS nor the RHS is
12127 // allowed to be a "vector bool".
12128 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12129 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12130 return InvalidOperands(Loc, LHS, RHS);
12131 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12132 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12133 return InvalidOperands(Loc, LHS, RHS);
12134 }
12135 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12136 }
12137
12138 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12139 RHS.get()->getType()->isSveVLSBuiltinType())
12140 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12141
12142 // Shifts don't perform usual arithmetic conversions, they just do integer
12143 // promotions on each operand. C99 6.5.7p3
12144
12145 // For the LHS, do usual unary conversions, but then reset them away
12146 // if this is a compound assignment.
12147 ExprResult OldLHS = LHS;
12148 LHS = UsualUnaryConversions(E: LHS.get());
12149 if (LHS.isInvalid())
12150 return QualType();
12151 QualType LHSType = LHS.get()->getType();
12152 if (IsCompAssign) LHS = OldLHS;
12153
12154 // The RHS is simpler.
12155 RHS = UsualUnaryConversions(E: RHS.get());
12156 if (RHS.isInvalid())
12157 return QualType();
12158 QualType RHSType = RHS.get()->getType();
12159
12160 // C99 6.5.7p2: Each of the operands shall have integer type.
12161 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12162 if ((!LHSType->isFixedPointOrIntegerType() &&
12163 !LHSType->hasIntegerRepresentation()) ||
12164 !RHSType->hasIntegerRepresentation()) {
12165 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12166 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12167 return ResultTy;
12168 }
12169
12170 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12171
12172 // "The type of the result is that of the promoted left operand."
12173 return LHSType;
12174}
12175
12176/// Diagnose bad pointer comparisons.
12177static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12178 ExprResult &LHS, ExprResult &RHS,
12179 bool IsError) {
12180 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12181 : diag::ext_typecheck_comparison_of_distinct_pointers)
12182 << LHS.get()->getType() << RHS.get()->getType()
12183 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12184}
12185
12186/// Returns false if the pointers are converted to a composite type,
12187/// true otherwise.
12188static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12189 ExprResult &LHS, ExprResult &RHS) {
12190 // C++ [expr.rel]p2:
12191 // [...] Pointer conversions (4.10) and qualification
12192 // conversions (4.4) are performed on pointer operands (or on
12193 // a pointer operand and a null pointer constant) to bring
12194 // them to their composite pointer type. [...]
12195 //
12196 // C++ [expr.eq]p1 uses the same notion for (in)equality
12197 // comparisons of pointers.
12198
12199 QualType LHSType = LHS.get()->getType();
12200 QualType RHSType = RHS.get()->getType();
12201 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12202 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12203
12204 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12205 if (T.isNull()) {
12206 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12207 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12208 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12209 else
12210 S.InvalidOperands(Loc, LHS, RHS);
12211 return true;
12212 }
12213
12214 return false;
12215}
12216
12217static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12218 ExprResult &LHS,
12219 ExprResult &RHS,
12220 bool IsError) {
12221 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12222 : diag::ext_typecheck_comparison_of_fptr_to_void)
12223 << LHS.get()->getType() << RHS.get()->getType()
12224 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12225}
12226
12227static bool isObjCObjectLiteral(ExprResult &E) {
12228 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12229 case Stmt::ObjCArrayLiteralClass:
12230 case Stmt::ObjCDictionaryLiteralClass:
12231 case Stmt::ObjCStringLiteralClass:
12232 case Stmt::ObjCBoxedExprClass:
12233 return true;
12234 default:
12235 // Note that ObjCBoolLiteral is NOT an object literal!
12236 return false;
12237 }
12238}
12239
12240static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12241 const ObjCObjectPointerType *Type =
12242 LHS->getType()->getAs<ObjCObjectPointerType>();
12243
12244 // If this is not actually an Objective-C object, bail out.
12245 if (!Type)
12246 return false;
12247
12248 // Get the LHS object's interface type.
12249 QualType InterfaceType = Type->getPointeeType();
12250
12251 // If the RHS isn't an Objective-C object, bail out.
12252 if (!RHS->getType()->isObjCObjectPointerType())
12253 return false;
12254
12255 // Try to find the -isEqual: method.
12256 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12257 ObjCMethodDecl *Method =
12258 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12259 /*IsInstance=*/true);
12260 if (!Method) {
12261 if (Type->isObjCIdType()) {
12262 // For 'id', just check the global pool.
12263 Method =
12264 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12265 /*receiverId=*/receiverIdOrClass: true);
12266 } else {
12267 // Check protocols.
12268 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12269 /*IsInstance=*/true);
12270 }
12271 }
12272
12273 if (!Method)
12274 return false;
12275
12276 QualType T = Method->parameters()[0]->getType();
12277 if (!T->isObjCObjectPointerType())
12278 return false;
12279
12280 QualType R = Method->getReturnType();
12281 if (!R->isScalarType())
12282 return false;
12283
12284 return true;
12285}
12286
12287static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12288 ExprResult &LHS, ExprResult &RHS,
12289 BinaryOperator::Opcode Opc){
12290 Expr *Literal;
12291 Expr *Other;
12292 if (isObjCObjectLiteral(E&: LHS)) {
12293 Literal = LHS.get();
12294 Other = RHS.get();
12295 } else {
12296 Literal = RHS.get();
12297 Other = LHS.get();
12298 }
12299
12300 // Don't warn on comparisons against nil.
12301 Other = Other->IgnoreParenCasts();
12302 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12303 NPC: Expr::NPC_ValueDependentIsNotNull))
12304 return;
12305
12306 // This should be kept in sync with warn_objc_literal_comparison.
12307 // LK_String should always be after the other literals, since it has its own
12308 // warning flag.
12309 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12310 assert(LiteralKind != SemaObjC::LK_Block);
12311 if (LiteralKind == SemaObjC::LK_None) {
12312 llvm_unreachable("Unknown Objective-C object literal kind");
12313 }
12314
12315 if (LiteralKind == SemaObjC::LK_String)
12316 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12317 << Literal->getSourceRange();
12318 else
12319 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12320 << LiteralKind << Literal->getSourceRange();
12321
12322 if (BinaryOperator::isEqualityOp(Opc) &&
12323 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12324 SourceLocation Start = LHS.get()->getBeginLoc();
12325 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12326 CharSourceRange OpRange =
12327 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12328
12329 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12330 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12331 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12332 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12333 }
12334}
12335
12336/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12337static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12338 ExprResult &RHS, SourceLocation Loc,
12339 BinaryOperatorKind Opc) {
12340 // Check that left hand side is !something.
12341 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12342 if (!UO || UO->getOpcode() != UO_LNot) return;
12343
12344 // Only check if the right hand side is non-bool arithmetic type.
12345 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12346
12347 // Make sure that the something in !something is not bool.
12348 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12349 if (SubExpr->isKnownToHaveBooleanValue()) return;
12350
12351 // Emit warning.
12352 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12353 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12354 << Loc << IsBitwiseOp;
12355
12356 // First note suggest !(x < y)
12357 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12358 SourceLocation FirstClose = RHS.get()->getEndLoc();
12359 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12360 if (FirstClose.isInvalid())
12361 FirstOpen = SourceLocation();
12362 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12363 << IsBitwiseOp
12364 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12365 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12366
12367 // Second note suggests (!x) < y
12368 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12369 SourceLocation SecondClose = LHS.get()->getEndLoc();
12370 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12371 if (SecondClose.isInvalid())
12372 SecondOpen = SourceLocation();
12373 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12374 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12375 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12376}
12377
12378// Returns true if E refers to a non-weak array.
12379static bool checkForArray(const Expr *E) {
12380 const ValueDecl *D = nullptr;
12381 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12382 D = DR->getDecl();
12383 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12384 if (Mem->isImplicitAccess())
12385 D = Mem->getMemberDecl();
12386 }
12387 if (!D)
12388 return false;
12389 return D->getType()->isArrayType() && !D->isWeak();
12390}
12391
12392/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12393/// pointer and size is an unsigned integer. Return whether the result is
12394/// always true/false.
12395static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12396 const Expr *RHS,
12397 BinaryOperatorKind Opc) {
12398 if (!LHS->getType()->isPointerType() ||
12399 S.getLangOpts().PointerOverflowDefined)
12400 return std::nullopt;
12401
12402 // Canonicalize to >= or < predicate.
12403 switch (Opc) {
12404 case BO_GE:
12405 case BO_LT:
12406 break;
12407 case BO_GT:
12408 std::swap(a&: LHS, b&: RHS);
12409 Opc = BO_LT;
12410 break;
12411 case BO_LE:
12412 std::swap(a&: LHS, b&: RHS);
12413 Opc = BO_GE;
12414 break;
12415 default:
12416 return std::nullopt;
12417 }
12418
12419 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12420 if (!BO || BO->getOpcode() != BO_Add)
12421 return std::nullopt;
12422
12423 Expr *Other;
12424 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12425 Other = BO->getRHS();
12426 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12427 Other = BO->getLHS();
12428 else
12429 return std::nullopt;
12430
12431 if (!Other->getType()->isUnsignedIntegerType())
12432 return std::nullopt;
12433
12434 return Opc == BO_GE;
12435}
12436
12437/// Diagnose some forms of syntactically-obvious tautological comparison.
12438static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12439 Expr *LHS, Expr *RHS,
12440 BinaryOperatorKind Opc) {
12441 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12442 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12443
12444 QualType LHSType = LHS->getType();
12445 QualType RHSType = RHS->getType();
12446 if (LHSType->hasFloatingRepresentation() ||
12447 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12448 S.inTemplateInstantiation())
12449 return;
12450
12451 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12452 // Tautological diagnostics.
12453 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12454 return;
12455
12456 // Comparisons between two array types are ill-formed for operator<=>, so
12457 // we shouldn't emit any additional warnings about it.
12458 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12459 return;
12460
12461 // For non-floating point types, check for self-comparisons of the form
12462 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12463 // often indicate logic errors in the program.
12464 //
12465 // NOTE: Don't warn about comparison expressions resulting from macro
12466 // expansion. Also don't warn about comparisons which are only self
12467 // comparisons within a template instantiation. The warnings should catch
12468 // obvious cases in the definition of the template anyways. The idea is to
12469 // warn when the typed comparison operator will always evaluate to the same
12470 // result.
12471
12472 // Used for indexing into %select in warn_comparison_always
12473 enum {
12474 AlwaysConstant,
12475 AlwaysTrue,
12476 AlwaysFalse,
12477 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12478 };
12479
12480 // C++1a [array.comp]:
12481 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12482 // operands of array type.
12483 // C++2a [depr.array.comp]:
12484 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12485 // operands of array type are deprecated.
12486 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12487 RHSStripped->getType()->isArrayType()) {
12488 auto IsDeprArrayComparionIgnored =
12489 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12490 auto DiagID = S.getLangOpts().CPlusPlus26
12491 ? diag::warn_array_comparison_cxx26
12492 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12493 ? diag::warn_array_comparison
12494 : diag::warn_depr_array_comparison;
12495 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12496 << LHSStripped->getType() << RHSStripped->getType();
12497 // Carry on to produce the tautological comparison warning, if this
12498 // expression is potentially-evaluated, we can resolve the array to a
12499 // non-weak declaration, and so on.
12500 }
12501
12502 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12503 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12504 unsigned Result;
12505 switch (Opc) {
12506 case BO_EQ:
12507 case BO_LE:
12508 case BO_GE:
12509 Result = AlwaysTrue;
12510 break;
12511 case BO_NE:
12512 case BO_LT:
12513 case BO_GT:
12514 Result = AlwaysFalse;
12515 break;
12516 case BO_Cmp:
12517 Result = AlwaysEqual;
12518 break;
12519 default:
12520 Result = AlwaysConstant;
12521 break;
12522 }
12523 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12524 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12525 << 0 /*self-comparison*/
12526 << Result);
12527 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12528 // What is it always going to evaluate to?
12529 unsigned Result;
12530 switch (Opc) {
12531 case BO_EQ: // e.g. array1 == array2
12532 Result = AlwaysFalse;
12533 break;
12534 case BO_NE: // e.g. array1 != array2
12535 Result = AlwaysTrue;
12536 break;
12537 default: // e.g. array1 <= array2
12538 // The best we can say is 'a constant'
12539 Result = AlwaysConstant;
12540 break;
12541 }
12542 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12543 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12544 << 1 /*array comparison*/
12545 << Result);
12546 } else if (std::optional<bool> Res =
12547 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12548 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12549 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12550 << 2 /*pointer comparison*/
12551 << (*Res ? AlwaysTrue : AlwaysFalse));
12552 }
12553 }
12554
12555 if (isa<CastExpr>(Val: LHSStripped))
12556 LHSStripped = LHSStripped->IgnoreParenCasts();
12557 if (isa<CastExpr>(Val: RHSStripped))
12558 RHSStripped = RHSStripped->IgnoreParenCasts();
12559
12560 // Warn about comparisons against a string constant (unless the other
12561 // operand is null); the user probably wants string comparison function.
12562 Expr *LiteralString = nullptr;
12563 Expr *LiteralStringStripped = nullptr;
12564 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12565 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12566 NPC: Expr::NPC_ValueDependentIsNull)) {
12567 LiteralString = LHS;
12568 LiteralStringStripped = LHSStripped;
12569 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12570 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12571 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12572 NPC: Expr::NPC_ValueDependentIsNull)) {
12573 LiteralString = RHS;
12574 LiteralStringStripped = RHSStripped;
12575 }
12576
12577 if (LiteralString) {
12578 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12579 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12580 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12581 << LiteralString->getSourceRange());
12582 }
12583}
12584
12585static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12586 switch (CK) {
12587 default: {
12588#ifndef NDEBUG
12589 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12590 << "\n";
12591#endif
12592 llvm_unreachable("unhandled cast kind");
12593 }
12594 case CK_UserDefinedConversion:
12595 return ICK_Identity;
12596 case CK_LValueToRValue:
12597 return ICK_Lvalue_To_Rvalue;
12598 case CK_ArrayToPointerDecay:
12599 return ICK_Array_To_Pointer;
12600 case CK_FunctionToPointerDecay:
12601 return ICK_Function_To_Pointer;
12602 case CK_IntegralCast:
12603 return ICK_Integral_Conversion;
12604 case CK_FloatingCast:
12605 return ICK_Floating_Conversion;
12606 case CK_IntegralToFloating:
12607 case CK_FloatingToIntegral:
12608 return ICK_Floating_Integral;
12609 case CK_IntegralComplexCast:
12610 case CK_FloatingComplexCast:
12611 case CK_FloatingComplexToIntegralComplex:
12612 case CK_IntegralComplexToFloatingComplex:
12613 return ICK_Complex_Conversion;
12614 case CK_FloatingComplexToReal:
12615 case CK_FloatingRealToComplex:
12616 case CK_IntegralComplexToReal:
12617 case CK_IntegralRealToComplex:
12618 return ICK_Complex_Real;
12619 case CK_HLSLArrayRValue:
12620 return ICK_HLSL_Array_RValue;
12621 }
12622}
12623
12624static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12625 QualType FromType,
12626 SourceLocation Loc) {
12627 // Check for a narrowing implicit conversion.
12628 StandardConversionSequence SCS;
12629 SCS.setAsIdentityConversion();
12630 SCS.setToType(Idx: 0, T: FromType);
12631 SCS.setToType(Idx: 1, T: ToType);
12632 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12633 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12634
12635 APValue PreNarrowingValue;
12636 QualType PreNarrowingType;
12637 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12638 ConstantType&: PreNarrowingType,
12639 /*IgnoreFloatToIntegralConversion*/ true)) {
12640 case NK_Dependent_Narrowing:
12641 // Implicit conversion to a narrower type, but the expression is
12642 // value-dependent so we can't tell whether it's actually narrowing.
12643 case NK_Not_Narrowing:
12644 return false;
12645
12646 case NK_Constant_Narrowing:
12647 // Implicit conversion to a narrower type, and the value is not a constant
12648 // expression.
12649 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12650 << /*Constant*/ 1
12651 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12652 return true;
12653
12654 case NK_Variable_Narrowing:
12655 // Implicit conversion to a narrower type, and the value is not a constant
12656 // expression.
12657 case NK_Type_Narrowing:
12658 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12659 << /*Constant*/ 0 << FromType << ToType;
12660 // TODO: It's not a constant expression, but what if the user intended it
12661 // to be? Can we produce notes to help them figure out why it isn't?
12662 return true;
12663 }
12664 llvm_unreachable("unhandled case in switch");
12665}
12666
12667static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12668 ExprResult &LHS,
12669 ExprResult &RHS,
12670 SourceLocation Loc) {
12671 QualType LHSType = LHS.get()->getType();
12672 QualType RHSType = RHS.get()->getType();
12673 // Dig out the original argument type and expression before implicit casts
12674 // were applied. These are the types/expressions we need to check the
12675 // [expr.spaceship] requirements against.
12676 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12677 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12678 QualType LHSStrippedType = LHSStripped.get()->getType();
12679 QualType RHSStrippedType = RHSStripped.get()->getType();
12680
12681 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12682 // other is not, the program is ill-formed.
12683 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12684 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12685 return QualType();
12686 }
12687
12688 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12689 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12690 RHSStrippedType->isEnumeralType();
12691 if (NumEnumArgs == 1) {
12692 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12693 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12694 if (OtherTy->hasFloatingRepresentation()) {
12695 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12696 return QualType();
12697 }
12698 }
12699 if (NumEnumArgs == 2) {
12700 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12701 // type E, the operator yields the result of converting the operands
12702 // to the underlying type of E and applying <=> to the converted operands.
12703 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12704 S.InvalidOperands(Loc, LHS, RHS);
12705 return QualType();
12706 }
12707 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12708 assert(IntType->isArithmeticType());
12709
12710 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12711 // promote the boolean type, and all other promotable integer types, to
12712 // avoid this.
12713 if (S.Context.isPromotableIntegerType(T: IntType))
12714 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12715
12716 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12717 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12718 LHSType = RHSType = IntType;
12719 }
12720
12721 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12722 // usual arithmetic conversions are applied to the operands.
12723 QualType Type =
12724 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12725 if (LHS.isInvalid() || RHS.isInvalid())
12726 return QualType();
12727 if (Type.isNull()) {
12728 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12729 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12730 return ResultTy;
12731 }
12732
12733 std::optional<ComparisonCategoryType> CCT =
12734 getComparisonCategoryForBuiltinCmp(T: Type);
12735 if (!CCT)
12736 return S.InvalidOperands(Loc, LHS, RHS);
12737
12738 bool HasNarrowing = checkThreeWayNarrowingConversion(
12739 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12740 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12741 Loc: RHS.get()->getBeginLoc());
12742 if (HasNarrowing)
12743 return QualType();
12744
12745 assert(!Type.isNull() && "composite type for <=> has not been set");
12746
12747 return S.CheckComparisonCategoryType(
12748 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12749}
12750
12751static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12752 ExprResult &RHS,
12753 SourceLocation Loc,
12754 BinaryOperatorKind Opc) {
12755 if (Opc == BO_Cmp)
12756 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12757
12758 // C99 6.5.8p3 / C99 6.5.9p4
12759 QualType Type =
12760 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12761 if (LHS.isInvalid() || RHS.isInvalid())
12762 return QualType();
12763 if (Type.isNull()) {
12764 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12765 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12766 return ResultTy;
12767 }
12768 assert(Type->isArithmeticType() || Type->isEnumeralType());
12769
12770 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12771 return S.InvalidOperands(Loc, LHS, RHS);
12772
12773 // Check for comparisons of floating point operands using != and ==.
12774 if (Type->hasFloatingRepresentation())
12775 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12776
12777 // The result of comparisons is 'bool' in C++, 'int' in C.
12778 return S.Context.getLogicalOperationType();
12779}
12780
12781void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12782 if (!NullE.get()->getType()->isAnyPointerType())
12783 return;
12784 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12785 if (!E.get()->getType()->isAnyPointerType() &&
12786 E.get()->isNullPointerConstant(Ctx&: Context,
12787 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12788 Expr::NPCK_ZeroExpression) {
12789 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12790 if (CL->getValue() == 0)
12791 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12792 << NullValue
12793 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12794 Code: NullValue ? "NULL" : "(void *)0");
12795 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12796 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12797 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12798 if (T == Context.CharTy)
12799 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12800 << NullValue
12801 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12802 Code: NullValue ? "NULL" : "(void *)0");
12803 }
12804 }
12805}
12806
12807// C99 6.5.8, C++ [expr.rel]
12808QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12809 SourceLocation Loc,
12810 BinaryOperatorKind Opc) {
12811 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12812 bool IsThreeWay = Opc == BO_Cmp;
12813 bool IsOrdered = IsRelational || IsThreeWay;
12814 auto IsAnyPointerType = [](ExprResult E) {
12815 QualType Ty = E.get()->getType();
12816 return Ty->isPointerType() || Ty->isMemberPointerType();
12817 };
12818
12819 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12820 // type, array-to-pointer, ..., conversions are performed on both operands to
12821 // bring them to their composite type.
12822 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12823 // any type-related checks.
12824 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12825 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12826 if (LHS.isInvalid())
12827 return QualType();
12828 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12829 if (RHS.isInvalid())
12830 return QualType();
12831 } else {
12832 LHS = DefaultLvalueConversion(E: LHS.get());
12833 if (LHS.isInvalid())
12834 return QualType();
12835 RHS = DefaultLvalueConversion(E: RHS.get());
12836 if (RHS.isInvalid())
12837 return QualType();
12838 }
12839
12840 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12841 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12842 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12843 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12844 }
12845
12846 // Handle vector comparisons separately.
12847 if (LHS.get()->getType()->isVectorType() ||
12848 RHS.get()->getType()->isVectorType())
12849 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12850
12851 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12852 RHS.get()->getType()->isSveVLSBuiltinType())
12853 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12854
12855 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12856 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12857
12858 QualType LHSType = LHS.get()->getType();
12859 QualType RHSType = RHS.get()->getType();
12860 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12861 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12862 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12863
12864 if ((LHSType->isPointerType() &&
12865 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12866 (RHSType->isPointerType() &&
12867 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12868 return InvalidOperands(Loc, LHS, RHS);
12869
12870 const Expr::NullPointerConstantKind LHSNullKind =
12871 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12872 const Expr::NullPointerConstantKind RHSNullKind =
12873 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12874 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12875 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12876
12877 auto computeResultTy = [&]() {
12878 if (Opc != BO_Cmp)
12879 return QualType(Context.getLogicalOperationType());
12880 assert(getLangOpts().CPlusPlus);
12881 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12882
12883 QualType CompositeTy = LHS.get()->getType();
12884 assert(!CompositeTy->isReferenceType());
12885
12886 std::optional<ComparisonCategoryType> CCT =
12887 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
12888 if (!CCT)
12889 return InvalidOperands(Loc, LHS, RHS);
12890
12891 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12892 // P0946R0: Comparisons between a null pointer constant and an object
12893 // pointer result in std::strong_equality, which is ill-formed under
12894 // P1959R0.
12895 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12896 << (LHSIsNull ? LHS.get()->getSourceRange()
12897 : RHS.get()->getSourceRange());
12898 return QualType();
12899 }
12900
12901 return CheckComparisonCategoryType(
12902 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
12903 };
12904
12905 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12906 bool IsEquality = Opc == BO_EQ;
12907 if (RHSIsNull)
12908 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
12909 Range: RHS.get()->getSourceRange());
12910 else
12911 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
12912 Range: LHS.get()->getSourceRange());
12913 }
12914
12915 if (IsOrdered && LHSType->isFunctionPointerType() &&
12916 RHSType->isFunctionPointerType()) {
12917 // Valid unless a relational comparison of function pointers
12918 bool IsError = Opc == BO_Cmp;
12919 auto DiagID =
12920 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12921 : getLangOpts().CPlusPlus
12922 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12923 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12924 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12925 << RHS.get()->getSourceRange();
12926 if (IsError)
12927 return QualType();
12928 }
12929
12930 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12931 (RHSType->isIntegerType() && !RHSIsNull)) {
12932 // Skip normal pointer conversion checks in this case; we have better
12933 // diagnostics for this below.
12934 } else if (getLangOpts().CPlusPlus) {
12935 // Equality comparison of a function pointer to a void pointer is invalid,
12936 // but we allow it as an extension.
12937 // FIXME: If we really want to allow this, should it be part of composite
12938 // pointer type computation so it works in conditionals too?
12939 if (!IsOrdered &&
12940 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12941 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12942 // This is a gcc extension compatibility comparison.
12943 // In a SFINAE context, we treat this as a hard error to maintain
12944 // conformance with the C++ standard.
12945 bool IsError = isSFINAEContext();
12946 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
12947
12948 if (IsError)
12949 return QualType();
12950
12951 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12952 return computeResultTy();
12953 }
12954
12955 // C++ [expr.eq]p2:
12956 // If at least one operand is a pointer [...] bring them to their
12957 // composite pointer type.
12958 // C++ [expr.spaceship]p6
12959 // If at least one of the operands is of pointer type, [...] bring them
12960 // to their composite pointer type.
12961 // C++ [expr.rel]p2:
12962 // If both operands are pointers, [...] bring them to their composite
12963 // pointer type.
12964 // For <=>, the only valid non-pointer types are arrays and functions, and
12965 // we already decayed those, so this is really the same as the relational
12966 // comparison rule.
12967 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12968 (IsOrdered ? 2 : 1) &&
12969 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12970 RHSType->isObjCObjectPointerType()))) {
12971 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
12972 return QualType();
12973 return computeResultTy();
12974 }
12975 } else if (LHSType->isPointerType() &&
12976 RHSType->isPointerType()) { // C99 6.5.8p2
12977 // All of the following pointer-related warnings are GCC extensions, except
12978 // when handling null pointer constants.
12979 QualType LCanPointeeTy =
12980 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12981 QualType RCanPointeeTy =
12982 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12983
12984 // C99 6.5.9p2 and C99 6.5.8p2
12985 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
12986 T2: RCanPointeeTy.getUnqualifiedType())) {
12987 if (IsRelational) {
12988 // Pointers both need to point to complete or incomplete types
12989 if ((LCanPointeeTy->isIncompleteType() !=
12990 RCanPointeeTy->isIncompleteType()) &&
12991 !getLangOpts().C11) {
12992 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
12993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12994 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12995 << RCanPointeeTy->isIncompleteType();
12996 }
12997 }
12998 } else if (!IsRelational &&
12999 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13000 // Valid unless comparison between non-null pointer and function pointer
13001 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13002 && !LHSIsNull && !RHSIsNull)
13003 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13004 /*isError*/IsError: false);
13005 } else {
13006 // Invalid
13007 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13008 }
13009 if (LCanPointeeTy != RCanPointeeTy) {
13010 // Treat NULL constant as a special case in OpenCL.
13011 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13012 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13013 Ctx: getASTContext())) {
13014 Diag(Loc,
13015 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13016 << LHSType << RHSType << 0 /* comparison */
13017 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13018 }
13019 }
13020 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13021 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13022 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13023 : CK_BitCast;
13024
13025 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13026 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13027 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13028 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13029 bool ChangingCFIUncheckedCallee =
13030 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13031
13032 if (LHSIsNull && !RHSIsNull)
13033 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13034 else if (!ChangingCFIUncheckedCallee)
13035 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13036 }
13037 return computeResultTy();
13038 }
13039
13040
13041 // C++ [expr.eq]p4:
13042 // Two operands of type std::nullptr_t or one operand of type
13043 // std::nullptr_t and the other a null pointer constant compare
13044 // equal.
13045 // C23 6.5.9p5:
13046 // If both operands have type nullptr_t or one operand has type nullptr_t
13047 // and the other is a null pointer constant, they compare equal if the
13048 // former is a null pointer.
13049 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13050 if (LHSType->isNullPtrType()) {
13051 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13052 return computeResultTy();
13053 }
13054 if (RHSType->isNullPtrType()) {
13055 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13056 return computeResultTy();
13057 }
13058 }
13059
13060 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13061 // C23 6.5.9p6:
13062 // Otherwise, at least one operand is a pointer. If one is a pointer and
13063 // the other is a null pointer constant or has type nullptr_t, they
13064 // compare equal
13065 if (LHSIsNull && RHSType->isPointerType()) {
13066 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13067 return computeResultTy();
13068 }
13069 if (RHSIsNull && LHSType->isPointerType()) {
13070 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13071 return computeResultTy();
13072 }
13073 }
13074
13075 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13076 // These aren't covered by the composite pointer type rules.
13077 if (!IsOrdered && RHSType->isNullPtrType() &&
13078 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13079 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13080 return computeResultTy();
13081 }
13082 if (!IsOrdered && LHSType->isNullPtrType() &&
13083 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13084 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13085 return computeResultTy();
13086 }
13087
13088 if (getLangOpts().CPlusPlus) {
13089 if (IsRelational &&
13090 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13091 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13092 // HACK: Relational comparison of nullptr_t against a pointer type is
13093 // invalid per DR583, but we allow it within std::less<> and friends,
13094 // since otherwise common uses of it break.
13095 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13096 // friends to have std::nullptr_t overload candidates.
13097 DeclContext *DC = CurContext;
13098 if (isa<FunctionDecl>(Val: DC))
13099 DC = DC->getParent();
13100 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13101 if (CTSD->isInStdNamespace() &&
13102 llvm::StringSwitch<bool>(CTSD->getName())
13103 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13104 .Default(Value: false)) {
13105 if (RHSType->isNullPtrType())
13106 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13107 else
13108 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13109 return computeResultTy();
13110 }
13111 }
13112 }
13113
13114 // C++ [expr.eq]p2:
13115 // If at least one operand is a pointer to member, [...] bring them to
13116 // their composite pointer type.
13117 if (!IsOrdered &&
13118 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13119 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13120 return QualType();
13121 else
13122 return computeResultTy();
13123 }
13124 }
13125
13126 // Handle block pointer types.
13127 if (!IsOrdered && LHSType->isBlockPointerType() &&
13128 RHSType->isBlockPointerType()) {
13129 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13130 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13131
13132 if (!LHSIsNull && !RHSIsNull &&
13133 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13134 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13135 << LHSType << RHSType << LHS.get()->getSourceRange()
13136 << RHS.get()->getSourceRange();
13137 }
13138 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13139 return computeResultTy();
13140 }
13141
13142 // Allow block pointers to be compared with null pointer constants.
13143 if (!IsOrdered
13144 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13145 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13146 if (!LHSIsNull && !RHSIsNull) {
13147 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13148 ->getPointeeType()->isVoidType())
13149 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13150 ->getPointeeType()->isVoidType())))
13151 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13152 << LHSType << RHSType << LHS.get()->getSourceRange()
13153 << RHS.get()->getSourceRange();
13154 }
13155 if (LHSIsNull && !RHSIsNull)
13156 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13157 CK: RHSType->isPointerType() ? CK_BitCast
13158 : CK_AnyPointerToBlockPointerCast);
13159 else
13160 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13161 CK: LHSType->isPointerType() ? CK_BitCast
13162 : CK_AnyPointerToBlockPointerCast);
13163 return computeResultTy();
13164 }
13165
13166 if (LHSType->isObjCObjectPointerType() ||
13167 RHSType->isObjCObjectPointerType()) {
13168 const PointerType *LPT = LHSType->getAs<PointerType>();
13169 const PointerType *RPT = RHSType->getAs<PointerType>();
13170 if (LPT || RPT) {
13171 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13172 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13173
13174 if (!LPtrToVoid && !RPtrToVoid &&
13175 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13176 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13177 /*isError*/IsError: false);
13178 }
13179 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13180 // the RHS, but we have test coverage for this behavior.
13181 // FIXME: Consider using convertPointersToCompositeType in C++.
13182 if (LHSIsNull && !RHSIsNull) {
13183 Expr *E = LHS.get();
13184 if (getLangOpts().ObjCAutoRefCount)
13185 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13186 CCK: CheckedConversionKind::Implicit);
13187 LHS = ImpCastExprToType(E, Type: RHSType,
13188 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13189 }
13190 else {
13191 Expr *E = RHS.get();
13192 if (getLangOpts().ObjCAutoRefCount)
13193 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13194 CCK: CheckedConversionKind::Implicit,
13195 /*Diagnose=*/true,
13196 /*DiagnoseCFAudited=*/false, Opc);
13197 RHS = ImpCastExprToType(E, Type: LHSType,
13198 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13199 }
13200 return computeResultTy();
13201 }
13202 if (LHSType->isObjCObjectPointerType() &&
13203 RHSType->isObjCObjectPointerType()) {
13204 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13205 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13206 /*isError*/IsError: false);
13207 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13208 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13209
13210 if (LHSIsNull && !RHSIsNull)
13211 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13212 else
13213 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13214 return computeResultTy();
13215 }
13216
13217 if (!IsOrdered && LHSType->isBlockPointerType() &&
13218 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13219 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13220 CK: CK_BlockPointerToObjCPointerCast);
13221 return computeResultTy();
13222 } else if (!IsOrdered &&
13223 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13224 RHSType->isBlockPointerType()) {
13225 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13226 CK: CK_BlockPointerToObjCPointerCast);
13227 return computeResultTy();
13228 }
13229 }
13230 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13231 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13232 unsigned DiagID = 0;
13233 bool isError = false;
13234 if (LangOpts.DebuggerSupport) {
13235 // Under a debugger, allow the comparison of pointers to integers,
13236 // since users tend to want to compare addresses.
13237 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13238 (RHSIsNull && RHSType->isIntegerType())) {
13239 if (IsOrdered) {
13240 isError = getLangOpts().CPlusPlus;
13241 DiagID =
13242 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13243 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13244 }
13245 } else if (getLangOpts().CPlusPlus) {
13246 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13247 isError = true;
13248 } else if (IsOrdered)
13249 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13250 else
13251 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13252
13253 if (DiagID) {
13254 Diag(Loc, DiagID)
13255 << LHSType << RHSType << LHS.get()->getSourceRange()
13256 << RHS.get()->getSourceRange();
13257 if (isError)
13258 return QualType();
13259 }
13260
13261 if (LHSType->isIntegerType())
13262 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13263 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13264 else
13265 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13266 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13267 return computeResultTy();
13268 }
13269
13270 // Handle block pointers.
13271 if (!IsOrdered && RHSIsNull
13272 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13273 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13274 return computeResultTy();
13275 }
13276 if (!IsOrdered && LHSIsNull
13277 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13278 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13279 return computeResultTy();
13280 }
13281
13282 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13283 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13284 return computeResultTy();
13285 }
13286
13287 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13288 return computeResultTy();
13289 }
13290
13291 if (LHSIsNull && RHSType->isQueueT()) {
13292 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13293 return computeResultTy();
13294 }
13295
13296 if (LHSType->isQueueT() && RHSIsNull) {
13297 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13298 return computeResultTy();
13299 }
13300 }
13301
13302 return InvalidOperands(Loc, LHS, RHS);
13303}
13304
13305QualType Sema::GetSignedVectorType(QualType V) {
13306 const VectorType *VTy = V->castAs<VectorType>();
13307 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13308
13309 if (isa<ExtVectorType>(Val: VTy)) {
13310 if (VTy->isExtVectorBoolType())
13311 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13312 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13313 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13314 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13315 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13316 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13317 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13318 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13319 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13320 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13321 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13322 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13323 "Unhandled vector element size in vector compare");
13324 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13325 }
13326
13327 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13328 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13329 VecKind: VectorKind::Generic);
13330 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13331 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13332 VecKind: VectorKind::Generic);
13333 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13334 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13335 VecKind: VectorKind::Generic);
13336 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13337 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13338 VecKind: VectorKind::Generic);
13339 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13340 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13341 VecKind: VectorKind::Generic);
13342 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13343 "Unhandled vector element size in vector compare");
13344 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13345 VecKind: VectorKind::Generic);
13346}
13347
13348QualType Sema::GetSignedSizelessVectorType(QualType V) {
13349 const BuiltinType *VTy = V->castAs<BuiltinType>();
13350 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13351
13352 const QualType ETy = V->getSveEltType(Ctx: Context);
13353 const auto TypeSize = Context.getTypeSize(T: ETy);
13354
13355 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13356 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13357 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13358}
13359
13360QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13361 SourceLocation Loc,
13362 BinaryOperatorKind Opc) {
13363 if (Opc == BO_Cmp) {
13364 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13365 return QualType();
13366 }
13367
13368 // Check to make sure we're operating on vectors of the same type and width,
13369 // Allowing one side to be a scalar of element type.
13370 QualType vType =
13371 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13372 /*AllowBothBool*/ true,
13373 /*AllowBoolConversions*/ getLangOpts().ZVector,
13374 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13375 /*ReportInvalid*/ true);
13376 if (vType.isNull())
13377 return vType;
13378
13379 QualType LHSType = LHS.get()->getType();
13380
13381 // Determine the return type of a vector compare. By default clang will return
13382 // a scalar for all vector compares except vector bool and vector pixel.
13383 // With the gcc compiler we will always return a vector type and with the xl
13384 // compiler we will always return a scalar type. This switch allows choosing
13385 // which behavior is prefered.
13386 if (getLangOpts().AltiVec) {
13387 switch (getLangOpts().getAltivecSrcCompat()) {
13388 case LangOptions::AltivecSrcCompatKind::Mixed:
13389 // If AltiVec, the comparison results in a numeric type, i.e.
13390 // bool for C++, int for C
13391 if (vType->castAs<VectorType>()->getVectorKind() ==
13392 VectorKind::AltiVecVector)
13393 return Context.getLogicalOperationType();
13394 else
13395 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13396 break;
13397 case LangOptions::AltivecSrcCompatKind::GCC:
13398 // For GCC we always return the vector type.
13399 break;
13400 case LangOptions::AltivecSrcCompatKind::XL:
13401 return Context.getLogicalOperationType();
13402 break;
13403 }
13404 }
13405
13406 // For non-floating point types, check for self-comparisons of the form
13407 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13408 // often indicate logic errors in the program.
13409 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13410
13411 // Check for comparisons of floating point operands using != and ==.
13412 if (LHSType->hasFloatingRepresentation()) {
13413 assert(RHS.get()->getType()->hasFloatingRepresentation());
13414 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13415 }
13416
13417 // Return a signed type for the vector.
13418 return GetSignedVectorType(V: vType);
13419}
13420
13421QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13422 ExprResult &RHS,
13423 SourceLocation Loc,
13424 BinaryOperatorKind Opc) {
13425 if (Opc == BO_Cmp) {
13426 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13427 return QualType();
13428 }
13429
13430 // Check to make sure we're operating on vectors of the same type and width,
13431 // Allowing one side to be a scalar of element type.
13432 QualType vType = CheckSizelessVectorOperands(
13433 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13434
13435 if (vType.isNull())
13436 return vType;
13437
13438 QualType LHSType = LHS.get()->getType();
13439
13440 // For non-floating point types, check for self-comparisons of the form
13441 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13442 // often indicate logic errors in the program.
13443 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13444
13445 // Check for comparisons of floating point operands using != and ==.
13446 if (LHSType->hasFloatingRepresentation()) {
13447 assert(RHS.get()->getType()->hasFloatingRepresentation());
13448 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13449 }
13450
13451 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13452 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13453
13454 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13455 RHSBuiltinTy->isSVEBool())
13456 return LHSType;
13457
13458 // Return a signed type for the vector.
13459 return GetSignedSizelessVectorType(V: vType);
13460}
13461
13462static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13463 const ExprResult &XorRHS,
13464 const SourceLocation Loc) {
13465 // Do not diagnose macros.
13466 if (Loc.isMacroID())
13467 return;
13468
13469 // Do not diagnose if both LHS and RHS are macros.
13470 if (XorLHS.get()->getExprLoc().isMacroID() &&
13471 XorRHS.get()->getExprLoc().isMacroID())
13472 return;
13473
13474 bool Negative = false;
13475 bool ExplicitPlus = false;
13476 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13477 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13478
13479 if (!LHSInt)
13480 return;
13481 if (!RHSInt) {
13482 // Check negative literals.
13483 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13484 UnaryOperatorKind Opc = UO->getOpcode();
13485 if (Opc != UO_Minus && Opc != UO_Plus)
13486 return;
13487 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13488 if (!RHSInt)
13489 return;
13490 Negative = (Opc == UO_Minus);
13491 ExplicitPlus = !Negative;
13492 } else {
13493 return;
13494 }
13495 }
13496
13497 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13498 llvm::APInt RightSideValue = RHSInt->getValue();
13499 if (LeftSideValue != 2 && LeftSideValue != 10)
13500 return;
13501
13502 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13503 return;
13504
13505 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13506 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13507 llvm::StringRef ExprStr =
13508 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13509
13510 CharSourceRange XorRange =
13511 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13512 llvm::StringRef XorStr =
13513 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13514 // Do not diagnose if xor keyword/macro is used.
13515 if (XorStr == "xor")
13516 return;
13517
13518 std::string LHSStr = std::string(Lexer::getSourceText(
13519 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13520 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13521 std::string RHSStr = std::string(Lexer::getSourceText(
13522 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13523 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13524
13525 if (Negative) {
13526 RightSideValue = -RightSideValue;
13527 RHSStr = "-" + RHSStr;
13528 } else if (ExplicitPlus) {
13529 RHSStr = "+" + RHSStr;
13530 }
13531
13532 StringRef LHSStrRef = LHSStr;
13533 StringRef RHSStrRef = RHSStr;
13534 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13535 // literals.
13536 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13537 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13538 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13539 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13540 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13541 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13542 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13543 return;
13544
13545 bool SuggestXor =
13546 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13547 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13548 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13549 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13550 std::string SuggestedExpr = "1 << " + RHSStr;
13551 bool Overflow = false;
13552 llvm::APInt One = (LeftSideValue - 1);
13553 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13554 if (Overflow) {
13555 if (RightSideIntValue < 64)
13556 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13557 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13558 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13559 else if (RightSideIntValue == 64)
13560 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13561 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13562 else
13563 return;
13564 } else {
13565 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13566 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13567 << toString(I: PowValue, Radix: 10, Signed: true)
13568 << FixItHint::CreateReplacement(
13569 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13570 }
13571
13572 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13573 << ("0x2 ^ " + RHSStr) << SuggestXor;
13574 } else if (LeftSideValue == 10) {
13575 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13576 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13577 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13578 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13579 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13580 << ("0xA ^ " + RHSStr) << SuggestXor;
13581 }
13582}
13583
13584QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13585 SourceLocation Loc,
13586 BinaryOperatorKind Opc) {
13587 // Ensure that either both operands are of the same vector type, or
13588 // one operand is of a vector type and the other is of its element type.
13589 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13590 /*AllowBothBool*/ true,
13591 /*AllowBoolConversions*/ false,
13592 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13593 /*ReportInvalid*/ false);
13594 if (vType.isNull())
13595 return InvalidOperands(Loc, LHS, RHS);
13596 if (getLangOpts().OpenCL &&
13597 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13598 vType->hasFloatingRepresentation())
13599 return InvalidOperands(Loc, LHS, RHS);
13600 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13601 // usage of the logical operators && and || with vectors in C. This
13602 // check could be notionally dropped.
13603 if (!getLangOpts().CPlusPlus &&
13604 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13605 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13606 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13607 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13608 // `select` functions.
13609 if (getLangOpts().HLSL &&
13610 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13611 (void)InvalidOperands(Loc, LHS, RHS);
13612 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13613 return QualType();
13614 }
13615
13616 return GetSignedVectorType(V: LHS.get()->getType());
13617}
13618
13619QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13620 SourceLocation Loc,
13621 BinaryOperatorKind Opc) {
13622
13623 if (!getLangOpts().HLSL) {
13624 assert(false && "Logical operands are not supported in C\\C++");
13625 return QualType();
13626 }
13627
13628 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13629 (void)InvalidOperands(Loc, LHS, RHS);
13630 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13631 return QualType();
13632 }
13633 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13634 << getLangOpts().getHLSLVersion();
13635 return QualType();
13636}
13637
13638QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13639 SourceLocation Loc,
13640 bool IsCompAssign) {
13641 if (!IsCompAssign) {
13642 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13643 if (LHS.isInvalid())
13644 return QualType();
13645 }
13646 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13647 if (RHS.isInvalid())
13648 return QualType();
13649
13650 // For conversion purposes, we ignore any qualifiers.
13651 // For example, "const float" and "float" are equivalent.
13652 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13653 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13654
13655 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13656 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13657 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13658
13659 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13660 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13661
13662 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13663 // case we have to return InvalidOperands.
13664 ExprResult OriginalLHS = LHS;
13665 ExprResult OriginalRHS = RHS;
13666 if (LHSMatType && !RHSMatType) {
13667 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13668 if (!RHS.isInvalid())
13669 return LHSType;
13670
13671 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13672 }
13673
13674 if (!LHSMatType && RHSMatType) {
13675 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13676 if (!LHS.isInvalid())
13677 return RHSType;
13678 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13679 }
13680
13681 return InvalidOperands(Loc, LHS, RHS);
13682}
13683
13684QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13685 SourceLocation Loc,
13686 bool IsCompAssign) {
13687 if (!IsCompAssign) {
13688 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13689 if (LHS.isInvalid())
13690 return QualType();
13691 }
13692 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13693 if (RHS.isInvalid())
13694 return QualType();
13695
13696 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13697 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13698 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13699
13700 if (LHSMatType && RHSMatType) {
13701 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13702 return InvalidOperands(Loc, LHS, RHS);
13703
13704 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13705 return Context.getCommonSugaredType(
13706 X: LHS.get()->getType().getUnqualifiedType(),
13707 Y: RHS.get()->getType().getUnqualifiedType());
13708
13709 QualType LHSELTy = LHSMatType->getElementType(),
13710 RHSELTy = RHSMatType->getElementType();
13711 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13712 return InvalidOperands(Loc, LHS, RHS);
13713
13714 return Context.getConstantMatrixType(
13715 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13716 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13717 }
13718 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13719}
13720
13721static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13722 switch (Opc) {
13723 default:
13724 return false;
13725 case BO_And:
13726 case BO_AndAssign:
13727 case BO_Or:
13728 case BO_OrAssign:
13729 case BO_Xor:
13730 case BO_XorAssign:
13731 return true;
13732 }
13733}
13734
13735inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13736 SourceLocation Loc,
13737 BinaryOperatorKind Opc) {
13738 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13739
13740 bool IsCompAssign =
13741 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13742
13743 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13744
13745 if (LHS.get()->getType()->isVectorType() ||
13746 RHS.get()->getType()->isVectorType()) {
13747 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13748 RHS.get()->getType()->hasIntegerRepresentation())
13749 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13750 /*AllowBothBool*/ true,
13751 /*AllowBoolConversions*/ getLangOpts().ZVector,
13752 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13753 /*ReportInvalid*/ true);
13754 return InvalidOperands(Loc, LHS, RHS);
13755 }
13756
13757 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13758 RHS.get()->getType()->isSveVLSBuiltinType()) {
13759 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13760 RHS.get()->getType()->hasIntegerRepresentation())
13761 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13762 OperationKind: ArithConvKind::BitwiseOp);
13763 return InvalidOperands(Loc, LHS, RHS);
13764 }
13765
13766 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13767 RHS.get()->getType()->isSveVLSBuiltinType()) {
13768 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13769 RHS.get()->getType()->hasIntegerRepresentation())
13770 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13771 OperationKind: ArithConvKind::BitwiseOp);
13772 return InvalidOperands(Loc, LHS, RHS);
13773 }
13774
13775 if (Opc == BO_And)
13776 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13777
13778 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13779 RHS.get()->getType()->hasFloatingRepresentation())
13780 return InvalidOperands(Loc, LHS, RHS);
13781
13782 ExprResult LHSResult = LHS, RHSResult = RHS;
13783 QualType compType = UsualArithmeticConversions(
13784 LHS&: LHSResult, RHS&: RHSResult, Loc,
13785 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13786 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13787 return QualType();
13788 LHS = LHSResult.get();
13789 RHS = RHSResult.get();
13790
13791 if (Opc == BO_Xor)
13792 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13793
13794 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13795 return compType;
13796 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13797 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13798 return ResultTy;
13799}
13800
13801// C99 6.5.[13,14]
13802inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13803 SourceLocation Loc,
13804 BinaryOperatorKind Opc) {
13805 // Check vector operands differently.
13806 if (LHS.get()->getType()->isVectorType() ||
13807 RHS.get()->getType()->isVectorType())
13808 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13809
13810 if (LHS.get()->getType()->isConstantMatrixType() ||
13811 RHS.get()->getType()->isConstantMatrixType())
13812 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13813
13814 bool EnumConstantInBoolContext = false;
13815 for (const ExprResult &HS : {LHS, RHS}) {
13816 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13817 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13818 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13819 EnumConstantInBoolContext = true;
13820 }
13821 }
13822
13823 if (EnumConstantInBoolContext)
13824 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13825
13826 // WebAssembly tables can't be used with logical operators.
13827 QualType LHSTy = LHS.get()->getType();
13828 QualType RHSTy = RHS.get()->getType();
13829 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13830 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13831 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13832 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13833 return InvalidOperands(Loc, LHS, RHS);
13834 }
13835
13836 // Diagnose cases where the user write a logical and/or but probably meant a
13837 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13838 // is a constant.
13839 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13840 !LHS.get()->getType()->isBooleanType() &&
13841 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13842 // Don't warn in macros or template instantiations.
13843 !Loc.isMacroID() && !inTemplateInstantiation()) {
13844 // If the RHS can be constant folded, and if it constant folds to something
13845 // that isn't 0 or 1 (which indicate a potential logical operation that
13846 // happened to fold to true/false) then warn.
13847 // Parens on the RHS are ignored.
13848 Expr::EvalResult EVResult;
13849 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13850 llvm::APSInt Result = EVResult.Val.getInt();
13851 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13852 !RHS.get()->getExprLoc().isMacroID()) ||
13853 (Result != 0 && Result != 1)) {
13854 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13855 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13856 // Suggest replacing the logical operator with the bitwise version
13857 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13858 << (Opc == BO_LAnd ? "&" : "|")
13859 << FixItHint::CreateReplacement(
13860 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13861 Code: Opc == BO_LAnd ? "&" : "|");
13862 if (Opc == BO_LAnd)
13863 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13864 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
13865 << FixItHint::CreateRemoval(
13866 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
13867 RHS.get()->getEndLoc()));
13868 }
13869 }
13870 }
13871
13872 if (!Context.getLangOpts().CPlusPlus) {
13873 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13874 // not operate on the built-in scalar and vector float types.
13875 if (Context.getLangOpts().OpenCL &&
13876 Context.getLangOpts().OpenCLVersion < 120) {
13877 if (LHS.get()->getType()->isFloatingType() ||
13878 RHS.get()->getType()->isFloatingType())
13879 return InvalidOperands(Loc, LHS, RHS);
13880 }
13881
13882 LHS = UsualUnaryConversions(E: LHS.get());
13883 if (LHS.isInvalid())
13884 return QualType();
13885
13886 RHS = UsualUnaryConversions(E: RHS.get());
13887 if (RHS.isInvalid())
13888 return QualType();
13889
13890 if (!LHS.get()->getType()->isScalarType() ||
13891 !RHS.get()->getType()->isScalarType())
13892 return InvalidOperands(Loc, LHS, RHS);
13893
13894 return Context.IntTy;
13895 }
13896
13897 // The following is safe because we only use this method for
13898 // non-overloadable operands.
13899
13900 // C++ [expr.log.and]p1
13901 // C++ [expr.log.or]p1
13902 // The operands are both contextually converted to type bool.
13903 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
13904 if (LHSRes.isInvalid()) {
13905 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13906 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13907 return ResultTy;
13908 }
13909 LHS = LHSRes;
13910
13911 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
13912 if (RHSRes.isInvalid()) {
13913 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13914 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13915 return ResultTy;
13916 }
13917 RHS = RHSRes;
13918
13919 // C++ [expr.log.and]p2
13920 // C++ [expr.log.or]p2
13921 // The result is a bool.
13922 return Context.BoolTy;
13923}
13924
13925static bool IsReadonlyMessage(Expr *E, Sema &S) {
13926 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
13927 if (!ME) return false;
13928 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
13929 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13930 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13931 if (!Base) return false;
13932 return Base->getMethodDecl() != nullptr;
13933}
13934
13935/// Is the given expression (which must be 'const') a reference to a
13936/// variable which was originally non-const, but which has become
13937/// 'const' due to being captured within a block?
13938enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13939static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13940 assert(E->isLValue() && E->getType().isConstQualified());
13941 E = E->IgnoreParens();
13942
13943 // Must be a reference to a declaration from an enclosing scope.
13944 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
13945 if (!DRE) return NCCK_None;
13946 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13947
13948 ValueDecl *Value = dyn_cast<ValueDecl>(Val: DRE->getDecl());
13949
13950 // The declaration must be a value which is not declared 'const'.
13951 if (!Value || Value->getType().isConstQualified())
13952 return NCCK_None;
13953
13954 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
13955 if (Binding) {
13956 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13957 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13958 return NCCK_Lambda;
13959 }
13960
13961 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
13962 if (!Var)
13963 return NCCK_None;
13964 if (Var->getType()->isReferenceType())
13965 return NCCK_None;
13966
13967 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13968
13969 // Decide whether the first capture was for a block or a lambda.
13970 DeclContext *DC = S.CurContext, *Prev = nullptr;
13971 // Decide whether the first capture was for a block or a lambda.
13972 while (DC) {
13973 // For init-capture, it is possible that the variable belongs to the
13974 // template pattern of the current context.
13975 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
13976 if (Var->isInitCapture() &&
13977 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13978 break;
13979 if (DC == Var->getDeclContext())
13980 break;
13981 Prev = DC;
13982 DC = DC->getParent();
13983 }
13984 // Unless we have an init-capture, we've gone one step too far.
13985 if (!Var->isInitCapture())
13986 DC = Prev;
13987 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
13988}
13989
13990static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13991 Ty = Ty.getNonReferenceType();
13992 if (IsDereference && Ty->isPointerType())
13993 Ty = Ty->getPointeeType();
13994 return !Ty.isConstQualified();
13995}
13996
13997// Update err_typecheck_assign_const and note_typecheck_assign_const
13998// when this enum is changed.
13999enum {
14000 ConstFunction,
14001 ConstVariable,
14002 ConstMember,
14003 NestedConstMember,
14004 ConstUnknown, // Keep as last element
14005};
14006
14007/// Emit the "read-only variable not assignable" error and print notes to give
14008/// more information about why the variable is not assignable, such as pointing
14009/// to the declaration of a const variable, showing that a method is const, or
14010/// that the function is returning a const reference.
14011static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14012 SourceLocation Loc) {
14013 SourceRange ExprRange = E->getSourceRange();
14014
14015 // Only emit one error on the first const found. All other consts will emit
14016 // a note to the error.
14017 bool DiagnosticEmitted = false;
14018
14019 // Track if the current expression is the result of a dereference, and if the
14020 // next checked expression is the result of a dereference.
14021 bool IsDereference = false;
14022 bool NextIsDereference = false;
14023
14024 // Loop to process MemberExpr chains.
14025 while (true) {
14026 IsDereference = NextIsDereference;
14027
14028 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14029 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14030 NextIsDereference = ME->isArrow();
14031 const ValueDecl *VD = ME->getMemberDecl();
14032 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14033 // Mutable fields can be modified even if the class is const.
14034 if (Field->isMutable()) {
14035 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14036 break;
14037 }
14038
14039 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14040 if (!DiagnosticEmitted) {
14041 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14042 << ExprRange << ConstMember << false /*static*/ << Field
14043 << Field->getType();
14044 DiagnosticEmitted = true;
14045 }
14046 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14047 << ConstMember << false /*static*/ << Field << Field->getType()
14048 << Field->getSourceRange();
14049 }
14050 E = ME->getBase();
14051 continue;
14052 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14053 if (VDecl->getType().isConstQualified()) {
14054 if (!DiagnosticEmitted) {
14055 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14056 << ExprRange << ConstMember << true /*static*/ << VDecl
14057 << VDecl->getType();
14058 DiagnosticEmitted = true;
14059 }
14060 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14061 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14062 << VDecl->getSourceRange();
14063 }
14064 // Static fields do not inherit constness from parents.
14065 break;
14066 }
14067 break; // End MemberExpr
14068 } else if (const ArraySubscriptExpr *ASE =
14069 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14070 E = ASE->getBase()->IgnoreParenImpCasts();
14071 continue;
14072 } else if (const ExtVectorElementExpr *EVE =
14073 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14074 E = EVE->getBase()->IgnoreParenImpCasts();
14075 continue;
14076 }
14077 break;
14078 }
14079
14080 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14081 // Function calls
14082 const FunctionDecl *FD = CE->getDirectCallee();
14083 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14084 if (!DiagnosticEmitted) {
14085 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14086 << ConstFunction << FD;
14087 DiagnosticEmitted = true;
14088 }
14089 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14090 DiagID: diag::note_typecheck_assign_const)
14091 << ConstFunction << FD << FD->getReturnType()
14092 << FD->getReturnTypeSourceRange();
14093 }
14094 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14095 // Point to variable declaration.
14096 if (const ValueDecl *VD = DRE->getDecl()) {
14097 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14098 if (!DiagnosticEmitted) {
14099 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14100 << ExprRange << ConstVariable << VD << VD->getType();
14101 DiagnosticEmitted = true;
14102 }
14103 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14104 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14105 }
14106 }
14107 } else if (isa<CXXThisExpr>(Val: E)) {
14108 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14109 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14110 if (MD->isConst()) {
14111 if (!DiagnosticEmitted) {
14112 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14113 << ExprRange << MD;
14114 DiagnosticEmitted = true;
14115 }
14116 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14117 << MD << MD->getSourceRange();
14118 }
14119 }
14120 }
14121 }
14122
14123 if (DiagnosticEmitted)
14124 return;
14125
14126 // Can't determine a more specific message, so display the generic error.
14127 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14128}
14129
14130enum OriginalExprKind {
14131 OEK_Variable,
14132 OEK_Member,
14133 OEK_LValue
14134};
14135
14136static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14137 const RecordType *Ty,
14138 SourceLocation Loc, SourceRange Range,
14139 OriginalExprKind OEK,
14140 bool &DiagnosticEmitted) {
14141 std::vector<const RecordType *> RecordTypeList;
14142 RecordTypeList.push_back(x: Ty);
14143 unsigned NextToCheckIndex = 0;
14144 // We walk the record hierarchy breadth-first to ensure that we print
14145 // diagnostics in field nesting order.
14146 while (RecordTypeList.size() > NextToCheckIndex) {
14147 bool IsNested = NextToCheckIndex > 0;
14148 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14149 ->getDecl()
14150 ->getDefinitionOrSelf()
14151 ->fields()) {
14152 // First, check every field for constness.
14153 QualType FieldTy = Field->getType();
14154 if (FieldTy.isConstQualified()) {
14155 if (!DiagnosticEmitted) {
14156 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14157 << Range << NestedConstMember << OEK << VD
14158 << IsNested << Field;
14159 DiagnosticEmitted = true;
14160 }
14161 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14162 << NestedConstMember << IsNested << Field
14163 << FieldTy << Field->getSourceRange();
14164 }
14165
14166 // Then we append it to the list to check next in order.
14167 FieldTy = FieldTy.getCanonicalType();
14168 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14169 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14170 RecordTypeList.push_back(x: FieldRecTy);
14171 }
14172 }
14173 ++NextToCheckIndex;
14174 }
14175}
14176
14177/// Emit an error for the case where a record we are trying to assign to has a
14178/// const-qualified field somewhere in its hierarchy.
14179static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14180 SourceLocation Loc) {
14181 QualType Ty = E->getType();
14182 assert(Ty->isRecordType() && "lvalue was not record?");
14183 SourceRange Range = E->getSourceRange();
14184 const auto *RTy = Ty->getAsCanonical<RecordType>();
14185 bool DiagEmitted = false;
14186
14187 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14188 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14189 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14190 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14191 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14192 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14193 else
14194 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14195 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14196 if (!DiagEmitted)
14197 DiagnoseConstAssignment(S, E, Loc);
14198}
14199
14200/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14201/// emit an error and return true. If so, return false.
14202static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14203 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14204
14205 S.CheckShadowingDeclModification(E, Loc);
14206
14207 SourceLocation OrigLoc = Loc;
14208 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14209 Loc: &Loc);
14210 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14211 IsLV = Expr::MLV_InvalidMessageExpression;
14212 if (IsLV == Expr::MLV_Valid)
14213 return false;
14214
14215 unsigned DiagID = 0;
14216 bool NeedType = false;
14217 switch (IsLV) { // C99 6.5.16p2
14218 case Expr::MLV_ConstQualified:
14219 // Use a specialized diagnostic when we're assigning to an object
14220 // from an enclosing function or block.
14221 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14222 if (NCCK == NCCK_Block)
14223 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14224 else
14225 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14226 break;
14227 }
14228
14229 // In ARC, use some specialized diagnostics for occasions where we
14230 // infer 'const'. These are always pseudo-strong variables.
14231 if (S.getLangOpts().ObjCAutoRefCount) {
14232 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14233 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14234 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14235
14236 // Use the normal diagnostic if it's pseudo-__strong but the
14237 // user actually wrote 'const'.
14238 if (var->isARCPseudoStrong() &&
14239 (!var->getTypeSourceInfo() ||
14240 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14241 // There are three pseudo-strong cases:
14242 // - self
14243 ObjCMethodDecl *method = S.getCurMethodDecl();
14244 if (method && var == method->getSelfDecl()) {
14245 DiagID = method->isClassMethod()
14246 ? diag::err_typecheck_arc_assign_self_class_method
14247 : diag::err_typecheck_arc_assign_self;
14248
14249 // - Objective-C externally_retained attribute.
14250 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14251 isa<ParmVarDecl>(Val: var)) {
14252 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14253
14254 // - fast enumeration variables
14255 } else {
14256 DiagID = diag::err_typecheck_arr_assign_enumeration;
14257 }
14258
14259 SourceRange Assign;
14260 if (Loc != OrigLoc)
14261 Assign = SourceRange(OrigLoc, OrigLoc);
14262 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14263 // We need to preserve the AST regardless, so migration tool
14264 // can do its job.
14265 return false;
14266 }
14267 }
14268 }
14269
14270 // If none of the special cases above are triggered, then this is a
14271 // simple const assignment.
14272 if (DiagID == 0) {
14273 DiagnoseConstAssignment(S, E, Loc);
14274 return true;
14275 }
14276
14277 break;
14278 case Expr::MLV_ConstAddrSpace:
14279 DiagnoseConstAssignment(S, E, Loc);
14280 return true;
14281 case Expr::MLV_ConstQualifiedField:
14282 DiagnoseRecursiveConstFields(S, E, Loc);
14283 return true;
14284 case Expr::MLV_ArrayType:
14285 case Expr::MLV_ArrayTemporary:
14286 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14287 NeedType = true;
14288 break;
14289 case Expr::MLV_NotObjectType:
14290 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14291 NeedType = true;
14292 break;
14293 case Expr::MLV_LValueCast:
14294 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14295 break;
14296 case Expr::MLV_Valid:
14297 llvm_unreachable("did not take early return for MLV_Valid");
14298 case Expr::MLV_InvalidExpression:
14299 case Expr::MLV_MemberFunction:
14300 case Expr::MLV_ClassTemporary:
14301 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14302 break;
14303 case Expr::MLV_IncompleteType:
14304 case Expr::MLV_IncompleteVoidType:
14305 return S.RequireCompleteType(Loc, T: E->getType(),
14306 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14307 case Expr::MLV_DuplicateVectorComponents:
14308 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14309 break;
14310 case Expr::MLV_DuplicateMatrixComponents:
14311 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14312 break;
14313 case Expr::MLV_NoSetterProperty:
14314 llvm_unreachable("readonly properties should be processed differently");
14315 case Expr::MLV_InvalidMessageExpression:
14316 DiagID = diag::err_readonly_message_assignment;
14317 break;
14318 case Expr::MLV_SubObjCPropertySetting:
14319 DiagID = diag::err_no_subobject_property_setting;
14320 break;
14321 }
14322
14323 SourceRange Assign;
14324 if (Loc != OrigLoc)
14325 Assign = SourceRange(OrigLoc, OrigLoc);
14326 if (NeedType)
14327 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14328 else
14329 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14330 return true;
14331}
14332
14333static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14334 SourceLocation Loc,
14335 Sema &Sema) {
14336 if (Sema.inTemplateInstantiation())
14337 return;
14338 if (Sema.isUnevaluatedContext())
14339 return;
14340 if (Loc.isInvalid() || Loc.isMacroID())
14341 return;
14342 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14343 return;
14344
14345 // C / C++ fields
14346 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14347 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14348 if (ML && MR) {
14349 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14350 return;
14351 const ValueDecl *LHSDecl =
14352 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14353 const ValueDecl *RHSDecl =
14354 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14355 if (LHSDecl != RHSDecl)
14356 return;
14357 if (LHSDecl->getType().isVolatileQualified())
14358 return;
14359 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14360 if (RefTy->getPointeeType().isVolatileQualified())
14361 return;
14362
14363 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14364 }
14365
14366 // Objective-C instance variables
14367 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14368 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14369 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14370 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14371 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14372 if (RL && RR && RL->getDecl() == RR->getDecl())
14373 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14374 }
14375}
14376
14377// C99 6.5.16.1
14378QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14379 SourceLocation Loc,
14380 QualType CompoundType,
14381 BinaryOperatorKind Opc) {
14382 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14383
14384 // Verify that LHS is a modifiable lvalue, and emit error if not.
14385 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14386 return QualType();
14387
14388 QualType LHSType = LHSExpr->getType();
14389 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14390 CompoundType;
14391
14392 if (RHS.isUsable()) {
14393 // Even if this check fails don't return early to allow the best
14394 // possible error recovery and to allow any subsequent diagnostics to
14395 // work.
14396 const ValueDecl *Assignee = nullptr;
14397 bool ShowFullyQualifiedAssigneeName = false;
14398 // In simple cases describe what is being assigned to
14399 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14400 Assignee = DR->getDecl();
14401 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14402 Assignee = ME->getMemberDecl();
14403 ShowFullyQualifiedAssigneeName = true;
14404 }
14405
14406 BoundsSafetyCheckAssignmentToCountAttrPtr(
14407 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14408 ShowFullyQualifiedAssigneeName);
14409 }
14410
14411 // OpenCL v1.2 s6.1.1.1 p2:
14412 // The half data type can only be used to declare a pointer to a buffer that
14413 // contains half values
14414 if (getLangOpts().OpenCL &&
14415 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14416 LHSType->isHalfType()) {
14417 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14418 << LHSType.getUnqualifiedType();
14419 return QualType();
14420 }
14421
14422 // WebAssembly tables can't be used on RHS of an assignment expression.
14423 if (RHSType->isWebAssemblyTableType()) {
14424 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14425 return QualType();
14426 }
14427
14428 AssignConvertType ConvTy;
14429 if (CompoundType.isNull()) {
14430 Expr *RHSCheck = RHS.get();
14431
14432 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14433
14434 QualType LHSTy(LHSType);
14435 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14436 if (RHS.isInvalid())
14437 return QualType();
14438 // Special case of NSObject attributes on c-style pointer types.
14439 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14440 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14441 RHSType->isObjCObjectPointerType()) ||
14442 (Context.isObjCNSObjectType(Ty: RHSType) &&
14443 LHSType->isObjCObjectPointerType())))
14444 ConvTy = AssignConvertType::Compatible;
14445
14446 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14447 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14448
14449 // If the RHS is a unary plus or minus, check to see if they = and + are
14450 // right next to each other. If so, the user may have typo'd "x =+ 4"
14451 // instead of "x += 4".
14452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14453 RHSCheck = ICE->getSubExpr();
14454 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14455 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14456 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14457 // Only if the two operators are exactly adjacent.
14458 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14459 // And there is a space or other character before the subexpr of the
14460 // unary +/-. We don't want to warn on "x=-1".
14461 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14462 UO->getSubExpr()->getBeginLoc().isFileID()) {
14463 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14464 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14465 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14466 }
14467 }
14468
14469 if (IsAssignConvertCompatible(ConvTy)) {
14470 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14471 // Warn about retain cycles where a block captures the LHS, but
14472 // not if the LHS is a simple variable into which the block is
14473 // being stored...unless that variable can be captured by reference!
14474 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14475 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14476 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14477 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14478 }
14479
14480 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14481 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14482 // It is safe to assign a weak reference into a strong variable.
14483 // Although this code can still have problems:
14484 // id x = self.weakProp;
14485 // id y = self.weakProp;
14486 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14487 // paths through the function. This should be revisited if
14488 // -Wrepeated-use-of-weak is made flow-sensitive.
14489 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14490 // variable, which will be valid for the current autorelease scope.
14491 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14492 Loc: RHS.get()->getBeginLoc()))
14493 getCurFunction()->markSafeWeakUse(E: RHS.get());
14494
14495 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14496 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14497 }
14498 }
14499 } else {
14500 // Compound assignment "x += y"
14501 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14502 }
14503
14504 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14505 Action: AssignmentAction::Assigning))
14506 return QualType();
14507
14508 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14509
14510 AssignedEntity AE{.LHS: LHSExpr};
14511 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14512
14513 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14514 if (CompoundType.isNull()) {
14515 // C++2a [expr.ass]p5:
14516 // A simple-assignment whose left operand is of a volatile-qualified
14517 // type is deprecated unless the assignment is either a discarded-value
14518 // expression or an unevaluated operand
14519 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14520 }
14521 }
14522
14523 // C11 6.5.16p3: The type of an assignment expression is the type of the
14524 // left operand would have after lvalue conversion.
14525 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14526 // qualified type, the value has the unqualified version of the type of the
14527 // lvalue; additionally, if the lvalue has atomic type, the value has the
14528 // non-atomic version of the type of the lvalue.
14529 // C++ 5.17p1: the type of the assignment expression is that of its left
14530 // operand.
14531 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14532}
14533
14534// Scenarios to ignore if expression E is:
14535// 1. an explicit cast expression into void
14536// 2. a function call expression that returns void
14537static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14538 E = E->IgnoreParens();
14539
14540 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14541 if (CE->getCastKind() == CK_ToVoid) {
14542 return true;
14543 }
14544
14545 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14546 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14547 CE->getSubExpr()->getType()->isDependentType()) {
14548 return true;
14549 }
14550 }
14551
14552 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14553 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14554 return false;
14555}
14556
14557void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14558 // No warnings in macros
14559 if (Loc.isMacroID())
14560 return;
14561
14562 // Don't warn in template instantiations.
14563 if (inTemplateInstantiation())
14564 return;
14565
14566 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14567 // instead, skip more than needed, then call back into here with the
14568 // CommaVisitor in SemaStmt.cpp.
14569 // The listed locations are the initialization and increment portions
14570 // of a for loop. The additional checks are on the condition of
14571 // if statements, do/while loops, and for loops.
14572 // Differences in scope flags for C89 mode requires the extra logic.
14573 const unsigned ForIncrementFlags =
14574 getLangOpts().C99 || getLangOpts().CPlusPlus
14575 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14576 : Scope::ContinueScope | Scope::BreakScope;
14577 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14578 const unsigned ScopeFlags = getCurScope()->getFlags();
14579 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14580 (ScopeFlags & ForInitFlags) == ForInitFlags)
14581 return;
14582
14583 // If there are multiple comma operators used together, get the RHS of the
14584 // of the comma operator as the LHS.
14585 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14586 if (BO->getOpcode() != BO_Comma)
14587 break;
14588 LHS = BO->getRHS();
14589 }
14590
14591 // Only allow some expressions on LHS to not warn.
14592 if (IgnoreCommaOperand(E: LHS, Context))
14593 return;
14594
14595 Diag(Loc, DiagID: diag::warn_comma_operator);
14596 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14597 << LHS->getSourceRange()
14598 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14599 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14600 : "(void)(")
14601 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14602 Code: ")");
14603}
14604
14605// C99 6.5.17
14606static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14607 SourceLocation Loc) {
14608 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14609 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14610 if (LHS.isInvalid() || RHS.isInvalid())
14611 return QualType();
14612
14613 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14614 // operands, but not unary promotions.
14615 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14616
14617 // So we treat the LHS as a ignored value, and in C++ we allow the
14618 // containing site to determine what should be done with the RHS.
14619 LHS = S.IgnoredValueConversions(E: LHS.get());
14620 if (LHS.isInvalid())
14621 return QualType();
14622
14623 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14624
14625 if (!S.getLangOpts().CPlusPlus) {
14626 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14627 if (RHS.isInvalid())
14628 return QualType();
14629 if (!RHS.get()->getType()->isVoidType())
14630 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14631 DiagID: diag::err_incomplete_type);
14632 }
14633
14634 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14635 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14636
14637 return RHS.get()->getType();
14638}
14639
14640/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14641/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14642static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14643 ExprValueKind &VK,
14644 ExprObjectKind &OK,
14645 SourceLocation OpLoc, bool IsInc,
14646 bool IsPrefix) {
14647 QualType ResType = Op->getType();
14648 // Atomic types can be used for increment / decrement where the non-atomic
14649 // versions can, so ignore the _Atomic() specifier for the purpose of
14650 // checking.
14651 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14652 ResType = ResAtomicType->getValueType();
14653
14654 assert(!ResType.isNull() && "no type for increment/decrement expression");
14655
14656 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14657 // Decrement of bool is not allowed.
14658 if (!IsInc) {
14659 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14660 return QualType();
14661 }
14662 // Increment of bool sets it to true, but is deprecated.
14663 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14664 : diag::warn_increment_bool)
14665 << Op->getSourceRange();
14666 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14667 // Error on enum increments and decrements in C++ mode
14668 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14669 return QualType();
14670 } else if (ResType->isRealType()) {
14671 // OK!
14672 } else if (ResType->isPointerType()) {
14673 // C99 6.5.2.4p2, 6.5.6p2
14674 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14675 return QualType();
14676 } else if (ResType->isOverflowBehaviorType()) {
14677 // OK!
14678 } else if (ResType->isObjCObjectPointerType()) {
14679 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14680 // Otherwise, we just need a complete type.
14681 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14682 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14683 return QualType();
14684 } else if (ResType->isAnyComplexType()) {
14685 // C99 does not support ++/-- on complex types, we allow as an extension.
14686 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14687 : diag::ext_c2y_increment_complex)
14688 << IsInc << Op->getSourceRange();
14689 } else if (ResType->isPlaceholderType()) {
14690 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14691 if (PR.isInvalid()) return QualType();
14692 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14693 IsInc, IsPrefix);
14694 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14695 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14696 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14697 (ResType->castAs<VectorType>()->getVectorKind() !=
14698 VectorKind::AltiVecBool)) {
14699 // The z vector extensions allow ++ and -- for non-bool vectors.
14700 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14701 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14702 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14703 } else {
14704 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14705 << ResType << int(IsInc) << Op->getSourceRange();
14706 return QualType();
14707 }
14708 // At this point, we know we have a real, complex or pointer type.
14709 // Now make sure the operand is a modifiable lvalue.
14710 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14711 return QualType();
14712 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14713 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14714 // An operand with volatile-qualified type is deprecated
14715 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14716 << IsInc << ResType;
14717 }
14718 // In C++, a prefix increment is the same type as the operand. Otherwise
14719 // (in C or with postfix), the increment is the unqualified type of the
14720 // operand.
14721 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14722 VK = VK_LValue;
14723 OK = Op->getObjectKind();
14724 return ResType;
14725 } else {
14726 VK = VK_PRValue;
14727 return ResType.getUnqualifiedType();
14728 }
14729}
14730
14731/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14732/// This routine allows us to typecheck complex/recursive expressions
14733/// where the declaration is needed for type checking. We only need to
14734/// handle cases when the expression references a function designator
14735/// or is an lvalue. Here are some examples:
14736/// - &(x) => x
14737/// - &*****f => f for f a function designator.
14738/// - &s.xx => s
14739/// - &s.zz[1].yy -> s, if zz is an array
14740/// - *(x + 1) -> x, if x is an array
14741/// - &"123"[2] -> 0
14742/// - & __real__ x -> x
14743///
14744/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14745/// members.
14746static ValueDecl *getPrimaryDecl(Expr *E) {
14747 switch (E->getStmtClass()) {
14748 case Stmt::DeclRefExprClass:
14749 return cast<DeclRefExpr>(Val: E)->getDecl();
14750 case Stmt::MemberExprClass:
14751 // If this is an arrow operator, the address is an offset from
14752 // the base's value, so the object the base refers to is
14753 // irrelevant.
14754 if (cast<MemberExpr>(Val: E)->isArrow())
14755 return nullptr;
14756 // Otherwise, the expression refers to a part of the base
14757 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14758 case Stmt::ArraySubscriptExprClass: {
14759 // FIXME: This code shouldn't be necessary! We should catch the implicit
14760 // promotion of register arrays earlier.
14761 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14762 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14763 if (ICE->getSubExpr()->getType()->isArrayType())
14764 return getPrimaryDecl(E: ICE->getSubExpr());
14765 }
14766 return nullptr;
14767 }
14768 case Stmt::UnaryOperatorClass: {
14769 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14770
14771 switch(UO->getOpcode()) {
14772 case UO_Real:
14773 case UO_Imag:
14774 case UO_Extension:
14775 return getPrimaryDecl(E: UO->getSubExpr());
14776 default:
14777 return nullptr;
14778 }
14779 }
14780 case Stmt::ParenExprClass:
14781 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14782 case Stmt::ImplicitCastExprClass:
14783 // If the result of an implicit cast is an l-value, we care about
14784 // the sub-expression; otherwise, the result here doesn't matter.
14785 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14786 case Stmt::CXXUuidofExprClass:
14787 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14788 default:
14789 return nullptr;
14790 }
14791}
14792
14793namespace {
14794enum {
14795 AO_Bit_Field = 0,
14796 AO_Vector_Element = 1,
14797 AO_Property_Expansion = 2,
14798 AO_Register_Variable = 3,
14799 AO_Matrix_Element = 4,
14800 AO_No_Error = 5
14801};
14802}
14803/// Diagnose invalid operand for address of operations.
14804///
14805/// \param Type The type of operand which cannot have its address taken.
14806static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14807 Expr *E, unsigned Type) {
14808 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14809}
14810
14811bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14812 const Expr *Op,
14813 const CXXMethodDecl *MD) {
14814 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14815
14816 if (Op != DRE)
14817 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14818 << Op->getSourceRange();
14819
14820 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14821 if (isa<CXXDestructorDecl>(Val: MD))
14822 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14823 << DRE->getSourceRange();
14824
14825 if (DRE->getQualifier())
14826 return false;
14827
14828 if (MD->getParent()->getName().empty())
14829 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14830 << DRE->getSourceRange();
14831
14832 SmallString<32> Str;
14833 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14834 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14835 << DRE->getSourceRange()
14836 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14837}
14838
14839QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14840 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14841 if (PTy->getKind() == BuiltinType::Overload) {
14842 Expr *E = OrigOp.get()->IgnoreParens();
14843 if (!isa<OverloadExpr>(Val: E)) {
14844 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14845 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14846 << OrigOp.get()->getSourceRange();
14847 return QualType();
14848 }
14849
14850 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14851 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14852 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14853 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14854 << OrigOp.get()->getSourceRange();
14855 return QualType();
14856 }
14857
14858 return Context.OverloadTy;
14859 }
14860
14861 if (PTy->getKind() == BuiltinType::UnknownAny)
14862 return Context.UnknownAnyTy;
14863
14864 if (PTy->getKind() == BuiltinType::BoundMember) {
14865 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14866 << OrigOp.get()->getSourceRange();
14867 return QualType();
14868 }
14869
14870 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
14871 if (OrigOp.isInvalid()) return QualType();
14872 }
14873
14874 if (OrigOp.get()->isTypeDependent())
14875 return Context.DependentTy;
14876
14877 assert(!OrigOp.get()->hasPlaceholderType());
14878
14879 // Make sure to ignore parentheses in subsequent checks
14880 Expr *op = OrigOp.get()->IgnoreParens();
14881
14882 // In OpenCL captures for blocks called as lambda functions
14883 // are located in the private address space. Blocks used in
14884 // enqueue_kernel can be located in a different address space
14885 // depending on a vendor implementation. Thus preventing
14886 // taking an address of the capture to avoid invalid AS casts.
14887 if (LangOpts.OpenCL) {
14888 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
14889 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14890 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
14891 return QualType();
14892 }
14893 }
14894
14895 if (getLangOpts().C99) {
14896 // Implement C99-only parts of addressof rules.
14897 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
14898 if (uOp->getOpcode() == UO_Deref)
14899 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14900 // (assuming the deref expression is valid).
14901 return uOp->getSubExpr()->getType();
14902 }
14903 // Technically, there should be a check for array subscript
14904 // expressions here, but the result of one is always an lvalue anyway.
14905 }
14906 ValueDecl *dcl = getPrimaryDecl(E: op);
14907
14908 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
14909 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14910 Loc: op->getBeginLoc()))
14911 return QualType();
14912
14913 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
14914 unsigned AddressOfError = AO_No_Error;
14915
14916 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14917 bool IsError = isSFINAEContext();
14918 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
14919 : diag::ext_typecheck_addrof_temporary)
14920 << op->getType() << op->getSourceRange();
14921 if (IsError)
14922 return QualType();
14923 // Materialize the temporary as an lvalue so that we can take its address.
14924 OrigOp = op =
14925 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
14926 } else if (isa<ObjCSelectorExpr>(Val: op)) {
14927 return Context.getPointerType(T: op->getType());
14928 } else if (lval == Expr::LV_MemberFunction) {
14929 // If it's an instance method, make a member pointer.
14930 // The expression must have exactly the form &A::foo.
14931
14932 // If the underlying expression isn't a decl ref, give up.
14933 if (!isa<DeclRefExpr>(Val: op)) {
14934 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14935 << OrigOp.get()->getSourceRange();
14936 return QualType();
14937 }
14938 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
14939 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
14940
14941 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14942 QualType MPTy = Context.getMemberPointerType(
14943 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
14944
14945 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14946 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14947 // When pointer authentication is enabled, argument and return types of
14948 // vitual member functions must be complete. This is because vitrual
14949 // member function pointers are implemented using virtual dispatch
14950 // thunks and the thunks cannot be emitted if the argument or return
14951 // types are incomplete.
14952 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14953 SourceLocation DeclRefLoc,
14954 SourceLocation RetArgTypeLoc) {
14955 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
14956 Diag(Loc: DeclRefLoc,
14957 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14958 Diag(Loc: RetArgTypeLoc,
14959 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14960 << T;
14961 return true;
14962 }
14963 return false;
14964 };
14965 QualType RetTy = MD->getReturnType();
14966 bool IsIncomplete =
14967 !RetTy->isVoidType() &&
14968 ReturnOrParamTypeIsIncomplete(
14969 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14970 for (auto *PVD : MD->parameters())
14971 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14972 PVD->getBeginLoc());
14973 if (IsIncomplete)
14974 return QualType();
14975 }
14976
14977 // Under the MS ABI, lock down the inheritance model now.
14978 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14979 (void)isCompleteType(Loc: OpLoc, T: MPTy);
14980 return MPTy;
14981 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14982 // C99 6.5.3.2p1
14983 // The operand must be either an l-value or a function designator
14984 if (!op->getType()->isFunctionType()) {
14985 // Use a special diagnostic for loads from property references.
14986 if (isa<PseudoObjectExpr>(Val: op)) {
14987 AddressOfError = AO_Property_Expansion;
14988 } else {
14989 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
14990 << op->getType() << op->getSourceRange();
14991 return QualType();
14992 }
14993 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
14994 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
14995 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14996 }
14997
14998 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14999 // The operand cannot be a bit-field
15000 AddressOfError = AO_Bit_Field;
15001 } else if (op->getObjectKind() == OK_VectorComponent) {
15002 // The operand cannot be an element of a vector
15003 AddressOfError = AO_Vector_Element;
15004 } else if (op->getObjectKind() == OK_MatrixComponent) {
15005 // The operand cannot be an element of a matrix.
15006 AddressOfError = AO_Matrix_Element;
15007 } else if (dcl) { // C99 6.5.3.2p1
15008 // We have an lvalue with a decl. Make sure the decl is not declared
15009 // with the register storage-class specifier.
15010 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15011 // in C++ it is not error to take address of a register
15012 // variable (c++03 7.1.1P3)
15013 if (vd->getStorageClass() == SC_Register &&
15014 !getLangOpts().CPlusPlus) {
15015 AddressOfError = AO_Register_Variable;
15016 }
15017 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15018 AddressOfError = AO_Property_Expansion;
15019 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15020 return Context.OverloadTy;
15021 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15022 // Okay: we can take the address of a field.
15023 // Could be a pointer to member, though, if there is an explicit
15024 // scope qualifier for the class.
15025
15026 // [C++26] [expr.prim.id.general]
15027 // If an id-expression E denotes a non-static non-type member
15028 // of some class C [...] and if E is a qualified-id, E is
15029 // not the un-parenthesized operand of the unary & operator [...]
15030 // the id-expression is transformed into a class member access expression.
15031 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15032 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15033 DeclContext *Ctx = dcl->getDeclContext();
15034 if (Ctx && Ctx->isRecord()) {
15035 if (dcl->getType()->isReferenceType()) {
15036 Diag(Loc: OpLoc,
15037 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15038 << dcl->getDeclName() << dcl->getType();
15039 return QualType();
15040 }
15041
15042 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15043 Ctx = Ctx->getParent();
15044
15045 QualType MPTy = Context.getMemberPointerType(
15046 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15047 // Under the MS ABI, lock down the inheritance model now.
15048 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15049 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15050 return MPTy;
15051 }
15052 }
15053 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15054 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15055 UnnamedGlobalConstantDecl>(Val: dcl))
15056 llvm_unreachable("Unknown/unexpected decl type");
15057 }
15058
15059 if (AddressOfError != AO_No_Error) {
15060 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15061 return QualType();
15062 }
15063
15064 if (lval == Expr::LV_IncompleteVoidType) {
15065 // Taking the address of a void variable is technically illegal, but we
15066 // allow it in cases which are otherwise valid.
15067 // Example: "extern void x; void* y = &x;".
15068 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15069 }
15070
15071 // If the operand has type "type", the result has type "pointer to type".
15072 if (op->getType()->isObjCObjectType())
15073 return Context.getObjCObjectPointerType(OIT: op->getType());
15074
15075 // Cannot take the address of WebAssembly references or tables.
15076 if (Context.getTargetInfo().getTriple().isWasm()) {
15077 QualType OpTy = op->getType();
15078 if (OpTy.isWebAssemblyReferenceType()) {
15079 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15080 << 1 << OrigOp.get()->getSourceRange();
15081 return QualType();
15082 }
15083 if (OpTy->isWebAssemblyTableType()) {
15084 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15085 << 1 << OrigOp.get()->getSourceRange();
15086 return QualType();
15087 }
15088 }
15089
15090 CheckAddressOfPackedMember(rhs: op);
15091
15092 return Context.getPointerType(T: op->getType());
15093}
15094
15095static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15096 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15097 if (!DRE)
15098 return;
15099 const Decl *D = DRE->getDecl();
15100 if (!D)
15101 return;
15102 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15103 if (!Param)
15104 return;
15105 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15106 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15107 return;
15108 if (FunctionScopeInfo *FD = S.getCurFunction())
15109 FD->ModifiedNonNullParams.insert(Ptr: Param);
15110}
15111
15112/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15113static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15114 SourceLocation OpLoc,
15115 bool IsAfterAmp = false) {
15116 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15117 if (ConvResult.isInvalid())
15118 return QualType();
15119 Op = ConvResult.get();
15120 QualType OpTy = Op->getType();
15121 QualType Result;
15122
15123 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15124 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15125 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15126 Range: Op->getSourceRange());
15127 }
15128
15129 if (const PointerType *PT = OpTy->getAs<PointerType>())
15130 {
15131 Result = PT->getPointeeType();
15132 }
15133 else if (const ObjCObjectPointerType *OPT =
15134 OpTy->getAs<ObjCObjectPointerType>())
15135 Result = OPT->getPointeeType();
15136 else {
15137 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15138 if (PR.isInvalid()) return QualType();
15139 if (PR.get() != Op)
15140 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15141 }
15142
15143 if (Result.isNull()) {
15144 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15145 << OpTy << Op->getSourceRange();
15146 return QualType();
15147 }
15148
15149 if (Result->isVoidType()) {
15150 // C++ [expr.unary.op]p1:
15151 // [...] the expression to which [the unary * operator] is applied shall
15152 // be a pointer to an object type, or a pointer to a function type
15153 LangOptions LO = S.getLangOpts();
15154 if (LO.CPlusPlus)
15155 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15156 << OpTy << Op->getSourceRange();
15157 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15158 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15159 << OpTy << Op->getSourceRange();
15160 }
15161
15162 // Dereferences are usually l-values...
15163 VK = VK_LValue;
15164
15165 // ...except that certain expressions are never l-values in C.
15166 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15167 VK = VK_PRValue;
15168
15169 return Result;
15170}
15171
15172BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15173 BinaryOperatorKind Opc;
15174 switch (Kind) {
15175 default: llvm_unreachable("Unknown binop!");
15176 case tok::periodstar: Opc = BO_PtrMemD; break;
15177 case tok::arrowstar: Opc = BO_PtrMemI; break;
15178 case tok::star: Opc = BO_Mul; break;
15179 case tok::slash: Opc = BO_Div; break;
15180 case tok::percent: Opc = BO_Rem; break;
15181 case tok::plus: Opc = BO_Add; break;
15182 case tok::minus: Opc = BO_Sub; break;
15183 case tok::lessless: Opc = BO_Shl; break;
15184 case tok::greatergreater: Opc = BO_Shr; break;
15185 case tok::lessequal: Opc = BO_LE; break;
15186 case tok::less: Opc = BO_LT; break;
15187 case tok::greaterequal: Opc = BO_GE; break;
15188 case tok::greater: Opc = BO_GT; break;
15189 case tok::exclaimequal: Opc = BO_NE; break;
15190 case tok::equalequal: Opc = BO_EQ; break;
15191 case tok::spaceship: Opc = BO_Cmp; break;
15192 case tok::amp: Opc = BO_And; break;
15193 case tok::caret: Opc = BO_Xor; break;
15194 case tok::pipe: Opc = BO_Or; break;
15195 case tok::ampamp: Opc = BO_LAnd; break;
15196 case tok::pipepipe: Opc = BO_LOr; break;
15197 case tok::equal: Opc = BO_Assign; break;
15198 case tok::starequal: Opc = BO_MulAssign; break;
15199 case tok::slashequal: Opc = BO_DivAssign; break;
15200 case tok::percentequal: Opc = BO_RemAssign; break;
15201 case tok::plusequal: Opc = BO_AddAssign; break;
15202 case tok::minusequal: Opc = BO_SubAssign; break;
15203 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15204 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15205 case tok::ampequal: Opc = BO_AndAssign; break;
15206 case tok::caretequal: Opc = BO_XorAssign; break;
15207 case tok::pipeequal: Opc = BO_OrAssign; break;
15208 case tok::comma: Opc = BO_Comma; break;
15209 }
15210 return Opc;
15211}
15212
15213static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15214 tok::TokenKind Kind) {
15215 UnaryOperatorKind Opc;
15216 switch (Kind) {
15217 default: llvm_unreachable("Unknown unary op!");
15218 case tok::plusplus: Opc = UO_PreInc; break;
15219 case tok::minusminus: Opc = UO_PreDec; break;
15220 case tok::amp: Opc = UO_AddrOf; break;
15221 case tok::star: Opc = UO_Deref; break;
15222 case tok::plus: Opc = UO_Plus; break;
15223 case tok::minus: Opc = UO_Minus; break;
15224 case tok::tilde: Opc = UO_Not; break;
15225 case tok::exclaim: Opc = UO_LNot; break;
15226 case tok::kw___real: Opc = UO_Real; break;
15227 case tok::kw___imag: Opc = UO_Imag; break;
15228 case tok::kw___extension__: Opc = UO_Extension; break;
15229 }
15230 return Opc;
15231}
15232
15233const FieldDecl *
15234Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15235 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15236 // common for setters.
15237 // struct A {
15238 // int X;
15239 // -void setX(int X) { X = X; }
15240 // +void setX(int X) { this->X = X; }
15241 // };
15242
15243 // Only consider parameters for self assignment fixes.
15244 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15245 return nullptr;
15246 const auto *Method =
15247 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15248 if (!Method)
15249 return nullptr;
15250
15251 const CXXRecordDecl *Parent = Method->getParent();
15252 // In theory this is fixable if the lambda explicitly captures this, but
15253 // that's added complexity that's rarely going to be used.
15254 if (Parent->isLambda())
15255 return nullptr;
15256
15257 // FIXME: Use an actual Lookup operation instead of just traversing fields
15258 // in order to get base class fields.
15259 auto Field =
15260 llvm::find_if(Range: Parent->fields(),
15261 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15262 return F->getDeclName() == Name;
15263 });
15264 return (Field != Parent->field_end()) ? *Field : nullptr;
15265}
15266
15267/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15268/// This warning suppressed in the event of macro expansions.
15269static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15270 SourceLocation OpLoc, bool IsBuiltin) {
15271 if (S.inTemplateInstantiation())
15272 return;
15273 if (S.isUnevaluatedContext())
15274 return;
15275 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15276 return;
15277 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15278 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15279 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15280 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15281 if (!LHSDeclRef || !RHSDeclRef ||
15282 LHSDeclRef->getLocation().isMacroID() ||
15283 RHSDeclRef->getLocation().isMacroID())
15284 return;
15285 const ValueDecl *LHSDecl =
15286 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15287 const ValueDecl *RHSDecl =
15288 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15289 if (LHSDecl != RHSDecl)
15290 return;
15291 if (LHSDecl->getType().isVolatileQualified())
15292 return;
15293 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15294 if (RefTy->getPointeeType().isVolatileQualified())
15295 return;
15296
15297 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15298 : diag::warn_self_assignment_overloaded)
15299 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15300 << RHSExpr->getSourceRange();
15301 if (const FieldDecl *SelfAssignField =
15302 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15303 Diag << 1 << SelfAssignField
15304 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15305 else
15306 Diag << 0;
15307}
15308
15309/// Check if a bitwise-& is performed on an Objective-C pointer. This
15310/// is usually indicative of introspection within the Objective-C pointer.
15311static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15312 SourceLocation OpLoc) {
15313 if (!S.getLangOpts().ObjC)
15314 return;
15315
15316 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15317 const Expr *LHS = L.get();
15318 const Expr *RHS = R.get();
15319
15320 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15321 ObjCPointerExpr = LHS;
15322 OtherExpr = RHS;
15323 }
15324 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15325 ObjCPointerExpr = RHS;
15326 OtherExpr = LHS;
15327 }
15328
15329 // This warning is deliberately made very specific to reduce false
15330 // positives with logic that uses '&' for hashing. This logic mainly
15331 // looks for code trying to introspect into tagged pointers, which
15332 // code should generally never do.
15333 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15334 unsigned Diag = diag::warn_objc_pointer_masking;
15335 // Determine if we are introspecting the result of performSelectorXXX.
15336 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15337 // Special case messages to -performSelector and friends, which
15338 // can return non-pointer values boxed in a pointer value.
15339 // Some clients may wish to silence warnings in this subcase.
15340 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15341 Selector S = ME->getSelector();
15342 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15343 if (SelArg0.starts_with(Prefix: "performSelector"))
15344 Diag = diag::warn_objc_pointer_masking_performSelector;
15345 }
15346
15347 S.Diag(Loc: OpLoc, DiagID: Diag)
15348 << ObjCPointerExpr->getSourceRange();
15349 }
15350}
15351
15352// This helper function promotes a binary operator's operands (which are of a
15353// half vector type) to a vector of floats and then truncates the result to
15354// a vector of either half or short.
15355static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15356 BinaryOperatorKind Opc, QualType ResultTy,
15357 ExprValueKind VK, ExprObjectKind OK,
15358 bool IsCompAssign, SourceLocation OpLoc,
15359 FPOptionsOverride FPFeatures) {
15360 auto &Context = S.getASTContext();
15361 assert((isVector(ResultTy, Context.HalfTy) ||
15362 isVector(ResultTy, Context.ShortTy)) &&
15363 "Result must be a vector of half or short");
15364 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15365 isVector(RHS.get()->getType(), Context.HalfTy) &&
15366 "both operands expected to be a half vector");
15367
15368 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15369 QualType BinOpResTy = RHS.get()->getType();
15370
15371 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15372 // change BinOpResTy to a vector of ints.
15373 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15374 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15375
15376 if (IsCompAssign)
15377 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15378 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15379 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15380
15381 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15382 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15383 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15384 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15385}
15386
15387/// Returns true if conversion between vectors of halfs and vectors of floats
15388/// is needed.
15389static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15390 Expr *E0, Expr *E1 = nullptr) {
15391 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15392 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15393 return false;
15394
15395 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15396 QualType Ty = E->IgnoreImplicit()->getType();
15397
15398 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15399 // to vectors of floats. Although the element type of the vectors is __fp16,
15400 // the vectors shouldn't be treated as storage-only types. See the
15401 // discussion here: https://reviews.llvm.org/rG825235c140e7
15402 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15403 if (VT->getVectorKind() == VectorKind::Neon)
15404 return false;
15405 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15406 }
15407 return false;
15408 };
15409
15410 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15411}
15412
15413ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15414 BinaryOperatorKind Opc, Expr *LHSExpr,
15415 Expr *RHSExpr, bool ForFoldExpression) {
15416 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15417 // The syntax only allows initializer lists on the RHS of assignment,
15418 // so we don't need to worry about accepting invalid code for
15419 // non-assignment operators.
15420 // C++11 5.17p9:
15421 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15422 // of x = {} is x = T().
15423 InitializationKind Kind = InitializationKind::CreateDirectList(
15424 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15425 InitializedEntity Entity =
15426 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15427 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15428 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15429 if (Init.isInvalid())
15430 return Init;
15431 RHSExpr = Init.get();
15432 }
15433
15434 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15435 QualType ResultTy; // Result type of the binary operator.
15436 // The following two variables are used for compound assignment operators
15437 QualType CompLHSTy; // Type of LHS after promotions for computation
15438 QualType CompResultTy; // Type of computation result
15439 ExprValueKind VK = VK_PRValue;
15440 ExprObjectKind OK = OK_Ordinary;
15441 bool ConvertHalfVec = false;
15442
15443 if (!LHS.isUsable() || !RHS.isUsable())
15444 return ExprError();
15445
15446 if (getLangOpts().OpenCL) {
15447 QualType LHSTy = LHSExpr->getType();
15448 QualType RHSTy = RHSExpr->getType();
15449 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15450 // the ATOMIC_VAR_INIT macro.
15451 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15452 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15453 if (BO_Assign == Opc)
15454 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15455 else
15456 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15457 return ExprError();
15458 }
15459
15460 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15461 // only with a builtin functions and therefore should be disallowed here.
15462 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15463 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15464 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15465 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15466 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15467 return ExprError();
15468 }
15469 }
15470
15471 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15472 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15473
15474 switch (Opc) {
15475 case BO_Assign:
15476 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15477 if (getLangOpts().CPlusPlus &&
15478 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15479 VK = LHS.get()->getValueKind();
15480 OK = LHS.get()->getObjectKind();
15481 }
15482 if (!ResultTy.isNull()) {
15483 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15484 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15485
15486 // Avoid copying a block to the heap if the block is assigned to a local
15487 // auto variable that is declared in the same scope as the block. This
15488 // optimization is unsafe if the local variable is declared in an outer
15489 // scope. For example:
15490 //
15491 // BlockTy b;
15492 // {
15493 // b = ^{...};
15494 // }
15495 // // It is unsafe to invoke the block here if it wasn't copied to the
15496 // // heap.
15497 // b();
15498
15499 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15500 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15501 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15502 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15503 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15504
15505 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15506 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15507 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15508 }
15509 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15510 break;
15511 case BO_PtrMemD:
15512 case BO_PtrMemI:
15513 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15514 isIndirect: Opc == BO_PtrMemI);
15515 break;
15516 case BO_Mul:
15517 case BO_Div:
15518 ConvertHalfVec = true;
15519 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15520 break;
15521 case BO_Rem:
15522 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15523 break;
15524 case BO_Add:
15525 ConvertHalfVec = true;
15526 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15527 break;
15528 case BO_Sub:
15529 ConvertHalfVec = true;
15530 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15531 break;
15532 case BO_Shl:
15533 case BO_Shr:
15534 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15535 break;
15536 case BO_LE:
15537 case BO_LT:
15538 case BO_GE:
15539 case BO_GT:
15540 ConvertHalfVec = true;
15541 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15542
15543 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15544 !ForFoldExpression && BI && BI->isComparisonOp())
15545 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15546 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15547
15548 break;
15549 case BO_EQ:
15550 case BO_NE:
15551 ConvertHalfVec = true;
15552 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15553 break;
15554 case BO_Cmp:
15555 ConvertHalfVec = true;
15556 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15557 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15558 break;
15559 case BO_And:
15560 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15561 [[fallthrough]];
15562 case BO_Xor:
15563 case BO_Or:
15564 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15565 break;
15566 case BO_LAnd:
15567 case BO_LOr:
15568 ConvertHalfVec = true;
15569 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15570 break;
15571 case BO_MulAssign:
15572 case BO_DivAssign:
15573 ConvertHalfVec = true;
15574 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15575 CompLHSTy = CompResultTy;
15576 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15577 ResultTy =
15578 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15579 break;
15580 case BO_RemAssign:
15581 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15582 CompLHSTy = CompResultTy;
15583 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15584 ResultTy =
15585 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15586 break;
15587 case BO_AddAssign:
15588 ConvertHalfVec = true;
15589 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15590 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15591 ResultTy =
15592 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15593 break;
15594 case BO_SubAssign:
15595 ConvertHalfVec = true;
15596 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15597 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15598 ResultTy =
15599 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15600 break;
15601 case BO_ShlAssign:
15602 case BO_ShrAssign:
15603 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15604 CompLHSTy = CompResultTy;
15605 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15606 ResultTy =
15607 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15608 break;
15609 case BO_AndAssign:
15610 case BO_OrAssign: // fallthrough
15611 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15612 [[fallthrough]];
15613 case BO_XorAssign:
15614 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15615 CompLHSTy = CompResultTy;
15616 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15617 ResultTy =
15618 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15619 break;
15620 case BO_Comma:
15621 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15622 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15623 VK = RHS.get()->getValueKind();
15624 OK = RHS.get()->getObjectKind();
15625 }
15626 break;
15627 }
15628 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15629 return ExprError();
15630
15631 // Some of the binary operations require promoting operands of half vector to
15632 // float vectors and truncating the result back to half vector. For now, we do
15633 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15634 // arm64).
15635 assert(
15636 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15637 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15638 "both sides are half vectors or neither sides are");
15639 ConvertHalfVec =
15640 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15641
15642 // Check for array bounds violations for both sides of the BinaryOperator
15643 CheckArrayAccess(E: LHS.get());
15644 CheckArrayAccess(E: RHS.get());
15645
15646 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15647 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15648 Name: &Context.Idents.get(Name: "object_setClass"),
15649 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15650 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15651 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15652 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15653 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15654 Code: "object_setClass(")
15655 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15656 Code: ",")
15657 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15658 }
15659 else
15660 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15661 }
15662 else if (const ObjCIvarRefExpr *OIRE =
15663 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15664 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15665
15666 // Opc is not a compound assignment if CompResultTy is null.
15667 if (CompResultTy.isNull()) {
15668 if (ConvertHalfVec)
15669 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15670 OpLoc, FPFeatures: CurFPFeatureOverrides());
15671 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15672 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15673 }
15674
15675 // Handle compound assignments.
15676 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15677 OK_ObjCProperty) {
15678 VK = VK_LValue;
15679 OK = LHS.get()->getObjectKind();
15680 }
15681
15682 // The LHS is not converted to the result type for fixed-point compound
15683 // assignment as the common type is computed on demand. Reset the CompLHSTy
15684 // to the LHS type we would have gotten after unary conversions.
15685 if (CompResultTy->isFixedPointType())
15686 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15687
15688 if (ConvertHalfVec)
15689 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15690 OpLoc, FPFeatures: CurFPFeatureOverrides());
15691
15692 return CompoundAssignOperator::Create(
15693 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15694 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15695}
15696
15697/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15698/// operators are mixed in a way that suggests that the programmer forgot that
15699/// comparison operators have higher precedence. The most typical example of
15700/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15701static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15702 SourceLocation OpLoc, Expr *LHSExpr,
15703 Expr *RHSExpr) {
15704 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15705 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15706
15707 // Check that one of the sides is a comparison operator and the other isn't.
15708 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15709 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15710 if (isLeftComp == isRightComp)
15711 return;
15712
15713 // Bitwise operations are sometimes used as eager logical ops.
15714 // Don't diagnose this.
15715 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15716 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15717 if (isLeftBitwise || isRightBitwise)
15718 return;
15719
15720 SourceRange DiagRange = isLeftComp
15721 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15722 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15723 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15724 SourceRange ParensRange =
15725 isLeftComp
15726 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15727 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15728
15729 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15730 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15731 SuggestParentheses(Self, Loc: OpLoc,
15732 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15733 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15734 SuggestParentheses(Self, Loc: OpLoc,
15735 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15736 << BinaryOperator::getOpcodeStr(Op: Opc),
15737 ParenRange: ParensRange);
15738}
15739
15740/// It accepts a '&&' expr that is inside a '||' one.
15741/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15742/// in parentheses.
15743static void
15744EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15745 BinaryOperator *Bop) {
15746 assert(Bop->getOpcode() == BO_LAnd);
15747 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15748 << Bop->getSourceRange() << OpLoc;
15749 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15750 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15751 << Bop->getOpcodeStr(),
15752 ParenRange: Bop->getSourceRange());
15753}
15754
15755/// Look for '&&' in the left hand of a '||' expr.
15756static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15757 Expr *LHSExpr, Expr *RHSExpr) {
15758 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15759 if (Bop->getOpcode() == BO_LAnd) {
15760 // If it's "string_literal && a || b" don't warn since the precedence
15761 // doesn't matter.
15762 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15763 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15764 } else if (Bop->getOpcode() == BO_LOr) {
15765 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15766 // If it's "a || b && string_literal || c" we didn't warn earlier for
15767 // "a || b && string_literal", but warn now.
15768 if (RBop->getOpcode() == BO_LAnd &&
15769 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15770 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15771 }
15772 }
15773 }
15774}
15775
15776/// Look for '&&' in the right hand of a '||' expr.
15777static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15778 Expr *LHSExpr, Expr *RHSExpr) {
15779 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15780 if (Bop->getOpcode() == BO_LAnd) {
15781 // If it's "a || b && string_literal" don't warn since the precedence
15782 // doesn't matter.
15783 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15784 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15785 }
15786 }
15787}
15788
15789/// Look for bitwise op in the left or right hand of a bitwise op with
15790/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15791/// the '&' expression in parentheses.
15792static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15793 SourceLocation OpLoc, Expr *SubExpr) {
15794 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15795 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15796 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15797 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15798 << Bop->getSourceRange() << OpLoc;
15799 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15800 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15801 << Bop->getOpcodeStr(),
15802 ParenRange: Bop->getSourceRange());
15803 }
15804 }
15805}
15806
15807static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15808 Expr *SubExpr, StringRef Shift) {
15809 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15810 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15811 StringRef Op = Bop->getOpcodeStr();
15812 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15813 << Bop->getSourceRange() << OpLoc << Shift << Op;
15814 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15815 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15816 ParenRange: Bop->getSourceRange());
15817 }
15818 }
15819}
15820
15821static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15822 Expr *LHSExpr, Expr *RHSExpr) {
15823 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15824 if (!OCE)
15825 return;
15826
15827 FunctionDecl *FD = OCE->getDirectCallee();
15828 if (!FD || !FD->isOverloadedOperator())
15829 return;
15830
15831 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15832 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15833 return;
15834
15835 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15836 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15837 << (Kind == OO_LessLess);
15838 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15839 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15840 << (Kind == OO_LessLess ? "<<" : ">>"),
15841 ParenRange: OCE->getSourceRange());
15842 SuggestParentheses(
15843 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15844 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15845}
15846
15847/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15848/// precedence.
15849static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15850 SourceLocation OpLoc, Expr *LHSExpr,
15851 Expr *RHSExpr){
15852 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15853 if (BinaryOperator::isBitwiseOp(Opc))
15854 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15855
15856 // Diagnose "arg1 & arg2 | arg3"
15857 if ((Opc == BO_Or || Opc == BO_Xor) &&
15858 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15859 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15860 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15861 }
15862
15863 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15864 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15865 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15866 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15867 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15868 }
15869
15870 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15871 || Opc == BO_Shr) {
15872 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15873 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15874 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15875 }
15876
15877 // Warn on overloaded shift operators and comparisons, such as:
15878 // cout << 5 == 4;
15879 if (BinaryOperator::isComparisonOp(Opc))
15880 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15881}
15882
15883ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15884 tok::TokenKind Kind,
15885 Expr *LHSExpr, Expr *RHSExpr) {
15886 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15887 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15888 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15889
15890 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15891 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15892
15893 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15894 ? BuiltinCountedByRefKind::Assignment
15895 : BuiltinCountedByRefKind::BinaryExpr;
15896
15897 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
15898 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
15899
15900 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
15901}
15902
15903void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15904 UnresolvedSetImpl &Functions) {
15905 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15906 if (OverOp != OO_None && OverOp != OO_Equal)
15907 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
15908
15909 // In C++20 onwards, we may have a second operator to look up.
15910 if (getLangOpts().CPlusPlus20) {
15911 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
15912 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
15913 }
15914}
15915
15916/// Build an overloaded binary operator expression in the given scope.
15917static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15918 BinaryOperatorKind Opc,
15919 Expr *LHS, Expr *RHS) {
15920 switch (Opc) {
15921 case BO_Assign:
15922 // In the non-overloaded case, we warn about self-assignment (x = x) for
15923 // both simple assignment and certain compound assignments where algebra
15924 // tells us the operation yields a constant result. When the operator is
15925 // overloaded, we can't do the latter because we don't want to assume that
15926 // those algebraic identities still apply; for example, a path-building
15927 // library might use operator/= to append paths. But it's still reasonable
15928 // to assume that simple assignment is just moving/copying values around
15929 // and so self-assignment is likely a bug.
15930 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
15931 [[fallthrough]];
15932 case BO_DivAssign:
15933 case BO_RemAssign:
15934 case BO_SubAssign:
15935 case BO_AndAssign:
15936 case BO_OrAssign:
15937 case BO_XorAssign:
15938 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
15939 break;
15940 default:
15941 break;
15942 }
15943
15944 // Find all of the overloaded operators visible from this point.
15945 UnresolvedSet<16> Functions;
15946 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
15947
15948 // Build the (potentially-overloaded, potentially-dependent)
15949 // binary operation.
15950 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
15951}
15952
15953ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15954 BinaryOperatorKind Opc, Expr *LHSExpr,
15955 Expr *RHSExpr, bool ForFoldExpression) {
15956 if (!LHSExpr || !RHSExpr)
15957 return ExprError();
15958
15959 // We want to end up calling one of SemaPseudoObject::checkAssignment
15960 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15961 // both expressions are overloadable or either is type-dependent),
15962 // or CreateBuiltinBinOp (in any other case). We also want to get
15963 // any placeholder types out of the way.
15964
15965 // Handle pseudo-objects in the LHS.
15966 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15967 // Assignments with a pseudo-object l-value need special analysis.
15968 if (pty->getKind() == BuiltinType::PseudoObject &&
15969 BinaryOperator::isAssignmentOp(Opc))
15970 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
15971
15972 // Don't resolve overloads if the other type is overloadable.
15973 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15974 // We can't actually test that if we still have a placeholder,
15975 // though. Fortunately, none of the exceptions we see in that
15976 // code below are valid when the LHS is an overload set. Note
15977 // that an overload set can be dependently-typed, but it never
15978 // instantiates to having an overloadable type.
15979 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
15980 if (resolvedRHS.isInvalid()) return ExprError();
15981 RHSExpr = resolvedRHS.get();
15982
15983 if (RHSExpr->isTypeDependent() ||
15984 RHSExpr->getType()->isOverloadableType())
15985 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15986 }
15987
15988 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15989 // template, diagnose the missing 'template' keyword instead of diagnosing
15990 // an invalid use of a bound member function.
15991 //
15992 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15993 // to C++1z [over.over]/1.4, but we already checked for that case above.
15994 if (Opc == BO_LT && inTemplateInstantiation() &&
15995 (pty->getKind() == BuiltinType::BoundMember ||
15996 pty->getKind() == BuiltinType::Overload)) {
15997 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
15998 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15999 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16000 return isa<FunctionTemplateDecl>(Val: ND);
16001 })) {
16002 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16003 : OE->getNameLoc(),
16004 DiagID: diag::err_template_kw_missing)
16005 << OE->getName().getAsIdentifierInfo();
16006 return ExprError();
16007 }
16008 }
16009
16010 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16011 if (LHS.isInvalid()) return ExprError();
16012 LHSExpr = LHS.get();
16013 }
16014
16015 // Handle pseudo-objects in the RHS.
16016 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16017 // An overload in the RHS can potentially be resolved by the type
16018 // being assigned to.
16019 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16020 if (getLangOpts().CPlusPlus &&
16021 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16022 LHSExpr->getType()->isOverloadableType()))
16023 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16024
16025 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16026 ForFoldExpression);
16027 }
16028
16029 // Don't resolve overloads if the other type is overloadable.
16030 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16031 LHSExpr->getType()->isOverloadableType())
16032 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16033
16034 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16035 if (!resolvedRHS.isUsable()) return ExprError();
16036 RHSExpr = resolvedRHS.get();
16037 }
16038
16039 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16040 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16041 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16042 return ExprError();
16043 }
16044
16045 if (getLangOpts().CPlusPlus) {
16046 // Otherwise, build an overloaded op if either expression is type-dependent
16047 // or has an overloadable type.
16048 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16049 LHSExpr->getType()->isOverloadableType() ||
16050 RHSExpr->getType()->isOverloadableType())
16051 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16052 }
16053
16054 if (getLangOpts().RecoveryAST &&
16055 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16056 assert(!getLangOpts().CPlusPlus);
16057 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16058 "Should only occur in error-recovery path.");
16059 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16060 // C [6.15.16] p3:
16061 // An assignment expression has the value of the left operand after the
16062 // assignment, but is not an lvalue.
16063 return CompoundAssignOperator::Create(
16064 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16065 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16066 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16067 QualType ResultType;
16068 switch (Opc) {
16069 case BO_Assign:
16070 ResultType = LHSExpr->getType().getUnqualifiedType();
16071 break;
16072 case BO_LT:
16073 case BO_GT:
16074 case BO_LE:
16075 case BO_GE:
16076 case BO_EQ:
16077 case BO_NE:
16078 case BO_LAnd:
16079 case BO_LOr:
16080 // These operators have a fixed result type regardless of operands.
16081 ResultType = Context.IntTy;
16082 break;
16083 case BO_Comma:
16084 ResultType = RHSExpr->getType();
16085 break;
16086 default:
16087 ResultType = Context.DependentTy;
16088 break;
16089 }
16090 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16091 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16092 FPFeatures: CurFPFeatureOverrides());
16093 }
16094
16095 // Build a built-in binary operation.
16096 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16097}
16098
16099static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16100 if (T.isNull() || T->isDependentType())
16101 return false;
16102
16103 if (!Ctx.isPromotableIntegerType(T))
16104 return true;
16105
16106 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16107}
16108
16109ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16110 UnaryOperatorKind Opc, Expr *InputExpr,
16111 bool IsAfterAmp) {
16112 ExprResult Input = InputExpr;
16113 ExprValueKind VK = VK_PRValue;
16114 ExprObjectKind OK = OK_Ordinary;
16115 QualType resultType;
16116 bool CanOverflow = false;
16117
16118 bool ConvertHalfVec = false;
16119 if (getLangOpts().OpenCL) {
16120 QualType Ty = InputExpr->getType();
16121 // The only legal unary operation for atomics is '&'.
16122 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16123 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16124 // only with a builtin functions and therefore should be disallowed here.
16125 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16126 || Ty->isBlockPointerType())) {
16127 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16128 << InputExpr->getType()
16129 << Input.get()->getSourceRange());
16130 }
16131 }
16132
16133 if (getLangOpts().HLSL && OpLoc.isValid()) {
16134 if (Opc == UO_AddrOf)
16135 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16136 if (Opc == UO_Deref)
16137 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16138 }
16139
16140 if (InputExpr->isTypeDependent() &&
16141 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16142 resultType = Context.DependentTy;
16143 } else {
16144 switch (Opc) {
16145 case UO_PreInc:
16146 case UO_PreDec:
16147 case UO_PostInc:
16148 case UO_PostDec:
16149 resultType =
16150 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16151 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16152 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16153 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16154 break;
16155 case UO_AddrOf:
16156 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16157 CheckAddressOfNoDeref(E: InputExpr);
16158 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16159 break;
16160 case UO_Deref: {
16161 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16162 if (Input.isInvalid())
16163 return ExprError();
16164 resultType =
16165 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16166 break;
16167 }
16168 case UO_Plus:
16169 case UO_Minus:
16170 CanOverflow = Opc == UO_Minus &&
16171 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16172 Input = UsualUnaryConversions(E: Input.get());
16173 if (Input.isInvalid())
16174 return ExprError();
16175 // Unary plus and minus require promoting an operand of half vector to a
16176 // float vector and truncating the result back to a half vector. For now,
16177 // we do this only when HalfArgsAndReturns is set (that is, when the
16178 // target is arm or arm64).
16179 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16180
16181 // If the operand is a half vector, promote it to a float vector.
16182 if (ConvertHalfVec)
16183 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16184 resultType = Input.get()->getType();
16185 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16186 break;
16187 else if (resultType->isVectorType() &&
16188 // The z vector extensions don't allow + or - with bool vectors.
16189 (!Context.getLangOpts().ZVector ||
16190 resultType->castAs<VectorType>()->getVectorKind() !=
16191 VectorKind::AltiVecBool))
16192 break;
16193 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16194 break;
16195 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16196 Opc == UO_Plus && resultType->isPointerType())
16197 break;
16198
16199 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16200 << resultType << Input.get()->getSourceRange());
16201
16202 case UO_Not: // bitwise complement
16203 Input = UsualUnaryConversions(E: Input.get());
16204 if (Input.isInvalid())
16205 return ExprError();
16206 resultType = Input.get()->getType();
16207 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16208 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16209 // C99 does not support '~' for complex conjugation.
16210 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16211 << resultType << Input.get()->getSourceRange();
16212 else if (resultType->hasIntegerRepresentation())
16213 break;
16214 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16215 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16216 // on vector float types.
16217 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16218 if (!T->isIntegerType())
16219 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16220 << resultType << Input.get()->getSourceRange());
16221 } else {
16222 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16223 << resultType << Input.get()->getSourceRange());
16224 }
16225 break;
16226
16227 case UO_LNot: // logical negation
16228 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16229 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16230 if (Input.isInvalid())
16231 return ExprError();
16232 resultType = Input.get()->getType();
16233
16234 // Though we still have to promote half FP to float...
16235 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16236 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16237 .get();
16238 resultType = Context.FloatTy;
16239 }
16240
16241 // WebAsembly tables can't be used in unary expressions.
16242 if (resultType->isPointerType() &&
16243 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16244 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16245 << resultType << Input.get()->getSourceRange());
16246 }
16247
16248 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16249 // C99 6.5.3.3p1: ok, fallthrough;
16250 if (Context.getLangOpts().CPlusPlus) {
16251 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16252 // operand contextually converted to bool.
16253 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16254 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16255 } else if (Context.getLangOpts().OpenCL &&
16256 Context.getLangOpts().OpenCLVersion < 120) {
16257 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16258 // operate on scalar float types.
16259 if (!resultType->isIntegerType() && !resultType->isPointerType())
16260 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16261 << resultType << Input.get()->getSourceRange());
16262 }
16263 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16264 !resultType->hasBooleanRepresentation()) {
16265 // HLSL unary logical 'not' behaves like C++, which states that the
16266 // operand is converted to bool and the result is bool, however HLSL
16267 // extends this property to vectors.
16268 const VectorType *VTy = resultType->castAs<VectorType>();
16269 resultType =
16270 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16271
16272 Input = ImpCastExprToType(
16273 E: Input.get(), Type: resultType,
16274 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16275 .get();
16276 break;
16277 } else if (resultType->isExtVectorType()) {
16278 if (Context.getLangOpts().OpenCL &&
16279 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16280 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16281 // operate on vector float types.
16282 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16283 if (!T->isIntegerType())
16284 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16285 << resultType << Input.get()->getSourceRange());
16286 }
16287 // Vector logical not returns the signed variant of the operand type.
16288 resultType = GetSignedVectorType(V: resultType);
16289 break;
16290 } else if (Context.getLangOpts().CPlusPlus &&
16291 resultType->isVectorType()) {
16292 const VectorType *VTy = resultType->castAs<VectorType>();
16293 if (VTy->getVectorKind() != VectorKind::Generic)
16294 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16295 << resultType << Input.get()->getSourceRange());
16296
16297 // Vector logical not returns the signed variant of the operand type.
16298 resultType = GetSignedVectorType(V: resultType);
16299 break;
16300 } else {
16301 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16302 << resultType << Input.get()->getSourceRange());
16303 }
16304
16305 // LNot always has type int. C99 6.5.3.3p5.
16306 // In C++, it's bool. C++ 5.3.1p8
16307 resultType = Context.getLogicalOperationType();
16308 break;
16309 case UO_Real:
16310 case UO_Imag:
16311 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16312 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16313 // ordinary complex l-values to ordinary l-values and all other values to
16314 // r-values.
16315 if (Input.isInvalid())
16316 return ExprError();
16317 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16318 if (Input.get()->isGLValue() &&
16319 Input.get()->getObjectKind() == OK_Ordinary)
16320 VK = Input.get()->getValueKind();
16321 } else if (!getLangOpts().CPlusPlus) {
16322 // In C, a volatile scalar is read by __imag. In C++, it is not.
16323 Input = DefaultLvalueConversion(E: Input.get());
16324 }
16325 break;
16326 case UO_Extension:
16327 resultType = Input.get()->getType();
16328 VK = Input.get()->getValueKind();
16329 OK = Input.get()->getObjectKind();
16330 break;
16331 case UO_Coawait:
16332 // It's unnecessary to represent the pass-through operator co_await in the
16333 // AST; just return the input expression instead.
16334 assert(!Input.get()->getType()->isDependentType() &&
16335 "the co_await expression must be non-dependant before "
16336 "building operator co_await");
16337 return Input;
16338 }
16339 }
16340 if (resultType.isNull() || Input.isInvalid())
16341 return ExprError();
16342
16343 // Check for array bounds violations in the operand of the UnaryOperator,
16344 // except for the '*' and '&' operators that have to be handled specially
16345 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16346 // that are explicitly defined as valid by the standard).
16347 if (Opc != UO_AddrOf && Opc != UO_Deref)
16348 CheckArrayAccess(E: Input.get());
16349
16350 auto *UO =
16351 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16352 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16353
16354 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16355 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16356 !isUnevaluatedContext())
16357 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16358
16359 // Convert the result back to a half vector.
16360 if (ConvertHalfVec)
16361 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16362 return UO;
16363}
16364
16365bool Sema::isQualifiedMemberAccess(Expr *E) {
16366 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16367 if (!DRE->getQualifier())
16368 return false;
16369
16370 ValueDecl *VD = DRE->getDecl();
16371 if (!VD->isCXXClassMember())
16372 return false;
16373
16374 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16375 return true;
16376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16377 return Method->isImplicitObjectMemberFunction();
16378
16379 return false;
16380 }
16381
16382 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16383 if (!ULE->getQualifier())
16384 return false;
16385
16386 for (NamedDecl *D : ULE->decls()) {
16387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16388 if (Method->isImplicitObjectMemberFunction())
16389 return true;
16390 } else {
16391 // Overload set does not contain methods.
16392 break;
16393 }
16394 }
16395
16396 return false;
16397 }
16398
16399 return false;
16400}
16401
16402ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16403 UnaryOperatorKind Opc, Expr *Input,
16404 bool IsAfterAmp) {
16405 // First things first: handle placeholders so that the
16406 // overloaded-operator check considers the right type.
16407 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16408 // Increment and decrement of pseudo-object references.
16409 if (pty->getKind() == BuiltinType::PseudoObject &&
16410 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16411 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16412
16413 // extension is always a builtin operator.
16414 if (Opc == UO_Extension)
16415 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16416
16417 // & gets special logic for several kinds of placeholder.
16418 // The builtin code knows what to do.
16419 if (Opc == UO_AddrOf &&
16420 (pty->getKind() == BuiltinType::Overload ||
16421 pty->getKind() == BuiltinType::UnknownAny ||
16422 pty->getKind() == BuiltinType::BoundMember))
16423 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16424
16425 // Anything else needs to be handled now.
16426 ExprResult Result = CheckPlaceholderExpr(E: Input);
16427 if (Result.isInvalid()) return ExprError();
16428 Input = Result.get();
16429 }
16430
16431 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16432 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16433 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16434 // Find all of the overloaded operators visible from this point.
16435 UnresolvedSet<16> Functions;
16436 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16437 if (S && OverOp != OO_None)
16438 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16439
16440 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16441 }
16442
16443 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16444}
16445
16446ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16447 Expr *Input, bool IsAfterAmp) {
16448 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16449 IsAfterAmp);
16450}
16451
16452ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16453 LabelDecl *TheDecl) {
16454 TheDecl->markUsed(C&: Context);
16455 // Create the AST node. The address of a label always has type 'void*'.
16456 auto *Res = new (Context) AddrLabelExpr(
16457 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16458
16459 if (getCurFunction())
16460 getCurFunction()->AddrLabels.push_back(Elt: Res);
16461
16462 return Res;
16463}
16464
16465void Sema::ActOnStartStmtExpr() {
16466 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16467 // Make sure we diagnose jumping into a statement expression.
16468 setFunctionHasBranchProtectedScope();
16469}
16470
16471void Sema::ActOnStmtExprError() {
16472 // Note that function is also called by TreeTransform when leaving a
16473 // StmtExpr scope without rebuilding anything.
16474
16475 DiscardCleanupsInEvaluationContext();
16476 PopExpressionEvaluationContext();
16477}
16478
16479ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16480 SourceLocation RPLoc) {
16481 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16482}
16483
16484ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16485 SourceLocation RPLoc, unsigned TemplateDepth) {
16486 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16487 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16488
16489 if (hasAnyUnrecoverableErrorsInThisFunction())
16490 DiscardCleanupsInEvaluationContext();
16491 assert(!Cleanup.exprNeedsCleanups() &&
16492 "cleanups within StmtExpr not correctly bound!");
16493 PopExpressionEvaluationContext();
16494
16495 // FIXME: there are a variety of strange constraints to enforce here, for
16496 // example, it is not possible to goto into a stmt expression apparently.
16497 // More semantic analysis is needed.
16498
16499 // If there are sub-stmts in the compound stmt, take the type of the last one
16500 // as the type of the stmtexpr.
16501 QualType Ty = Context.VoidTy;
16502 bool StmtExprMayBindToTemp = false;
16503 if (!Compound->body_empty()) {
16504 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16505 if (const Expr *Value = LastStmt->getExprStmt()) {
16506 StmtExprMayBindToTemp = true;
16507 Ty = Value->getType();
16508 }
16509 }
16510 }
16511
16512 // FIXME: Check that expression type is complete/non-abstract; statement
16513 // expressions are not lvalues.
16514 Expr *ResStmtExpr =
16515 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16516 if (StmtExprMayBindToTemp)
16517 return MaybeBindToTemporary(E: ResStmtExpr);
16518 return ResStmtExpr;
16519}
16520
16521ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16522 if (ER.isInvalid())
16523 return ExprError();
16524
16525 // Do function/array conversion on the last expression, but not
16526 // lvalue-to-rvalue. However, initialize an unqualified type.
16527 ER = DefaultFunctionArrayConversion(E: ER.get());
16528 if (ER.isInvalid())
16529 return ExprError();
16530 Expr *E = ER.get();
16531
16532 if (E->isTypeDependent())
16533 return E;
16534
16535 // In ARC, if the final expression ends in a consume, splice
16536 // the consume out and bind it later. In the alternate case
16537 // (when dealing with a retainable type), the result
16538 // initialization will create a produce. In both cases the
16539 // result will be +1, and we'll need to balance that out with
16540 // a bind.
16541 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16542 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16543 return Cast->getSubExpr();
16544
16545 // FIXME: Provide a better location for the initialization.
16546 return PerformCopyInitialization(
16547 Entity: InitializedEntity::InitializeStmtExprResult(
16548 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16549 EqualLoc: SourceLocation(), Init: E);
16550}
16551
16552ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16553 TypeSourceInfo *TInfo,
16554 ArrayRef<OffsetOfComponent> Components,
16555 SourceLocation RParenLoc) {
16556 QualType ArgTy = TInfo->getType();
16557 bool Dependent = ArgTy->isDependentType();
16558 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16559
16560 // We must have at least one component that refers to the type, and the first
16561 // one is known to be a field designator. Verify that the ArgTy represents
16562 // a struct/union/class.
16563 if (!Dependent && !ArgTy->isRecordType())
16564 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16565 << ArgTy << TypeRange);
16566
16567 // Type must be complete per C99 7.17p3 because a declaring a variable
16568 // with an incomplete type would be ill-formed.
16569 if (!Dependent
16570 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16571 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16572 return ExprError();
16573
16574 bool DidWarnAboutNonPOD = false;
16575 QualType CurrentType = ArgTy;
16576 SmallVector<OffsetOfNode, 4> Comps;
16577 SmallVector<Expr*, 4> Exprs;
16578 for (const OffsetOfComponent &OC : Components) {
16579 if (OC.isBrackets) {
16580 // Offset of an array sub-field. TODO: Should we allow vector elements?
16581 if (!CurrentType->isDependentType()) {
16582 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16583 if(!AT)
16584 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type)
16585 << CurrentType);
16586 CurrentType = AT->getElementType();
16587 } else
16588 CurrentType = Context.DependentTy;
16589
16590 ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E));
16591 if (IdxRval.isInvalid())
16592 return ExprError();
16593 Expr *Idx = IdxRval.get();
16594
16595 // The expression must be an integral expression.
16596 // FIXME: An integral constant expression?
16597 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16598 !Idx->getType()->isIntegerType())
16599 return ExprError(
16600 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16601 << Idx->getSourceRange());
16602
16603 // Record this array index.
16604 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16605 Exprs.push_back(Elt: Idx);
16606 continue;
16607 }
16608
16609 // Offset of a field.
16610 if (CurrentType->isDependentType()) {
16611 // We have the offset of a field, but we can't look into the dependent
16612 // type. Just record the identifier of the field.
16613 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16614 CurrentType = Context.DependentTy;
16615 continue;
16616 }
16617
16618 // We need to have a complete type to look into.
16619 if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType,
16620 DiagID: diag::err_offsetof_incomplete_type))
16621 return ExprError();
16622
16623 // Look for the designated field.
16624 auto *RD = CurrentType->getAsRecordDecl();
16625 if (!RD)
16626 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type)
16627 << CurrentType);
16628
16629 // C++ [lib.support.types]p5:
16630 // The macro offsetof accepts a restricted set of type arguments in this
16631 // International Standard. type shall be a POD structure or a POD union
16632 // (clause 9).
16633 // C++11 [support.types]p4:
16634 // If type is not a standard-layout class (Clause 9), the results are
16635 // undefined.
16636 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16637 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16638 unsigned DiagID =
16639 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16640 : diag::ext_offsetof_non_pod_type;
16641
16642 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16643 Diag(Loc: BuiltinLoc, DiagID)
16644 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16645 DidWarnAboutNonPOD = true;
16646 }
16647 }
16648
16649 // Look for the field.
16650 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16651 LookupQualifiedName(R, LookupCtx: RD);
16652 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16653 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16654 if (!MemberDecl) {
16655 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16656 MemberDecl = IndirectMemberDecl->getAnonField();
16657 }
16658
16659 if (!MemberDecl) {
16660 // Lookup could be ambiguous when looking up a placeholder variable
16661 // __builtin_offsetof(S, _).
16662 // In that case we would already have emitted a diagnostic
16663 if (!R.isAmbiguous())
16664 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16665 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16666 return ExprError();
16667 }
16668
16669 // C99 7.17p3:
16670 // (If the specified member is a bit-field, the behavior is undefined.)
16671 //
16672 // We diagnose this as an error.
16673 if (MemberDecl->isBitField()) {
16674 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield)
16675 << MemberDecl->getDeclName()
16676 << SourceRange(BuiltinLoc, RParenLoc);
16677 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16678 return ExprError();
16679 }
16680
16681 RecordDecl *Parent = MemberDecl->getParent();
16682 if (IndirectMemberDecl)
16683 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16684
16685 // If the member was found in a base class, introduce OffsetOfNodes for
16686 // the base class indirections.
16687 CXXBasePaths Paths;
16688 if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType,
16689 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16690 if (Paths.getDetectedVirtual()) {
16691 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base)
16692 << MemberDecl->getDeclName()
16693 << SourceRange(BuiltinLoc, RParenLoc);
16694 return ExprError();
16695 }
16696
16697 CXXBasePath &Path = Paths.front();
16698 for (const CXXBasePathElement &B : Path)
16699 Comps.push_back(Elt: OffsetOfNode(B.Base));
16700 }
16701
16702 if (IndirectMemberDecl) {
16703 for (auto *FI : IndirectMemberDecl->chain()) {
16704 assert(isa<FieldDecl>(FI));
16705 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16706 cast<FieldDecl>(Val: FI), OC.LocEnd));
16707 }
16708 } else
16709 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16710
16711 CurrentType = MemberDecl->getType().getNonReferenceType();
16712 }
16713
16714 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16715 comps: Comps, exprs: Exprs, RParenLoc);
16716}
16717
16718ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16719 SourceLocation BuiltinLoc,
16720 SourceLocation TypeLoc,
16721 ParsedType ParsedArgTy,
16722 ArrayRef<OffsetOfComponent> Components,
16723 SourceLocation RParenLoc) {
16724
16725 TypeSourceInfo *ArgTInfo;
16726 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16727 if (ArgTy.isNull())
16728 return ExprError();
16729
16730 if (!ArgTInfo)
16731 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16732
16733 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16734}
16735
16736
16737ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16738 Expr *CondExpr,
16739 Expr *LHSExpr, Expr *RHSExpr,
16740 SourceLocation RPLoc) {
16741 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16742
16743 ExprValueKind VK = VK_PRValue;
16744 ExprObjectKind OK = OK_Ordinary;
16745 QualType resType;
16746 bool CondIsTrue = false;
16747 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16748 resType = Context.DependentTy;
16749 } else {
16750 // The conditional expression is required to be a constant expression.
16751 llvm::APSInt condEval(32);
16752 ExprResult CondICE = VerifyIntegerConstantExpression(
16753 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16754 if (CondICE.isInvalid())
16755 return ExprError();
16756 CondExpr = CondICE.get();
16757 CondIsTrue = condEval.getZExtValue();
16758
16759 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16760 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16761
16762 resType = ActiveExpr->getType();
16763 VK = ActiveExpr->getValueKind();
16764 OK = ActiveExpr->getObjectKind();
16765 }
16766
16767 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16768 resType, VK, OK, RPLoc, CondIsTrue);
16769}
16770
16771//===----------------------------------------------------------------------===//
16772// Clang Extensions.
16773//===----------------------------------------------------------------------===//
16774
16775void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16776 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16777
16778 if (LangOpts.CPlusPlus) {
16779 MangleNumberingContext *MCtx;
16780 Decl *ManglingContextDecl;
16781 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16782 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16783 if (MCtx) {
16784 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16785 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16786 }
16787 }
16788
16789 PushBlockScope(BlockScope: CurScope, Block);
16790 CurContext->addDecl(D: Block);
16791 if (CurScope)
16792 PushDeclContext(S: CurScope, DC: Block);
16793 else
16794 CurContext = Block;
16795
16796 getCurBlock()->HasImplicitReturnType = true;
16797
16798 // Enter a new evaluation context to insulate the block from any
16799 // cleanups from the enclosing full-expression.
16800 PushExpressionEvaluationContext(
16801 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16802}
16803
16804void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16805 Scope *CurScope) {
16806 assert(ParamInfo.getIdentifier() == nullptr &&
16807 "block-id should have no identifier!");
16808 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16809 BlockScopeInfo *CurBlock = getCurBlock();
16810
16811 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16812 QualType T = Sig->getType();
16813 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16814
16815 // GetTypeForDeclarator always produces a function type for a block
16816 // literal signature. Furthermore, it is always a FunctionProtoType
16817 // unless the function was written with a typedef.
16818 assert(T->isFunctionType() &&
16819 "GetTypeForDeclarator made a non-function block signature");
16820
16821 // Look for an explicit signature in that function type.
16822 FunctionProtoTypeLoc ExplicitSignature;
16823
16824 if ((ExplicitSignature = Sig->getTypeLoc()
16825 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16826
16827 // Check whether that explicit signature was synthesized by
16828 // GetTypeForDeclarator. If so, don't save that as part of the
16829 // written signature.
16830 if (ExplicitSignature.getLocalRangeBegin() ==
16831 ExplicitSignature.getLocalRangeEnd()) {
16832 // This would be much cheaper if we stored TypeLocs instead of
16833 // TypeSourceInfos.
16834 TypeLoc Result = ExplicitSignature.getReturnLoc();
16835 unsigned Size = Result.getFullDataSize();
16836 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16837 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16838
16839 ExplicitSignature = FunctionProtoTypeLoc();
16840 }
16841 }
16842
16843 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16844 CurBlock->FunctionType = T;
16845
16846 const auto *Fn = T->castAs<FunctionType>();
16847 QualType RetTy = Fn->getReturnType();
16848 bool isVariadic =
16849 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
16850
16851 CurBlock->TheDecl->setIsVariadic(isVariadic);
16852
16853 // Context.DependentTy is used as a placeholder for a missing block
16854 // return type. TODO: what should we do with declarators like:
16855 // ^ * { ... }
16856 // If the answer is "apply template argument deduction"....
16857 if (RetTy != Context.DependentTy) {
16858 CurBlock->ReturnType = RetTy;
16859 CurBlock->TheDecl->setBlockMissingReturnType(false);
16860 CurBlock->HasImplicitReturnType = false;
16861 }
16862
16863 // Push block parameters from the declarator if we had them.
16864 SmallVector<ParmVarDecl*, 8> Params;
16865 if (ExplicitSignature) {
16866 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16867 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
16868 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16869 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16870 // Diagnose this as an extension in C17 and earlier.
16871 if (!getLangOpts().C23)
16872 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
16873 }
16874 Params.push_back(Elt: Param);
16875 }
16876
16877 // Fake up parameter variables if we have a typedef, like
16878 // ^ fntype { ... }
16879 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16880 for (const auto &I : Fn->param_types()) {
16881 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16882 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
16883 Params.push_back(Elt: Param);
16884 }
16885 }
16886
16887 // Set the parameters on the block decl.
16888 if (!Params.empty()) {
16889 CurBlock->TheDecl->setParams(Params);
16890 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
16891 /*CheckParameterNames=*/false);
16892 }
16893
16894 // Finally we can process decl attributes.
16895 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
16896
16897 // Put the parameter variables in scope.
16898 for (auto *AI : CurBlock->TheDecl->parameters()) {
16899 AI->setOwningFunction(CurBlock->TheDecl);
16900
16901 // If this has an identifier, add it to the scope stack.
16902 if (AI->getIdentifier()) {
16903 CheckShadow(S: CurBlock->TheScope, D: AI);
16904
16905 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
16906 }
16907
16908 if (AI->isInvalidDecl())
16909 CurBlock->TheDecl->setInvalidDecl();
16910 }
16911}
16912
16913void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16914 // Leave the expression-evaluation context.
16915 DiscardCleanupsInEvaluationContext();
16916 PopExpressionEvaluationContext();
16917
16918 // Pop off CurBlock, handle nested blocks.
16919 PopDeclContext();
16920 PopFunctionScopeInfo();
16921}
16922
16923ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16924 Stmt *Body, Scope *CurScope) {
16925 // If blocks are disabled, emit an error.
16926 if (!LangOpts.Blocks)
16927 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
16928
16929 // Leave the expression-evaluation context.
16930 if (hasAnyUnrecoverableErrorsInThisFunction())
16931 DiscardCleanupsInEvaluationContext();
16932 assert(!Cleanup.exprNeedsCleanups() &&
16933 "cleanups within block not correctly bound!");
16934 PopExpressionEvaluationContext();
16935
16936 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
16937 BlockDecl *BD = BSI->TheDecl;
16938
16939 maybeAddDeclWithEffects(D: BD);
16940
16941 if (BSI->HasImplicitReturnType)
16942 deduceClosureReturnType(CSI&: *BSI);
16943
16944 QualType RetTy = Context.VoidTy;
16945 if (!BSI->ReturnType.isNull())
16946 RetTy = BSI->ReturnType;
16947
16948 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16949 QualType BlockTy;
16950
16951 // If the user wrote a function type in some form, try to use that.
16952 if (!BSI->FunctionType.isNull()) {
16953 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16954
16955 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16956 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
16957
16958 // Turn protoless block types into nullary block types.
16959 if (isa<FunctionNoProtoType>(Val: FTy)) {
16960 FunctionProtoType::ExtProtoInfo EPI;
16961 EPI.ExtInfo = Ext;
16962 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16963
16964 // Otherwise, if we don't need to change anything about the function type,
16965 // preserve its sugar structure.
16966 } else if (FTy->getReturnType() == RetTy &&
16967 (!NoReturn || FTy->getNoReturnAttr())) {
16968 BlockTy = BSI->FunctionType;
16969
16970 // Otherwise, make the minimal modifications to the function type.
16971 } else {
16972 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
16973 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16974 EPI.TypeQuals = Qualifiers();
16975 EPI.ExtInfo = Ext;
16976 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
16977 }
16978
16979 // If we don't have a function type, just build one from nothing.
16980 } else {
16981 FunctionProtoType::ExtProtoInfo EPI;
16982 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
16983 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16984 }
16985
16986 DiagnoseUnusedParameters(Parameters: BD->parameters());
16987 BlockTy = Context.getBlockPointerType(T: BlockTy);
16988
16989 // If needed, diagnose invalid gotos and switches in the block.
16990 if (getCurFunction()->NeedsScopeChecking() &&
16991 !PP.isCodeCompletionEnabled())
16992 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
16993
16994 BD->setBody(cast<CompoundStmt>(Val: Body));
16995
16996 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16997 DiagnoseUnguardedAvailabilityViolations(FD: BD);
16998
16999 // Try to apply the named return value optimization. We have to check again
17000 // if we can do this, though, because blocks keep return statements around
17001 // to deduce an implicit return type.
17002 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17003 !BD->isDependentContext())
17004 computeNRVO(Body, Scope: BSI);
17005
17006 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17007 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17008 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17009 UseContext: NonTrivialCUnionContext::FunctionReturn,
17010 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17011
17012 PopDeclContext();
17013
17014 // Set the captured variables on the block.
17015 SmallVector<BlockDecl::Capture, 4> Captures;
17016 for (Capture &Cap : BSI->Captures) {
17017 if (Cap.isInvalid() || Cap.isThisCapture())
17018 continue;
17019 // Cap.getVariable() is always a VarDecl because
17020 // blocks cannot capture structured bindings or other ValueDecl kinds.
17021 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17022 Expr *CopyExpr = nullptr;
17023 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17024 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17025 // The capture logic needs the destructor, so make sure we mark it.
17026 // Usually this is unnecessary because most local variables have
17027 // their destructors marked at declaration time, but parameters are
17028 // an exception because it's technically only the call site that
17029 // actually requires the destructor.
17030 if (isa<ParmVarDecl>(Val: Var))
17031 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17032
17033 // Enter a separate potentially-evaluated context while building block
17034 // initializers to isolate their cleanups from those of the block
17035 // itself.
17036 // FIXME: Is this appropriate even when the block itself occurs in an
17037 // unevaluated operand?
17038 EnterExpressionEvaluationContext EvalContext(
17039 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17040
17041 SourceLocation Loc = Cap.getLocation();
17042
17043 ExprResult Result = BuildDeclarationNameExpr(
17044 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17045
17046 // According to the blocks spec, the capture of a variable from
17047 // the stack requires a const copy constructor. This is not true
17048 // of the copy/move done to move a __block variable to the heap.
17049 if (!Result.isInvalid() &&
17050 !Result.get()->getType().isConstQualified()) {
17051 Result = ImpCastExprToType(E: Result.get(),
17052 Type: Result.get()->getType().withConst(),
17053 CK: CK_NoOp, VK: VK_LValue);
17054 }
17055
17056 if (!Result.isInvalid()) {
17057 Result = PerformCopyInitialization(
17058 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17059 Type: Cap.getCaptureType()),
17060 EqualLoc: Loc, Init: Result.get());
17061 }
17062
17063 // Build a full-expression copy expression if initialization
17064 // succeeded and used a non-trivial constructor. Recover from
17065 // errors by pretending that the copy isn't necessary.
17066 if (!Result.isInvalid() &&
17067 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17068 ->isTrivial()) {
17069 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17070 CopyExpr = Result.get();
17071 }
17072 }
17073 }
17074
17075 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17076 CopyExpr);
17077 Captures.push_back(Elt: NewCap);
17078 }
17079 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17080
17081 // Pop the block scope now but keep it alive to the end of this function.
17082 AnalysisBasedWarnings::Policy WP =
17083 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17084 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17085
17086 BlockExpr *Result = new (Context)
17087 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17088
17089 // If the block isn't obviously global, i.e. it captures anything at
17090 // all, then we need to do a few things in the surrounding context:
17091 if (Result->getBlockDecl()->hasCaptures()) {
17092 // First, this expression has a new cleanup object.
17093 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17094 Cleanup.setExprNeedsCleanups(true);
17095
17096 // It also gets a branch-protected scope if any of the captured
17097 // variables needs destruction.
17098 for (const auto &CI : Result->getBlockDecl()->captures()) {
17099 const VarDecl *var = CI.getVariable();
17100 if (var->getType().isDestructedType() != QualType::DK_none) {
17101 setFunctionHasBranchProtectedScope();
17102 break;
17103 }
17104 }
17105 }
17106
17107 if (getCurFunction())
17108 getCurFunction()->addBlock(BD);
17109
17110 // This can happen if the block's return type is deduced, but
17111 // the return expression is invalid.
17112 if (BD->isInvalidDecl())
17113 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17114 SubExprs: {Result}, T: Result->getType());
17115 return Result;
17116}
17117
17118ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17119 SourceLocation RPLoc) {
17120 TypeSourceInfo *TInfo;
17121 GetTypeFromParser(Ty, TInfo: &TInfo);
17122 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17123}
17124
17125ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17126 Expr *E, TypeSourceInfo *TInfo,
17127 SourceLocation RPLoc) {
17128 Expr *OrigExpr = E;
17129 bool IsMS = false;
17130
17131 // CUDA device global function does not support varargs.
17132 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17133 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17134 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17135 if (T == CUDAFunctionTarget::Global)
17136 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17137 }
17138 }
17139
17140 // NVPTX does not support va_arg expression.
17141 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17142 Context.getTargetInfo().getTriple().isNVPTX())
17143 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17144
17145 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17146 // as Microsoft ABI on an actual Microsoft platform, where
17147 // __builtin_ms_va_list and __builtin_va_list are the same.)
17148 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17149 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17150 QualType MSVaListType = Context.getBuiltinMSVaListType();
17151 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17152 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17153 return ExprError();
17154 IsMS = true;
17155 }
17156 }
17157
17158 // Get the va_list type
17159 QualType VaListType = Context.getBuiltinVaListType();
17160 if (!IsMS) {
17161 if (VaListType->isArrayType()) {
17162 // Deal with implicit array decay; for example, on x86-64,
17163 // va_list is an array, but it's supposed to decay to
17164 // a pointer for va_arg.
17165 VaListType = Context.getArrayDecayedType(T: VaListType);
17166 // Make sure the input expression also decays appropriately.
17167 ExprResult Result = UsualUnaryConversions(E);
17168 if (Result.isInvalid())
17169 return ExprError();
17170 E = Result.get();
17171 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17172 // If va_list is a record type and we are compiling in C++ mode,
17173 // check the argument using reference binding.
17174 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17175 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17176 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17177 if (Init.isInvalid())
17178 return ExprError();
17179 E = Init.getAs<Expr>();
17180 } else {
17181 // Otherwise, the va_list argument must be an l-value because
17182 // it is modified by va_arg.
17183 if (!E->isTypeDependent() &&
17184 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17185 return ExprError();
17186 }
17187 }
17188
17189 if (!IsMS && !E->isTypeDependent() &&
17190 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17191 return ExprError(
17192 Diag(Loc: E->getBeginLoc(),
17193 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17194 << OrigExpr->getType() << E->getSourceRange());
17195
17196 if (!TInfo->getType()->isDependentType()) {
17197 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17198 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17199 Args: TInfo->getTypeLoc()))
17200 return ExprError();
17201
17202 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17203 T: TInfo->getType(),
17204 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17205 Args: TInfo->getTypeLoc()))
17206 return ExprError();
17207
17208 if (!TInfo->getType().isPODType(Context)) {
17209 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17210 DiagID: TInfo->getType()->isObjCLifetimeType()
17211 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17212 : diag::warn_second_parameter_to_va_arg_not_pod)
17213 << TInfo->getType()
17214 << TInfo->getTypeLoc().getSourceRange();
17215 }
17216
17217 if (TInfo->getType()->isArrayType()) {
17218 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17219 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17220 << TInfo->getType()
17221 << TInfo->getTypeLoc().getSourceRange());
17222 }
17223
17224 // Check for va_arg where arguments of the given type will be promoted
17225 // (i.e. this va_arg is guaranteed to have undefined behavior).
17226 QualType PromoteType;
17227 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17228 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17229 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17230 // and C23 7.16.1.1p2 says, in part:
17231 // If type is not compatible with the type of the actual next argument
17232 // (as promoted according to the default argument promotions), the
17233 // behavior is undefined, except for the following cases:
17234 // - both types are pointers to qualified or unqualified versions of
17235 // compatible types;
17236 // - one type is compatible with a signed integer type, the other
17237 // type is compatible with the corresponding unsigned integer type,
17238 // and the value is representable in both types;
17239 // - one type is pointer to qualified or unqualified void and the
17240 // other is a pointer to a qualified or unqualified character type;
17241 // - or, the type of the next argument is nullptr_t and type is a
17242 // pointer type that has the same representation and alignment
17243 // requirements as a pointer to a character type.
17244 // Given that type compatibility is the primary requirement (ignoring
17245 // qualifications), you would think we could call typesAreCompatible()
17246 // directly to test this. However, in C++, that checks for *same type*,
17247 // which causes false positives when passing an enumeration type to
17248 // va_arg. Instead, get the underlying type of the enumeration and pass
17249 // that.
17250 QualType UnderlyingType = TInfo->getType();
17251 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17252 UnderlyingType = ED->getIntegerType();
17253 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17254 /*CompareUnqualified*/ true))
17255 PromoteType = QualType();
17256
17257 // If the types are still not compatible, we need to test whether the
17258 // promoted type and the underlying type are the same except for
17259 // signedness. Ask the AST for the correctly corresponding type and see
17260 // if that's compatible.
17261 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17262 PromoteType->isUnsignedIntegerType() !=
17263 UnderlyingType->isUnsignedIntegerType()) {
17264 UnderlyingType =
17265 UnderlyingType->isUnsignedIntegerType()
17266 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17267 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17268 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17269 /*CompareUnqualified*/ true))
17270 PromoteType = QualType();
17271 }
17272 }
17273 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17274 PromoteType = Context.DoubleTy;
17275 if (!PromoteType.isNull())
17276 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17277 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17278 << TInfo->getType()
17279 << PromoteType
17280 << TInfo->getTypeLoc().getSourceRange());
17281 }
17282
17283 QualType T = TInfo->getType().getNonLValueExprType(Context);
17284 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17285}
17286
17287ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17288 // The type of __null will be int or long, depending on the size of
17289 // pointers on the target.
17290 QualType Ty;
17291 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17292 if (pw == Context.getTargetInfo().getIntWidth())
17293 Ty = Context.IntTy;
17294 else if (pw == Context.getTargetInfo().getLongWidth())
17295 Ty = Context.LongTy;
17296 else if (pw == Context.getTargetInfo().getLongLongWidth())
17297 Ty = Context.LongLongTy;
17298 else {
17299 llvm_unreachable("I don't know size of pointer!");
17300 }
17301
17302 return new (Context) GNUNullExpr(Ty, TokenLoc);
17303}
17304
17305static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17306 CXXRecordDecl *ImplDecl = nullptr;
17307
17308 // Fetch the std::source_location::__impl decl.
17309 if (NamespaceDecl *Std = S.getStdNamespace()) {
17310 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17311 Loc, Sema::LookupOrdinaryName);
17312 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17313 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17314 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17315 Loc, Sema::LookupOrdinaryName);
17316 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17317 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17318 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17319 }
17320 }
17321 }
17322 }
17323
17324 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17325 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17326 return nullptr;
17327 }
17328
17329 // Verify that __impl is a trivial struct type, with no base classes, and with
17330 // only the four expected fields.
17331 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17332 ImplDecl->getNumBases() != 0) {
17333 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17334 return nullptr;
17335 }
17336
17337 unsigned Count = 0;
17338 for (FieldDecl *F : ImplDecl->fields()) {
17339 StringRef Name = F->getName();
17340
17341 if (Name == "_M_file_name") {
17342 if (F->getType() !=
17343 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17344 break;
17345 Count++;
17346 } else if (Name == "_M_function_name") {
17347 if (F->getType() !=
17348 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17349 break;
17350 Count++;
17351 } else if (Name == "_M_line") {
17352 if (!F->getType()->isIntegerType())
17353 break;
17354 Count++;
17355 } else if (Name == "_M_column") {
17356 if (!F->getType()->isIntegerType())
17357 break;
17358 Count++;
17359 } else {
17360 Count = 100; // invalid
17361 break;
17362 }
17363 }
17364 if (Count != 4) {
17365 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17366 return nullptr;
17367 }
17368
17369 return ImplDecl;
17370}
17371
17372ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17373 SourceLocation BuiltinLoc,
17374 SourceLocation RPLoc) {
17375 QualType ResultTy;
17376 switch (Kind) {
17377 case SourceLocIdentKind::File:
17378 case SourceLocIdentKind::FileName:
17379 case SourceLocIdentKind::Function:
17380 case SourceLocIdentKind::FuncSig: {
17381 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17382 ResultTy =
17383 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17384 break;
17385 }
17386 case SourceLocIdentKind::Line:
17387 case SourceLocIdentKind::Column:
17388 ResultTy = Context.UnsignedIntTy;
17389 break;
17390 case SourceLocIdentKind::SourceLocStruct:
17391 if (!StdSourceLocationImplDecl) {
17392 StdSourceLocationImplDecl =
17393 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17394 if (!StdSourceLocationImplDecl)
17395 return ExprError();
17396 }
17397 ResultTy = Context.getPointerType(
17398 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17399 break;
17400 }
17401
17402 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17403}
17404
17405ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17406 SourceLocation BuiltinLoc,
17407 SourceLocation RPLoc,
17408 DeclContext *ParentContext) {
17409 return new (Context)
17410 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17411}
17412
17413ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17414 StringLiteral *BinaryData, StringRef FileName) {
17415 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17416 Data->BinaryData = BinaryData;
17417 Data->FileName = FileName;
17418 return new (Context)
17419 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17420 Data->getDataElementCount());
17421}
17422
17423static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17424 const Expr *SrcExpr) {
17425 if (!DstType->isFunctionPointerType() ||
17426 !SrcExpr->getType()->isFunctionType())
17427 return false;
17428
17429 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17430 if (!DRE)
17431 return false;
17432
17433 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17434 if (!FD)
17435 return false;
17436
17437 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17438 /*Complain=*/true,
17439 Loc: SrcExpr->getBeginLoc());
17440}
17441
17442bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17443 SourceLocation Loc,
17444 QualType DstType, QualType SrcType,
17445 Expr *SrcExpr, AssignmentAction Action,
17446 bool *Complained) {
17447 if (Complained)
17448 *Complained = false;
17449
17450 // Decode the result (notice that AST's are still created for extensions).
17451 bool CheckInferredResultType = false;
17452 bool isInvalid = false;
17453 unsigned DiagKind = 0;
17454 ConversionFixItGenerator ConvHints;
17455 bool MayHaveConvFixit = false;
17456 bool MayHaveFunctionDiff = false;
17457 const ObjCInterfaceDecl *IFace = nullptr;
17458 const ObjCProtocolDecl *PDecl = nullptr;
17459
17460 switch (ConvTy) {
17461 case AssignConvertType::Compatible:
17462 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17463 return false;
17464 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17465 // Still a valid conversion, but we may want to diagnose for C++
17466 // compatibility reasons.
17467 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17468 break;
17469 case AssignConvertType::PointerToInt:
17470 if (getLangOpts().CPlusPlus) {
17471 DiagKind = diag::err_typecheck_convert_pointer_int;
17472 isInvalid = true;
17473 } else {
17474 DiagKind = diag::ext_typecheck_convert_pointer_int;
17475 }
17476 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17477 MayHaveConvFixit = true;
17478 break;
17479 case AssignConvertType::IntToPointer:
17480 if (getLangOpts().CPlusPlus) {
17481 DiagKind = diag::err_typecheck_convert_int_pointer;
17482 isInvalid = true;
17483 } else {
17484 DiagKind = diag::ext_typecheck_convert_int_pointer;
17485 }
17486 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17487 MayHaveConvFixit = true;
17488 break;
17489 case AssignConvertType::IncompatibleFunctionPointerStrict:
17490 DiagKind =
17491 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17492 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17493 MayHaveConvFixit = true;
17494 break;
17495 case AssignConvertType::IncompatibleFunctionPointer:
17496 if (getLangOpts().CPlusPlus) {
17497 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17498 isInvalid = true;
17499 } else {
17500 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17501 }
17502 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17503 MayHaveConvFixit = true;
17504 break;
17505 case AssignConvertType::IncompatiblePointer:
17506 if (Action == AssignmentAction::Passing_CFAudited) {
17507 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17508 } else if (getLangOpts().CPlusPlus) {
17509 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17510 isInvalid = true;
17511 } else {
17512 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17513 }
17514 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17515 SrcType->isObjCObjectPointerType();
17516 if (CheckInferredResultType) {
17517 SrcType = SrcType.getUnqualifiedType();
17518 DstType = DstType.getUnqualifiedType();
17519 } else {
17520 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17521 }
17522 MayHaveConvFixit = true;
17523 break;
17524 case AssignConvertType::IncompatiblePointerSign:
17525 if (getLangOpts().CPlusPlus) {
17526 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17527 isInvalid = true;
17528 } else {
17529 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17530 }
17531 break;
17532 case AssignConvertType::FunctionVoidPointer:
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17538 }
17539 break;
17540 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17541 // Perform array-to-pointer decay if necessary.
17542 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType);
17543
17544 isInvalid = true;
17545
17546 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17547 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17548 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17549 DiagKind = diag::err_typecheck_incompatible_address_space;
17550 break;
17551 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17552 DiagKind = diag::err_typecheck_incompatible_ownership;
17553 break;
17554 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17555 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17556 break;
17557 }
17558
17559 llvm_unreachable("unknown error case for discarding qualifiers!");
17560 // fallthrough
17561 }
17562 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17563 if (SrcType->isArrayType())
17564 SrcType = Context.getArrayDecayedType(T: SrcType);
17565
17566 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17567 break;
17568 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17569 // If the qualifiers lost were because we were applying the
17570 // (deprecated) C++ conversion from a string literal to a char*
17571 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17572 // Ideally, this check would be performed in
17573 // checkPointerTypesForAssignment. However, that would require a
17574 // bit of refactoring (so that the second argument is an
17575 // expression, rather than a type), which should be done as part
17576 // of a larger effort to fix checkPointerTypesForAssignment for
17577 // C++ semantics.
17578 if (getLangOpts().CPlusPlus &&
17579 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17580 return false;
17581 if (getLangOpts().CPlusPlus) {
17582 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17583 isInvalid = true;
17584 } else {
17585 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17586 }
17587
17588 break;
17589 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17590 if (getLangOpts().CPlusPlus) {
17591 isInvalid = true;
17592 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17593 } else {
17594 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17595 }
17596 break;
17597 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17598 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17599 isInvalid = true;
17600 break;
17601 case AssignConvertType::IntToBlockPointer:
17602 DiagKind = diag::err_int_to_block_pointer;
17603 isInvalid = true;
17604 break;
17605 case AssignConvertType::IncompatibleBlockPointer:
17606 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17607 isInvalid = true;
17608 break;
17609 case AssignConvertType::IncompatibleObjCQualifiedId: {
17610 if (SrcType->isObjCQualifiedIdType()) {
17611 const ObjCObjectPointerType *srcOPT =
17612 SrcType->castAs<ObjCObjectPointerType>();
17613 for (auto *srcProto : srcOPT->quals()) {
17614 PDecl = srcProto;
17615 break;
17616 }
17617 if (const ObjCInterfaceType *IFaceT =
17618 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17619 IFace = IFaceT->getDecl();
17620 }
17621 else if (DstType->isObjCQualifiedIdType()) {
17622 const ObjCObjectPointerType *dstOPT =
17623 DstType->castAs<ObjCObjectPointerType>();
17624 for (auto *dstProto : dstOPT->quals()) {
17625 PDecl = dstProto;
17626 break;
17627 }
17628 if (const ObjCInterfaceType *IFaceT =
17629 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17630 IFace = IFaceT->getDecl();
17631 }
17632 if (getLangOpts().CPlusPlus) {
17633 DiagKind = diag::err_incompatible_qualified_id;
17634 isInvalid = true;
17635 } else {
17636 DiagKind = diag::warn_incompatible_qualified_id;
17637 }
17638 break;
17639 }
17640 case AssignConvertType::IncompatibleVectors:
17641 if (getLangOpts().CPlusPlus) {
17642 DiagKind = diag::err_incompatible_vectors;
17643 isInvalid = true;
17644 } else {
17645 DiagKind = diag::warn_incompatible_vectors;
17646 }
17647 break;
17648 case AssignConvertType::IncompatibleObjCWeakRef:
17649 DiagKind = diag::err_arc_weak_unavailable_assign;
17650 isInvalid = true;
17651 break;
17652 case AssignConvertType::CompatibleOBTDiscards:
17653 return false;
17654 case AssignConvertType::IncompatibleOBTKinds: {
17655 auto getOBTKindName = [](QualType Ty) -> StringRef {
17656 if (Ty->isPointerType())
17657 Ty = Ty->getPointeeType();
17658 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17659 return OBT->getBehaviorKind() ==
17660 OverflowBehaviorType::OverflowBehaviorKind::Trap
17661 ? "__ob_trap"
17662 : "__ob_wrap";
17663 }
17664 llvm_unreachable("OBT kind unhandled");
17665 };
17666
17667 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17668 << DstType << SrcType << getOBTKindName(DstType)
17669 << getOBTKindName(SrcType);
17670 isInvalid = true;
17671 return true;
17672 }
17673 case AssignConvertType::Incompatible:
17674 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17675 if (Complained)
17676 *Complained = true;
17677 return true;
17678 }
17679
17680 DiagKind = diag::err_typecheck_convert_incompatible;
17681 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17682 MayHaveConvFixit = true;
17683 isInvalid = true;
17684 MayHaveFunctionDiff = true;
17685 break;
17686 }
17687
17688 QualType FirstType, SecondType;
17689 switch (Action) {
17690 case AssignmentAction::Assigning:
17691 case AssignmentAction::Initializing:
17692 // The destination type comes first.
17693 FirstType = DstType;
17694 SecondType = SrcType;
17695 break;
17696
17697 case AssignmentAction::Returning:
17698 case AssignmentAction::Passing:
17699 case AssignmentAction::Passing_CFAudited:
17700 case AssignmentAction::Converting:
17701 case AssignmentAction::Sending:
17702 case AssignmentAction::Casting:
17703 // The source type comes first.
17704 FirstType = SrcType;
17705 SecondType = DstType;
17706 break;
17707 }
17708
17709 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17710 AssignmentAction ActionForDiag = Action;
17711 if (Action == AssignmentAction::Passing_CFAudited)
17712 ActionForDiag = AssignmentAction::Passing;
17713
17714 FDiag << FirstType << SecondType << ActionForDiag
17715 << SrcExpr->getSourceRange();
17716
17717 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17718 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17719 auto isPlainChar = [](const clang::Type *Type) {
17720 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17721 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17722 };
17723 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17724 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17725 }
17726
17727 // If we can fix the conversion, suggest the FixIts.
17728 if (!ConvHints.isNull()) {
17729 for (FixItHint &H : ConvHints.Hints)
17730 FDiag << H;
17731 }
17732
17733 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17734
17735 if (MayHaveFunctionDiff)
17736 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17737
17738 Diag(Loc, PD: FDiag);
17739 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17740 DiagKind == diag::err_incompatible_qualified_id) &&
17741 PDecl && IFace && !IFace->hasDefinition())
17742 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17743 << IFace << PDecl;
17744
17745 if (SecondType == Context.OverloadTy)
17746 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17747 DestType: FirstType, /*TakingAddress=*/true);
17748
17749 if (CheckInferredResultType)
17750 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17751
17752 if (Action == AssignmentAction::Returning &&
17753 ConvTy == AssignConvertType::IncompatiblePointer)
17754 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17755
17756 if (Complained)
17757 *Complained = true;
17758 return isInvalid;
17759}
17760
17761ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17762 llvm::APSInt *Result,
17763 AllowFoldKind CanFold) {
17764 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17765 public:
17766 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17767 QualType T) override {
17768 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17769 << T << S.LangOpts.CPlusPlus;
17770 }
17771 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17772 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17773 }
17774 } Diagnoser;
17775
17776 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17777}
17778
17779ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17780 llvm::APSInt *Result,
17781 unsigned DiagID,
17782 AllowFoldKind CanFold) {
17783 class IDDiagnoser : public VerifyICEDiagnoser {
17784 unsigned DiagID;
17785
17786 public:
17787 IDDiagnoser(unsigned DiagID)
17788 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17789
17790 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17791 return S.Diag(Loc, DiagID);
17792 }
17793 } Diagnoser(DiagID);
17794
17795 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17796}
17797
17798Sema::SemaDiagnosticBuilder
17799Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17800 QualType T) {
17801 return diagnoseNotICE(S, Loc);
17802}
17803
17804Sema::SemaDiagnosticBuilder
17805Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17806 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17807}
17808
17809ExprResult
17810Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17811 VerifyICEDiagnoser &Diagnoser,
17812 AllowFoldKind CanFold) {
17813 SourceLocation DiagLoc = E->getBeginLoc();
17814
17815 if (getLangOpts().CPlusPlus11) {
17816 // C++11 [expr.const]p5:
17817 // If an expression of literal class type is used in a context where an
17818 // integral constant expression is required, then that class type shall
17819 // have a single non-explicit conversion function to an integral or
17820 // unscoped enumeration type
17821 ExprResult Converted;
17822 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17823 VerifyICEDiagnoser &BaseDiagnoser;
17824 public:
17825 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17826 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17827 BaseDiagnoser.Suppress, true),
17828 BaseDiagnoser(BaseDiagnoser) {}
17829
17830 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17831 QualType T) override {
17832 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17833 }
17834
17835 SemaDiagnosticBuilder diagnoseIncomplete(
17836 Sema &S, SourceLocation Loc, QualType T) override {
17837 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
17838 }
17839
17840 SemaDiagnosticBuilder diagnoseExplicitConv(
17841 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17842 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
17843 }
17844
17845 SemaDiagnosticBuilder noteExplicitConv(
17846 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17847 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17848 << ConvTy->isEnumeralType() << ConvTy;
17849 }
17850
17851 SemaDiagnosticBuilder diagnoseAmbiguous(
17852 Sema &S, SourceLocation Loc, QualType T) override {
17853 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
17854 }
17855
17856 SemaDiagnosticBuilder noteAmbiguous(
17857 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17858 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17859 << ConvTy->isEnumeralType() << ConvTy;
17860 }
17861
17862 SemaDiagnosticBuilder diagnoseConversion(
17863 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17864 llvm_unreachable("conversion functions are permitted");
17865 }
17866 } ConvertDiagnoser(Diagnoser);
17867
17868 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
17869 Converter&: ConvertDiagnoser);
17870 if (Converted.isInvalid())
17871 return Converted;
17872 E = Converted.get();
17873 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17874 // don't try to evaluate it later. We also don't want to return the
17875 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17876 // this function will attempt to use 'Value'.
17877 if (isa<RecoveryExpr>(Val: E))
17878 return ExprError();
17879 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17880 return ExprError();
17881 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17882 // An ICE must be of integral or unscoped enumeration type.
17883 if (!Diagnoser.Suppress)
17884 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
17885 << E->getSourceRange();
17886 return ExprError();
17887 }
17888
17889 ExprResult RValueExpr = DefaultLvalueConversion(E);
17890 if (RValueExpr.isInvalid())
17891 return ExprError();
17892
17893 E = RValueExpr.get();
17894
17895 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17896 // in the non-ICE case.
17897 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
17898 SmallVector<PartialDiagnosticAt, 8> Notes;
17899 if (Result)
17900 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
17901 if (!isa<ConstantExpr>(Val: E))
17902 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
17903 : ConstantExpr::Create(Context, E);
17904
17905 if (Notes.empty())
17906 return E;
17907
17908 // If our only note is the usual "invalid subexpression" note, just point
17909 // the caret at its location rather than producing an essentially
17910 // redundant note.
17911 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17912 diag::note_invalid_subexpr_in_const_expr) {
17913 DiagLoc = Notes[0].first;
17914 Notes.clear();
17915 }
17916
17917 if (getLangOpts().CPlusPlus) {
17918 if (!Diagnoser.Suppress) {
17919 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17920 for (const PartialDiagnosticAt &Note : Notes)
17921 Diag(Loc: Note.first, PD: Note.second);
17922 }
17923 return ExprError();
17924 }
17925
17926 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17927 for (const PartialDiagnosticAt &Note : Notes)
17928 Diag(Loc: Note.first, PD: Note.second);
17929
17930 return E;
17931 }
17932
17933 Expr::EvalResult EvalResult;
17934 SmallVector<PartialDiagnosticAt, 8> Notes;
17935 EvalResult.Diag = &Notes;
17936
17937 // Try to evaluate the expression, and produce diagnostics explaining why it's
17938 // not a constant expression as a side-effect.
17939 bool Folded =
17940 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
17941 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17942 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17943
17944 if (!isa<ConstantExpr>(Val: E))
17945 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
17946
17947 // In C++11, we can rely on diagnostics being produced for any expression
17948 // which is not a constant expression. If no diagnostics were produced, then
17949 // this is a constant expression.
17950 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17951 if (Result)
17952 *Result = EvalResult.Val.getInt();
17953 return E;
17954 }
17955
17956 // If our only note is the usual "invalid subexpression" note, just point
17957 // the caret at its location rather than producing an essentially
17958 // redundant note.
17959 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17960 diag::note_invalid_subexpr_in_const_expr) {
17961 DiagLoc = Notes[0].first;
17962 Notes.clear();
17963 }
17964
17965 if (!Folded || CanFold == AllowFoldKind::No) {
17966 if (!Diagnoser.Suppress) {
17967 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17968 for (const PartialDiagnosticAt &Note : Notes)
17969 Diag(Loc: Note.first, PD: Note.second);
17970 }
17971
17972 return ExprError();
17973 }
17974
17975 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17976 for (const PartialDiagnosticAt &Note : Notes)
17977 Diag(Loc: Note.first, PD: Note.second);
17978
17979 if (Result)
17980 *Result = EvalResult.Val.getInt();
17981 return E;
17982}
17983
17984namespace {
17985 // Handle the case where we conclude a expression which we speculatively
17986 // considered to be unevaluated is actually evaluated.
17987 class TransformToPE : public TreeTransform<TransformToPE> {
17988 typedef TreeTransform<TransformToPE> BaseTransform;
17989
17990 public:
17991 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17992
17993 // Make sure we redo semantic analysis
17994 bool AlwaysRebuild() { return true; }
17995 bool ReplacingOriginal() { return true; }
17996
17997 // We need to special-case DeclRefExprs referring to FieldDecls which
17998 // are not part of a member pointer formation; normal TreeTransforming
17999 // doesn't catch this case because of the way we represent them in the AST.
18000 // FIXME: This is a bit ugly; is it really the best way to handle this
18001 // case?
18002 //
18003 // Error on DeclRefExprs referring to FieldDecls.
18004 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18005 if (isa<FieldDecl>(Val: E->getDecl()) &&
18006 !SemaRef.isUnevaluatedContext())
18007 return SemaRef.Diag(Loc: E->getLocation(),
18008 DiagID: diag::err_invalid_non_static_member_use)
18009 << E->getDecl() << E->getSourceRange();
18010
18011 return BaseTransform::TransformDeclRefExpr(E);
18012 }
18013
18014 // Exception: filter out member pointer formation
18015 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18016 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18017 return E;
18018
18019 return BaseTransform::TransformUnaryOperator(E);
18020 }
18021
18022 // The body of a lambda-expression is in a separate expression evaluation
18023 // context so never needs to be transformed.
18024 // FIXME: Ideally we wouldn't transform the closure type either, and would
18025 // just recreate the capture expressions and lambda expression.
18026 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18027 return SkipLambdaBody(E, S: Body);
18028 }
18029 };
18030}
18031
18032ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18033 assert(isUnevaluatedContext() &&
18034 "Should only transform unevaluated expressions");
18035 ExprEvalContexts.back().Context =
18036 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18037 if (isUnevaluatedContext())
18038 return E;
18039 return TransformToPE(*this).TransformExpr(E);
18040}
18041
18042TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18043 assert(isUnevaluatedContext() &&
18044 "Should only transform unevaluated expressions");
18045 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18046 if (isUnevaluatedContext())
18047 return TInfo;
18048 return TransformToPE(*this).TransformType(TSI: TInfo);
18049}
18050
18051void
18052Sema::PushExpressionEvaluationContext(
18053 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18054 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18055 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18056 Args&: LambdaContextDecl, Args&: ExprContext);
18057
18058 // Discarded statements and immediate contexts nested in other
18059 // discarded statements or immediate context are themselves
18060 // a discarded statement or an immediate context, respectively.
18061 ExprEvalContexts.back().InDiscardedStatement =
18062 parentEvaluationContext().isDiscardedStatementContext();
18063
18064 // C++23 [expr.const]/p15
18065 // An expression or conversion is in an immediate function context if [...]
18066 // it is a subexpression of a manifestly constant-evaluated expression or
18067 // conversion.
18068 const auto &Prev = parentEvaluationContext();
18069 ExprEvalContexts.back().InImmediateFunctionContext =
18070 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18071
18072 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18073 Prev.InImmediateEscalatingFunctionContext;
18074
18075 Cleanup.reset();
18076 if (!MaybeODRUseExprs.empty())
18077 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18078}
18079
18080void
18081Sema::PushExpressionEvaluationContext(
18082 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18083 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18084 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18085 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18086}
18087
18088void Sema::PushExpressionEvaluationContextForFunction(
18089 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18090 // [expr.const]/p14.1
18091 // An expression or conversion is in an immediate function context if it is
18092 // potentially evaluated and either: its innermost enclosing non-block scope
18093 // is a function parameter scope of an immediate function.
18094 PushExpressionEvaluationContext(
18095 NewContext: FD && FD->isConsteval()
18096 ? ExpressionEvaluationContext::ImmediateFunctionContext
18097 : NewContext);
18098 const Sema::ExpressionEvaluationContextRecord &Parent =
18099 parentEvaluationContext();
18100 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18101
18102 Current.InDiscardedStatement = false;
18103
18104 if (FD) {
18105
18106 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18107 // context is nested in an immediate function context, so smaller contexts
18108 // that appear inside immediate functions (like variable initializers) are
18109 // considered to be inside an immediate function context even though by
18110 // themselves they are not immediate function contexts. But when a new
18111 // function is entered, we need to reset this tracking, since the entered
18112 // function might be not an immediate function.
18113
18114 Current.InImmediateEscalatingFunctionContext =
18115 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18116
18117 if (isLambdaMethod(DC: FD))
18118 Current.InImmediateFunctionContext =
18119 FD->isConsteval() ||
18120 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18121 Parent.isImmediateFunctionContext()));
18122 else
18123 Current.InImmediateFunctionContext = FD->isConsteval();
18124 }
18125}
18126
18127ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18128 TypeSourceInfo *TSI) {
18129 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18130}
18131
18132ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18133 TypeSourceInfo *TSI) {
18134 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18135}
18136
18137namespace {
18138
18139const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18140 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18141 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18142 if (E->getOpcode() == UO_Deref)
18143 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18144 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18145 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18146 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18147 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18148 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18149 QualType Inner;
18150 QualType Ty = E->getType();
18151 if (const auto *Ptr = Ty->getAs<PointerType>())
18152 Inner = Ptr->getPointeeType();
18153 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18154 Inner = Arr->getElementType();
18155 else
18156 return nullptr;
18157
18158 if (Inner->hasAttr(AK: attr::NoDeref))
18159 return E;
18160 }
18161 return nullptr;
18162}
18163
18164} // namespace
18165
18166void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18167 for (const Expr *E : Rec.PossibleDerefs) {
18168 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18169 if (DeclRef) {
18170 const ValueDecl *Decl = DeclRef->getDecl();
18171 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18172 << Decl->getName() << E->getSourceRange();
18173 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18174 } else {
18175 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18176 << E->getSourceRange();
18177 }
18178 }
18179 Rec.PossibleDerefs.clear();
18180}
18181
18182void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18183 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18184 return;
18185
18186 // Note: ignoring parens here is not justified by the standard rules, but
18187 // ignoring parentheses seems like a more reasonable approach, and this only
18188 // drives a deprecation warning so doesn't affect conformance.
18189 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18190 if (BO->getOpcode() == BO_Assign) {
18191 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18192 llvm::erase(C&: LHSs, V: BO->getLHS());
18193 }
18194 }
18195}
18196
18197void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18198 assert(getLangOpts().CPlusPlus20 &&
18199 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18200 "Cannot mark an immediate escalating expression outside of an "
18201 "immediate escalating context");
18202 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18203 Call && Call->getCallee()) {
18204 if (auto *DeclRef =
18205 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18206 DeclRef->setIsImmediateEscalating(true);
18207 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18208 Ctr->setIsImmediateEscalating(true);
18209 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18210 DeclRef->setIsImmediateEscalating(true);
18211 } else {
18212 assert(false && "expected an immediately escalating expression");
18213 }
18214 if (FunctionScopeInfo *FI = getCurFunction())
18215 FI->FoundImmediateEscalatingExpression = true;
18216}
18217
18218ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18219 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18220 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18221 isCheckingDefaultArgumentOrInitializer() ||
18222 RebuildingImmediateInvocation || isImmediateFunctionContext())
18223 return E;
18224
18225 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18226 /// It's OK if this fails; we'll also remove this in
18227 /// HandleImmediateInvocations, but catching it here allows us to avoid
18228 /// walking the AST looking for it in simple cases.
18229 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18230 if (auto *DeclRef =
18231 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18232 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18233
18234 // C++23 [expr.const]/p16
18235 // An expression or conversion is immediate-escalating if it is not initially
18236 // in an immediate function context and it is [...] an immediate invocation
18237 // that is not a constant expression and is not a subexpression of an
18238 // immediate invocation.
18239 APValue Cached;
18240 auto CheckConstantExpressionAndKeepResult = [&]() {
18241 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18242 Expr::EvalResult Eval;
18243 Eval.Diag = &Notes;
18244 bool Res = E.get()->EvaluateAsConstantExpr(
18245 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18246 if (Res && Notes.empty()) {
18247 Cached = std::move(Eval.Val);
18248 return true;
18249 }
18250 return false;
18251 };
18252
18253 if (!E.get()->isValueDependent() &&
18254 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18255 !CheckConstantExpressionAndKeepResult()) {
18256 MarkExpressionAsImmediateEscalating(E: E.get());
18257 return E;
18258 }
18259
18260 if (Cleanup.exprNeedsCleanups()) {
18261 // Since an immediate invocation is a full expression itself - it requires
18262 // an additional ExprWithCleanups node, but it can participate to a bigger
18263 // full expression which actually requires cleanups to be run after so
18264 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18265 // may discard cleanups for outer expression too early.
18266
18267 // Note that ExprWithCleanups created here must always have empty cleanup
18268 // objects:
18269 // - compound literals do not create cleanup objects in C++ and immediate
18270 // invocations are C++-only.
18271 // - blocks are not allowed inside constant expressions and compiler will
18272 // issue an error if they appear there.
18273 //
18274 // Hence, in correct code any cleanup objects created inside current
18275 // evaluation context must be outside the immediate invocation.
18276 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18277 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18278 }
18279
18280 ConstantExpr *Res = ConstantExpr::Create(
18281 Context: getASTContext(), E: E.get(),
18282 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18283 Context: getASTContext()),
18284 /*IsImmediateInvocation*/ true);
18285 if (Cached.hasValue())
18286 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18287 /// Value-dependent constant expressions should not be immediately
18288 /// evaluated until they are instantiated.
18289 if (!Res->isValueDependent())
18290 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18291 return Res;
18292}
18293
18294static void EvaluateAndDiagnoseImmediateInvocation(
18295 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18296 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18297 Expr::EvalResult Eval;
18298 Eval.Diag = &Notes;
18299 ConstantExpr *CE = Candidate.getPointer();
18300 bool Result = CE->EvaluateAsConstantExpr(
18301 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18302 if (!Result || !Notes.empty()) {
18303 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18304 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18305 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18306 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18307 FunctionDecl *FD = nullptr;
18308 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18309 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18310 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18311 FD = Call->getConstructor();
18312 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18313 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18314
18315 assert(FD && FD->isImmediateFunction() &&
18316 "could not find an immediate function in this expression");
18317 if (FD->isInvalidDecl())
18318 return;
18319 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18320 << FD << FD->isConsteval();
18321 if (auto Context =
18322 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18323 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18324 << Context->Decl;
18325 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18326 }
18327 if (!FD->isConsteval())
18328 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18329 for (auto &Note : Notes)
18330 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18331 return;
18332 }
18333 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18334}
18335
18336static void RemoveNestedImmediateInvocation(
18337 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18338 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18339 struct ComplexRemove : TreeTransform<ComplexRemove> {
18340 using Base = TreeTransform<ComplexRemove>;
18341 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18342 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18343 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18344 CurrentII;
18345 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18346 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18347 SmallVector<Sema::ImmediateInvocationCandidate,
18348 4>::reverse_iterator Current)
18349 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18350 void RemoveImmediateInvocation(ConstantExpr* E) {
18351 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18352 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18353 return Elem.getPointer() == E;
18354 });
18355 // It is possible that some subexpression of the current immediate
18356 // invocation was handled from another expression evaluation context. Do
18357 // not handle the current immediate invocation if some of its
18358 // subexpressions failed before.
18359 if (It == IISet.rend()) {
18360 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18361 CurrentII->setInt(1);
18362 } else {
18363 It->setInt(1); // Mark as deleted
18364 }
18365 }
18366 ExprResult TransformConstantExpr(ConstantExpr *E) {
18367 if (!E->isImmediateInvocation())
18368 return Base::TransformConstantExpr(E);
18369 RemoveImmediateInvocation(E);
18370 return Base::TransformExpr(E: E->getSubExpr());
18371 }
18372 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18373 /// we need to remove its DeclRefExpr from the DRSet.
18374 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18375 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18376 return Base::TransformCXXOperatorCallExpr(E);
18377 }
18378 /// Base::TransformUserDefinedLiteral doesn't preserve the
18379 /// UserDefinedLiteral node.
18380 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18381 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18382 /// here.
18383 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18384 if (!Init)
18385 return Init;
18386
18387 // We cannot use IgnoreImpCasts because we need to preserve
18388 // full expressions.
18389 while (true) {
18390 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18391 Init = ICE->getSubExpr();
18392 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18393 Init = ICE->getSubExpr();
18394 else
18395 break;
18396 }
18397 /// ConstantExprs are the first layer of implicit node to be removed so if
18398 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18399 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18400 CE && CE->isImmediateInvocation())
18401 RemoveImmediateInvocation(E: CE);
18402 return Base::TransformInitializer(Init, NotCopyInit);
18403 }
18404 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18405 DRSet.erase(Ptr: E);
18406 return E;
18407 }
18408 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18409 // Do not rebuild lambdas to avoid creating a new type.
18410 // Lambdas have already been processed inside their eval contexts.
18411 return E;
18412 }
18413 bool AlwaysRebuild() { return false; }
18414 bool ReplacingOriginal() { return true; }
18415 bool AllowSkippingCXXConstructExpr() {
18416 bool Res = AllowSkippingFirstCXXConstructExpr;
18417 AllowSkippingFirstCXXConstructExpr = true;
18418 return Res;
18419 }
18420 bool AllowSkippingFirstCXXConstructExpr = true;
18421 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18422 Rec.ImmediateInvocationCandidates, It);
18423
18424 /// CXXConstructExpr with a single argument are getting skipped by
18425 /// TreeTransform in some situtation because they could be implicit. This
18426 /// can only occur for the top-level CXXConstructExpr because it is used
18427 /// nowhere in the expression being transformed therefore will not be rebuilt.
18428 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18429 /// skipping the first CXXConstructExpr.
18430 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18431 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18432
18433 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18434 // The result may not be usable in case of previous compilation errors.
18435 // In this case evaluation of the expression may result in crash so just
18436 // don't do anything further with the result.
18437 if (Res.isUsable()) {
18438 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18439 It->getPointer()->setSubExpr(Res.get());
18440 }
18441}
18442
18443static void
18444HandleImmediateInvocations(Sema &SemaRef,
18445 Sema::ExpressionEvaluationContextRecord &Rec) {
18446 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18447 Rec.ReferenceToConsteval.size() == 0) ||
18448 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18449 return;
18450
18451 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18452 // [...]
18453 // - the initializer of a variable that is usable in constant expressions or
18454 // has constant initialization.
18455 if (SemaRef.getLangOpts().CPlusPlus23 &&
18456 Rec.ExprContext ==
18457 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18458 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18459 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18460 VD->hasConstantInitialization())) {
18461 // An expression or conversion is in an 'immediate function context' if it
18462 // is potentially evaluated and either:
18463 // [...]
18464 // - it is a subexpression of a manifestly constant-evaluated expression
18465 // or conversion.
18466 return;
18467 }
18468 }
18469
18470 /// When we have more than 1 ImmediateInvocationCandidates or previously
18471 /// failed immediate invocations, we need to check for nested
18472 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18473 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18474 /// invocation.
18475 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18476 !SemaRef.FailedImmediateInvocations.empty()) {
18477
18478 /// Prevent sema calls during the tree transform from adding pointers that
18479 /// are already in the sets.
18480 llvm::SaveAndRestore DisableIITracking(
18481 SemaRef.RebuildingImmediateInvocation, true);
18482
18483 /// Prevent diagnostic during tree transfrom as they are duplicates
18484 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18485
18486 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18487 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18488 if (!It->getInt())
18489 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18490 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18491 Rec.ReferenceToConsteval.size()) {
18492 struct SimpleRemove : DynamicRecursiveASTVisitor {
18493 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18494 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18495 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18496 DRSet.erase(Ptr: E);
18497 return DRSet.size();
18498 }
18499 } Visitor(Rec.ReferenceToConsteval);
18500 Visitor.TraverseStmt(
18501 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18502 }
18503 for (auto CE : Rec.ImmediateInvocationCandidates)
18504 if (!CE.getInt())
18505 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18506 for (auto *DR : Rec.ReferenceToConsteval) {
18507 // If the expression is immediate escalating, it is not an error;
18508 // The outer context itself becomes immediate and further errors,
18509 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18510 if (DR->isImmediateEscalating())
18511 continue;
18512 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18513 const NamedDecl *ND = FD;
18514 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18515 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18516 ND = MD->getParent();
18517
18518 // C++23 [expr.const]/p16
18519 // An expression or conversion is immediate-escalating if it is not
18520 // initially in an immediate function context and it is [...] a
18521 // potentially-evaluated id-expression that denotes an immediate function
18522 // that is not a subexpression of an immediate invocation.
18523 bool ImmediateEscalating = false;
18524 bool IsPotentiallyEvaluated =
18525 Rec.Context ==
18526 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18527 Rec.Context ==
18528 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18529 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18530 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18531
18532 if (!Rec.InImmediateEscalatingFunctionContext ||
18533 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18534 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18535 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18536 if (!FD->getBuiltinID())
18537 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18538 if (auto Context =
18539 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18540 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18541 << Context->Decl;
18542 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18543 }
18544 if (FD->isImmediateEscalating() && !FD->isConsteval())
18545 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18546
18547 } else {
18548 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18549 }
18550 }
18551}
18552
18553void Sema::PopExpressionEvaluationContext() {
18554 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18555 if (!Rec.Lambdas.empty()) {
18556 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18557 if (!getLangOpts().CPlusPlus20 &&
18558 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18559 Rec.isUnevaluated() ||
18560 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18561 unsigned D;
18562 if (Rec.isUnevaluated()) {
18563 // C++11 [expr.prim.lambda]p2:
18564 // A lambda-expression shall not appear in an unevaluated operand
18565 // (Clause 5).
18566 D = diag::err_lambda_unevaluated_operand;
18567 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18568 // C++1y [expr.const]p2:
18569 // A conditional-expression e is a core constant expression unless the
18570 // evaluation of e, following the rules of the abstract machine, would
18571 // evaluate [...] a lambda-expression.
18572 D = diag::err_lambda_in_constant_expression;
18573 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18574 // C++17 [expr.prim.lamda]p2:
18575 // A lambda-expression shall not appear [...] in a template-argument.
18576 D = diag::err_lambda_in_invalid_context;
18577 } else
18578 llvm_unreachable("Couldn't infer lambda error message.");
18579
18580 for (const auto *L : Rec.Lambdas)
18581 Diag(Loc: L->getBeginLoc(), DiagID: D);
18582 }
18583 }
18584
18585 // Append the collected materialized temporaries into previous context before
18586 // exit if the previous also is a lifetime extending context.
18587 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18588 parentEvaluationContext().InLifetimeExtendingContext &&
18589 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18590 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18591 RHS: Rec.ForRangeLifetimeExtendTemps);
18592 }
18593
18594 WarnOnPendingNoDerefs(Rec);
18595 HandleImmediateInvocations(SemaRef&: *this, Rec);
18596
18597 // Warn on any volatile-qualified simple-assignments that are not discarded-
18598 // value expressions nor unevaluated operands (those cases get removed from
18599 // this list by CheckUnusedVolatileAssignment).
18600 for (auto *BO : Rec.VolatileAssignmentLHSs)
18601 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18602 << BO->getType();
18603
18604 // When are coming out of an unevaluated context, clear out any
18605 // temporaries that we may have created as part of the evaluation of
18606 // the expression in that context: they aren't relevant because they
18607 // will never be constructed.
18608 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18609 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18610 CE: ExprCleanupObjects.end());
18611 Cleanup = Rec.ParentCleanup;
18612 CleanupVarDeclMarking();
18613 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18614 // Otherwise, merge the contexts together.
18615 } else {
18616 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18617 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18618 }
18619
18620 DiagnoseMisalignedMembers();
18621
18622 // Pop the current expression evaluation context off the stack.
18623 ExprEvalContexts.pop_back();
18624}
18625
18626void Sema::DiscardCleanupsInEvaluationContext() {
18627 ExprCleanupObjects.erase(
18628 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18629 CE: ExprCleanupObjects.end());
18630 Cleanup.reset();
18631 MaybeODRUseExprs.clear();
18632}
18633
18634ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18635 ExprResult Result = CheckPlaceholderExpr(E);
18636 if (Result.isInvalid())
18637 return ExprError();
18638 E = Result.get();
18639 if (!E->getType()->isVariablyModifiedType())
18640 return E;
18641 return TransformToPotentiallyEvaluated(E);
18642}
18643
18644/// Are we in a context that is potentially constant evaluated per C++20
18645/// [expr.const]p12?
18646static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18647 /// C++2a [expr.const]p12:
18648 // An expression or conversion is potentially constant evaluated if it is
18649 switch (SemaRef.ExprEvalContexts.back().Context) {
18650 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18651 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18652
18653 // -- a manifestly constant-evaluated expression,
18654 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18655 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18656 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18657 // -- a potentially-evaluated expression,
18658 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18659 // -- an immediate subexpression of a braced-init-list,
18660
18661 // -- [FIXME] an expression of the form & cast-expression that occurs
18662 // within a templated entity
18663 // -- a subexpression of one of the above that is not a subexpression of
18664 // a nested unevaluated operand.
18665 return true;
18666
18667 case Sema::ExpressionEvaluationContext::Unevaluated:
18668 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18669 // Expressions in this context are never evaluated.
18670 return false;
18671 }
18672 llvm_unreachable("Invalid context");
18673}
18674
18675/// Return true if this function has a calling convention that requires mangling
18676/// in the size of the parameter pack.
18677static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18678 // These manglings are only applicable for targets whcih use Microsoft
18679 // mangling scheme for C.
18680 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18681 return false;
18682
18683 // If this is C++ and this isn't an extern "C" function, parameters do not
18684 // need to be complete. In this case, C++ mangling will apply, which doesn't
18685 // use the size of the parameters.
18686 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18687 return false;
18688
18689 // Stdcall, fastcall, and vectorcall need this special treatment.
18690 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18691 switch (CC) {
18692 case CC_X86StdCall:
18693 case CC_X86FastCall:
18694 case CC_X86VectorCall:
18695 return true;
18696 default:
18697 break;
18698 }
18699 return false;
18700}
18701
18702/// Require that all of the parameter types of function be complete. Normally,
18703/// parameter types are only required to be complete when a function is called
18704/// or defined, but to mangle functions with certain calling conventions, the
18705/// mangler needs to know the size of the parameter list. In this situation,
18706/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18707/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18708/// result in a linker error. Clang doesn't implement this behavior, and instead
18709/// attempts to error at compile time.
18710static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18711 SourceLocation Loc) {
18712 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18713 FunctionDecl *FD;
18714 ParmVarDecl *Param;
18715
18716 public:
18717 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18718 : FD(FD), Param(Param) {}
18719
18720 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18721 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18722 StringRef CCName;
18723 switch (CC) {
18724 case CC_X86StdCall:
18725 CCName = "stdcall";
18726 break;
18727 case CC_X86FastCall:
18728 CCName = "fastcall";
18729 break;
18730 case CC_X86VectorCall:
18731 CCName = "vectorcall";
18732 break;
18733 default:
18734 llvm_unreachable("CC does not need mangling");
18735 }
18736
18737 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18738 << Param->getDeclName() << FD->getDeclName() << CCName;
18739 }
18740 };
18741
18742 for (ParmVarDecl *Param : FD->parameters()) {
18743 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18744 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18745 }
18746}
18747
18748namespace {
18749enum class OdrUseContext {
18750 /// Declarations in this context are not odr-used.
18751 None,
18752 /// Declarations in this context are formally odr-used, but this is a
18753 /// dependent context.
18754 Dependent,
18755 /// Declarations in this context are odr-used but not actually used (yet).
18756 FormallyOdrUsed,
18757 /// Declarations in this context are used.
18758 Used
18759};
18760}
18761
18762/// Are we within a context in which references to resolved functions or to
18763/// variables result in odr-use?
18764static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18765 const Sema::ExpressionEvaluationContextRecord &Context =
18766 SemaRef.currentEvaluationContext();
18767
18768 if (Context.isUnevaluated())
18769 return OdrUseContext::None;
18770
18771 if (SemaRef.CurContext->isDependentContext())
18772 return OdrUseContext::Dependent;
18773
18774 if (Context.isDiscardedStatementContext())
18775 return OdrUseContext::FormallyOdrUsed;
18776
18777 else if (Context.Context ==
18778 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18779 return OdrUseContext::FormallyOdrUsed;
18780
18781 return OdrUseContext::Used;
18782}
18783
18784static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18785 if (!Func->isConstexpr())
18786 return false;
18787
18788 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18789 return true;
18790
18791 // Lambda conversion operators are never user provided.
18792 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18793 return isLambdaConversionOperator(C: Conv);
18794
18795 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18796 return CCD && CCD->getInheritedConstructor();
18797}
18798
18799void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18800 bool MightBeOdrUse) {
18801 assert(Func && "No function?");
18802
18803 Func->setReferenced();
18804
18805 // Recursive functions aren't really used until they're used from some other
18806 // context.
18807 bool IsRecursiveCall = CurContext == Func;
18808
18809 // C++11 [basic.def.odr]p3:
18810 // A function whose name appears as a potentially-evaluated expression is
18811 // odr-used if it is the unique lookup result or the selected member of a
18812 // set of overloaded functions [...].
18813 //
18814 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18815 // can just check that here.
18816 OdrUseContext OdrUse =
18817 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18818 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18819 OdrUse = OdrUseContext::FormallyOdrUsed;
18820
18821 // Trivial default constructors and destructors are never actually used.
18822 // FIXME: What about other special members?
18823 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18824 OdrUse == OdrUseContext::Used) {
18825 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18826 if (Constructor->isDefaultConstructor())
18827 OdrUse = OdrUseContext::FormallyOdrUsed;
18828 if (isa<CXXDestructorDecl>(Val: Func))
18829 OdrUse = OdrUseContext::FormallyOdrUsed;
18830 }
18831
18832 // C++20 [expr.const]p12:
18833 // A function [...] is needed for constant evaluation if it is [...] a
18834 // constexpr function that is named by an expression that is potentially
18835 // constant evaluated
18836 bool NeededForConstantEvaluation =
18837 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18838 isImplicitlyDefinableConstexprFunction(Func);
18839
18840 // Determine whether we require a function definition to exist, per
18841 // C++11 [temp.inst]p3:
18842 // Unless a function template specialization has been explicitly
18843 // instantiated or explicitly specialized, the function template
18844 // specialization is implicitly instantiated when the specialization is
18845 // referenced in a context that requires a function definition to exist.
18846 // C++20 [temp.inst]p7:
18847 // The existence of a definition of a [...] function is considered to
18848 // affect the semantics of the program if the [...] function is needed for
18849 // constant evaluation by an expression
18850 // C++20 [basic.def.odr]p10:
18851 // Every program shall contain exactly one definition of every non-inline
18852 // function or variable that is odr-used in that program outside of a
18853 // discarded statement
18854 // C++20 [special]p1:
18855 // The implementation will implicitly define [defaulted special members]
18856 // if they are odr-used or needed for constant evaluation.
18857 //
18858 // Note that we skip the implicit instantiation of templates that are only
18859 // used in unused default arguments or by recursive calls to themselves.
18860 // This is formally non-conforming, but seems reasonable in practice.
18861 bool NeedDefinition =
18862 !IsRecursiveCall &&
18863 (OdrUse == OdrUseContext::Used ||
18864 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18865
18866 // C++14 [temp.expl.spec]p6:
18867 // If a template [...] is explicitly specialized then that specialization
18868 // shall be declared before the first use of that specialization that would
18869 // cause an implicit instantiation to take place, in every translation unit
18870 // in which such a use occurs
18871 if (NeedDefinition &&
18872 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18873 Func->getMemberSpecializationInfo()))
18874 checkSpecializationReachability(Loc, Spec: Func);
18875
18876 if (getLangOpts().CUDA)
18877 CUDA().CheckCall(Loc, Callee: Func);
18878
18879 // If we need a definition, try to create one.
18880 if (NeedDefinition && !Func->getBody()) {
18881 runWithSufficientStackSpace(Loc, Fn: [&] {
18882 if (CXXConstructorDecl *Constructor =
18883 dyn_cast<CXXConstructorDecl>(Val: Func)) {
18884 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
18885 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18886 if (Constructor->isDefaultConstructor()) {
18887 if (Constructor->isTrivial() &&
18888 !Constructor->hasAttr<DLLExportAttr>())
18889 return;
18890 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
18891 } else if (Constructor->isCopyConstructor()) {
18892 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18893 } else if (Constructor->isMoveConstructor()) {
18894 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18895 }
18896 } else if (Constructor->getInheritedConstructor()) {
18897 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18898 }
18899 } else if (CXXDestructorDecl *Destructor =
18900 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18901 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
18902 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18903 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18904 return;
18905 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18906 }
18907 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18908 MarkVTableUsed(Loc, Class: Destructor->getParent());
18909 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
18910 if (MethodDecl->isOverloadedOperator() &&
18911 MethodDecl->getOverloadedOperator() == OO_Equal) {
18912 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
18913 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18914 if (MethodDecl->isCopyAssignmentOperator())
18915 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
18916 else if (MethodDecl->isMoveAssignmentOperator())
18917 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
18918 }
18919 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
18920 MethodDecl->getParent()->isLambda()) {
18921 CXXConversionDecl *Conversion =
18922 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
18923 if (Conversion->isLambdaToBlockPointerConversion())
18924 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18925 else
18926 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18927 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18928 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
18929 }
18930
18931 if (Func->isDefaulted() && !Func->isDeleted()) {
18932 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
18933 if (DCK != DefaultedComparisonKind::None)
18934 DefineDefaultedComparison(Loc, FD: Func, DCK);
18935 }
18936
18937 // Implicit instantiation of function templates and member functions of
18938 // class templates.
18939 if (Func->isImplicitlyInstantiable()) {
18940 TemplateSpecializationKind TSK =
18941 Func->getTemplateSpecializationKindForInstantiation();
18942 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18943 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18944 if (FirstInstantiation) {
18945 PointOfInstantiation = Loc;
18946 if (auto *MSI = Func->getMemberSpecializationInfo())
18947 MSI->setPointOfInstantiation(Loc);
18948 // FIXME: Notify listener.
18949 else
18950 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18951 } else if (TSK != TSK_ImplicitInstantiation) {
18952 // Use the point of use as the point of instantiation, instead of the
18953 // point of explicit instantiation (which we track as the actual point
18954 // of instantiation). This gives better backtraces in diagnostics.
18955 PointOfInstantiation = Loc;
18956 }
18957
18958 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18959 Func->isConstexpr()) {
18960 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
18961 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
18962 CodeSynthesisContexts.size())
18963 PendingLocalImplicitInstantiations.push_back(
18964 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18965 else if (Func->isConstexpr())
18966 // Do not defer instantiations of constexpr functions, to avoid the
18967 // expression evaluator needing to call back into Sema if it sees a
18968 // call to such a function.
18969 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
18970 else {
18971 Func->setInstantiationIsPending(true);
18972 PendingInstantiations.push_back(
18973 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18974 if (llvm::isTimeTraceVerbose()) {
18975 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
18976 std::string Name;
18977 llvm::raw_string_ostream OS(Name);
18978 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
18979 /*Qualified=*/true);
18980 return Name;
18981 });
18982 }
18983 // Notify the consumer that a function was implicitly instantiated.
18984 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
18985 }
18986 }
18987 } else {
18988 // Walk redefinitions, as some of them may be instantiable.
18989 for (auto *i : Func->redecls()) {
18990 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
18991 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
18992 }
18993 }
18994 });
18995 }
18996
18997 // If a constructor was defined in the context of a default parameter
18998 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18999 // context), its initializers may not be referenced yet.
19000 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19001 EnterExpressionEvaluationContext EvalContext(
19002 *this,
19003 Constructor->isImmediateFunction()
19004 ? ExpressionEvaluationContext::ImmediateFunctionContext
19005 : ExpressionEvaluationContext::PotentiallyEvaluated,
19006 Constructor);
19007 for (CXXCtorInitializer *Init : Constructor->inits()) {
19008 if (Init->isInClassMemberInitializer())
19009 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19010 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19011 });
19012 }
19013 }
19014
19015 // C++14 [except.spec]p17:
19016 // An exception-specification is considered to be needed when:
19017 // - the function is odr-used or, if it appears in an unevaluated operand,
19018 // would be odr-used if the expression were potentially-evaluated;
19019 //
19020 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19021 // function is a pure virtual function we're calling, and in that case the
19022 // function was selected by overload resolution and we need to resolve its
19023 // exception specification for a different reason.
19024 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19025 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19026 ResolveExceptionSpec(Loc, FPT);
19027
19028 // A callee could be called by a host function then by a device function.
19029 // If we only try recording once, we will miss recording the use on device
19030 // side. Therefore keep trying until it is recorded.
19031 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19032 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19033 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19034
19035 // If this is the first "real" use, act on that.
19036 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19037 // Keep track of used but undefined functions.
19038 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19039 if (mightHaveNonExternalLinkage(FD: Func))
19040 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19041 else if (Func->getMostRecentDecl()->isInlined() &&
19042 !LangOpts.GNUInline &&
19043 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19044 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19045 else if (isExternalWithNoLinkageType(VD: Func))
19046 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19047 }
19048
19049 // Some x86 Windows calling conventions mangle the size of the parameter
19050 // pack into the name. Computing the size of the parameters requires the
19051 // parameter types to be complete. Check that now.
19052 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19053 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19054
19055 // In the MS C++ ABI, the compiler emits destructor variants where they are
19056 // used. If the destructor is used here but defined elsewhere, mark the
19057 // virtual base destructors referenced. If those virtual base destructors
19058 // are inline, this will ensure they are defined when emitting the complete
19059 // destructor variant. This checking may be redundant if the destructor is
19060 // provided later in this TU.
19061 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19062 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19063 CXXRecordDecl *Parent = Dtor->getParent();
19064 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19065 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19066 }
19067 }
19068
19069 Func->markUsed(C&: Context);
19070 }
19071}
19072
19073/// Directly mark a variable odr-used. Given a choice, prefer to use
19074/// MarkVariableReferenced since it does additional checks and then
19075/// calls MarkVarDeclODRUsed.
19076/// If the variable must be captured:
19077/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19078/// - else capture it in the DeclContext that maps to the
19079/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19080static void
19081MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19082 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19083 // Keep track of used but undefined variables.
19084 // FIXME: We shouldn't suppress this warning for static data members.
19085 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19086 assert(Var && "expected a capturable variable");
19087
19088 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19089 (!Var->isExternallyVisible() || Var->isInline() ||
19090 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19091 !(Var->isStaticDataMember() && Var->hasInit())) {
19092 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19093 if (old.isInvalid())
19094 old = Loc;
19095 }
19096 QualType CaptureType, DeclRefType;
19097 if (SemaRef.LangOpts.OpenMP)
19098 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19099 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19100 /*EllipsisLoc*/ SourceLocation(),
19101 /*BuildAndDiagnose*/ true, CaptureType,
19102 DeclRefType, FunctionScopeIndexToStopAt);
19103
19104 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19105 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19106 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19107 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19108 if (VarTarget == SemaCUDA::CVT_Host &&
19109 (UserTarget == CUDAFunctionTarget::Device ||
19110 UserTarget == CUDAFunctionTarget::HostDevice ||
19111 UserTarget == CUDAFunctionTarget::Global)) {
19112 // Diagnose ODR-use of host global variables in device functions.
19113 // Reference of device global variables in host functions is allowed
19114 // through shadow variables therefore it is not diagnosed.
19115 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19116 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19117 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19118 SemaRef.targetDiag(Loc: Var->getLocation(),
19119 DiagID: Var->getType().isConstQualified()
19120 ? diag::note_cuda_const_var_unpromoted
19121 : diag::note_cuda_host_var);
19122 }
19123 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19124 // Also capture __device__ const variables, which are classified
19125 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19126 // an explicit CUDADeviceAttr to distinguish them from plain
19127 // const variables (no __device__), which also get CVT_Both but
19128 // only have an implicit CUDADeviceAttr.
19129 (VarTarget == SemaCUDA::CVT_Both &&
19130 Var->hasAttr<CUDADeviceAttr>() &&
19131 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19132 !Var->hasAttr<CUDASharedAttr>() &&
19133 (UserTarget == CUDAFunctionTarget::Host ||
19134 UserTarget == CUDAFunctionTarget::HostDevice)) {
19135 // Record a CUDA/HIP device side variable if it is ODR-used
19136 // by host code. This is done conservatively, when the variable is
19137 // referenced in any of the following contexts:
19138 // - a non-function context
19139 // - a host function
19140 // - a host device function
19141 // This makes the ODR-use of the device side variable by host code to
19142 // be visible in the device compilation for the compiler to be able to
19143 // emit template variables instantiated by host code only and to
19144 // externalize the static device side variable ODR-used by host code.
19145 if (!Var->hasExternalStorage())
19146 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var);
19147 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19148 (!FD || (!FD->getDescribedFunctionTemplate() &&
19149 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19150 GVA_StrongExternal)))
19151 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19152 }
19153 }
19154
19155 V->markUsed(C&: SemaRef.Context);
19156}
19157
19158void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19159 SourceLocation Loc,
19160 unsigned CapturingScopeIndex) {
19161 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19162}
19163
19164static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19165 SourceLocation loc,
19166 ValueDecl *var) {
19167 DeclContext *VarDC = var->getDeclContext();
19168
19169 // If the parameter still belongs to the translation unit, then
19170 // we're actually just using one parameter in the declaration of
19171 // the next.
19172 if (isa<ParmVarDecl>(Val: var) &&
19173 isa<TranslationUnitDecl>(Val: VarDC))
19174 return;
19175
19176 // For C code, don't diagnose about capture if we're not actually in code
19177 // right now; it's impossible to write a non-constant expression outside of
19178 // function context, so we'll get other (more useful) diagnostics later.
19179 //
19180 // For C++, things get a bit more nasty... it would be nice to suppress this
19181 // diagnostic for certain cases like using a local variable in an array bound
19182 // for a member of a local class, but the correct predicate is not obvious.
19183 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19184 return;
19185
19186 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19187 unsigned ContextKind = 3; // unknown
19188 if (isa<CXXMethodDecl>(Val: VarDC) &&
19189 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19190 ContextKind = 2;
19191 } else if (isa<FunctionDecl>(Val: VarDC)) {
19192 ContextKind = 0;
19193 } else if (isa<BlockDecl>(Val: VarDC)) {
19194 ContextKind = 1;
19195 }
19196
19197 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19198 << var << ValueKind << ContextKind << VarDC;
19199 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19200 << var;
19201
19202 // FIXME: Add additional diagnostic info about class etc. which prevents
19203 // capture.
19204}
19205
19206static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19207 ValueDecl *Var,
19208 bool &SubCapturesAreNested,
19209 QualType &CaptureType,
19210 QualType &DeclRefType) {
19211 // Check whether we've already captured it.
19212 if (CSI->CaptureMap.count(Val: Var)) {
19213 // If we found a capture, any subcaptures are nested.
19214 SubCapturesAreNested = true;
19215
19216 // Retrieve the capture type for this variable.
19217 CaptureType = CSI->getCapture(Var).getCaptureType();
19218
19219 // Compute the type of an expression that refers to this variable.
19220 DeclRefType = CaptureType.getNonReferenceType();
19221
19222 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19223 // are mutable in the sense that user can change their value - they are
19224 // private instances of the captured declarations.
19225 const Capture &Cap = CSI->getCapture(Var);
19226 // C++ [expr.prim.lambda]p10:
19227 // The type of such a data member is [...] an lvalue reference to the
19228 // referenced function type if the entity is a reference to a function.
19229 // [...]
19230 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19231 !(isa<LambdaScopeInfo>(Val: CSI) &&
19232 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19233 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19234 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19235 DeclRefType.addConst();
19236 return true;
19237 }
19238 return false;
19239}
19240
19241// Only block literals, captured statements, and lambda expressions can
19242// capture; other scopes don't work.
19243static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19244 ValueDecl *Var,
19245 SourceLocation Loc,
19246 const bool Diagnose,
19247 Sema &S) {
19248 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19249 return getLambdaAwareParentOfDeclContext(DC);
19250
19251 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19252 if (Underlying) {
19253 if (Underlying->hasLocalStorage() && Diagnose)
19254 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19255 }
19256 return nullptr;
19257}
19258
19259// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19260// certain types of variables (unnamed, variably modified types etc.)
19261// so check for eligibility.
19262static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19263 SourceLocation Loc, const bool Diagnose,
19264 Sema &S) {
19265
19266 assert((isa<VarDecl, BindingDecl>(Var)) &&
19267 "Only variables and structured bindings can be captured");
19268
19269 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19270 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19271
19272 // Lambdas are not allowed to capture unnamed variables
19273 // (e.g. anonymous unions).
19274 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19275 // assuming that's the intent.
19276 if (IsLambda && !Var->getDeclName()) {
19277 if (Diagnose) {
19278 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19279 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19280 }
19281 return false;
19282 }
19283
19284 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19285 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19286 if (Diagnose) {
19287 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19288 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19289 }
19290 return false;
19291 }
19292 // Prohibit structs with flexible array members too.
19293 // We cannot capture what is in the tail end of the struct.
19294 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19295 VTD && VTD->hasFlexibleArrayMember()) {
19296 if (Diagnose) {
19297 if (IsBlock)
19298 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19299 else
19300 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19301 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19302 }
19303 return false;
19304 }
19305 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19306 // Lambdas and captured statements are not allowed to capture __block
19307 // variables; they don't support the expected semantics.
19308 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19309 if (Diagnose) {
19310 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19311 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19312 }
19313 return false;
19314 }
19315 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19316 if (S.getLangOpts().OpenCL && IsBlock &&
19317 Var->getType()->isBlockPointerType()) {
19318 if (Diagnose)
19319 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19320 return false;
19321 }
19322
19323 if (isa<BindingDecl>(Val: Var)) {
19324 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19325 if (Diagnose)
19326 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19327 return false;
19328 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19329 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19330 ? diag::warn_cxx17_compat_capture_binding
19331 : diag::ext_capture_binding)
19332 << Var;
19333 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19334 }
19335 }
19336
19337 return true;
19338}
19339
19340// Returns true if the capture by block was successful.
19341static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19342 SourceLocation Loc, const bool BuildAndDiagnose,
19343 QualType &CaptureType, QualType &DeclRefType,
19344 const bool Nested, Sema &S, bool Invalid) {
19345 bool ByRef = false;
19346
19347 // Blocks are not allowed to capture arrays, excepting OpenCL.
19348 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19349 // (decayed to pointers).
19350 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19351 if (BuildAndDiagnose) {
19352 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19353 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19354 Invalid = true;
19355 } else {
19356 return false;
19357 }
19358 }
19359
19360 // Forbid the block-capture of autoreleasing variables.
19361 if (!Invalid &&
19362 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19363 if (BuildAndDiagnose) {
19364 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19365 << /*block*/ 0;
19366 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19367 Invalid = true;
19368 } else {
19369 return false;
19370 }
19371 }
19372
19373 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19374 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19375 QualType PointeeTy = PT->getPointeeType();
19376
19377 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19378 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19379 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19380 if (BuildAndDiagnose) {
19381 SourceLocation VarLoc = Var->getLocation();
19382 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19383 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19384 }
19385 }
19386 }
19387
19388 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19389 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19390 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19391 // Block capture by reference does not change the capture or
19392 // declaration reference types.
19393 ByRef = true;
19394 } else {
19395 // Block capture by copy introduces 'const'.
19396 CaptureType = CaptureType.getNonReferenceType().withConst();
19397 DeclRefType = CaptureType;
19398 }
19399
19400 // Actually capture the variable.
19401 if (BuildAndDiagnose)
19402 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19403 CaptureType, Invalid);
19404
19405 return !Invalid;
19406}
19407
19408/// Capture the given variable in the captured region.
19409static bool captureInCapturedRegion(
19410 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19411 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19412 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19413 Sema &S, bool Invalid) {
19414 // By default, capture variables by reference.
19415 bool ByRef = true;
19416 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19417 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19418 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19419 // Using an LValue reference type is consistent with Lambdas (see below).
19420 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19421 bool HasConst = DeclRefType.isConstQualified();
19422 DeclRefType = DeclRefType.getUnqualifiedType();
19423 // Don't lose diagnostics about assignments to const.
19424 if (HasConst)
19425 DeclRefType.addConst();
19426 }
19427 // Do not capture firstprivates in tasks.
19428 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19429 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19430 return true;
19431 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19432 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19433 }
19434
19435 if (ByRef)
19436 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19437 else
19438 CaptureType = DeclRefType;
19439
19440 // Actually capture the variable.
19441 if (BuildAndDiagnose)
19442 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19443 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19444
19445 return !Invalid;
19446}
19447
19448/// Capture the given variable in the lambda.
19449static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19450 SourceLocation Loc, const bool BuildAndDiagnose,
19451 QualType &CaptureType, QualType &DeclRefType,
19452 const bool RefersToCapturedVariable,
19453 const TryCaptureKind Kind,
19454 SourceLocation EllipsisLoc, const bool IsTopScope,
19455 Sema &S, bool Invalid) {
19456 // Determine whether we are capturing by reference or by value.
19457 bool ByRef = false;
19458 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19459 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19460 } else {
19461 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19462 }
19463
19464 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19465 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19466 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19467 Invalid = true;
19468 }
19469
19470 // Compute the type of the field that will capture this variable.
19471 if (ByRef) {
19472 // C++11 [expr.prim.lambda]p15:
19473 // An entity is captured by reference if it is implicitly or
19474 // explicitly captured but not captured by copy. It is
19475 // unspecified whether additional unnamed non-static data
19476 // members are declared in the closure type for entities
19477 // captured by reference.
19478 //
19479 // FIXME: It is not clear whether we want to build an lvalue reference
19480 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19481 // to do the former, while EDG does the latter. Core issue 1249 will
19482 // clarify, but for now we follow GCC because it's a more permissive and
19483 // easily defensible position.
19484 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19485 } else {
19486 // C++11 [expr.prim.lambda]p14:
19487 // For each entity captured by copy, an unnamed non-static
19488 // data member is declared in the closure type. The
19489 // declaration order of these members is unspecified. The type
19490 // of such a data member is the type of the corresponding
19491 // captured entity if the entity is not a reference to an
19492 // object, or the referenced type otherwise. [Note: If the
19493 // captured entity is a reference to a function, the
19494 // corresponding data member is also a reference to a
19495 // function. - end note ]
19496 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19497 if (!RefType->getPointeeType()->isFunctionType())
19498 CaptureType = RefType->getPointeeType();
19499 }
19500
19501 // Forbid the lambda copy-capture of autoreleasing variables.
19502 if (!Invalid &&
19503 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19504 if (BuildAndDiagnose) {
19505 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19506 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19507 << Var->getDeclName();
19508 Invalid = true;
19509 } else {
19510 return false;
19511 }
19512 }
19513
19514 // Make sure that by-copy captures are of a complete and non-abstract type.
19515 if (!Invalid && BuildAndDiagnose) {
19516 if (!CaptureType->isDependentType() &&
19517 S.RequireCompleteSizedType(
19518 Loc, T: CaptureType,
19519 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19520 Args: Var->getDeclName()))
19521 Invalid = true;
19522 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19523 DiagID: diag::err_capture_of_abstract_type))
19524 Invalid = true;
19525 }
19526 }
19527
19528 // Compute the type of a reference to this captured variable.
19529 if (ByRef)
19530 DeclRefType = CaptureType.getNonReferenceType();
19531 else {
19532 // C++ [expr.prim.lambda]p5:
19533 // The closure type for a lambda-expression has a public inline
19534 // function call operator [...]. This function call operator is
19535 // declared const (9.3.1) if and only if the lambda-expression's
19536 // parameter-declaration-clause is not followed by mutable.
19537 DeclRefType = CaptureType.getNonReferenceType();
19538 bool Const = LSI->lambdaCaptureShouldBeConst();
19539 // C++ [expr.prim.lambda]p10:
19540 // The type of such a data member is [...] an lvalue reference to the
19541 // referenced function type if the entity is a reference to a function.
19542 // [...]
19543 if (Const && !CaptureType->isReferenceType() &&
19544 !DeclRefType->isFunctionType())
19545 DeclRefType.addConst();
19546 }
19547
19548 // Add the capture.
19549 if (BuildAndDiagnose)
19550 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19551 Loc, EllipsisLoc, CaptureType, Invalid);
19552
19553 return !Invalid;
19554}
19555
19556static bool canCaptureVariableByCopy(ValueDecl *Var,
19557 const ASTContext &Context) {
19558 // Offer a Copy fix even if the type is dependent.
19559 if (Var->getType()->isDependentType())
19560 return true;
19561 QualType T = Var->getType().getNonReferenceType();
19562 if (T.isTriviallyCopyableType(Context))
19563 return true;
19564 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19565
19566 if (!(RD = RD->getDefinition()))
19567 return false;
19568 if (RD->hasSimpleCopyConstructor())
19569 return true;
19570 if (RD->hasUserDeclaredCopyConstructor())
19571 for (CXXConstructorDecl *Ctor : RD->ctors())
19572 if (Ctor->isCopyConstructor())
19573 return !Ctor->isDeleted();
19574 }
19575 return false;
19576}
19577
19578/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19579/// default capture. Fixes may be omitted if they aren't allowed by the
19580/// standard, for example we can't emit a default copy capture fix-it if we
19581/// already explicitly copy capture capture another variable.
19582static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19583 ValueDecl *Var) {
19584 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19585 // Don't offer Capture by copy of default capture by copy fixes if Var is
19586 // known not to be copy constructible.
19587 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19588
19589 SmallString<32> FixBuffer;
19590 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19591 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19592 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19593 if (ShouldOfferCopyFix) {
19594 // Offer fixes to insert an explicit capture for the variable.
19595 // [] -> [VarName]
19596 // [OtherCapture] -> [OtherCapture, VarName]
19597 FixBuffer.assign(Refs: {Separator, Var->getName()});
19598 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19599 << Var << /*value*/ 0
19600 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19601 }
19602 // As above but capture by reference.
19603 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19604 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19605 << Var << /*reference*/ 1
19606 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19607 }
19608
19609 // Only try to offer default capture if there are no captures excluding this
19610 // and init captures.
19611 // [this]: OK.
19612 // [X = Y]: OK.
19613 // [&A, &B]: Don't offer.
19614 // [A, B]: Don't offer.
19615 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19616 return !C.isThisCapture() && !C.isInitCapture();
19617 }))
19618 return;
19619
19620 // The default capture specifiers, '=' or '&', must appear first in the
19621 // capture body.
19622 SourceLocation DefaultInsertLoc =
19623 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19624
19625 if (ShouldOfferCopyFix) {
19626 bool CanDefaultCopyCapture = true;
19627 // [=, *this] OK since c++17
19628 // [=, this] OK since c++20
19629 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19630 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19631 ? LSI->getCXXThisCapture().isCopyCapture()
19632 : false;
19633 // We can't use default capture by copy if any captures already specified
19634 // capture by copy.
19635 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19636 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19637 })) {
19638 FixBuffer.assign(Refs: {"=", Separator});
19639 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19640 << /*value*/ 0
19641 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19642 }
19643 }
19644
19645 // We can't use default capture by reference if any captures already specified
19646 // capture by reference.
19647 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19648 return !C.isInitCapture() && C.isReferenceCapture() &&
19649 !C.isThisCapture();
19650 })) {
19651 FixBuffer.assign(Refs: {"&", Separator});
19652 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19653 << /*reference*/ 1
19654 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19655 }
19656}
19657
19658bool Sema::tryCaptureVariable(
19659 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19660 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19661 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19662 // An init-capture is notionally from the context surrounding its
19663 // declaration, but its parent DC is the lambda class.
19664 DeclContext *VarDC = Var->getDeclContext();
19665 DeclContext *DC = CurContext;
19666
19667 // Skip past RequiresExprBodys because they don't constitute function scopes.
19668 while (DC->isRequiresExprBody())
19669 DC = DC->getParent();
19670
19671 // tryCaptureVariable is called every time a DeclRef is formed,
19672 // it can therefore have non-negigible impact on performances.
19673 // For local variables and when there is no capturing scope,
19674 // we can bailout early.
19675 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19676 return true;
19677
19678 // Exception: Function parameters are not tied to the function's DeclContext
19679 // until we enter the function definition. Capturing them anyway would result
19680 // in an out-of-bounds error while traversing DC and its parents.
19681 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19682 return true;
19683
19684 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19685 if (VD) {
19686 if (VD->isInitCapture())
19687 VarDC = VarDC->getParent();
19688 } else {
19689 VD = Var->getPotentiallyDecomposedVarDecl();
19690 }
19691 assert(VD && "Cannot capture a null variable");
19692
19693 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19694 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19695 // We need to sync up the Declaration Context with the
19696 // FunctionScopeIndexToStopAt
19697 if (FunctionScopeIndexToStopAt) {
19698 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19699 unsigned FSIndex = FunctionScopes.size() - 1;
19700 // When we're parsing the lambda parameter list, the current DeclContext is
19701 // NOT the lambda but its parent. So move away the current LSI before
19702 // aligning DC and FunctionScopeIndexToStopAt.
19703 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19704 FSIndex && LSI && !LSI->AfterParameterList)
19705 --FSIndex;
19706 assert(MaxFunctionScopesIndex <= FSIndex &&
19707 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19708 "FunctionScopes.");
19709 while (FSIndex != MaxFunctionScopesIndex) {
19710 DC = getLambdaAwareParentOfDeclContext(DC);
19711 --FSIndex;
19712 }
19713 }
19714
19715 // Capture global variables if it is required to use private copy of this
19716 // variable.
19717 bool IsGlobal = !VD->hasLocalStorage();
19718 if (IsGlobal && !(LangOpts.OpenMP &&
19719 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19720 StopAt: MaxFunctionScopesIndex)))
19721 return true;
19722
19723 if (isa<VarDecl>(Val: Var))
19724 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19725
19726 // Walk up the stack to determine whether we can capture the variable,
19727 // performing the "simple" checks that don't depend on type. We stop when
19728 // we've either hit the declared scope of the variable or find an existing
19729 // capture of that variable. We start from the innermost capturing-entity
19730 // (the DC) and ensure that all intervening capturing-entities
19731 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19732 // declcontext can either capture the variable or have already captured
19733 // the variable.
19734 CaptureType = Var->getType();
19735 DeclRefType = CaptureType.getNonReferenceType();
19736 bool Nested = false;
19737 bool Explicit = (Kind != TryCaptureKind::Implicit);
19738 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19739 do {
19740
19741 LambdaScopeInfo *LSI = nullptr;
19742 if (!FunctionScopes.empty())
19743 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19744 Val: FunctionScopes[FunctionScopesIndex]);
19745
19746 bool IsInScopeDeclarationContext =
19747 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19748
19749 if (LSI && !LSI->AfterParameterList) {
19750 // This allows capturing parameters from a default value which does not
19751 // seems correct
19752 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19753 return true;
19754 }
19755 // If the variable is declared in the current context, there is no need to
19756 // capture it.
19757 if (IsInScopeDeclarationContext &&
19758 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19759 return true;
19760
19761 // Only block literals, captured statements, and lambda expressions can
19762 // capture; other scopes don't work.
19763 DeclContext *ParentDC =
19764 !IsInScopeDeclarationContext
19765 ? DC->getParent()
19766 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19767 Diagnose: BuildAndDiagnose, S&: *this);
19768 // We need to check for the parent *first* because, if we *have*
19769 // private-captured a global variable, we need to recursively capture it in
19770 // intermediate blocks, lambdas, etc.
19771 if (!ParentDC) {
19772 if (IsGlobal) {
19773 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19774 break;
19775 }
19776 return true;
19777 }
19778
19779 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19780 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19781
19782 // Check whether we've already captured it.
19783 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19784 DeclRefType)) {
19785 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19786 break;
19787 }
19788
19789 // When evaluating some attributes (like enable_if) we might refer to a
19790 // function parameter appertaining to the same declaration as that
19791 // attribute.
19792 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19793 Parm && Parm->getDeclContext() == DC)
19794 return true;
19795
19796 // If we are instantiating a generic lambda call operator body,
19797 // we do not want to capture new variables. What was captured
19798 // during either a lambdas transformation or initial parsing
19799 // should be used.
19800 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19801 if (BuildAndDiagnose) {
19802 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19803 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19804 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19805 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19806 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19807 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19808 } else
19809 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19810 }
19811 return true;
19812 }
19813
19814 // Try to capture variable-length arrays types.
19815 if (Var->getType()->isVariablyModifiedType()) {
19816 // We're going to walk down into the type and look for VLA
19817 // expressions.
19818 QualType QTy = Var->getType();
19819 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19820 QTy = PVD->getOriginalType();
19821 captureVariablyModifiedType(Context, T: QTy, CSI);
19822 }
19823
19824 if (getLangOpts().OpenMP) {
19825 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19826 // OpenMP private variables should not be captured in outer scope, so
19827 // just break here. Similarly, global variables that are captured in a
19828 // target region should not be captured outside the scope of the region.
19829 if (RSI->CapRegionKind == CR_OpenMP) {
19830 // FIXME: We should support capturing structured bindings in OpenMP.
19831 if (isa<BindingDecl>(Val: Var)) {
19832 if (BuildAndDiagnose) {
19833 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
19834 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19835 }
19836 return true;
19837 }
19838 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19839 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
19840 // If the variable is private (i.e. not captured) and has variably
19841 // modified type, we still need to capture the type for correct
19842 // codegen in all regions, associated with the construct. Currently,
19843 // it is captured in the innermost captured region only.
19844 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19845 Var->getType()->isVariablyModifiedType()) {
19846 QualType QTy = Var->getType();
19847 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19848 QTy = PVD->getOriginalType();
19849 for (int I = 1,
19850 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19851 I < E; ++I) {
19852 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19853 Val: FunctionScopes[FunctionScopesIndex - I]);
19854 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19855 "Wrong number of captured regions associated with the "
19856 "OpenMP construct.");
19857 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
19858 }
19859 }
19860 bool IsTargetCap =
19861 IsOpenMPPrivateDecl != OMPC_private &&
19862 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19863 CaptureLevel: RSI->OpenMPCaptureLevel);
19864 // Do not capture global if it is not privatized in outer regions.
19865 bool IsGlobalCap =
19866 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19867 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
19868
19869 // When we detect target captures we are looking from inside the
19870 // target region, therefore we need to propagate the capture from the
19871 // enclosing region. Therefore, the capture is not initially nested.
19872 if (IsTargetCap)
19873 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19874 Level: RSI->OpenMPLevel);
19875
19876 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19877 (IsGlobal && !IsGlobalCap)) {
19878 Nested = !IsTargetCap;
19879 bool HasConst = DeclRefType.isConstQualified();
19880 DeclRefType = DeclRefType.getUnqualifiedType();
19881 // Don't lose diagnostics about assignments to const.
19882 if (HasConst)
19883 DeclRefType.addConst();
19884 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
19885 break;
19886 }
19887 }
19888 }
19889 }
19890 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19891 // No capture-default, and this is not an explicit capture
19892 // so cannot capture this variable.
19893 if (BuildAndDiagnose) {
19894 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19895 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19896 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
19897 if (LSI->Lambda) {
19898 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19899 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19900 }
19901 // FIXME: If we error out because an outer lambda can not implicitly
19902 // capture a variable that an inner lambda explicitly captures, we
19903 // should have the inner lambda do the explicit capture - because
19904 // it makes for cleaner diagnostics later. This would purely be done
19905 // so that the diagnostic does not misleadingly claim that a variable
19906 // can not be captured by a lambda implicitly even though it is captured
19907 // explicitly. Suggestion:
19908 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19909 // at the function head
19910 // - cache the StartingDeclContext - this must be a lambda
19911 // - captureInLambda in the innermost lambda the variable.
19912 }
19913 return true;
19914 }
19915 Explicit = false;
19916 FunctionScopesIndex--;
19917 if (IsInScopeDeclarationContext)
19918 DC = ParentDC;
19919 } while (!VarDC->Equals(DC));
19920
19921 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19922 // computing the type of the capture at each step, checking type-specific
19923 // requirements, and adding captures if requested.
19924 // If the variable had already been captured previously, we start capturing
19925 // at the lambda nested within that one.
19926 bool Invalid = false;
19927 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19928 ++I) {
19929 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
19930
19931 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19932 // certain types of variables (unnamed, variably modified types etc.)
19933 // so check for eligibility.
19934 if (!Invalid)
19935 Invalid =
19936 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
19937
19938 // After encountering an error, if we're actually supposed to capture, keep
19939 // capturing in nested contexts to suppress any follow-on diagnostics.
19940 if (Invalid && !BuildAndDiagnose)
19941 return true;
19942
19943 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
19944 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19945 DeclRefType, Nested, S&: *this, Invalid);
19946 Nested = true;
19947 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19948 Invalid = !captureInCapturedRegion(
19949 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
19950 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19951 Nested = true;
19952 } else {
19953 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19954 Invalid =
19955 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19956 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
19957 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19958 Nested = true;
19959 }
19960
19961 if (Invalid && !BuildAndDiagnose)
19962 return true;
19963 }
19964 return Invalid;
19965}
19966
19967bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19968 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19969 QualType CaptureType;
19970 QualType DeclRefType;
19971 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
19972 /*BuildAndDiagnose=*/true, CaptureType,
19973 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19974}
19975
19976bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19977 QualType CaptureType;
19978 QualType DeclRefType;
19979 return !tryCaptureVariable(
19980 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19981 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19982}
19983
19984QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19985 assert(Var && "Null value cannot be captured");
19986
19987 QualType CaptureType;
19988 QualType DeclRefType;
19989
19990 // Determine whether we can capture this variable.
19991 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19992 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19993 FunctionScopeIndexToStopAt: nullptr))
19994 return QualType();
19995
19996 return DeclRefType;
19997}
19998
19999namespace {
20000// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20001// The produced TemplateArgumentListInfo* points to data stored within this
20002// object, so should only be used in contexts where the pointer will not be
20003// used after the CopiedTemplateArgs object is destroyed.
20004class CopiedTemplateArgs {
20005 bool HasArgs;
20006 TemplateArgumentListInfo TemplateArgStorage;
20007public:
20008 template<typename RefExpr>
20009 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20010 if (HasArgs)
20011 E->copyTemplateArgumentsInto(TemplateArgStorage);
20012 }
20013 operator TemplateArgumentListInfo*()
20014#ifdef __has_cpp_attribute
20015#if __has_cpp_attribute(clang::lifetimebound)
20016 [[clang::lifetimebound]]
20017#endif
20018#endif
20019 {
20020 return HasArgs ? &TemplateArgStorage : nullptr;
20021 }
20022};
20023}
20024
20025/// Walk the set of potential results of an expression and mark them all as
20026/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20027///
20028/// \return A new expression if we found any potential results, ExprEmpty() if
20029/// not, and ExprError() if we diagnosed an error.
20030static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20031 NonOdrUseReason NOUR) {
20032 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20033 // an object that satisfies the requirements for appearing in a
20034 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20035 // is immediately applied." This function handles the lvalue-to-rvalue
20036 // conversion part.
20037 //
20038 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20039 // transform it into the relevant kind of non-odr-use node and rebuild the
20040 // tree of nodes leading to it.
20041 //
20042 // This is a mini-TreeTransform that only transforms a restricted subset of
20043 // nodes (and only certain operands of them).
20044
20045 // Rebuild a subexpression.
20046 auto Rebuild = [&](Expr *Sub) {
20047 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20048 };
20049
20050 // Check whether a potential result satisfies the requirements of NOUR.
20051 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20052 // Any entity other than a VarDecl is always odr-used whenever it's named
20053 // in a potentially-evaluated expression.
20054 auto *VD = dyn_cast<VarDecl>(Val: D);
20055 if (!VD)
20056 return true;
20057
20058 // C++2a [basic.def.odr]p4:
20059 // A variable x whose name appears as a potentially-evalauted expression
20060 // e is odr-used by e unless
20061 // -- x is a reference that is usable in constant expressions, or
20062 // -- x is a variable of non-reference type that is usable in constant
20063 // expressions and has no mutable subobjects, and e is an element of
20064 // the set of potential results of an expression of
20065 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20066 // conversion is applied, or
20067 // -- x is a variable of non-reference type, and e is an element of the
20068 // set of potential results of a discarded-value expression to which
20069 // the lvalue-to-rvalue conversion is not applied
20070 //
20071 // We check the first bullet and the "potentially-evaluated" condition in
20072 // BuildDeclRefExpr. We check the type requirements in the second bullet
20073 // in CheckLValueToRValueConversionOperand below.
20074 switch (NOUR) {
20075 case NOUR_None:
20076 case NOUR_Unevaluated:
20077 llvm_unreachable("unexpected non-odr-use-reason");
20078
20079 case NOUR_Constant:
20080 // Constant references were handled when they were built.
20081 if (VD->getType()->isReferenceType())
20082 return true;
20083 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20084 if (RD->hasDefinition() && RD->hasMutableFields())
20085 return true;
20086 if (!VD->isUsableInConstantExpressions(C: S.Context))
20087 return true;
20088 break;
20089
20090 case NOUR_Discarded:
20091 if (VD->getType()->isReferenceType())
20092 return true;
20093 break;
20094 }
20095 return false;
20096 };
20097
20098 // Check whether this expression may be odr-used in CUDA/HIP.
20099 auto MaybeCUDAODRUsed = [&]() -> bool {
20100 if (!S.LangOpts.CUDA)
20101 return false;
20102 LambdaScopeInfo *LSI = S.getCurLambda();
20103 if (!LSI)
20104 return false;
20105 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20106 if (!DRE)
20107 return false;
20108 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20109 if (!VD)
20110 return false;
20111 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20112 };
20113
20114 // Mark that this expression does not constitute an odr-use.
20115 auto MarkNotOdrUsed = [&] {
20116 if (!MaybeCUDAODRUsed()) {
20117 S.MaybeODRUseExprs.remove(X: E);
20118 if (LambdaScopeInfo *LSI = S.getCurLambda())
20119 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20120 }
20121 };
20122
20123 // C++2a [basic.def.odr]p2:
20124 // The set of potential results of an expression e is defined as follows:
20125 switch (E->getStmtClass()) {
20126 // -- If e is an id-expression, ...
20127 case Expr::DeclRefExprClass: {
20128 auto *DRE = cast<DeclRefExpr>(Val: E);
20129 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20130 break;
20131
20132 // Rebuild as a non-odr-use DeclRefExpr.
20133 MarkNotOdrUsed();
20134 return DeclRefExpr::Create(
20135 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20136 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20137 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20138 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20139 }
20140
20141 case Expr::FunctionParmPackExprClass: {
20142 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20143 // If any of the declarations in the pack is odr-used, then the expression
20144 // as a whole constitutes an odr-use.
20145 for (ValueDecl *D : *FPPE)
20146 if (IsPotentialResultOdrUsed(D))
20147 return ExprEmpty();
20148
20149 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20150 // nothing cares about whether we marked this as an odr-use, but it might
20151 // be useful for non-compiler tools.
20152 MarkNotOdrUsed();
20153 break;
20154 }
20155
20156 // -- If e is a subscripting operation with an array operand...
20157 case Expr::ArraySubscriptExprClass: {
20158 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20159 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20160 if (!OldBase->getType()->isArrayType())
20161 break;
20162 ExprResult Base = Rebuild(OldBase);
20163 if (!Base.isUsable())
20164 return Base;
20165 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20166 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20167 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20168 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20169 rbLoc: ASE->getRBracketLoc());
20170 }
20171
20172 case Expr::MemberExprClass: {
20173 auto *ME = cast<MemberExpr>(Val: E);
20174 // -- If e is a class member access expression [...] naming a non-static
20175 // data member...
20176 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20177 ExprResult Base = Rebuild(ME->getBase());
20178 if (!Base.isUsable())
20179 return Base;
20180 return MemberExpr::Create(
20181 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20182 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20183 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20184 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20185 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20186 }
20187
20188 if (ME->getMemberDecl()->isCXXInstanceMember())
20189 break;
20190
20191 // -- If e is a class member access expression naming a static data member,
20192 // ...
20193 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20194 break;
20195
20196 // Rebuild as a non-odr-use MemberExpr.
20197 MarkNotOdrUsed();
20198 return MemberExpr::Create(
20199 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20200 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20201 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20202 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20203 }
20204
20205 case Expr::BinaryOperatorClass: {
20206 auto *BO = cast<BinaryOperator>(Val: E);
20207 Expr *LHS = BO->getLHS();
20208 Expr *RHS = BO->getRHS();
20209 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20210 if (BO->getOpcode() == BO_PtrMemD) {
20211 ExprResult Sub = Rebuild(LHS);
20212 if (!Sub.isUsable())
20213 return Sub;
20214 BO->setLHS(Sub.get());
20215 // -- If e is a comma expression, ...
20216 } else if (BO->getOpcode() == BO_Comma) {
20217 ExprResult Sub = Rebuild(RHS);
20218 if (!Sub.isUsable())
20219 return Sub;
20220 BO->setRHS(Sub.get());
20221 } else {
20222 break;
20223 }
20224 return ExprResult(BO);
20225 }
20226
20227 // -- If e has the form (e1)...
20228 case Expr::ParenExprClass: {
20229 auto *PE = cast<ParenExpr>(Val: E);
20230 ExprResult Sub = Rebuild(PE->getSubExpr());
20231 if (!Sub.isUsable())
20232 return Sub;
20233 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20234 }
20235
20236 // -- If e is a glvalue conditional expression, ...
20237 // We don't apply this to a binary conditional operator. FIXME: Should we?
20238 case Expr::ConditionalOperatorClass: {
20239 auto *CO = cast<ConditionalOperator>(Val: E);
20240 ExprResult LHS = Rebuild(CO->getLHS());
20241 if (LHS.isInvalid())
20242 return ExprError();
20243 ExprResult RHS = Rebuild(CO->getRHS());
20244 if (RHS.isInvalid())
20245 return ExprError();
20246 if (!LHS.isUsable() && !RHS.isUsable())
20247 return ExprEmpty();
20248 if (!LHS.isUsable())
20249 LHS = CO->getLHS();
20250 if (!RHS.isUsable())
20251 RHS = CO->getRHS();
20252 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20253 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20254 }
20255
20256 // [Clang extension]
20257 // -- If e has the form __extension__ e1...
20258 case Expr::UnaryOperatorClass: {
20259 auto *UO = cast<UnaryOperator>(Val: E);
20260 if (UO->getOpcode() != UO_Extension)
20261 break;
20262 ExprResult Sub = Rebuild(UO->getSubExpr());
20263 if (!Sub.isUsable())
20264 return Sub;
20265 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20266 Input: Sub.get());
20267 }
20268
20269 // [Clang extension]
20270 // -- If e has the form _Generic(...), the set of potential results is the
20271 // union of the sets of potential results of the associated expressions.
20272 case Expr::GenericSelectionExprClass: {
20273 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20274
20275 SmallVector<Expr *, 4> AssocExprs;
20276 bool AnyChanged = false;
20277 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20278 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20279 if (AssocExpr.isInvalid())
20280 return ExprError();
20281 if (AssocExpr.isUsable()) {
20282 AssocExprs.push_back(Elt: AssocExpr.get());
20283 AnyChanged = true;
20284 } else {
20285 AssocExprs.push_back(Elt: OrigAssocExpr);
20286 }
20287 }
20288
20289 void *ExOrTy = nullptr;
20290 bool IsExpr = GSE->isExprPredicate();
20291 if (IsExpr)
20292 ExOrTy = GSE->getControllingExpr();
20293 else
20294 ExOrTy = GSE->getControllingType();
20295 return AnyChanged ? S.CreateGenericSelectionExpr(
20296 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20297 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20298 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20299 : ExprEmpty();
20300 }
20301
20302 // [Clang extension]
20303 // -- If e has the form __builtin_choose_expr(...), the set of potential
20304 // results is the union of the sets of potential results of the
20305 // second and third subexpressions.
20306 case Expr::ChooseExprClass: {
20307 auto *CE = cast<ChooseExpr>(Val: E);
20308
20309 ExprResult LHS = Rebuild(CE->getLHS());
20310 if (LHS.isInvalid())
20311 return ExprError();
20312
20313 ExprResult RHS = Rebuild(CE->getLHS());
20314 if (RHS.isInvalid())
20315 return ExprError();
20316
20317 if (!LHS.get() && !RHS.get())
20318 return ExprEmpty();
20319 if (!LHS.isUsable())
20320 LHS = CE->getLHS();
20321 if (!RHS.isUsable())
20322 RHS = CE->getRHS();
20323
20324 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20325 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20326 }
20327
20328 // Step through non-syntactic nodes.
20329 case Expr::ConstantExprClass: {
20330 auto *CE = cast<ConstantExpr>(Val: E);
20331 ExprResult Sub = Rebuild(CE->getSubExpr());
20332 if (!Sub.isUsable())
20333 return Sub;
20334 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20335 }
20336
20337 // We could mostly rely on the recursive rebuilding to rebuild implicit
20338 // casts, but not at the top level, so rebuild them here.
20339 case Expr::ImplicitCastExprClass: {
20340 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20341 // Only step through the narrow set of cast kinds we expect to encounter.
20342 // Anything else suggests we've left the region in which potential results
20343 // can be found.
20344 switch (ICE->getCastKind()) {
20345 case CK_NoOp:
20346 case CK_DerivedToBase:
20347 case CK_UncheckedDerivedToBase: {
20348 ExprResult Sub = Rebuild(ICE->getSubExpr());
20349 if (!Sub.isUsable())
20350 return Sub;
20351 CXXCastPath Path(ICE->path());
20352 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20353 VK: ICE->getValueKind(), BasePath: &Path);
20354 }
20355
20356 default:
20357 break;
20358 }
20359 break;
20360 }
20361
20362 default:
20363 break;
20364 }
20365
20366 // Can't traverse through this node. Nothing to do.
20367 return ExprEmpty();
20368}
20369
20370ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20371 // Check whether the operand is or contains an object of non-trivial C union
20372 // type.
20373 if (E->getType().isVolatileQualified() &&
20374 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20375 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20376 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20377 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20378 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20379
20380 // C++2a [basic.def.odr]p4:
20381 // [...] an expression of non-volatile-qualified non-class type to which
20382 // the lvalue-to-rvalue conversion is applied [...]
20383 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20384 return E;
20385
20386 ExprResult Result =
20387 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20388 if (Result.isInvalid())
20389 return ExprError();
20390 return Result.get() ? Result : E;
20391}
20392
20393ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20394 if (!Res.isUsable())
20395 return Res;
20396
20397 // If a constant-expression is a reference to a variable where we delay
20398 // deciding whether it is an odr-use, just assume we will apply the
20399 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20400 // (a non-type template argument), we have special handling anyway.
20401 return CheckLValueToRValueConversionOperand(E: Res.get());
20402}
20403
20404void Sema::CleanupVarDeclMarking() {
20405 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20406 // call.
20407 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20408 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20409
20410 for (Expr *E : LocalMaybeODRUseExprs) {
20411 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20412 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20413 Loc: DRE->getLocation(), SemaRef&: *this);
20414 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20415 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20416 SemaRef&: *this);
20417 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20418 for (ValueDecl *VD : *FP)
20419 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20420 } else {
20421 llvm_unreachable("Unexpected expression");
20422 }
20423 }
20424
20425 assert(MaybeODRUseExprs.empty() &&
20426 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20427}
20428
20429static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20430 ValueDecl *Var, Expr *E) {
20431 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20432 if (!VD)
20433 return;
20434
20435 const bool RefersToEnclosingScope =
20436 (SemaRef.CurContext != VD->getDeclContext() &&
20437 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20438 if (RefersToEnclosingScope) {
20439 LambdaScopeInfo *const LSI =
20440 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20441 if (LSI && (!LSI->CallOperator ||
20442 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20443 // If a variable could potentially be odr-used, defer marking it so
20444 // until we finish analyzing the full expression for any
20445 // lvalue-to-rvalue
20446 // or discarded value conversions that would obviate odr-use.
20447 // Add it to the list of potential captures that will be analyzed
20448 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20449 // unless the variable is a reference that was initialized by a constant
20450 // expression (this will never need to be captured or odr-used).
20451 //
20452 // FIXME: We can simplify this a lot after implementing P0588R1.
20453 assert(E && "Capture variable should be used in an expression.");
20454 if (!Var->getType()->isReferenceType() ||
20455 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20456 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20457 }
20458 }
20459}
20460
20461static void DoMarkVarDeclReferenced(
20462 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20463 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20464 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20465 isa<FunctionParmPackExpr>(E)) &&
20466 "Invalid Expr argument to DoMarkVarDeclReferenced");
20467 Var->setReferenced();
20468
20469 if (Var->isInvalidDecl())
20470 return;
20471
20472 auto *MSI = Var->getMemberSpecializationInfo();
20473 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20474 : Var->getTemplateSpecializationKind();
20475
20476 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20477 bool UsableInConstantExpr =
20478 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20479
20480 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20481 RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++;
20482 }
20483
20484 // C++20 [expr.const]p12:
20485 // A variable [...] is needed for constant evaluation if it is [...] a
20486 // variable whose name appears as a potentially constant evaluated
20487 // expression that is either a contexpr variable or is of non-volatile
20488 // const-qualified integral type or of reference type
20489 bool NeededForConstantEvaluation =
20490 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20491
20492 bool NeedDefinition =
20493 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20494 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20495 Var->getType()->isUndeducedType());
20496
20497 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20498 "Can't instantiate a partial template specialization.");
20499
20500 // If this might be a member specialization of a static data member, check
20501 // the specialization is visible. We already did the checks for variable
20502 // template specializations when we created them.
20503 if (NeedDefinition && TSK != TSK_Undeclared &&
20504 !isa<VarTemplateSpecializationDecl>(Val: Var))
20505 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20506
20507 // Perform implicit instantiation of static data members, static data member
20508 // templates of class templates, and variable template specializations. Delay
20509 // instantiations of variable templates, except for those that could be used
20510 // in a constant expression.
20511 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20512 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20513 // instantiation declaration if a variable is usable in a constant
20514 // expression (among other cases).
20515 bool TryInstantiating =
20516 TSK == TSK_ImplicitInstantiation ||
20517 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20518
20519 if (TryInstantiating) {
20520 SourceLocation PointOfInstantiation =
20521 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20522 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20523 if (FirstInstantiation) {
20524 PointOfInstantiation = Loc;
20525 if (MSI)
20526 MSI->setPointOfInstantiation(PointOfInstantiation);
20527 // FIXME: Notify listener.
20528 else
20529 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20530 }
20531
20532 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20533 // Do not defer instantiations of variables that could be used in a
20534 // constant expression.
20535 // The type deduction also needs a complete initializer.
20536 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20537 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20538 });
20539
20540 // The size of an incomplete array type can be updated by
20541 // instantiating the initializer. The DeclRefExpr's type should be
20542 // updated accordingly too, or users of it would be confused!
20543 if (E)
20544 SemaRef.getCompletedType(E);
20545
20546 // Re-set the member to trigger a recomputation of the dependence bits
20547 // for the expression.
20548 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20549 DRE->setDecl(DRE->getDecl());
20550 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20551 ME->setMemberDecl(ME->getMemberDecl());
20552 } else if (FirstInstantiation) {
20553 SemaRef.PendingInstantiations
20554 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20555 } else {
20556 bool Inserted = false;
20557 for (auto &I : SemaRef.SavedPendingInstantiations) {
20558 auto Iter = llvm::find_if(
20559 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20560 return P.first == Var;
20561 });
20562 if (Iter != I.end()) {
20563 SemaRef.PendingInstantiations.push_back(x: *Iter);
20564 I.erase(position: Iter);
20565 Inserted = true;
20566 break;
20567 }
20568 }
20569
20570 // FIXME: For a specialization of a variable template, we don't
20571 // distinguish between "declaration and type implicitly instantiated"
20572 // and "implicit instantiation of definition requested", so we have
20573 // no direct way to avoid enqueueing the pending instantiation
20574 // multiple times.
20575 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20576 SemaRef.PendingInstantiations
20577 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20578 }
20579 }
20580 }
20581
20582 // C++2a [basic.def.odr]p4:
20583 // A variable x whose name appears as a potentially-evaluated expression e
20584 // is odr-used by e unless
20585 // -- x is a reference that is usable in constant expressions
20586 // -- x is a variable of non-reference type that is usable in constant
20587 // expressions and has no mutable subobjects [FIXME], and e is an
20588 // element of the set of potential results of an expression of
20589 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20590 // conversion is applied
20591 // -- x is a variable of non-reference type, and e is an element of the set
20592 // of potential results of a discarded-value expression to which the
20593 // lvalue-to-rvalue conversion is not applied [FIXME]
20594 //
20595 // We check the first part of the second bullet here, and
20596 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20597 // FIXME: To get the third bullet right, we need to delay this even for
20598 // variables that are not usable in constant expressions.
20599
20600 // If we already know this isn't an odr-use, there's nothing more to do.
20601 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20602 if (DRE->isNonOdrUse())
20603 return;
20604 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20605 if (ME->isNonOdrUse())
20606 return;
20607
20608 switch (OdrUse) {
20609 case OdrUseContext::None:
20610 // In some cases, a variable may not have been marked unevaluated, if it
20611 // appears in a defaukt initializer.
20612 assert((!E || isa<FunctionParmPackExpr>(E) ||
20613 SemaRef.isUnevaluatedContext()) &&
20614 "missing non-odr-use marking for unevaluated decl ref");
20615 break;
20616
20617 case OdrUseContext::FormallyOdrUsed:
20618 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20619 // behavior.
20620 break;
20621
20622 case OdrUseContext::Used:
20623 // If we might later find that this expression isn't actually an odr-use,
20624 // delay the marking.
20625 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20626 SemaRef.MaybeODRUseExprs.insert(X: E);
20627 else
20628 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20629 break;
20630
20631 case OdrUseContext::Dependent:
20632 // If this is a dependent context, we don't need to mark variables as
20633 // odr-used, but we may still need to track them for lambda capture.
20634 // FIXME: Do we also need to do this inside dependent typeid expressions
20635 // (which are modeled as unevaluated at this point)?
20636 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20637 break;
20638 }
20639}
20640
20641static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20642 BindingDecl *BD, Expr *E) {
20643 BD->setReferenced();
20644
20645 if (BD->isInvalidDecl())
20646 return;
20647
20648 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20649 if (OdrUse == OdrUseContext::Used) {
20650 QualType CaptureType, DeclRefType;
20651 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20652 /*EllipsisLoc*/ SourceLocation(),
20653 /*BuildAndDiagnose*/ true, CaptureType,
20654 DeclRefType,
20655 /*FunctionScopeIndexToStopAt*/ nullptr);
20656 } else if (OdrUse == OdrUseContext::Dependent) {
20657 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20658 }
20659}
20660
20661void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20662 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20663}
20664
20665// C++ [temp.dep.expr]p3:
20666// An id-expression is type-dependent if it contains:
20667// - an identifier associated by name lookup with an entity captured by copy
20668// in a lambda-expression that has an explicit object parameter whose type
20669// is dependent ([dcl.fct]),
20670static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20671 Sema &SemaRef, ValueDecl *D, Expr *E) {
20672 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20673 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20674 return;
20675
20676 // If any enclosing lambda with a dependent explicit object parameter either
20677 // explicitly captures the variable by value, or has a capture default of '='
20678 // and does not capture the variable by reference, then the type of the DRE
20679 // is dependent on the type of that lambda's explicit object parameter.
20680 auto IsDependent = [&]() {
20681 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20682 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20683 if (!LSI)
20684 continue;
20685
20686 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20687 LSI->AfterParameterList)
20688 return false;
20689
20690 const auto *MD = LSI->CallOperator;
20691 if (MD->getType().isNull())
20692 continue;
20693
20694 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20695 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20696 !Ty->getParamType(i: 0)->isDependentType())
20697 continue;
20698
20699 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20700 if (C->isCopyCapture())
20701 return true;
20702 continue;
20703 }
20704
20705 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20706 return true;
20707 }
20708 return false;
20709 }();
20710
20711 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20712 Set: IsDependent, Context: SemaRef.getASTContext());
20713}
20714
20715static void
20716MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20717 bool MightBeOdrUse,
20718 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20719 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20720 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20721
20722 if (SemaRef.getLangOpts().OpenACC)
20723 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20724
20725 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20726 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20727 if (SemaRef.getLangOpts().CPlusPlus)
20728 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20729 D: Var, E);
20730 return;
20731 }
20732
20733 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20734 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20735 if (SemaRef.getLangOpts().CPlusPlus)
20736 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20737 D: Decl, E);
20738 return;
20739 }
20740 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20741
20742 // If this is a call to a method via a cast, also mark the method in the
20743 // derived class used in case codegen can devirtualize the call.
20744 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20745 if (!ME)
20746 return;
20747 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20748 if (!MD)
20749 return;
20750 // Only attempt to devirtualize if this is truly a virtual call.
20751 bool IsVirtualCall = MD->isVirtual() &&
20752 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20753 if (!IsVirtualCall)
20754 return;
20755
20756 // If it's possible to devirtualize the call, mark the called function
20757 // referenced.
20758 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20759 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20760 if (DM)
20761 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20762}
20763
20764void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20765 // [basic.def.odr] (CWG 1614)
20766 // A function is named by an expression or conversion [...]
20767 // unless it is a pure virtual function and either the expression is not an
20768 // id-expression naming the function with an explicitly qualified name or
20769 // the expression forms a pointer to member
20770 bool OdrUse = true;
20771 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20772 if (Method->isVirtual() &&
20773 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20774 OdrUse = false;
20775
20776 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20777 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20778 !isImmediateFunctionContext() &&
20779 !isCheckingDefaultArgumentOrInitializer() &&
20780 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20781 !FD->isDependentContext())
20782 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20783 }
20784 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20785 RefsMinusAssignments);
20786}
20787
20788void Sema::MarkMemberReferenced(MemberExpr *E) {
20789 // C++11 [basic.def.odr]p2:
20790 // A non-overloaded function whose name appears as a potentially-evaluated
20791 // expression or a member of a set of candidate functions, if selected by
20792 // overload resolution when referred to from a potentially-evaluated
20793 // expression, is odr-used, unless it is a pure virtual function and its
20794 // name is not explicitly qualified.
20795 bool MightBeOdrUse = true;
20796 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20798 if (Method->isPureVirtual())
20799 MightBeOdrUse = false;
20800 }
20801 SourceLocation Loc =
20802 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20803 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20804 RefsMinusAssignments);
20805}
20806
20807void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20808 for (ValueDecl *VD : *E)
20809 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20810 RefsMinusAssignments);
20811}
20812
20813/// Perform marking for a reference to an arbitrary declaration. It
20814/// marks the declaration referenced, and performs odr-use checking for
20815/// functions and variables. This method should not be used when building a
20816/// normal expression which refers to a variable.
20817void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20818 bool MightBeOdrUse) {
20819 if (MightBeOdrUse) {
20820 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20821 MarkVariableReferenced(Loc, Var: VD);
20822 return;
20823 }
20824 }
20825 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20826 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20827 return;
20828 }
20829 D->setReferenced();
20830}
20831
20832namespace {
20833 // Mark all of the declarations used by a type as referenced.
20834 // FIXME: Not fully implemented yet! We need to have a better understanding
20835 // of when we're entering a context we should not recurse into.
20836 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20837 // TreeTransforms rebuilding the type in a new context. Rather than
20838 // duplicating the TreeTransform logic, we should consider reusing it here.
20839 // Currently that causes problems when rebuilding LambdaExprs.
20840class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20841 Sema &S;
20842 SourceLocation Loc;
20843
20844public:
20845 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20846
20847 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20848};
20849}
20850
20851bool MarkReferencedDecls::TraverseTemplateArgument(
20852 const TemplateArgument &Arg) {
20853 {
20854 // A non-type template argument is a constant-evaluated context.
20855 EnterExpressionEvaluationContext Evaluated(
20856 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20857 if (Arg.getKind() == TemplateArgument::Declaration) {
20858 if (Decl *D = Arg.getAsDecl())
20859 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20860 } else if (Arg.getKind() == TemplateArgument::Expression) {
20861 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20862 }
20863 }
20864
20865 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20866}
20867
20868void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20869 MarkReferencedDecls Marker(*this, Loc);
20870 Marker.TraverseType(T);
20871}
20872
20873namespace {
20874/// Helper class that marks all of the declarations referenced by
20875/// potentially-evaluated subexpressions as "referenced".
20876class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20877public:
20878 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20879 bool SkipLocalVariables;
20880 ArrayRef<const Expr *> StopAt;
20881
20882 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20883 ArrayRef<const Expr *> StopAt)
20884 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20885
20886 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20887 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20888 }
20889
20890 void Visit(Expr *E) {
20891 if (llvm::is_contained(Range&: StopAt, Element: E))
20892 return;
20893 Inherited::Visit(S: E);
20894 }
20895
20896 void VisitConstantExpr(ConstantExpr *E) {
20897 // Don't mark declarations within a ConstantExpression, as this expression
20898 // will be evaluated and folded to a value.
20899 }
20900
20901 void VisitDeclRefExpr(DeclRefExpr *E) {
20902 // If we were asked not to visit local variables, don't.
20903 if (SkipLocalVariables) {
20904 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
20905 if (VD->hasLocalStorage())
20906 return;
20907 }
20908
20909 // FIXME: This can trigger the instantiation of the initializer of a
20910 // variable, which can cause the expression to become value-dependent
20911 // or error-dependent. Do we need to propagate the new dependence bits?
20912 S.MarkDeclRefReferenced(E);
20913 }
20914
20915 void VisitMemberExpr(MemberExpr *E) {
20916 S.MarkMemberReferenced(E);
20917 Visit(E: E->getBase());
20918 }
20919};
20920} // namespace
20921
20922void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20923 bool SkipLocalVariables,
20924 ArrayRef<const Expr*> StopAt) {
20925 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20926}
20927
20928/// Emit a diagnostic when statements are reachable.
20929bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20930 const PartialDiagnostic &PD) {
20931 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20932 // The initializer of a constexpr variable or of the first declaration of a
20933 // static data member is not syntactically a constant evaluated constant,
20934 // but nonetheless is always required to be a constant expression, so we
20935 // can skip diagnosing.
20936 if (Decl &&
20937 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20938 Decl->isFirstDecl() && !Decl->isInline())))
20939 return false;
20940
20941 if (Stmts.empty()) {
20942 Diag(Loc, PD);
20943 return true;
20944 }
20945
20946 if (getCurFunction()) {
20947 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20948 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20949 return true;
20950 }
20951
20952 // For non-constexpr file-scope variables with reachability context (non-empty
20953 // Stmts), build a CFG for the initializer and check whether the context in
20954 // question is reachable.
20955 if (Decl && Decl->isFileVarDecl()) {
20956 AnalysisWarnings.registerVarDeclWarning(
20957 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20958 return true;
20959 }
20960
20961 Diag(Loc, PD);
20962 return true;
20963}
20964
20965/// Emit a diagnostic that describes an effect on the run-time behavior
20966/// of the program being compiled.
20967///
20968/// This routine emits the given diagnostic when the code currently being
20969/// type-checked is "potentially evaluated", meaning that there is a
20970/// possibility that the code will actually be executable. Code in sizeof()
20971/// expressions, code used only during overload resolution, etc., are not
20972/// potentially evaluated. This routine will suppress such diagnostics or,
20973/// in the absolutely nutty case of potentially potentially evaluated
20974/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20975/// later.
20976///
20977/// This routine should be used for all diagnostics that describe the run-time
20978/// behavior of a program, such as passing a non-POD value through an ellipsis.
20979/// Failure to do so will likely result in spurious diagnostics or failures
20980/// during overload resolution or within sizeof/alignof/typeof/typeid.
20981bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20982 const PartialDiagnostic &PD) {
20983
20984 if (ExprEvalContexts.back().isDiscardedStatementContext())
20985 return false;
20986
20987 switch (ExprEvalContexts.back().Context) {
20988 case ExpressionEvaluationContext::Unevaluated:
20989 case ExpressionEvaluationContext::UnevaluatedList:
20990 case ExpressionEvaluationContext::UnevaluatedAbstract:
20991 case ExpressionEvaluationContext::DiscardedStatement:
20992 // The argument will never be evaluated, so don't complain.
20993 break;
20994
20995 case ExpressionEvaluationContext::ConstantEvaluated:
20996 case ExpressionEvaluationContext::ImmediateFunctionContext:
20997 // Relevant diagnostics should be produced by constant evaluation.
20998 break;
20999
21000 case ExpressionEvaluationContext::PotentiallyEvaluated:
21001 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21002 return DiagIfReachable(Loc, Stmts, PD);
21003 }
21004
21005 return false;
21006}
21007
21008bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21009 const PartialDiagnostic &PD) {
21010 return DiagRuntimeBehavior(
21011 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21012 PD);
21013}
21014
21015bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21016 CallExpr *CE, FunctionDecl *FD) {
21017 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21018 return false;
21019
21020 // If we're inside a decltype's expression, don't check for a valid return
21021 // type or construct temporaries until we know whether this is the last call.
21022 if (ExprEvalContexts.back().ExprContext ==
21023 ExpressionEvaluationContextRecord::EK_Decltype) {
21024 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21025 return false;
21026 }
21027
21028 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21029 FunctionDecl *FD;
21030 CallExpr *CE;
21031
21032 public:
21033 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21034 : FD(FD), CE(CE) { }
21035
21036 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21037 if (!FD) {
21038 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21039 << T << CE->getSourceRange();
21040 return;
21041 }
21042
21043 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21044 << CE->getSourceRange() << FD << T;
21045 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21046 << FD->getDeclName();
21047 }
21048 } Diagnoser(FD, CE);
21049
21050 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21051 return true;
21052
21053 return false;
21054}
21055
21056// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21057// will prevent this condition from triggering, which is what we want.
21058void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21059 SourceLocation Loc;
21060
21061 unsigned diagnostic = diag::warn_condition_is_assignment;
21062 bool IsOrAssign = false;
21063
21064 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21065 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21066 return;
21067
21068 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21069
21070 // Greylist some idioms by putting them into a warning subcategory.
21071 if (ObjCMessageExpr *ME
21072 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21073 Selector Sel = ME->getSelector();
21074
21075 // self = [<foo> init...]
21076 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21077 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21078
21079 // <foo> = [<bar> nextObject]
21080 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21081 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21082 }
21083
21084 Loc = Op->getOperatorLoc();
21085 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21086 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21087 return;
21088
21089 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21090 Loc = Op->getOperatorLoc();
21091 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21092 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21093 else {
21094 // Not an assignment.
21095 return;
21096 }
21097
21098 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21099
21100 SourceLocation Open = E->getBeginLoc();
21101 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21102 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21103 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21104 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21105
21106 if (IsOrAssign)
21107 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21108 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21109 else
21110 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21111 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21112}
21113
21114void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21115 // Don't warn if the parens came from a macro.
21116 SourceLocation parenLoc = ParenE->getBeginLoc();
21117 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21118 return;
21119 // Don't warn for dependent expressions.
21120 if (ParenE->isTypeDependent())
21121 return;
21122
21123 Expr *E = ParenE->IgnoreParens();
21124 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21125 return;
21126
21127 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21128 if (opE->getOpcode() == BO_EQ &&
21129 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21130 == Expr::MLV_Valid) {
21131 SourceLocation Loc = opE->getOperatorLoc();
21132
21133 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21134 SourceRange ParenERange = ParenE->getSourceRange();
21135 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21136 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21137 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21138 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21139 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21140 }
21141}
21142
21143ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21144 bool IsConstexpr) {
21145 DiagnoseAssignmentAsCondition(E);
21146 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21147 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21148
21149 ExprResult result = CheckPlaceholderExpr(E);
21150 if (result.isInvalid()) return ExprError();
21151 E = result.get();
21152
21153 if (!E->isTypeDependent()) {
21154 if (getLangOpts().CPlusPlus)
21155 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21156
21157 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21158 if (ERes.isInvalid())
21159 return ExprError();
21160 E = ERes.get();
21161
21162 QualType T = E->getType();
21163 if (!T->isScalarType()) { // C99 6.8.4.1p1
21164 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21165 << T << E->getSourceRange();
21166 return ExprError();
21167 }
21168 CheckBoolLikeConversion(E, CC: Loc);
21169 }
21170
21171 return E;
21172}
21173
21174Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21175 Expr *SubExpr, ConditionKind CK,
21176 bool MissingOK) {
21177 // MissingOK indicates whether having no condition expression is valid
21178 // (for loop) or invalid (e.g. while loop).
21179 if (!SubExpr)
21180 return MissingOK ? ConditionResult() : ConditionError();
21181
21182 ExprResult Cond;
21183 switch (CK) {
21184 case ConditionKind::Boolean:
21185 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21186 break;
21187
21188 case ConditionKind::ConstexprIf:
21189 // Note: this might produce a FullExpr
21190 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21191 break;
21192
21193 case ConditionKind::Switch:
21194 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21195 break;
21196 }
21197 if (Cond.isInvalid()) {
21198 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21199 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21200 if (!Cond.get())
21201 return ConditionError();
21202 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21203 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21204
21205 if (!Cond.isUsable())
21206 return ConditionError();
21207
21208 return ConditionResult(*this, nullptr, Cond,
21209 CK == ConditionKind::ConstexprIf);
21210}
21211
21212namespace {
21213 /// A visitor for rebuilding a call to an __unknown_any expression
21214 /// to have an appropriate type.
21215 struct RebuildUnknownAnyFunction
21216 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21217
21218 Sema &S;
21219
21220 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21221
21222 ExprResult VisitStmt(Stmt *S) {
21223 llvm_unreachable("unexpected statement!");
21224 }
21225
21226 ExprResult VisitExpr(Expr *E) {
21227 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21228 << E->getSourceRange();
21229 return ExprError();
21230 }
21231
21232 /// Rebuild an expression which simply semantically wraps another
21233 /// expression which it shares the type and value kind of.
21234 template <class T> ExprResult rebuildSugarExpr(T *E) {
21235 ExprResult SubResult = Visit(S: E->getSubExpr());
21236 if (SubResult.isInvalid()) return ExprError();
21237
21238 Expr *SubExpr = SubResult.get();
21239 E->setSubExpr(SubExpr);
21240 E->setType(SubExpr->getType());
21241 E->setValueKind(SubExpr->getValueKind());
21242 assert(E->getObjectKind() == OK_Ordinary);
21243 return E;
21244 }
21245
21246 ExprResult VisitParenExpr(ParenExpr *E) {
21247 return rebuildSugarExpr(E);
21248 }
21249
21250 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21251 return rebuildSugarExpr(E);
21252 }
21253
21254 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21255 ExprResult SubResult = Visit(S: E->getSubExpr());
21256 if (SubResult.isInvalid()) return ExprError();
21257
21258 Expr *SubExpr = SubResult.get();
21259 E->setSubExpr(SubExpr);
21260 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21261 assert(E->isPRValue());
21262 assert(E->getObjectKind() == OK_Ordinary);
21263 return E;
21264 }
21265
21266 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21267 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21268
21269 E->setType(VD->getType());
21270
21271 assert(E->isPRValue());
21272 if (S.getLangOpts().CPlusPlus &&
21273 !(isa<CXXMethodDecl>(Val: VD) &&
21274 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21275 E->setValueKind(VK_LValue);
21276
21277 return E;
21278 }
21279
21280 ExprResult VisitMemberExpr(MemberExpr *E) {
21281 return resolveDecl(E, VD: E->getMemberDecl());
21282 }
21283
21284 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21285 return resolveDecl(E, VD: E->getDecl());
21286 }
21287 };
21288}
21289
21290/// Given a function expression of unknown-any type, try to rebuild it
21291/// to have a function type.
21292static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21293 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21294 if (Result.isInvalid()) return ExprError();
21295 return S.DefaultFunctionArrayConversion(E: Result.get());
21296}
21297
21298namespace {
21299 /// A visitor for rebuilding an expression of type __unknown_anytype
21300 /// into one which resolves the type directly on the referring
21301 /// expression. Strict preservation of the original source
21302 /// structure is not a goal.
21303 struct RebuildUnknownAnyExpr
21304 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21305
21306 Sema &S;
21307
21308 /// The current destination type.
21309 QualType DestType;
21310
21311 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21312 : S(S), DestType(CastType) {}
21313
21314 ExprResult VisitStmt(Stmt *S) {
21315 llvm_unreachable("unexpected statement!");
21316 }
21317
21318 ExprResult VisitExpr(Expr *E) {
21319 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21320 << E->getSourceRange();
21321 return ExprError();
21322 }
21323
21324 ExprResult VisitCallExpr(CallExpr *E);
21325 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21326
21327 /// Rebuild an expression which simply semantically wraps another
21328 /// expression which it shares the type and value kind of.
21329 template <class T> ExprResult rebuildSugarExpr(T *E) {
21330 ExprResult SubResult = Visit(S: E->getSubExpr());
21331 if (SubResult.isInvalid()) return ExprError();
21332 Expr *SubExpr = SubResult.get();
21333 E->setSubExpr(SubExpr);
21334 E->setType(SubExpr->getType());
21335 E->setValueKind(SubExpr->getValueKind());
21336 assert(E->getObjectKind() == OK_Ordinary);
21337 return E;
21338 }
21339
21340 ExprResult VisitParenExpr(ParenExpr *E) {
21341 return rebuildSugarExpr(E);
21342 }
21343
21344 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21345 return rebuildSugarExpr(E);
21346 }
21347
21348 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21349 const PointerType *Ptr = DestType->getAs<PointerType>();
21350 if (!Ptr) {
21351 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21352 << E->getSourceRange();
21353 return ExprError();
21354 }
21355
21356 if (isa<CallExpr>(Val: E->getSubExpr())) {
21357 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21358 << E->getSourceRange();
21359 return ExprError();
21360 }
21361
21362 assert(E->isPRValue());
21363 assert(E->getObjectKind() == OK_Ordinary);
21364 E->setType(DestType);
21365
21366 // Build the sub-expression as if it were an object of the pointee type.
21367 DestType = Ptr->getPointeeType();
21368 ExprResult SubResult = Visit(S: E->getSubExpr());
21369 if (SubResult.isInvalid()) return ExprError();
21370 E->setSubExpr(SubResult.get());
21371 return E;
21372 }
21373
21374 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21375
21376 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21377
21378 ExprResult VisitMemberExpr(MemberExpr *E) {
21379 return resolveDecl(E, VD: E->getMemberDecl());
21380 }
21381
21382 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21383 return resolveDecl(E, VD: E->getDecl());
21384 }
21385 };
21386}
21387
21388/// Rebuilds a call expression which yielded __unknown_anytype.
21389ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21390 Expr *CalleeExpr = E->getCallee();
21391
21392 enum FnKind {
21393 FK_MemberFunction,
21394 FK_FunctionPointer,
21395 FK_BlockPointer
21396 };
21397
21398 FnKind Kind;
21399 QualType CalleeType = CalleeExpr->getType();
21400 if (CalleeType == S.Context.BoundMemberTy) {
21401 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21402 Kind = FK_MemberFunction;
21403 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21404 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21405 CalleeType = Ptr->getPointeeType();
21406 Kind = FK_FunctionPointer;
21407 } else {
21408 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21409 Kind = FK_BlockPointer;
21410 }
21411 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21412
21413 // Verify that this is a legal result type of a function.
21414 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21415 DestType->isFunctionType()) {
21416 unsigned diagID = diag::err_func_returning_array_function;
21417 if (Kind == FK_BlockPointer)
21418 diagID = diag::err_block_returning_array_function;
21419
21420 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21421 << DestType->isFunctionType() << DestType;
21422 return ExprError();
21423 }
21424
21425 // Otherwise, go ahead and set DestType as the call's result.
21426 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21427 E->setValueKind(Expr::getValueKindForType(T: DestType));
21428 assert(E->getObjectKind() == OK_Ordinary);
21429
21430 // Rebuild the function type, replacing the result type with DestType.
21431 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21432 if (Proto) {
21433 // __unknown_anytype(...) is a special case used by the debugger when
21434 // it has no idea what a function's signature is.
21435 //
21436 // We want to build this call essentially under the K&R
21437 // unprototyped rules, but making a FunctionNoProtoType in C++
21438 // would foul up all sorts of assumptions. However, we cannot
21439 // simply pass all arguments as variadic arguments, nor can we
21440 // portably just call the function under a non-variadic type; see
21441 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21442 // However, it turns out that in practice it is generally safe to
21443 // call a function declared as "A foo(B,C,D);" under the prototype
21444 // "A foo(B,C,D,...);". The only known exception is with the
21445 // Windows ABI, where any variadic function is implicitly cdecl
21446 // regardless of its normal CC. Therefore we change the parameter
21447 // types to match the types of the arguments.
21448 //
21449 // This is a hack, but it is far superior to moving the
21450 // corresponding target-specific code from IR-gen to Sema/AST.
21451
21452 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21453 SmallVector<QualType, 8> ArgTypes;
21454 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21455 ArgTypes.reserve(N: E->getNumArgs());
21456 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21457 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21458 }
21459 ParamTypes = ArgTypes;
21460 }
21461 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21462 EPI: Proto->getExtProtoInfo());
21463 } else {
21464 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21465 Info: FnType->getExtInfo());
21466 }
21467
21468 // Rebuild the appropriate pointer-to-function type.
21469 switch (Kind) {
21470 case FK_MemberFunction:
21471 // Nothing to do.
21472 break;
21473
21474 case FK_FunctionPointer:
21475 DestType = S.Context.getPointerType(T: DestType);
21476 break;
21477
21478 case FK_BlockPointer:
21479 DestType = S.Context.getBlockPointerType(T: DestType);
21480 break;
21481 }
21482
21483 // Finally, we can recurse.
21484 ExprResult CalleeResult = Visit(S: CalleeExpr);
21485 if (!CalleeResult.isUsable()) return ExprError();
21486 E->setCallee(CalleeResult.get());
21487
21488 // Bind a temporary if necessary.
21489 return S.MaybeBindToTemporary(E);
21490}
21491
21492ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21493 // Verify that this is a legal result type of a call.
21494 if (DestType->isArrayType() || DestType->isFunctionType()) {
21495 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21496 << DestType->isFunctionType() << DestType;
21497 return ExprError();
21498 }
21499
21500 // Rewrite the method result type if available.
21501 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21502 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21503 Method->setReturnType(DestType);
21504 }
21505
21506 // Change the type of the message.
21507 E->setType(DestType.getNonReferenceType());
21508 E->setValueKind(Expr::getValueKindForType(T: DestType));
21509
21510 return S.MaybeBindToTemporary(E);
21511}
21512
21513ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21514 // The only case we should ever see here is a function-to-pointer decay.
21515 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21516 assert(E->isPRValue());
21517 assert(E->getObjectKind() == OK_Ordinary);
21518
21519 E->setType(DestType);
21520
21521 // Rebuild the sub-expression as the pointee (function) type.
21522 DestType = DestType->castAs<PointerType>()->getPointeeType();
21523
21524 ExprResult Result = Visit(S: E->getSubExpr());
21525 if (!Result.isUsable()) return ExprError();
21526
21527 E->setSubExpr(Result.get());
21528 return E;
21529 } else if (E->getCastKind() == CK_LValueToRValue) {
21530 assert(E->isPRValue());
21531 assert(E->getObjectKind() == OK_Ordinary);
21532
21533 assert(isa<BlockPointerType>(E->getType()));
21534
21535 E->setType(DestType);
21536
21537 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21538 DestType = S.Context.getLValueReferenceType(T: DestType);
21539
21540 ExprResult Result = Visit(S: E->getSubExpr());
21541 if (!Result.isUsable()) return ExprError();
21542
21543 E->setSubExpr(Result.get());
21544 return E;
21545 } else {
21546 llvm_unreachable("Unhandled cast type!");
21547 }
21548}
21549
21550ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21551 ExprValueKind ValueKind = VK_LValue;
21552 QualType Type = DestType;
21553
21554 // We know how to make this work for certain kinds of decls:
21555
21556 // - functions
21557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21558 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21559 DestType = Ptr->getPointeeType();
21560 ExprResult Result = resolveDecl(E, VD);
21561 if (Result.isInvalid()) return ExprError();
21562 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21563 VK: VK_PRValue);
21564 }
21565
21566 if (!Type->isFunctionType()) {
21567 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21568 << VD << E->getSourceRange();
21569 return ExprError();
21570 }
21571 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21572 // We must match the FunctionDecl's type to the hack introduced in
21573 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21574 // type. See the lengthy commentary in that routine.
21575 QualType FDT = FD->getType();
21576 const FunctionType *FnType = FDT->castAs<FunctionType>();
21577 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21578 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21579 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21580 SourceLocation Loc = FD->getLocation();
21581 FunctionDecl *NewFD = FunctionDecl::Create(
21582 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21583 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21584 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21585 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21586 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21587
21588 if (FD->getQualifier())
21589 NewFD->setQualifierInfo(FD->getQualifierLoc());
21590
21591 SmallVector<ParmVarDecl*, 16> Params;
21592 for (const auto &AI : FT->param_types()) {
21593 ParmVarDecl *Param =
21594 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21595 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21596 Params.push_back(Elt: Param);
21597 }
21598 NewFD->setParams(Params);
21599 DRE->setDecl(NewFD);
21600 VD = DRE->getDecl();
21601 }
21602 }
21603
21604 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21605 if (MD->isInstance()) {
21606 ValueKind = VK_PRValue;
21607 Type = S.Context.BoundMemberTy;
21608 }
21609
21610 // Function references aren't l-values in C.
21611 if (!S.getLangOpts().CPlusPlus)
21612 ValueKind = VK_PRValue;
21613
21614 // - variables
21615 } else if (isa<VarDecl>(Val: VD)) {
21616 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21617 Type = RefTy->getPointeeType();
21618 } else if (Type->isFunctionType()) {
21619 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21620 << VD << E->getSourceRange();
21621 return ExprError();
21622 }
21623
21624 // - nothing else
21625 } else {
21626 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21627 << VD << E->getSourceRange();
21628 return ExprError();
21629 }
21630
21631 // Modifying the declaration like this is friendly to IR-gen but
21632 // also really dangerous.
21633 VD->setType(DestType);
21634 E->setType(Type);
21635 E->setValueKind(ValueKind);
21636 return E;
21637}
21638
21639ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21640 Expr *CastExpr, CastKind &CastKind,
21641 ExprValueKind &VK, CXXCastPath &Path) {
21642 // The type we're casting to must be either void or complete.
21643 if (!CastType->isVoidType() &&
21644 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21645 DiagID: diag::err_typecheck_cast_to_incomplete))
21646 return ExprError();
21647
21648 // Rewrite the casted expression from scratch.
21649 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21650 if (!result.isUsable()) return ExprError();
21651
21652 CastExpr = result.get();
21653 VK = CastExpr->getValueKind();
21654 CastKind = CK_NoOp;
21655
21656 return CastExpr;
21657}
21658
21659ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21660 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21661}
21662
21663ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21664 Expr *arg, QualType &paramType) {
21665 // If the syntactic form of the argument is not an explicit cast of
21666 // any sort, just do default argument promotion.
21667 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21668 if (!castArg) {
21669 ExprResult result = DefaultArgumentPromotion(E: arg);
21670 if (result.isInvalid()) return ExprError();
21671 paramType = result.get()->getType();
21672 return result;
21673 }
21674
21675 // Otherwise, use the type that was written in the explicit cast.
21676 assert(!arg->hasPlaceholderType());
21677 paramType = castArg->getTypeAsWritten();
21678
21679 // Copy-initialize a parameter of that type.
21680 InitializedEntity entity =
21681 InitializedEntity::InitializeParameter(Context, Type: paramType,
21682 /*consumed*/ Consumed: false);
21683 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21684}
21685
21686static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21687 Expr *orig = E;
21688 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21689 while (true) {
21690 E = E->IgnoreParenImpCasts();
21691 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21692 E = call->getCallee();
21693 diagID = diag::err_uncasted_call_of_unknown_any;
21694 } else {
21695 break;
21696 }
21697 }
21698
21699 SourceLocation loc;
21700 NamedDecl *d;
21701 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21702 loc = ref->getLocation();
21703 d = ref->getDecl();
21704 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21705 loc = mem->getMemberLoc();
21706 d = mem->getMemberDecl();
21707 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21708 diagID = diag::err_uncasted_call_of_unknown_any;
21709 loc = msg->getSelectorStartLoc();
21710 d = msg->getMethodDecl();
21711 if (!d) {
21712 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21713 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21714 << orig->getSourceRange();
21715 return ExprError();
21716 }
21717 } else {
21718 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21719 << E->getSourceRange();
21720 return ExprError();
21721 }
21722
21723 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21724
21725 // Never recoverable.
21726 return ExprError();
21727}
21728
21729ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21730 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21731 if (!placeholderType) return E;
21732
21733 switch (placeholderType->getKind()) {
21734 case BuiltinType::UnresolvedTemplate: {
21735 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
21736 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21737 // There's only one FoundDecl for UnresolvedTemplate type. See
21738 // BuildTemplateIdExpr.
21739 NamedDecl *Temp = *ULE->decls_begin();
21740 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21741
21742 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21743 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21744 // as it models only the unqualified-id case, where this case can clearly be
21745 // qualified. Thus we can't just qualify an assumed template.
21746 TemplateName TN;
21747 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21748 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21749 Template: TemplateName(TD));
21750 else
21751 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21752
21753 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21754 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21755 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21756 << IsTypeAliasTemplateDecl;
21757
21758 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21759 bool HasAnyDependentTA = false;
21760 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21761 HasAnyDependentTA |= Arg.getArgument().isDependent();
21762 TAL.addArgument(Loc: Arg);
21763 }
21764
21765 QualType TST;
21766 {
21767 SFINAETrap Trap(*this);
21768 TST = CheckTemplateIdType(
21769 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21770 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21771 }
21772 if (TST.isNull())
21773 TST = Context.getTemplateSpecializationType(
21774 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21775 /*CanonicalArgs=*/{},
21776 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21777 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21778 T: TST);
21779 }
21780
21781 // Overloaded expressions.
21782 case BuiltinType::Overload: {
21783 // Try to resolve a single function template specialization.
21784 // This is obligatory.
21785 ExprResult Result = E;
21786 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21787 return Result;
21788
21789 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21790 // leaves Result unchanged on failure.
21791 Result = E;
21792 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21793 return Result;
21794
21795 // If that failed, try to recover with a call.
21796 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21797 /*complain*/ ForceComplain: true);
21798 return Result;
21799 }
21800
21801 // Bound member functions.
21802 case BuiltinType::BoundMember: {
21803 ExprResult result = E;
21804 const Expr *BME = E->IgnoreParens();
21805 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21806 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21807 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21808 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21809 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21810 if (ME->getMemberNameInfo().getName().getNameKind() ==
21811 DeclarationName::CXXDestructorName)
21812 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21813 }
21814 tryToRecoverWithCall(E&: result, PD,
21815 /*complain*/ ForceComplain: true);
21816 return result;
21817 }
21818
21819 // ARC unbridged casts.
21820 case BuiltinType::ARCUnbridgedCast: {
21821 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
21822 ObjC().diagnoseARCUnbridgedCast(e: realCast);
21823 return realCast;
21824 }
21825
21826 // Expressions of unknown type.
21827 case BuiltinType::UnknownAny:
21828 return diagnoseUnknownAnyExpr(S&: *this, E);
21829
21830 // Pseudo-objects.
21831 case BuiltinType::PseudoObject:
21832 return PseudoObject().checkRValue(E);
21833
21834 case BuiltinType::BuiltinFn: {
21835 // Accept __noop without parens by implicitly converting it to a call expr.
21836 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21837 if (DRE) {
21838 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21839 unsigned BuiltinID = FD->getBuiltinID();
21840 if (BuiltinID == Builtin::BI__noop) {
21841 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
21842 CK: CK_BuiltinFnToFnPtr)
21843 .get();
21844 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21845 VK: VK_PRValue, RParenLoc: SourceLocation(),
21846 FPFeatures: FPOptionsOverride());
21847 }
21848
21849 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21850 // Any use of these other than a direct call is ill-formed as of C++20,
21851 // because they are not addressable functions. In earlier language
21852 // modes, warn and force an instantiation of the real body.
21853 Diag(Loc: E->getBeginLoc(),
21854 DiagID: getLangOpts().CPlusPlus20
21855 ? diag::err_use_of_unaddressable_function
21856 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21857 if (FD->isImplicitlyInstantiable()) {
21858 // Require a definition here because a normal attempt at
21859 // instantiation for a builtin will be ignored, and we won't try
21860 // again later. We assume that the definition of the template
21861 // precedes this use.
21862 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21863 /*Recursive=*/false,
21864 /*DefinitionRequired=*/true,
21865 /*AtEndOfTU=*/false);
21866 }
21867 // Produce a properly-typed reference to the function.
21868 CXXScopeSpec SS;
21869 SS.Adopt(Other: DRE->getQualifierLoc());
21870 TemplateArgumentListInfo TemplateArgs;
21871 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
21872 return BuildDeclRefExpr(
21873 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
21874 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
21875 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
21876 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21877 }
21878 }
21879
21880 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
21881 return ExprError();
21882 }
21883
21884 case BuiltinType::IncompleteMatrixIdx: {
21885 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
21886 // At this point, we know there was no second [] to complete the operator.
21887 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21888 if (getLangOpts().HLSL) {
21889 return CreateBuiltinMatrixSingleSubscriptExpr(
21890 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
21891 }
21892 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
21893 return ExprError();
21894 }
21895
21896 // Expressions of unknown type.
21897 case BuiltinType::ArraySection:
21898 // If we've already diagnosed something on the array section type, we
21899 // shouldn't need to do any further diagnostic here.
21900 if (!E->containsErrors())
21901 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
21902 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
21903 return ExprError();
21904
21905 // Expressions of unknown type.
21906 case BuiltinType::OMPArrayShaping:
21907 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
21908
21909 case BuiltinType::OMPIterator:
21910 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
21911
21912 // Everything else should be impossible.
21913#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21914 case BuiltinType::Id:
21915#include "clang/Basic/OpenCLImageTypes.def"
21916#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21917 case BuiltinType::Id:
21918#include "clang/Basic/OpenCLExtensionTypes.def"
21919#define SVE_TYPE(Name, Id, SingletonId) \
21920 case BuiltinType::Id:
21921#include "clang/Basic/AArch64ACLETypes.def"
21922#define PPC_VECTOR_TYPE(Name, Id, Size) \
21923 case BuiltinType::Id:
21924#include "clang/Basic/PPCTypes.def"
21925#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21926#include "clang/Basic/RISCVVTypes.def"
21927#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21928#include "clang/Basic/WebAssemblyReferenceTypes.def"
21929#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21930#include "clang/Basic/AMDGPUTypes.def"
21931#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21932#include "clang/Basic/HLSLIntangibleTypes.def"
21933#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21934#define PLACEHOLDER_TYPE(Id, SingletonId)
21935#include "clang/AST/BuiltinTypes.def"
21936 break;
21937 }
21938
21939 llvm_unreachable("invalid placeholder type!");
21940}
21941
21942bool Sema::CheckCaseExpression(Expr *E) {
21943 if (E->isTypeDependent())
21944 return true;
21945 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
21946 return E->getType()->isIntegralOrEnumerationType();
21947 return false;
21948}
21949
21950ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21951 ArrayRef<Expr *> SubExprs, QualType T) {
21952 if (!Context.getLangOpts().RecoveryAST)
21953 return ExprError();
21954
21955 if (isSFINAEContext())
21956 return ExprError();
21957
21958 if (T.isNull() || T->isUndeducedType() ||
21959 !Context.getLangOpts().RecoveryASTType)
21960 // We don't know the concrete type, fallback to dependent type.
21961 T = Context.DependentTy;
21962
21963 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
21964}
21965