Debian Codegraph @

clang/lib/Sema/SemaExpr.cpp

raw
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/Attrs.inc"
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/Type.h"
34 #include "clang/AST/TypeLoc.h"
35 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/DiagnosticSema.h"
37 #include "clang/Basic/PartialDiagnostic.h"
38 #include "clang/Basic/SourceManager.h"
39 #include "clang/Basic/Specifiers.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/TypeTraits.h"
42 #include "clang/Lex/LiteralSupport.h"
43 #include "clang/Lex/Preprocessor.h"
44 #include "clang/Sema/AnalysisBasedWarnings.h"
45 #include "clang/Sema/DeclSpec.h"
46 #include "clang/Sema/DelayedDiagnostic.h"
47 #include "clang/Sema/Designator.h"
48 #include "clang/Sema/EnterExpressionEvaluationContext.h"
49 #include "clang/Sema/Initialization.h"
50 #include "clang/Sema/Lookup.h"
51 #include "clang/Sema/Overload.h"
52 #include "clang/Sema/ParsedTemplate.h"
53 #include "clang/Sema/Scope.h"
54 #include "clang/Sema/ScopeInfo.h"
55 #include "clang/Sema/SemaARM.h"
56 #include "clang/Sema/SemaCUDA.h"
57 #include "clang/Sema/SemaFixItUtils.h"
58 #include "clang/Sema/SemaHLSL.h"
59 #include "clang/Sema/SemaObjC.h"
60 #include "clang/Sema/SemaOpenMP.h"
61 #include "clang/Sema/SemaPseudoObject.h"
62 #include "clang/Sema/Template.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/StringExtras.h"
65 #include "llvm/Support/ConvertUTF.h"
66 #include "llvm/Support/SaveAndRestore.h"
67 #include "llvm/Support/TimeProfiler.h"
68 #include "llvm/Support/TypeSize.h"
69 #include <limits>
70 #include <optional>
71
72 using namespace clang;
73 using namespace sema;
74
75 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
76 // See if this is an auto-typed variable whose initializer we are parsing.
77 if (ParsingInitForAutoVars.count(D))
78 return false;
79
80 // See if this is a deleted function.
81 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
82 if (FD->isDeleted())
83 return false;
84
85 // If the function has a deduced return type, and we can't deduce it,
86 // then we can't use it either.
87 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
88 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
89 return false;
90
91 // See if this is an aligned allocation/deallocation function that is
92 // unavailable.
93 if (TreatUnavailableAsInvalid &&
94 isUnavailableAlignedAllocationFunction(*FD))
95 return false;
96 }
97
98 // See if this function is unavailable.
99 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
100 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
101 return false;
102
103 if (isa<UnresolvedUsingIfExistsDecl>(D))
104 return false;
105
106 return true;
107 }
108
109 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
110 // Warn if this is used but marked unused.
111 if (const auto *A = D->getAttr<UnusedAttr>()) {
112 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
113 // should diagnose them.
114 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
115 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
116 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
117 if (DC && !DC->hasAttr<UnusedAttr>())
118 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
119 }
120 }
121 }
122
123 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
124 assert(Decl && Decl->isDeleted());
125
126 if (Decl->isDefaulted()) {
127 // If the method was explicitly defaulted, point at that declaration.
128 if (!Decl->isImplicit())
129 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
130
131 // Try to diagnose why this special member function was implicitly
132 // deleted. This might fail, if that reason no longer applies.
133 DiagnoseDeletedDefaultedFunction(Decl);
134 return;
135 }
136
137 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
138 if (Ctor && Ctor->isInheritingConstructor())
139 return NoteDeletedInheritingConstructor(Ctor);
140
141 Diag(Decl->getLocation(), diag::note_availability_specified_here)
142 << Decl << 1;
143 }
144
145 /// Determine whether a FunctionDecl was ever declared with an
146 /// explicit storage class.
147 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
148 for (auto *I : D->redecls()) {
149 if (I->getStorageClass() != SC_None)
150 return true;
151 }
152 return false;
153 }
154
155 /// Check whether we're in an extern inline function and referring to a
156 /// variable or function with internal linkage (C11 6.7.4p3).
157 ///
158 /// This is only a warning because we used to silently accept this code, but
159 /// in many cases it will not behave correctly. This is not enabled in C++ mode
160 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
161 /// and so while there may still be user mistakes, most of the time we can't
162 /// prove that there are errors.
163 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
164 const NamedDecl *D,
165 SourceLocation Loc) {
166 // This is disabled under C++; there are too many ways for this to fire in
167 // contexts where the warning is a false positive, or where it is technically
168 // correct but benign.
169 //
170 // WG14 N3622 which removed the constraint entirely in C2y. It is left
171 // enabled in earlier language modes because this is a constraint in those
172 // language modes. But in C2y mode, we still want to issue the "incompatible
173 // with previous standards" diagnostic, too.
174 if (S.getLangOpts().CPlusPlus)
175 return;
176
177 // Check if this is an inlined function or method.
178 FunctionDecl *Current = S.getCurFunctionDecl();
179 if (!Current)
180 return;
181 if (!Current->isInlined())
182 return;
183 if (!Current->isExternallyVisible())
184 return;
185
186 // Check if the decl has internal linkage.
187 if (D->getFormalLinkage() != Linkage::Internal)
188 return;
189
190 // Downgrade from ExtWarn to Extension if
191 // (1) the supposedly external inline function is in the main file,
192 // and probably won't be included anywhere else.
193 // (2) the thing we're referencing is a pure function.
194 // (3) the thing we're referencing is another inline function.
195 // This last can give us false negatives, but it's better than warning on
196 // wrappers for simple C library functions.
197 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
198 unsigned DiagID;
199 if (S.getLangOpts().C2y)
200 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
201 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
202 S.getSourceManager().isInMainFile(Loc))
203 DiagID = diag::ext_internal_in_extern_inline_quiet;
204 else
205 DiagID = diag::ext_internal_in_extern_inline;
206
207 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
208 S.MaybeSuggestAddingStaticToDecl(Current);
209 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
210 << D;
211 }
212
213 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
214 const FunctionDecl *First = Cur->getFirstDecl();
215
216 // Suggest "static" on the function, if possible.
217 if (!hasAnyExplicitStorageClass(First)) {
218 SourceLocation DeclBegin = First->getSourceRange().getBegin();
219 Diag(DeclBegin, diag::note_convert_inline_to_static)
220 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
221 }
222 }
223
224 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
225 const ObjCInterfaceDecl *UnknownObjCClass,
226 bool ObjCPropertyAccess,
227 bool AvoidPartialAvailabilityChecks,
228 ObjCInterfaceDecl *ClassReceiver,
229 bool SkipTrailingRequiresClause) {
230 SourceLocation Loc = Locs.front();
231 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
232 // If there were any diagnostics suppressed by template argument deduction,
233 // emit them now.
234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
236 for (const auto &[DiagLoc, PD] : Pos->second) {
237 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
238 PD.Emit(Builder);
239 }
240 // Clear out the list of suppressed diagnostics, so that we don't emit
241 // them again for this specialization. However, we don't obsolete this
242 // entry from the table, because we want to avoid ever emitting these
243 // diagnostics again.
244 Pos->second.clear();
245 }
246
247 // C++ [basic.start.main]p3:
248 // The function 'main' shall not be used within a program.
249 if (cast<FunctionDecl>(D)->isMain())
250 Diag(Loc, diag::ext_main_used);
251
252 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
253 }
254
255 // See if this is an auto-typed variable whose initializer we are parsing.
256 if (ParsingInitForAutoVars.count(D)) {
257 if (isa<BindingDecl>(D)) {
258 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
259 << D->getDeclName();
260 } else {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << diag::ParsingInitFor::Var << D->getDeclName()
263 << cast<VarDecl>(D)->getType();
264 }
265 return true;
266 }
267
268 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269 // See if this is a deleted function.
270 if (FD->isDeleted()) {
271 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
272 if (Ctor && Ctor->isInheritingConstructor())
273 Diag(Loc, diag::err_deleted_inherited_ctor_use)
274 << Ctor->getParent()
275 << Ctor->getInheritedConstructor().getConstructor()->getParent();
276 else {
277 StringLiteral *Msg = FD->getDeletedMessage();
278 Diag(Loc, diag::err_deleted_function_use)
279 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
280 }
281 NoteDeletedFunction(FD);
282 return true;
283 }
284
285 // [expr.prim.id]p4
286 // A program that refers explicitly or implicitly to a function with a
287 // trailing requires-clause whose constraint-expression is not satisfied,
288 // other than to declare it, is ill-formed. [...]
289 //
290 // See if this is a function with constraints that need to be satisfied.
291 // Check this before deducing the return type, as it might instantiate the
292 // definition.
293 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
294 ConstraintSatisfaction Satisfaction;
295 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
296 /*ForOverloadResolution*/ true))
297 // A diagnostic will have already been generated (non-constant
298 // constraint expression, for example)
299 return true;
300 if (!Satisfaction.IsSatisfied) {
301 Diag(Loc,
302 diag::err_reference_to_function_with_unsatisfied_constraints)
303 << D;
304 DiagnoseUnsatisfiedConstraint(Satisfaction);
305 return true;
306 }
307 }
308
309 // If the function has a deduced return type, and we can't deduce it,
310 // then we can't use it either.
311 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
312 DeduceReturnType(FD, Loc))
313 return true;
314
315 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
316 return true;
317
318 }
319
320 if (auto *Concept = dyn_cast<ConceptDecl>(D);
321 Concept && CheckConceptUseInDefinition(Concept, Loc))
322 return true;
323
324 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
325 // Lambdas are only default-constructible or assignable in C++2a onwards.
326 if (MD->getParent()->isLambda() &&
327 ((isa<CXXConstructorDecl>(MD) &&
328 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
329 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
330 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
331 << !isa<CXXConstructorDecl>(MD);
332 }
333 }
334
335 auto getReferencedObjCProp = [](const NamedDecl *D) ->
336 const ObjCPropertyDecl * {
337 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
338 return MD->findPropertyDecl();
339 return nullptr;
340 };
341 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
342 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
343 return true;
344 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
345 return true;
346 }
347
348 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
349 // Only the variables omp_in and omp_out are allowed in the combiner.
350 // Only the variables omp_priv and omp_orig are allowed in the
351 // initializer-clause.
352 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
353 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
354 isa<VarDecl>(D)) {
355 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
356 << getCurFunction()->HasOMPDeclareReductionCombiner;
357 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358 return true;
359 }
360
361 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
362 // List-items in map clauses on this construct may only refer to the declared
363 // variable var and entities that could be referenced by a procedure defined
364 // at the same location.
365 // [OpenMP 5.2] Also allow iterator declared variables.
366 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
367 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
368 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
369 << OpenMP().getOpenMPDeclareMapperVarName();
370 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
371 return true;
372 }
373
374 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
375 Diag(Loc, diag::err_use_of_empty_using_if_exists);
376 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
377 return true;
378 }
379
380 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
381 AvoidPartialAvailabilityChecks, ClassReceiver);
382
383 DiagnoseUnusedOfDecl(*this, D, Loc);
384
385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
386
387 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
388 if (getLangOpts().getFPEvalMethod() !=
389 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
390 PP.getLastFPEvalPragmaLocation().isValid() &&
391 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
392 Diag(D->getLocation(),
393 diag::err_type_available_only_in_default_eval_method)
394 << D->getName();
395 }
396
397 if (auto *VD = dyn_cast<ValueDecl>(D))
398 checkTypeSupport(VD->getType(), Loc, VD);
399
400 if (LangOpts.SYCLIsDevice ||
401 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
402 if (!Context.getTargetInfo().isTLSSupported())
403 if (const auto *VD = dyn_cast<VarDecl>(D))
404 if (VD->getTLSKind() != VarDecl::TLS_None)
405 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
406 }
407
408 return false;
409 }
410
411 void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
412 ArrayRef<Expr *> Args) {
413 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
414 if (!Attr)
415 return;
416
417 // The number of formal parameters of the declaration.
418 unsigned NumFormalParams;
419
420 // The kind of declaration. This is also an index into a %select in
421 // the diagnostic.
422 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
423
424 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
425 NumFormalParams = MD->param_size();
426 CalleeKind = CK_Method;
427 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
428 NumFormalParams = FD->param_size();
429 CalleeKind = CK_Function;
430 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
431 QualType Ty = VD->getType();
432 const FunctionType *Fn = nullptr;
433 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
434 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
435 if (!Fn)
436 return;
437 CalleeKind = CK_Function;
438 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
439 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
440 CalleeKind = CK_Block;
441 } else {
442 return;
443 }
444
445 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
446 NumFormalParams = proto->getNumParams();
447 else
448 NumFormalParams = 0;
449 } else {
450 return;
451 }
452
453 // "NullPos" is the number of formal parameters at the end which
454 // effectively count as part of the variadic arguments. This is
455 // useful if you would prefer to not have *any* formal parameters,
456 // but the language forces you to have at least one.
457 unsigned NullPos = Attr->getNullPos();
458 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
459 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
460
461 // The number of arguments which should follow the sentinel.
462 unsigned NumArgsAfterSentinel = Attr->getSentinel();
463
464 // If there aren't enough arguments for all the formal parameters,
465 // the sentinel, and the args after the sentinel, complain.
466 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
467 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
468 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
469 return;
470 }
471
472 // Otherwise, find the sentinel expression.
473 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
474 if (!SentinelExpr)
475 return;
476 if (SentinelExpr->isValueDependent())
477 return;
478 if (Context.isSentinelNullExpr(SentinelExpr))
479 return;
480
481 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
482 // or 'NULL' if those are actually defined in the context. Only use
483 // 'nil' for ObjC methods, where it's much more likely that the
484 // variadic arguments form a list of object pointers.
485 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
486 std::string NullValue;
487 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
488 NullValue = "nil";
489 else if (getLangOpts().CPlusPlus11)
490 NullValue = "nullptr";
491 else if (PP.isMacroDefined("NULL"))
492 NullValue = "NULL";
493 else
494 NullValue = "(void*) 0";
495
496 if (MissingNilLoc.isInvalid())
497 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
498 else
499 Diag(MissingNilLoc, diag::warn_missing_sentinel)
500 << int(CalleeKind)
501 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
502 Diag(D->getLocation(), diag::note_sentinel_here)
503 << int(CalleeKind) << Attr->getRange();
504 }
505
506 SourceRange Sema::getExprRange(Expr *E) const {
507 return E ? E->getSourceRange() : SourceRange();
508 }
509
510 //===----------------------------------------------------------------------===//
511 // Standard Promotions and Conversions
512 //===----------------------------------------------------------------------===//
513
514 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
515 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
516 // Handle any placeholder expressions which made it here.
517 if (E->hasPlaceholderType()) {
518 ExprResult result = CheckPlaceholderExpr(E);
519 if (result.isInvalid()) return ExprError();
520 E = result.get();
521 }
522
523 QualType Ty = E->getType();
524 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
525
526 if (Ty->isFunctionType()) {
527 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
528 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
529 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
530 return ExprError();
531
532 E = ImpCastExprToType(E, Context.getPointerType(Ty),
533 CK_FunctionToPointerDecay).get();
534 } else if (Ty->isArrayType()) {
535 // In C90 mode, arrays only promote to pointers if the array expression is
536 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
537 // type 'array of type' is converted to an expression that has type 'pointer
538 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
539 // that has type 'array of type' ...". The relevant change is "an lvalue"
540 // (C90) to "an expression" (C99).
541 //
542 // C++ 4.2p1:
543 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
544 // T" can be converted to an rvalue of type "pointer to T".
545 //
546 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
547 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
548 CK_ArrayToPointerDecay);
549 if (Res.isInvalid())
550 return ExprError();
551 E = Res.get();
552 }
553 }
554 return E;
555 }
556
557 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
558 // Check to see if we are dereferencing a null pointer. If so,
559 // and if not volatile-qualified, this is undefined behavior that the
560 // optimizer will delete, so warn about it. People sometimes try to use this
561 // to get a deterministic trap and are surprised by clang's behavior. This
562 // only handles the pattern "*null", which is a very syntactic check.
563 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
564 if (UO && UO->getOpcode() == UO_Deref &&
565 UO->getSubExpr()->getType()->isPointerType()) {
566 const LangAS AS =
567 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
568 if ((!isTargetAddressSpace(AS) ||
569 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
570 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
571 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
572 !UO->getType().isVolatileQualified()) {
573 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
574 S.PDiag(diag::warn_indirection_through_null)
575 << UO->getSubExpr()->getSourceRange());
576 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
577 S.PDiag(diag::note_indirection_through_null));
578 }
579 }
580 }
581
582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
583 SourceLocation AssignLoc,
584 const Expr* RHS) {
585 const ObjCIvarDecl *IV = OIRE->getDecl();
586 if (!IV)
587 return;
588
589 DeclarationName MemberName = IV->getDeclName();
590 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
591 if (!Member || !Member->isStr("isa"))
592 return;
593
594 const Expr *Base = OIRE->getBase();
595 QualType BaseType = Base->getType();
596 if (OIRE->isArrow())
597 BaseType = BaseType->getPointeeType();
598 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
599 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
600 ObjCInterfaceDecl *ClassDeclared = nullptr;
601 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
602 if (!ClassDeclared->getSuperClass()
603 && (*ClassDeclared->ivar_begin()) == IV) {
604 if (RHS) {
605 NamedDecl *ObjectSetClass =
606 S.LookupSingleName(S.TUScope,
607 &S.Context.Idents.get("object_setClass"),
608 SourceLocation(), S.LookupOrdinaryName);
609 if (ObjectSetClass) {
610 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
612 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
613 "object_setClass(")
614 << FixItHint::CreateReplacement(
615 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
616 << FixItHint::CreateInsertion(RHSLocEnd, ")");
617 }
618 else
619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
620 } else {
621 NamedDecl *ObjectGetClass =
622 S.LookupSingleName(S.TUScope,
623 &S.Context.Idents.get("object_getClass"),
624 SourceLocation(), S.LookupOrdinaryName);
625 if (ObjectGetClass)
626 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
627 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
628 "object_getClass(")
629 << FixItHint::CreateReplacement(
630 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
631 else
632 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
633 }
634 S.Diag(IV->getLocation(), diag::note_ivar_decl);
635 }
636 }
637 }
638
639 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
640 // Handle any placeholder expressions which made it here.
641 if (E->hasPlaceholderType()) {
642 ExprResult result = CheckPlaceholderExpr(E);
643 if (result.isInvalid()) return ExprError();
644 E = result.get();
645 }
646
647 // C++ [conv.lval]p1:
648 // A glvalue of a non-function, non-array type T can be
649 // converted to a prvalue.
650 if (!E->isGLValue()) return E;
651
652 QualType T = E->getType();
653 assert(!T.isNull() && "r-value conversion on typeless expression?");
654
655 // lvalue-to-rvalue conversion cannot be applied to types that decay to
656 // pointers (i.e. function or array types).
657 if (T->canDecayToPointerType())
658 return E;
659
660 // We don't want to throw lvalue-to-rvalue casts on top of
661 // expressions of certain types in C++.
662 if (getLangOpts().CPlusPlus) {
663 if (T == Context.OverloadTy || T->isRecordType() ||
664 (T->isDependentType() && !T->isAnyPointerType() &&
665 !T->isMemberPointerType()))
666 return E;
667 }
668
669 // The C standard is actually really unclear on this point, and
670 // DR106 tells us what the result should be but not why. It's
671 // generally best to say that void types just doesn't undergo
672 // lvalue-to-rvalue at all. Note that expressions of unqualified
673 // 'void' type are never l-values, but qualified void can be.
674 if (T->isVoidType())
675 return E;
676
677 // OpenCL usually rejects direct accesses to values of 'half' type.
678 if (getLangOpts().OpenCL &&
679 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
680 T->isHalfType()) {
681 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
682 << 0 << T;
683 return ExprError();
684 }
685
686 CheckForNullPointerDereference(*this, E);
687 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
688 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
689 &Context.Idents.get("object_getClass"),
690 SourceLocation(), LookupOrdinaryName);
691 if (ObjectGetClass)
692 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
693 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
694 << FixItHint::CreateReplacement(
695 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
696 else
697 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
698 }
699 else if (const ObjCIvarRefExpr *OIRE =
700 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
701 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
702
703 // C++ [conv.lval]p1:
704 // [...] If T is a non-class type, the type of the prvalue is the
705 // cv-unqualified version of T. Otherwise, the type of the
706 // rvalue is T.
707 //
708 // C99 6.3.2.1p2:
709 // If the lvalue has qualified type, the value has the unqualified
710 // version of the type of the lvalue; otherwise, the value has the
711 // type of the lvalue.
712 if (T.hasQualifiers())
713 T = T.getUnqualifiedType();
714
715 // Under the MS ABI, lock down the inheritance model now.
716 if (T->isMemberPointerType() &&
717 Context.getTargetInfo().getCXXABI().isMicrosoft())
718 (void)isCompleteType(E->getExprLoc(), T);
719
720 ExprResult Res = CheckLValueToRValueConversionOperand(E);
721 if (Res.isInvalid())
722 return Res;
723 E = Res.get();
724
725 // Loading a __weak object implicitly retains the value, so we need a cleanup to
726 // balance that.
727 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
728 Cleanup.setExprNeedsCleanups(true);
729
730 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
731 Cleanup.setExprNeedsCleanups(true);
732
733 if (!BoundsSafetyCheckUseOfCountAttrPtr(Res.get()))
734 return ExprError();
735
736 // C++ [conv.lval]p3:
737 // If T is cv std::nullptr_t, the result is a null pointer constant.
738 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
739 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
740 CurFPFeatureOverrides());
741
742 // C11 6.3.2.1p2:
743 // ... if the lvalue has atomic type, the value has the non-atomic version
744 // of the type of the lvalue ...
745 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
746 T = Atomic->getValueType().getUnqualifiedType();
747 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
748 nullptr, VK_PRValue, FPOptionsOverride());
749 }
750
751 return Res;
752 }
753
754 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
755 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
756 if (Res.isInvalid())
757 return ExprError();
758 Res = DefaultLvalueConversion(Res.get());
759 if (Res.isInvalid())
760 return ExprError();
761 return Res;
762 }
763
764 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
765 QualType Ty = E->getType();
766 ExprResult Res = E;
767 // Only do implicit cast for a function type, but not for a pointer
768 // to function type.
769 if (Ty->isFunctionType()) {
770 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
771 CK_FunctionToPointerDecay);
772 if (Res.isInvalid())
773 return ExprError();
774 }
775 Res = DefaultLvalueConversion(Res.get());
776 if (Res.isInvalid())
777 return ExprError();
778 return Res.get();
779 }
780
781 /// UsualUnaryFPConversions - Promotes floating-point types according to the
782 /// current language semantics.
783 ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
784 QualType Ty = E->getType();
785 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
786
787 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
788 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
789 (getLangOpts().getFPEvalMethod() !=
790 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
791 PP.getLastFPEvalPragmaLocation().isValid())) {
792 switch (EvalMethod) {
793 default:
794 llvm_unreachable("Unrecognized float evaluation method");
795 break;
796 case LangOptions::FEM_UnsetOnCommandLine:
797 llvm_unreachable("Float evaluation method should be set by now");
798 break;
799 case LangOptions::FEM_Double:
800 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
801 // Widen the expression to double.
802 return Ty->isComplexType()
803 ? ImpCastExprToType(E,
804 Context.getComplexType(Context.DoubleTy),
805 CK_FloatingComplexCast)
806 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
807 break;
808 case LangOptions::FEM_Extended:
809 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
810 // Widen the expression to long double.
811 return Ty->isComplexType()
812 ? ImpCastExprToType(
813 E, Context.getComplexType(Context.LongDoubleTy),
814 CK_FloatingComplexCast)
815 : ImpCastExprToType(E, Context.LongDoubleTy,
816 CK_FloatingCast);
817 break;
818 }
819 }
820
821 // Half FP have to be promoted to float unless it is natively supported
822 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
823 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
824
825 return E;
826 }
827
828 /// UsualUnaryConversions - Performs various conversions that are common to most
829 /// operators (C99 6.3). The conversions of array and function types are
830 /// sometimes suppressed. For example, the array->pointer conversion doesn't
831 /// apply if the array is an argument to the sizeof or address (&) operators.
832 /// In these instances, this routine should *not* be called.
833 ExprResult Sema::UsualUnaryConversions(Expr *E) {
834 // First, convert to an r-value.
835 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
836 if (Res.isInvalid())
837 return ExprError();
838
839 // Promote floating-point types.
840 Res = UsualUnaryFPConversions(Res.get());
841 if (Res.isInvalid())
842 return ExprError();
843 E = Res.get();
844
845 QualType Ty = E->getType();
846 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
847
848 // Try to perform integral promotions if the object has a theoretically
849 // promotable type.
850 if (Ty->isIntegralOrUnscopedEnumerationType()) {
851 // C99 6.3.1.1p2:
852 //
853 // The following may be used in an expression wherever an int or
854 // unsigned int may be used:
855 // - an object or expression with an integer type whose integer
856 // conversion rank is less than or equal to the rank of int
857 // and unsigned int.
858 // - A bit-field of type _Bool, int, signed int, or unsigned int.
859 //
860 // If an int can represent all values of the original type, the
861 // value is converted to an int; otherwise, it is converted to an
862 // unsigned int. These are called the integer promotions. All
863 // other types are unchanged by the integer promotions.
864
865 QualType PTy = Context.isPromotableBitField(E);
866 if (!PTy.isNull()) {
867 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
868 return E;
869 }
870 if (Context.isPromotableIntegerType(Ty)) {
871 QualType PT = Context.getPromotedIntegerType(Ty);
872 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
873 return E;
874 }
875 }
876 return E;
877 }
878
879 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
880 /// do not have a prototype. Arguments that have type float or __fp16
881 /// are promoted to double. All other argument types are converted by
882 /// UsualUnaryConversions().
883 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
884 QualType Ty = E->getType();
885 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
886
887 ExprResult Res = UsualUnaryConversions(E);
888 if (Res.isInvalid())
889 return ExprError();
890 E = Res.get();
891
892 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
893 // promote to double.
894 // Note that default argument promotion applies only to float (and
895 // half/fp16); it does not apply to _Float16.
896 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
897 if (BTy && (BTy->getKind() == BuiltinType::Half ||
898 BTy->getKind() == BuiltinType::Float)) {
899 if (getLangOpts().OpenCL &&
900 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
901 if (BTy->getKind() == BuiltinType::Half) {
902 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
903 }
904 } else {
905 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
906 }
907 }
908 if (BTy &&
909 getLangOpts().getExtendIntArgs() ==
910 LangOptions::ExtendArgsKind::ExtendTo64 &&
911 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
912 Context.getTypeSizeInChars(BTy) <
913 Context.getTypeSizeInChars(Context.LongLongTy)) {
914 E = (Ty->isUnsignedIntegerType())
915 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
916 .get()
917 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
918 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
919 "Unexpected typesize for LongLongTy");
920 }
921
922 // C++ performs lvalue-to-rvalue conversion as a default argument
923 // promotion, even on class types, but note:
924 // C++11 [conv.lval]p2:
925 // When an lvalue-to-rvalue conversion occurs in an unevaluated
926 // operand or a subexpression thereof the value contained in the
927 // referenced object is not accessed. Otherwise, if the glvalue
928 // has a class type, the conversion copy-initializes a temporary
929 // of type T from the glvalue and the result of the conversion
930 // is a prvalue for the temporary.
931 // FIXME: add some way to gate this entire thing for correctness in
932 // potentially potentially evaluated contexts.
933 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
934 ExprResult Temp = PerformCopyInitialization(
935 InitializedEntity::InitializeTemporary(E->getType()),
936 E->getExprLoc(), E);
937 if (Temp.isInvalid())
938 return ExprError();
939 E = Temp.get();
940 }
941
942 // C++ [expr.call]p7, per CWG722:
943 // An argument that has (possibly cv-qualified) type std::nullptr_t is
944 // converted to void* ([conv.ptr]).
945 // (This does not apply to C23 nullptr)
946 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
947 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
948
949 return E;
950 }
951
952 VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
953 if (Ty->isIncompleteType()) {
954 // C++11 [expr.call]p7:
955 // After these conversions, if the argument does not have arithmetic,
956 // enumeration, pointer, pointer to member, or class type, the program
957 // is ill-formed.
958 //
959 // Since we've already performed null pointer conversion, array-to-pointer
960 // decay and function-to-pointer decay, the only such type in C++ is cv
961 // void. This also handles initializer lists as variadic arguments.
962 if (Ty->isVoidType())
963 return VarArgKind::Invalid;
964
965 if (Ty->isObjCObjectType())
966 return VarArgKind::Invalid;
967 return VarArgKind::Valid;
968 }
969
970 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
971 return VarArgKind::Invalid;
972
973 if (Context.getTargetInfo().getTriple().isWasm() &&
974 Ty.isWebAssemblyReferenceType()) {
975 return VarArgKind::Invalid;
976 }
977
978 if (Ty.isCXX98PODType(Context))
979 return VarArgKind::Valid;
980
981 // C++11 [expr.call]p7:
982 // Passing a potentially-evaluated argument of class type (Clause 9)
983 // having a non-trivial copy constructor, a non-trivial move constructor,
984 // or a non-trivial destructor, with no corresponding parameter,
985 // is conditionally-supported with implementation-defined semantics.
986 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
987 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
988 if (!Record->hasNonTrivialCopyConstructor() &&
989 !Record->hasNonTrivialMoveConstructor() &&
990 !Record->hasNonTrivialDestructor())
991 return VarArgKind::ValidInCXX11;
992
993 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
994 return VarArgKind::Valid;
995
996 if (Ty->isObjCObjectType())
997 return VarArgKind::Invalid;
998
999 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1000 return VarArgKind::Valid;
1001
1002 if (getLangOpts().MSVCCompat)
1003 return VarArgKind::MSVCUndefined;
1004
1005 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1006 return VarArgKind::Valid;
1007
1008 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1009 // permitted to reject them. We should consider doing so.
1010 return VarArgKind::Undefined;
1011 }
1012
1013 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1014 // Don't allow one to pass an Objective-C interface to a vararg.
1015 const QualType &Ty = E->getType();
1016 VarArgKind VAK = isValidVarArgType(Ty);
1017
1018 // Complain about passing non-POD types through varargs.
1019 switch (VAK) {
1020 case VarArgKind::ValidInCXX11:
1021 DiagRuntimeBehavior(
1022 E->getBeginLoc(), nullptr,
1023 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1024 [[fallthrough]];
1025 case VarArgKind::Valid:
1026 if (Ty->isRecordType()) {
1027 // This is unlikely to be what the user intended. If the class has a
1028 // 'c_str' member function, the user probably meant to call that.
1029 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1030 PDiag(diag::warn_pass_class_arg_to_vararg)
1031 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1032 }
1033 break;
1034
1035 case VarArgKind::Undefined:
1036 case VarArgKind::MSVCUndefined:
1037 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1038 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1039 << getLangOpts().CPlusPlus11 << Ty << CT);
1040 break;
1041
1042 case VarArgKind::Invalid:
1043 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1044 Diag(E->getBeginLoc(),
1045 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1046 << Ty << CT;
1047 else if (Ty->isObjCObjectType())
1048 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1049 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1050 << Ty << CT);
1051 else
1052 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1053 << isa<InitListExpr>(E) << Ty << CT;
1054 break;
1055 }
1056 }
1057
1058 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1059 FunctionDecl *FDecl) {
1060 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1061 // Strip the unbridged-cast placeholder expression off, if applicable.
1062 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1063 (CT == VariadicCallType::Method ||
1064 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1065 E = ObjC().stripARCUnbridgedCast(E);
1066
1067 // Otherwise, do normal placeholder checking.
1068 } else {
1069 ExprResult ExprRes = CheckPlaceholderExpr(E);
1070 if (ExprRes.isInvalid())
1071 return ExprError();
1072 E = ExprRes.get();
1073 }
1074 }
1075
1076 ExprResult ExprRes = DefaultArgumentPromotion(E);
1077 if (ExprRes.isInvalid())
1078 return ExprError();
1079
1080 // Copy blocks to the heap.
1081 if (ExprRes.get()->getType()->isBlockPointerType())
1082 maybeExtendBlockObject(ExprRes);
1083
1084 E = ExprRes.get();
1085
1086 // Diagnostics regarding non-POD argument types are
1087 // emitted along with format string checking in Sema::CheckFunctionCall().
1088 if (isValidVarArgType(E->getType()) == VarArgKind::Undefined) {
1089 // Turn this into a trap.
1090 CXXScopeSpec SS;
1091 SourceLocation TemplateKWLoc;
1092 UnqualifiedId Name;
1093 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1094 E->getBeginLoc());
1095 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1096 /*HasTrailingLParen=*/true,
1097 /*IsAddressOfOperand=*/false);
1098 if (TrapFn.isInvalid())
1099 return ExprError();
1100
1101 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1102 E->getEndLoc());
1103 if (Call.isInvalid())
1104 return ExprError();
1105
1106 ExprResult Comma =
1107 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1108 if (Comma.isInvalid())
1109 return ExprError();
1110 return Comma.get();
1111 }
1112
1113 if (!getLangOpts().CPlusPlus &&
1114 RequireCompleteType(E->getExprLoc(), E->getType(),
1115 diag::err_call_incomplete_argument))
1116 return ExprError();
1117
1118 return E;
1119 }
1120
1121 /// Convert complex integers to complex floats and real integers to
1122 /// real floats as required for complex arithmetic. Helper function of
1123 /// UsualArithmeticConversions()
1124 ///
1125 /// \return false if the integer expression is an integer type and is
1126 /// successfully converted to the (complex) float type.
1127 static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1128 ExprResult &ComplexExpr,
1129 QualType IntTy,
1130 QualType ComplexTy,
1131 bool SkipCast) {
1132 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1133 if (SkipCast) return false;
1134 if (IntTy->isIntegerType()) {
1135 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1136 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1137 } else {
1138 assert(IntTy->isComplexIntegerType());
1139 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1140 CK_IntegralComplexToFloatingComplex);
1141 }
1142 return false;
1143 }
1144
1145 // This handles complex/complex, complex/float, or float/complex.
1146 // When both operands are complex, the shorter operand is converted to the
1147 // type of the longer, and that is the type of the result. This corresponds
1148 // to what is done when combining two real floating-point operands.
1149 // The fun begins when size promotion occur across type domains.
1150 // From H&S 6.3.4: When one operand is complex and the other is a real
1151 // floating-point type, the less precise type is converted, within it's
1152 // real or complex domain, to the precision of the other type. For example,
1153 // when combining a "long double" with a "double _Complex", the
1154 // "double _Complex" is promoted to "long double _Complex".
1155 static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1156 QualType ShorterType,
1157 QualType LongerType,
1158 bool PromotePrecision) {
1159 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1160 QualType Result =
1161 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1162
1163 if (PromotePrecision) {
1164 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1165 Shorter =
1166 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1167 } else {
1168 if (LongerIsComplex)
1169 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1170 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1171 }
1172 }
1173 return Result;
1174 }
1175
1176 /// Handle arithmetic conversion with complex types. Helper function of
1177 /// UsualArithmeticConversions()
1178 static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1179 ExprResult &RHS, QualType LHSType,
1180 QualType RHSType, bool IsCompAssign) {
1181 // Handle (complex) integer types.
1182 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1183 /*SkipCast=*/false))
1184 return LHSType;
1185 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1186 /*SkipCast=*/IsCompAssign))
1187 return RHSType;
1188
1189 // Compute the rank of the two types, regardless of whether they are complex.
1190 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1191 if (Order < 0)
1192 // Promote the precision of the LHS if not an assignment.
1193 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1194 /*PromotePrecision=*/!IsCompAssign);
1195 // Promote the precision of the RHS unless it is already the same as the LHS.
1196 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1197 /*PromotePrecision=*/Order > 0);
1198 }
1199
1200 /// Handle arithmetic conversion from integer to float. Helper function
1201 /// of UsualArithmeticConversions()
1202 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1203 ExprResult &IntExpr,
1204 QualType FloatTy, QualType IntTy,
1205 bool ConvertFloat, bool ConvertInt) {
1206 if (IntTy->isIntegerType()) {
1207 if (ConvertInt)
1208 // Convert intExpr to the lhs floating point type.
1209 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1210 CK_IntegralToFloating);
1211 return FloatTy;
1212 }
1213
1214 // Convert both sides to the appropriate complex float.
1215 assert(IntTy->isComplexIntegerType());
1216 QualType result = S.Context.getComplexType(FloatTy);
1217
1218 // _Complex int -> _Complex float
1219 if (ConvertInt)
1220 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1221 CK_IntegralComplexToFloatingComplex);
1222
1223 // float -> _Complex float
1224 if (ConvertFloat)
1225 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1226 CK_FloatingRealToComplex);
1227
1228 return result;
1229 }
1230
1231 /// Handle arithmethic conversion with floating point types. Helper
1232 /// function of UsualArithmeticConversions()
1233 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1234 ExprResult &RHS, QualType LHSType,
1235 QualType RHSType, bool IsCompAssign) {
1236 bool LHSFloat = LHSType->isRealFloatingType();
1237 bool RHSFloat = RHSType->isRealFloatingType();
1238
1239 // N1169 4.1.4: If one of the operands has a floating type and the other
1240 // operand has a fixed-point type, the fixed-point operand
1241 // is converted to the floating type [...]
1242 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1243 if (LHSFloat)
1244 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1245 else if (!IsCompAssign)
1246 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1247 return LHSFloat ? LHSType : RHSType;
1248 }
1249
1250 // If we have two real floating types, convert the smaller operand
1251 // to the bigger result.
1252 if (LHSFloat && RHSFloat) {
1253 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1254 if (order > 0) {
1255 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1256 return LHSType;
1257 }
1258
1259 assert(order < 0 && "illegal float comparison");
1260 if (!IsCompAssign)
1261 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1262 return RHSType;
1263 }
1264
1265 if (LHSFloat) {
1266 // Half FP has to be promoted to float unless it is natively supported
1267 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1268 LHSType = S.Context.FloatTy;
1269
1270 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1271 /*ConvertFloat=*/!IsCompAssign,
1272 /*ConvertInt=*/ true);
1273 }
1274 assert(RHSFloat);
1275 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1276 /*ConvertFloat=*/ true,
1277 /*ConvertInt=*/!IsCompAssign);
1278 }
1279
1280 /// Diagnose attempts to convert between __float128, __ibm128 and
1281 /// long double if there is no support for such conversion.
1282 /// Helper function of UsualArithmeticConversions().
1283 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1284 QualType RHSType) {
1285 // No issue if either is not a floating point type.
1286 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1287 return false;
1288
1289 // No issue if both have the same 128-bit float semantics.
1290 auto *LHSComplex = LHSType->getAs<ComplexType>();
1291 auto *RHSComplex = RHSType->getAs<ComplexType>();
1292
1293 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1294 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1295
1296 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1297 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1298
1299 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1300 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1301 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1302 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1303 return false;
1304
1305 return true;
1306 }
1307
1308 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1309
1310 namespace {
1311 /// These helper callbacks are placed in an anonymous namespace to
1312 /// permit their use as function template parameters.
1313 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1314 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1315 }
1316
1317 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1318 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1319 CK_IntegralComplexCast);
1320 }
1321 }
1322
1323 /// Handle integer arithmetic conversions. Helper function of
1324 /// UsualArithmeticConversions()
1325 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1326 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1327 ExprResult &RHS, QualType LHSType,
1328 QualType RHSType, bool IsCompAssign) {
1329 // The rules for this case are in C99 6.3.1.8
1330 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1331 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1332 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1333 if (LHSSigned == RHSSigned) {
1334 // Same signedness; use the higher-ranked type
1335 if (order >= 0) {
1336 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1337 return LHSType;
1338 } else if (!IsCompAssign)
1339 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1340 return RHSType;
1341 } else if (order != (LHSSigned ? 1 : -1)) {
1342 // The unsigned type has greater than or equal rank to the
1343 // signed type, so use the unsigned type
1344 if (RHSSigned) {
1345 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1346 return LHSType;
1347 } else if (!IsCompAssign)
1348 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1349 return RHSType;
1350 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1351 // The two types are different widths; if we are here, that
1352 // means the signed type is larger than the unsigned type, so
1353 // use the signed type.
1354 if (LHSSigned) {
1355 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1356 return LHSType;
1357 } else if (!IsCompAssign)
1358 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1359 return RHSType;
1360 } else {
1361 // The signed type is higher-ranked than the unsigned type,
1362 // but isn't actually any bigger (like unsigned int and long
1363 // on most 32-bit systems). Use the unsigned type corresponding
1364 // to the signed type.
1365 QualType result =
1366 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1367 RHS = (*doRHSCast)(S, RHS.get(), result);
1368 if (!IsCompAssign)
1369 LHS = (*doLHSCast)(S, LHS.get(), result);
1370 return result;
1371 }
1372 }
1373
1374 /// Handle conversions with GCC complex int extension. Helper function
1375 /// of UsualArithmeticConversions()
1376 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1377 ExprResult &RHS, QualType LHSType,
1378 QualType RHSType,
1379 bool IsCompAssign) {
1380 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1381 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1382
1383 if (LHSComplexInt && RHSComplexInt) {
1384 QualType LHSEltType = LHSComplexInt->getElementType();
1385 QualType RHSEltType = RHSComplexInt->getElementType();
1386 QualType ScalarType =
1387 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1388 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1389
1390 return S.Context.getComplexType(ScalarType);
1391 }
1392
1393 if (LHSComplexInt) {
1394 QualType LHSEltType = LHSComplexInt->getElementType();
1395 QualType ScalarType =
1396 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1397 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1398 QualType ComplexType = S.Context.getComplexType(ScalarType);
1399 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1400 CK_IntegralRealToComplex);
1401
1402 return ComplexType;
1403 }
1404
1405 assert(RHSComplexInt);
1406
1407 QualType RHSEltType = RHSComplexInt->getElementType();
1408 QualType ScalarType =
1409 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1410 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1411 QualType ComplexType = S.Context.getComplexType(ScalarType);
1412
1413 if (!IsCompAssign)
1414 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1415 CK_IntegralRealToComplex);
1416 return ComplexType;
1417 }
1418
1419 /// Return the rank of a given fixed point or integer type. The value itself
1420 /// doesn't matter, but the values must be increasing with proper increasing
1421 /// rank as described in N1169 4.1.1.
1422 static unsigned GetFixedPointRank(QualType Ty) {
1423 const auto *BTy = Ty->getAs<BuiltinType>();
1424 assert(BTy && "Expected a builtin type.");
1425
1426 switch (BTy->getKind()) {
1427 case BuiltinType::ShortFract:
1428 case BuiltinType::UShortFract:
1429 case BuiltinType::SatShortFract:
1430 case BuiltinType::SatUShortFract:
1431 return 1;
1432 case BuiltinType::Fract:
1433 case BuiltinType::UFract:
1434 case BuiltinType::SatFract:
1435 case BuiltinType::SatUFract:
1436 return 2;
1437 case BuiltinType::LongFract:
1438 case BuiltinType::ULongFract:
1439 case BuiltinType::SatLongFract:
1440 case BuiltinType::SatULongFract:
1441 return 3;
1442 case BuiltinType::ShortAccum:
1443 case BuiltinType::UShortAccum:
1444 case BuiltinType::SatShortAccum:
1445 case BuiltinType::SatUShortAccum:
1446 return 4;
1447 case BuiltinType::Accum:
1448 case BuiltinType::UAccum:
1449 case BuiltinType::SatAccum:
1450 case BuiltinType::SatUAccum:
1451 return 5;
1452 case BuiltinType::LongAccum:
1453 case BuiltinType::ULongAccum:
1454 case BuiltinType::SatLongAccum:
1455 case BuiltinType::SatULongAccum:
1456 return 6;
1457 default:
1458 if (BTy->isInteger())
1459 return 0;
1460 llvm_unreachable("Unexpected fixed point or integer type");
1461 }
1462 }
1463
1464 /// handleFixedPointConversion - Fixed point operations between fixed
1465 /// point types and integers or other fixed point types do not fall under
1466 /// usual arithmetic conversion since these conversions could result in loss
1467 /// of precsision (N1169 4.1.4). These operations should be calculated with
1468 /// the full precision of their result type (N1169 4.1.6.2.1).
1469 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1470 QualType RHSTy) {
1471 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1472 "Expected at least one of the operands to be a fixed point type");
1473 assert((LHSTy->isFixedPointOrIntegerType() ||
1474 RHSTy->isFixedPointOrIntegerType()) &&
1475 "Special fixed point arithmetic operation conversions are only "
1476 "applied to ints or other fixed point types");
1477
1478 // If one operand has signed fixed-point type and the other operand has
1479 // unsigned fixed-point type, then the unsigned fixed-point operand is
1480 // converted to its corresponding signed fixed-point type and the resulting
1481 // type is the type of the converted operand.
1482 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1483 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1484 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1485 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1486
1487 // The result type is the type with the highest rank, whereby a fixed-point
1488 // conversion rank is always greater than an integer conversion rank; if the
1489 // type of either of the operands is a saturating fixedpoint type, the result
1490 // type shall be the saturating fixed-point type corresponding to the type
1491 // with the highest rank; the resulting value is converted (taking into
1492 // account rounding and overflow) to the precision of the resulting type.
1493 // Same ranks between signed and unsigned types are resolved earlier, so both
1494 // types are either signed or both unsigned at this point.
1495 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1496 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1497
1498 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1499
1500 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1501 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1502
1503 return ResultTy;
1504 }
1505
1506 /// Check that the usual arithmetic conversions can be performed on this pair of
1507 /// expressions that might be of enumeration type.
1508 void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1509 SourceLocation Loc,
1510 ArithConvKind ACK) {
1511 // C++2a [expr.arith.conv]p1:
1512 // If one operand is of enumeration type and the other operand is of a
1513 // different enumeration type or a floating-point type, this behavior is
1514 // deprecated ([depr.arith.conv.enum]).
1515 //
1516 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1517 // Eventually we will presumably reject these cases (in C++23 onwards?).
1518 QualType L = LHS->getEnumCoercedType(Context),
1519 R = RHS->getEnumCoercedType(Context);
1520 bool LEnum = L->isUnscopedEnumerationType(),
1521 REnum = R->isUnscopedEnumerationType();
1522 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1523 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1524 (REnum && L->isFloatingType())) {
1525 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1526 : getLangOpts().CPlusPlus20
1527 ? diag::warn_arith_conv_enum_float_cxx20
1528 : diag::warn_arith_conv_enum_float)
1529 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1530 << L << R;
1531 } else if (!IsCompAssign && LEnum && REnum &&
1532 !Context.hasSameUnqualifiedType(L, R)) {
1533 unsigned DiagID;
1534 // In C++ 26, usual arithmetic conversions between 2 different enum types
1535 // are ill-formed.
1536 if (getLangOpts().CPlusPlus26)
1537 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1538 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1539 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1540 // If either enumeration type is unnamed, it's less likely that the
1541 // user cares about this, but this situation is still deprecated in
1542 // C++2a. Use a different warning group.
1543 DiagID = getLangOpts().CPlusPlus20
1544 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1545 : diag::warn_arith_conv_mixed_anon_enum_types;
1546 } else if (ACK == ArithConvKind::Conditional) {
1547 // Conditional expressions are separated out because they have
1548 // historically had a different warning flag.
1549 DiagID = getLangOpts().CPlusPlus20
1550 ? diag::warn_conditional_mixed_enum_types_cxx20
1551 : diag::warn_conditional_mixed_enum_types;
1552 } else if (ACK == ArithConvKind::Comparison) {
1553 // Comparison expressions are separated out because they have
1554 // historically had a different warning flag.
1555 DiagID = getLangOpts().CPlusPlus20
1556 ? diag::warn_comparison_mixed_enum_types_cxx20
1557 : diag::warn_comparison_mixed_enum_types;
1558 } else {
1559 DiagID = getLangOpts().CPlusPlus20
1560 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1561 : diag::warn_arith_conv_mixed_enum_types;
1562 }
1563 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1564 << (int)ACK << L << R;
1565 }
1566 }
1567
1568 static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1569 Expr *RHS, SourceLocation Loc,
1570 ArithConvKind ACK) {
1571 QualType LHSType = LHS->getType().getUnqualifiedType();
1572 QualType RHSType = RHS->getType().getUnqualifiedType();
1573
1574 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1575 !RHSType->isUnicodeCharacterType())
1576 return;
1577
1578 if (ACK == ArithConvKind::Comparison) {
1579 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1580 return;
1581
1582 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1583 if (T->isChar8Type())
1584 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1585 if (T->isChar16Type())
1586 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1587 assert(T->isChar32Type());
1588 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1589 };
1590
1591 Expr::EvalResult LHSRes, RHSRes;
1592 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1593 Expr::SE_AllowSideEffects,
1594 SemaRef.isConstantEvaluatedContext());
1595 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1596 Expr::SE_AllowSideEffects,
1597 SemaRef.isConstantEvaluatedContext());
1598
1599 // Don't warn if the one known value is a representable
1600 // in the type of both expressions.
1601 if (LHSSuccess != RHSuccess) {
1602 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1603 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1604 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1605 return;
1606 }
1607
1608 if (!LHSSuccess || !RHSuccess) {
1609 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1610 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1611 << RHSType;
1612 return;
1613 }
1614
1615 llvm::APSInt LHSValue(32);
1616 LHSValue = LHSRes.Val.getInt();
1617 llvm::APSInt RHSValue(32);
1618 RHSValue = RHSRes.Val.getInt();
1619
1620 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1621 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1622 if (LHSSafe && RHSSafe)
1623 return;
1624
1625 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1626 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1627 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1628 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1629 return;
1630 }
1631
1632 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1633 return;
1634
1635 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1636 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1637 << RHSType;
1638 }
1639
1640 /// UsualArithmeticConversions - Performs various conversions that are common to
1641 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1642 /// routine returns the first non-arithmetic type found. The client is
1643 /// responsible for emitting appropriate error diagnostics.
1644 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1645 SourceLocation Loc,
1646 ArithConvKind ACK) {
1647
1648 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1649
1650 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1651
1652 if (ACK != ArithConvKind::CompAssign) {
1653 LHS = UsualUnaryConversions(LHS.get());
1654 if (LHS.isInvalid())
1655 return QualType();
1656 }
1657
1658 RHS = UsualUnaryConversions(RHS.get());
1659 if (RHS.isInvalid())
1660 return QualType();
1661
1662 // For conversion purposes, we ignore any qualifiers.
1663 // For example, "const float" and "float" are equivalent.
1664 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1665 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1666
1667 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1668 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1669 LHSType = AtomicLHS->getValueType();
1670
1671 // If both types are identical, no conversion is needed.
1672 if (Context.hasSameType(LHSType, RHSType))
1673 return Context.getCommonSugaredType(LHSType, RHSType);
1674
1675 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1676 // The caller can deal with this (e.g. pointer + int).
1677 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1678 return QualType();
1679
1680 // Apply unary and bitfield promotions to the LHS's type.
1681 QualType LHSUnpromotedType = LHSType;
1682 if (Context.isPromotableIntegerType(LHSType))
1683 LHSType = Context.getPromotedIntegerType(LHSType);
1684 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1685 if (!LHSBitfieldPromoteTy.isNull())
1686 LHSType = LHSBitfieldPromoteTy;
1687 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1688 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1689
1690 // If both types are identical, no conversion is needed.
1691 if (Context.hasSameType(LHSType, RHSType))
1692 return Context.getCommonSugaredType(LHSType, RHSType);
1693
1694 // At this point, we have two different arithmetic types.
1695
1696 // Diagnose attempts to convert between __ibm128, __float128 and long double
1697 // where such conversions currently can't be handled.
1698 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1699 return QualType();
1700
1701 // Handle complex types first (C99 6.3.1.8p1).
1702 if (LHSType->isComplexType() || RHSType->isComplexType())
1703 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1704 ACK == ArithConvKind::CompAssign);
1705
1706 // Now handle "real" floating types (i.e. float, double, long double).
1707 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1708 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1709 ACK == ArithConvKind::CompAssign);
1710
1711 // Handle GCC complex int extension.
1712 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1713 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1714 ACK == ArithConvKind::CompAssign);
1715
1716 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1717 return handleFixedPointConversion(*this, LHSType, RHSType);
1718
1719 // Finally, we have two differing integer types.
1720 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1721 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1722 }
1723
1724 //===----------------------------------------------------------------------===//
1725 // Semantic Analysis for various Expression Types
1726 //===----------------------------------------------------------------------===//
1727
1728
1729 ExprResult Sema::ActOnGenericSelectionExpr(
1730 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1731 bool PredicateIsExpr, void *ControllingExprOrType,
1732 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1733 unsigned NumAssocs = ArgTypes.size();
1734 assert(NumAssocs == ArgExprs.size());
1735
1736 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1737 for (unsigned i = 0; i < NumAssocs; ++i) {
1738 if (ArgTypes[i])
1739 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1740 else
1741 Types[i] = nullptr;
1742 }
1743
1744 // If we have a controlling type, we need to convert it from a parsed type
1745 // into a semantic type and then pass that along.
1746 if (!PredicateIsExpr) {
1747 TypeSourceInfo *ControllingType;
1748 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1749 &ControllingType);
1750 assert(ControllingType && "couldn't get the type out of the parser");
1751 ControllingExprOrType = ControllingType;
1752 }
1753
1754 ExprResult ER = CreateGenericSelectionExpr(
1755 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1756 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1757 delete [] Types;
1758 return ER;
1759 }
1760
1761 ExprResult Sema::CreateGenericSelectionExpr(
1762 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1763 bool PredicateIsExpr, void *ControllingExprOrType,
1764 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1765 unsigned NumAssocs = Types.size();
1766 assert(NumAssocs == Exprs.size());
1767 assert(ControllingExprOrType &&
1768 "Must have either a controlling expression or a controlling type");
1769
1770 Expr *ControllingExpr = nullptr;
1771 TypeSourceInfo *ControllingType = nullptr;
1772 if (PredicateIsExpr) {
1773 // Decay and strip qualifiers for the controlling expression type, and
1774 // handle placeholder type replacement. See committee discussion from WG14
1775 // DR423.
1776 EnterExpressionEvaluationContext Unevaluated(
1777 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1778 ExprResult R = DefaultFunctionArrayLvalueConversion(
1779 reinterpret_cast<Expr *>(ControllingExprOrType));
1780 if (R.isInvalid())
1781 return ExprError();
1782 ControllingExpr = R.get();
1783 } else {
1784 // The extension form uses the type directly rather than converting it.
1785 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1786 if (!ControllingType)
1787 return ExprError();
1788 }
1789
1790 bool TypeErrorFound = false,
1791 IsResultDependent = ControllingExpr
1792 ? ControllingExpr->isTypeDependent()
1793 : ControllingType->getType()->isDependentType(),
1794 ContainsUnexpandedParameterPack =
1795 ControllingExpr
1796 ? ControllingExpr->containsUnexpandedParameterPack()
1797 : ControllingType->getType()->containsUnexpandedParameterPack();
1798
1799 // The controlling expression is an unevaluated operand, so side effects are
1800 // likely unintended.
1801 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1802 ControllingExpr->HasSideEffects(Context, false))
1803 Diag(ControllingExpr->getExprLoc(),
1804 diag::warn_side_effects_unevaluated_context);
1805
1806 for (unsigned i = 0; i < NumAssocs; ++i) {
1807 if (Exprs[i]->containsUnexpandedParameterPack())
1808 ContainsUnexpandedParameterPack = true;
1809
1810 if (Types[i]) {
1811 if (Types[i]->getType()->containsUnexpandedParameterPack())
1812 ContainsUnexpandedParameterPack = true;
1813
1814 if (Types[i]->getType()->isDependentType()) {
1815 IsResultDependent = true;
1816 } else {
1817 // We relax the restriction on use of incomplete types and non-object
1818 // types with the type-based extension of _Generic. Allowing incomplete
1819 // objects means those can be used as "tags" for a type-safe way to map
1820 // to a value. Similarly, matching on function types rather than
1821 // function pointer types can be useful. However, the restriction on VM
1822 // types makes sense to retain as there are open questions about how
1823 // the selection can be made at compile time.
1824 //
1825 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1826 // complete object type other than a variably modified type."
1827 // C2y removed the requirement that an expression form must
1828 // use a complete type, though it's still as-if the type has undergone
1829 // lvalue conversion. We support this as an extension in C23 and
1830 // earlier because GCC does so.
1831 unsigned D = 0;
1832 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1833 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1834 : diag::ext_assoc_type_incomplete;
1835 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1836 D = diag::err_assoc_type_nonobject;
1837 else if (Types[i]->getType()->isVariablyModifiedType())
1838 D = diag::err_assoc_type_variably_modified;
1839 else if (ControllingExpr) {
1840 // Because the controlling expression undergoes lvalue conversion,
1841 // array conversion, and function conversion, an association which is
1842 // of array type, function type, or is qualified can never be
1843 // reached. We will warn about this so users are less surprised by
1844 // the unreachable association. However, we don't have to handle
1845 // function types; that's not an object type, so it's handled above.
1846 //
1847 // The logic is somewhat different for C++ because C++ has different
1848 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1849 // If T is a non-class type, the type of the prvalue is the cv-
1850 // unqualified version of T. Otherwise, the type of the prvalue is T.
1851 // The result of these rules is that all qualified types in an
1852 // association in C are unreachable, and in C++, only qualified non-
1853 // class types are unreachable.
1854 //
1855 // NB: this does not apply when the first operand is a type rather
1856 // than an expression, because the type form does not undergo
1857 // conversion.
1858 unsigned Reason = 0;
1859 QualType QT = Types[i]->getType();
1860 if (QT->isArrayType())
1861 Reason = 1;
1862 else if (QT.hasQualifiers() &&
1863 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1864 Reason = 2;
1865
1866 if (Reason)
1867 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1868 diag::warn_unreachable_association)
1869 << QT << (Reason - 1);
1870 }
1871
1872 if (D != 0) {
1873 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1874 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1875 if (getDiagnostics().getDiagnosticLevel(
1876 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1877 DiagnosticsEngine::Error)
1878 TypeErrorFound = true;
1879 }
1880
1881 // C11 6.5.1.1p2 "No two generic associations in the same generic
1882 // selection shall specify compatible types."
1883 for (unsigned j = i+1; j < NumAssocs; ++j)
1884 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1885 Context.typesAreCompatible(Types[i]->getType(),
1886 Types[j]->getType())) {
1887 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1888 diag::err_assoc_compatible_types)
1889 << Types[j]->getTypeLoc().getSourceRange()
1890 << Types[j]->getType()
1891 << Types[i]->getType();
1892 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1893 diag::note_compat_assoc)
1894 << Types[i]->getTypeLoc().getSourceRange()
1895 << Types[i]->getType();
1896 TypeErrorFound = true;
1897 }
1898 }
1899 }
1900 }
1901 if (TypeErrorFound)
1902 return ExprError();
1903
1904 // If we determined that the generic selection is result-dependent, don't
1905 // try to compute the result expression.
1906 if (IsResultDependent) {
1907 if (ControllingExpr)
1908 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1909 Types, Exprs, DefaultLoc, RParenLoc,
1910 ContainsUnexpandedParameterPack);
1911 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1912 Exprs, DefaultLoc, RParenLoc,
1913 ContainsUnexpandedParameterPack);
1914 }
1915
1916 SmallVector<unsigned, 1> CompatIndices;
1917 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1918 // Look at the canonical type of the controlling expression in case it was a
1919 // deduced type like __auto_type. However, when issuing diagnostics, use the
1920 // type the user wrote in source rather than the canonical one.
1921 for (unsigned i = 0; i < NumAssocs; ++i) {
1922 if (!Types[i])
1923 DefaultIndex = i;
1924 else if (ControllingExpr &&
1925 Context.typesAreCompatible(
1926 ControllingExpr->getType().getCanonicalType(),
1927 Types[i]->getType()))
1928 CompatIndices.push_back(i);
1929 else if (ControllingType &&
1930 Context.typesAreCompatible(
1931 ControllingType->getType().getCanonicalType(),
1932 Types[i]->getType()))
1933 CompatIndices.push_back(i);
1934 }
1935
1936 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1937 TypeSourceInfo *ControllingType) {
1938 // We strip parens here because the controlling expression is typically
1939 // parenthesized in macro definitions.
1940 if (ControllingExpr)
1941 ControllingExpr = ControllingExpr->IgnoreParens();
1942
1943 SourceRange SR = ControllingExpr
1944 ? ControllingExpr->getSourceRange()
1945 : ControllingType->getTypeLoc().getSourceRange();
1946 QualType QT = ControllingExpr ? ControllingExpr->getType()
1947 : ControllingType->getType();
1948
1949 return std::make_pair(SR, QT);
1950 };
1951
1952 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1953 // type compatible with at most one of the types named in its generic
1954 // association list."
1955 if (CompatIndices.size() > 1) {
1956 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1957 SourceRange SR = P.first;
1958 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1959 << SR << P.second << (unsigned)CompatIndices.size();
1960 for (unsigned I : CompatIndices) {
1961 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1962 diag::note_compat_assoc)
1963 << Types[I]->getTypeLoc().getSourceRange()
1964 << Types[I]->getType();
1965 }
1966 return ExprError();
1967 }
1968
1969 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1970 // its controlling expression shall have type compatible with exactly one of
1971 // the types named in its generic association list."
1972 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1973 CompatIndices.size() == 0) {
1974 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1975 SourceRange SR = P.first;
1976 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1977 return ExprError();
1978 }
1979
1980 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1981 // type name that is compatible with the type of the controlling expression,
1982 // then the result expression of the generic selection is the expression
1983 // in that generic association. Otherwise, the result expression of the
1984 // generic selection is the expression in the default generic association."
1985 unsigned ResultIndex =
1986 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1987
1988 if (ControllingExpr) {
1989 return GenericSelectionExpr::Create(
1990 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1991 ContainsUnexpandedParameterPack, ResultIndex);
1992 }
1993 return GenericSelectionExpr::Create(
1994 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1995 ContainsUnexpandedParameterPack, ResultIndex);
1996 }
1997
1998 static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
1999 switch (Kind) {
2000 default:
2001 llvm_unreachable("unexpected TokenKind");
2002 case tok::kw___func__:
2003 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2004 case tok::kw___FUNCTION__:
2005 return PredefinedIdentKind::Function;
2006 case tok::kw___FUNCDNAME__:
2007 return PredefinedIdentKind::FuncDName; // [MS]
2008 case tok::kw___FUNCSIG__:
2009 return PredefinedIdentKind::FuncSig; // [MS]
2010 case tok::kw_L__FUNCTION__:
2011 return PredefinedIdentKind::LFunction; // [MS]
2012 case tok::kw_L__FUNCSIG__:
2013 return PredefinedIdentKind::LFuncSig; // [MS]
2014 case tok::kw___PRETTY_FUNCTION__:
2015 return PredefinedIdentKind::PrettyFunction; // [GNU]
2016 }
2017 }
2018
2019 /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2020 /// to determine the value of a PredefinedExpr. This can be either a
2021 /// block, lambda, captured statement, function, otherwise a nullptr.
2022 static Decl *getPredefinedExprDecl(DeclContext *DC) {
2023 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
2024 DC = DC->getParent();
2025 return cast_or_null<Decl>(DC);
2026 }
2027
2028 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2029 /// location of the token and the offset of the ud-suffix within it.
2030 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2031 unsigned Offset) {
2032 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2033 S.getLangOpts());
2034 }
2035
2036 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2037 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
2038 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2039 IdentifierInfo *UDSuffix,
2040 SourceLocation UDSuffixLoc,
2041 ArrayRef<Expr*> Args,
2042 SourceLocation LitEndLoc) {
2043 assert(Args.size() <= 2 && "too many arguments for literal operator");
2044
2045 QualType ArgTy[2];
2046 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2047 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2048 if (ArgTy[ArgIdx]->isArrayType())
2049 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2050 }
2051
2052 DeclarationName OpName =
2053 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2054 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2055 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2056
2057 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2058 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2059 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2060 /*AllowStringTemplatePack*/ false,
2061 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2062 return ExprError();
2063
2064 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2065 }
2066
2067 ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2068 // StringToks needs backing storage as it doesn't hold array elements itself
2069 std::vector<Token> ExpandedToks;
2070 if (getLangOpts().MicrosoftExt)
2071 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2072
2073 StringLiteralParser Literal(StringToks, PP,
2074 StringLiteralEvalMethod::Unevaluated);
2075 if (Literal.hadError)
2076 return ExprError();
2077
2078 SmallVector<SourceLocation, 4> StringTokLocs;
2079 for (const Token &Tok : StringToks)
2080 StringTokLocs.push_back(Tok.getLocation());
2081
2082 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2083 StringLiteralKind::Unevaluated,
2084 false, {}, StringTokLocs);
2085
2086 if (!Literal.getUDSuffix().empty()) {
2087 SourceLocation UDSuffixLoc =
2088 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2089 Literal.getUDSuffixOffset());
2090 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2091 }
2092
2093 return Lit;
2094 }
2095
2096 std::vector<Token>
2097 Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2098 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2099 // local macros that expand to string literals that may be concatenated.
2100 // These macros are expanded here (in Sema), because StringLiteralParser
2101 // (in Lex) doesn't know the enclosing function (because it hasn't been
2102 // parsed yet).
2103 assert(getLangOpts().MicrosoftExt);
2104
2105 // Note: Although function local macros are defined only inside functions,
2106 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2107 // expansion of macros into empty string literals without additional checks.
2108 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2109 if (!CurrentDecl)
2110 CurrentDecl = Context.getTranslationUnitDecl();
2111
2112 std::vector<Token> ExpandedToks;
2113 ExpandedToks.reserve(Toks.size());
2114 for (const Token &Tok : Toks) {
2115 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2116 assert(tok::isStringLiteral(Tok.getKind()));
2117 ExpandedToks.emplace_back(Tok);
2118 continue;
2119 }
2120 if (isa<TranslationUnitDecl>(CurrentDecl))
2121 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2122 // Stringify predefined expression
2123 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2124 << Tok.getKind();
2125 SmallString<64> Str;
2126 llvm::raw_svector_ostream OS(Str);
2127 Token &Exp = ExpandedToks.emplace_back();
2128 Exp.startToken();
2129 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2130 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2131 OS << 'L';
2132 Exp.setKind(tok::wide_string_literal);
2133 } else {
2134 Exp.setKind(tok::string_literal);
2135 }
2136 OS << '"'
2137 << Lexer::Stringify(PredefinedExpr::ComputeName(
2138 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2139 << '"';
2140 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2141 }
2142 return ExpandedToks;
2143 }
2144
2145 ExprResult
2146 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2147 assert(!StringToks.empty() && "Must have at least one string!");
2148
2149 // StringToks needs backing storage as it doesn't hold array elements itself
2150 std::vector<Token> ExpandedToks;
2151 if (getLangOpts().MicrosoftExt)
2152 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2153
2154 StringLiteralParser Literal(StringToks, PP);
2155 if (Literal.hadError)
2156 return ExprError();
2157
2158 SmallVector<SourceLocation, 4> StringTokLocs;
2159 for (const Token &Tok : StringToks)
2160 StringTokLocs.push_back(Tok.getLocation());
2161
2162 QualType CharTy = Context.CharTy;
2163 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2164 if (Literal.isWide()) {
2165 CharTy = Context.getWideCharType();
2166 Kind = StringLiteralKind::Wide;
2167 } else if (Literal.isUTF8()) {
2168 if (getLangOpts().Char8)
2169 CharTy = Context.Char8Ty;
2170 else if (getLangOpts().C23)
2171 CharTy = Context.UnsignedCharTy;
2172 Kind = StringLiteralKind::UTF8;
2173 } else if (Literal.isUTF16()) {
2174 CharTy = Context.Char16Ty;
2175 Kind = StringLiteralKind::UTF16;
2176 } else if (Literal.isUTF32()) {
2177 CharTy = Context.Char32Ty;
2178 Kind = StringLiteralKind::UTF32;
2179 } else if (Literal.isPascal()) {
2180 CharTy = Context.UnsignedCharTy;
2181 }
2182
2183 // Warn on u8 string literals before C++20 and C23, whose type
2184 // was an array of char before but becomes an array of char8_t.
2185 // In C++20, it cannot be used where a pointer to char is expected.
2186 // In C23, it might have an unexpected value if char was signed.
2187 if (Kind == StringLiteralKind::UTF8 &&
2188 (getLangOpts().CPlusPlus
2189 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2190 : !getLangOpts().C23)) {
2191 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2192 ? diag::warn_cxx20_compat_utf8_string
2193 : diag::warn_c23_compat_utf8_string);
2194
2195 // Create removals for all 'u8' prefixes in the string literal(s). This
2196 // ensures C++20/C23 compatibility (but may change the program behavior when
2197 // built by non-Clang compilers for which the execution character set is
2198 // not always UTF-8).
2199 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2200 SourceLocation RemovalDiagLoc;
2201 for (const Token &Tok : StringToks) {
2202 if (Tok.getKind() == tok::utf8_string_literal) {
2203 if (RemovalDiagLoc.isInvalid())
2204 RemovalDiagLoc = Tok.getLocation();
2205 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2206 Tok.getLocation(),
2207 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2208 getSourceManager(), getLangOpts())));
2209 }
2210 }
2211 Diag(RemovalDiagLoc, RemovalDiag);
2212 }
2213
2214 QualType StrTy =
2215 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2216
2217 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2218 StringLiteral *Lit = StringLiteral::Create(
2219 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2220 if (Literal.getUDSuffix().empty())
2221 return Lit;
2222
2223 // We're building a user-defined literal.
2224 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2225 SourceLocation UDSuffixLoc =
2226 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2227 Literal.getUDSuffixOffset());
2228
2229 // Make sure we're allowed user-defined literals here.
2230 if (!UDLScope)
2231 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2232
2233 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2234 // operator "" X (str, len)
2235 QualType SizeType = Context.getSizeType();
2236
2237 DeclarationName OpName =
2238 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2239 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2240 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2241
2242 QualType ArgTy[] = {
2243 Context.getArrayDecayedType(StrTy), SizeType
2244 };
2245
2246 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2247 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2248 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2249 /*AllowStringTemplatePack*/ true,
2250 /*DiagnoseMissing*/ true, Lit)) {
2251
2252 case LOLR_Cooked: {
2253 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2254 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2255 StringTokLocs[0]);
2256 Expr *Args[] = { Lit, LenArg };
2257
2258 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2259 }
2260
2261 case LOLR_Template: {
2262 TemplateArgumentListInfo ExplicitArgs;
2263 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2264 TemplateArgumentLocInfo ArgInfo(Lit);
2265 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2266 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2267 &ExplicitArgs);
2268 }
2269
2270 case LOLR_StringTemplatePack: {
2271 TemplateArgumentListInfo ExplicitArgs;
2272
2273 unsigned CharBits = Context.getIntWidth(CharTy);
2274 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2275 llvm::APSInt Value(CharBits, CharIsUnsigned);
2276
2277 TemplateArgument TypeArg(CharTy);
2278 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2279 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2280
2281 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2282 Value = Lit->getCodeUnit(I);
2283 TemplateArgument Arg(Context, Value, CharTy);
2284 TemplateArgumentLocInfo ArgInfo;
2285 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2286 }
2287 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2288 &ExplicitArgs);
2289 }
2290 case LOLR_Raw:
2291 case LOLR_ErrorNoDiagnostic:
2292 llvm_unreachable("unexpected literal operator lookup result");
2293 case LOLR_Error:
2294 return ExprError();
2295 }
2296 llvm_unreachable("unexpected literal operator lookup result");
2297 }
2298
2299 DeclRefExpr *
2300 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2301 SourceLocation Loc,
2302 const CXXScopeSpec *SS) {
2303 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2304 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2305 }
2306
2307 DeclRefExpr *
2308 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2309 const DeclarationNameInfo &NameInfo,
2310 const CXXScopeSpec *SS, NamedDecl *FoundD,
2311 SourceLocation TemplateKWLoc,
2312 const TemplateArgumentListInfo *TemplateArgs) {
2313 NestedNameSpecifierLoc NNS =
2314 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2315 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2316 TemplateArgs);
2317 }
2318
2319 // CUDA/HIP: Check whether a captured reference variable is referencing a
2320 // host variable in a device or host device lambda.
2321 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2322 VarDecl *VD) {
2323 if (!S.getLangOpts().CUDA || !VD->hasInit())
2324 return false;
2325 assert(VD->getType()->isReferenceType());
2326
2327 // Check whether the reference variable is referencing a host variable.
2328 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2329 if (!DRE)
2330 return false;
2331 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2332 if (!Referee || !Referee->hasGlobalStorage() ||
2333 Referee->hasAttr<CUDADeviceAttr>())
2334 return false;
2335
2336 // Check whether the current function is a device or host device lambda.
2337 // Check whether the reference variable is a capture by getDeclContext()
2338 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2339 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2340 if (MD && MD->getParent()->isLambda() &&
2341 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2342 VD->getDeclContext() != MD)
2343 return true;
2344
2345 return false;
2346 }
2347
2348 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2349 // A declaration named in an unevaluated operand never constitutes an odr-use.
2350 if (isUnevaluatedContext())
2351 return NOUR_Unevaluated;
2352
2353 // C++2a [basic.def.odr]p4:
2354 // A variable x whose name appears as a potentially-evaluated expression e
2355 // is odr-used by e unless [...] x is a reference that is usable in
2356 // constant expressions.
2357 // CUDA/HIP:
2358 // If a reference variable referencing a host variable is captured in a
2359 // device or host device lambda, the value of the referee must be copied
2360 // to the capture and the reference variable must be treated as odr-use
2361 // since the value of the referee is not known at compile time and must
2362 // be loaded from the captured.
2363 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2364 if (VD->getType()->isReferenceType() &&
2365 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2366 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2367 VD->isUsableInConstantExpressions(Context))
2368 return NOUR_Constant;
2369 }
2370
2371 // All remaining non-variable cases constitute an odr-use. For variables, we
2372 // need to wait and see how the expression is used.
2373 return NOUR_None;
2374 }
2375
2376 DeclRefExpr *
2377 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2378 const DeclarationNameInfo &NameInfo,
2379 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2380 SourceLocation TemplateKWLoc,
2381 const TemplateArgumentListInfo *TemplateArgs) {
2382 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2383 NeedToCaptureVariable(D, NameInfo.getLoc());
2384
2385 DeclRefExpr *E = DeclRefExpr::Create(
2386 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2387 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2388 MarkDeclRefReferenced(E);
2389
2390 // C++ [except.spec]p17:
2391 // An exception-specification is considered to be needed when:
2392 // - in an expression, the function is the unique lookup result or
2393 // the selected member of a set of overloaded functions.
2394 //
2395 // We delay doing this until after we've built the function reference and
2396 // marked it as used so that:
2397 // a) if the function is defaulted, we get errors from defining it before /
2398 // instead of errors from computing its exception specification, and
2399 // b) if the function is a defaulted comparison, we can use the body we
2400 // build when defining it as input to the exception specification
2401 // computation rather than computing a new body.
2402 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2403 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2404 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2405 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2406 }
2407 }
2408
2409 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2410 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2411 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2412 getCurFunction()->recordUseOfWeak(E);
2413
2414 const auto *FD = dyn_cast<FieldDecl>(D);
2415 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2416 FD = IFD->getAnonField();
2417 if (FD) {
2418 UnusedPrivateFields.remove(FD);
2419 // Just in case we're building an illegal pointer-to-member.
2420 if (FD->isBitField())
2421 E->setObjectKind(OK_BitField);
2422 }
2423
2424 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2425 // designates a bit-field.
2426 if (const auto *BD = dyn_cast<BindingDecl>(D))
2427 if (const auto *BE = BD->getBinding())
2428 E->setObjectKind(BE->getObjectKind());
2429
2430 return E;
2431 }
2432
2433 void
2434 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2435 TemplateArgumentListInfo &Buffer,
2436 DeclarationNameInfo &NameInfo,
2437 const TemplateArgumentListInfo *&TemplateArgs) {
2438 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2439 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2440 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2441
2442 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2443 Id.TemplateId->NumArgs);
2444 translateTemplateArguments(TemplateArgsPtr, Buffer);
2445
2446 TemplateName TName = Id.TemplateId->Template.get();
2447 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2448 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2449 TemplateArgs = &Buffer;
2450 } else {
2451 NameInfo = GetNameFromUnqualifiedId(Id);
2452 TemplateArgs = nullptr;
2453 }
2454 }
2455
2456 bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2457 // During a default argument instantiation the CurContext points
2458 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2459 // function parameter list, hence add an explicit check.
2460 bool isDefaultArgument =
2461 !CodeSynthesisContexts.empty() &&
2462 CodeSynthesisContexts.back().Kind ==
2463 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2464 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2465 bool isInstance = CurMethod && CurMethod->isInstance() &&
2466 R.getNamingClass() == CurMethod->getParent() &&
2467 !isDefaultArgument;
2468
2469 // There are two ways we can find a class-scope declaration during template
2470 // instantiation that we did not find in the template definition: if it is a
2471 // member of a dependent base class, or if it is declared after the point of
2472 // use in the same class. Distinguish these by comparing the class in which
2473 // the member was found to the naming class of the lookup.
2474 unsigned DiagID = diag::err_found_in_dependent_base;
2475 unsigned NoteID = diag::note_member_declared_at;
2476 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2477 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2478 : diag::err_found_later_in_class;
2479 } else if (getLangOpts().MSVCCompat) {
2480 DiagID = diag::ext_found_in_dependent_base;
2481 NoteID = diag::note_dependent_member_use;
2482 }
2483
2484 if (isInstance) {
2485 // Give a code modification hint to insert 'this->'.
2486 Diag(R.getNameLoc(), DiagID)
2487 << R.getLookupName()
2488 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2489 CheckCXXThisCapture(R.getNameLoc());
2490 } else {
2491 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2492 // they're not shadowed).
2493 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2494 }
2495
2496 for (const NamedDecl *D : R)
2497 Diag(D->getLocation(), NoteID);
2498
2499 // Return true if we are inside a default argument instantiation
2500 // and the found name refers to an instance member function, otherwise
2501 // the caller will try to create an implicit member call and this is wrong
2502 // for default arguments.
2503 //
2504 // FIXME: Is this special case necessary? We could allow the caller to
2505 // diagnose this.
2506 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2507 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2508 return true;
2509 }
2510
2511 // Tell the callee to try to recover.
2512 return false;
2513 }
2514
2515 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2516 CorrectionCandidateCallback &CCC,
2517 TemplateArgumentListInfo *ExplicitTemplateArgs,
2518 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2519 DeclarationName Name = R.getLookupName();
2520 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2521
2522 unsigned diagnostic = diag::err_undeclared_var_use;
2523 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2524 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2525 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2526 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2527 diagnostic = diag::err_undeclared_use;
2528 diagnostic_suggest = diag::err_undeclared_use_suggest;
2529 }
2530
2531 // If the original lookup was an unqualified lookup, fake an
2532 // unqualified lookup. This is useful when (for example) the
2533 // original lookup would not have found something because it was a
2534 // dependent name.
2535 DeclContext *DC =
2536 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2537 while (DC) {
2538 if (isa<CXXRecordDecl>(DC)) {
2539 if (ExplicitTemplateArgs) {
2540 if (LookupTemplateName(
2541 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2542 /*EnteringContext*/ false, TemplateNameIsRequired,
2543 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2544 return true;
2545 } else {
2546 LookupQualifiedName(R, DC);
2547 }
2548
2549 if (!R.empty()) {
2550 // Don't give errors about ambiguities in this lookup.
2551 R.suppressDiagnostics();
2552
2553 // If there's a best viable function among the results, only mention
2554 // that one in the notes.
2555 OverloadCandidateSet Candidates(R.getNameLoc(),
2556 OverloadCandidateSet::CSK_Normal);
2557 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2558 OverloadCandidateSet::iterator Best;
2559 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2560 OR_Success) {
2561 R.clear();
2562 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2563 R.resolveKind();
2564 }
2565
2566 return DiagnoseDependentMemberLookup(R);
2567 }
2568
2569 R.clear();
2570 }
2571
2572 DC = DC->getLookupParent();
2573 }
2574
2575 // We didn't find anything, so try to correct for a typo.
2576 TypoCorrection Corrected;
2577 if (S && (Corrected =
2578 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2579 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2580 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2581 bool DroppedSpecifier =
2582 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2583 R.setLookupName(Corrected.getCorrection());
2584
2585 bool AcceptableWithRecovery = false;
2586 bool AcceptableWithoutRecovery = false;
2587 NamedDecl *ND = Corrected.getFoundDecl();
2588 if (ND) {
2589 if (Corrected.isOverloaded()) {
2590 OverloadCandidateSet OCS(R.getNameLoc(),
2591 OverloadCandidateSet::CSK_Normal);
2592 OverloadCandidateSet::iterator Best;
2593 for (NamedDecl *CD : Corrected) {
2594 if (FunctionTemplateDecl *FTD =
2595 dyn_cast<FunctionTemplateDecl>(CD))
2596 AddTemplateOverloadCandidate(
2597 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2598 Args, OCS);
2599 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2600 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2601 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2602 Args, OCS);
2603 }
2604 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2605 case OR_Success:
2606 ND = Best->FoundDecl;
2607 Corrected.setCorrectionDecl(ND);
2608 break;
2609 default:
2610 // FIXME: Arbitrarily pick the first declaration for the note.
2611 Corrected.setCorrectionDecl(ND);
2612 break;
2613 }
2614 }
2615 R.addDecl(ND);
2616 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2617 CXXRecordDecl *Record =
2618 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2619 if (!Record)
2620 Record = cast<CXXRecordDecl>(
2621 ND->getDeclContext()->getRedeclContext());
2622 R.setNamingClass(Record);
2623 }
2624
2625 auto *UnderlyingND = ND->getUnderlyingDecl();
2626 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2627 isa<FunctionTemplateDecl>(UnderlyingND);
2628 // FIXME: If we ended up with a typo for a type name or
2629 // Objective-C class name, we're in trouble because the parser
2630 // is in the wrong place to recover. Suggest the typo
2631 // correction, but don't make it a fix-it since we're not going
2632 // to recover well anyway.
2633 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2634 getAsTypeTemplateDecl(UnderlyingND) ||
2635 isa<ObjCInterfaceDecl>(UnderlyingND);
2636 } else {
2637 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2638 // because we aren't able to recover.
2639 AcceptableWithoutRecovery = true;
2640 }
2641
2642 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2643 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2644 ? diag::note_implicit_param_decl
2645 : diag::note_previous_decl;
2646 if (SS.isEmpty())
2647 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2648 PDiag(NoteID), AcceptableWithRecovery);
2649 else
2650 diagnoseTypo(Corrected,
2651 PDiag(diag::err_no_member_suggest)
2652 << Name << computeDeclContext(SS, false)
2653 << DroppedSpecifier << NameRange,
2654 PDiag(NoteID), AcceptableWithRecovery);
2655
2656 if (Corrected.WillReplaceSpecifier()) {
2657 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2658 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2659 SS.MakeTrivial(Context, NNS,
2660 NNS ? NameRange.getBegin() : SourceRange());
2661 }
2662
2663 // Tell the callee whether to try to recover.
2664 return !AcceptableWithRecovery;
2665 }
2666 }
2667 R.clear();
2668
2669 // Emit a special diagnostic for failed member lookups.
2670 // FIXME: computing the declaration context might fail here (?)
2671 if (!SS.isEmpty()) {
2672 Diag(R.getNameLoc(), diag::err_no_member)
2673 << Name << computeDeclContext(SS, false) << NameRange;
2674 return true;
2675 }
2676
2677 // Give up, we can't recover.
2678 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2679 return true;
2680 }
2681
2682 /// In Microsoft mode, if we are inside a template class whose parent class has
2683 /// dependent base classes, and we can't resolve an unqualified identifier, then
2684 /// assume the identifier is a member of a dependent base class. We can only
2685 /// recover successfully in static methods, instance methods, and other contexts
2686 /// where 'this' is available. This doesn't precisely match MSVC's
2687 /// instantiation model, but it's close enough.
2688 static Expr *
2689 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2690 DeclarationNameInfo &NameInfo,
2691 SourceLocation TemplateKWLoc,
2692 const TemplateArgumentListInfo *TemplateArgs) {
2693 // Only try to recover from lookup into dependent bases in static methods or
2694 // contexts where 'this' is available.
2695 QualType ThisType = S.getCurrentThisType();
2696 const CXXRecordDecl *RD = nullptr;
2697 if (!ThisType.isNull())
2698 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2699 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2700 RD = MD->getParent();
2701 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2702 return nullptr;
2703
2704 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2705 // is available, suggest inserting 'this->' as a fixit.
2706 SourceLocation Loc = NameInfo.getLoc();
2707 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2708 DB << NameInfo.getName() << RD;
2709
2710 if (!ThisType.isNull()) {
2711 DB << FixItHint::CreateInsertion(Loc, "this->");
2712 return CXXDependentScopeMemberExpr::Create(
2713 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2714 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2715 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2716 }
2717
2718 // Synthesize a fake NNS that points to the derived class. This will
2719 // perform name lookup during template instantiation.
2720 CXXScopeSpec SS;
2721 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2722 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2723 return DependentScopeDeclRefExpr::Create(
2724 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2725 TemplateArgs);
2726 }
2727
2728 ExprResult
2729 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2730 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2731 bool HasTrailingLParen, bool IsAddressOfOperand,
2732 CorrectionCandidateCallback *CCC,
2733 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2734 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2735 "cannot be direct & operand and have a trailing lparen");
2736 if (SS.isInvalid())
2737 return ExprError();
2738
2739 TemplateArgumentListInfo TemplateArgsBuffer;
2740
2741 // Decompose the UnqualifiedId into the following data.
2742 DeclarationNameInfo NameInfo;
2743 const TemplateArgumentListInfo *TemplateArgs;
2744 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2745
2746 DeclarationName Name = NameInfo.getName();
2747 IdentifierInfo *II = Name.getAsIdentifierInfo();
2748 SourceLocation NameLoc = NameInfo.getLoc();
2749
2750 if (II && II->isEditorPlaceholder()) {
2751 // FIXME: When typed placeholders are supported we can create a typed
2752 // placeholder expression node.
2753 return ExprError();
2754 }
2755
2756 // This specially handles arguments of attributes appertains to a type of C
2757 // struct field such that the name lookup within a struct finds the member
2758 // name, which is not the case for other contexts in C.
2759 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2760 // See if this is reference to a field of struct.
2761 LookupResult R(*this, NameInfo, LookupMemberName);
2762 // LookupName handles a name lookup from within anonymous struct.
2763 if (LookupName(R, S)) {
2764 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2765 QualType type = VD->getType().getNonReferenceType();
2766 // This will eventually be translated into MemberExpr upon
2767 // the use of instantiated struct fields.
2768 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2769 }
2770 }
2771 }
2772
2773 // Perform the required lookup.
2774 LookupResult R(*this, NameInfo,
2775 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2776 ? LookupObjCImplicitSelfParam
2777 : LookupOrdinaryName);
2778 if (TemplateKWLoc.isValid() || TemplateArgs) {
2779 // Lookup the template name again to correctly establish the context in
2780 // which it was found. This is really unfortunate as we already did the
2781 // lookup to determine that it was a template name in the first place. If
2782 // this becomes a performance hit, we can work harder to preserve those
2783 // results until we get here but it's likely not worth it.
2784 AssumedTemplateKind AssumedTemplate;
2785 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2786 /*EnteringContext=*/false, TemplateKWLoc,
2787 &AssumedTemplate))
2788 return ExprError();
2789
2790 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2791 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2792 IsAddressOfOperand, TemplateArgs);
2793 } else {
2794 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2795 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2796 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2797
2798 // If the result might be in a dependent base class, this is a dependent
2799 // id-expression.
2800 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2801 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2802 IsAddressOfOperand, TemplateArgs);
2803
2804 // If this reference is in an Objective-C method, then we need to do
2805 // some special Objective-C lookup, too.
2806 if (IvarLookupFollowUp) {
2807 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2808 if (E.isInvalid())
2809 return ExprError();
2810
2811 if (Expr *Ex = E.getAs<Expr>())
2812 return Ex;
2813 }
2814 }
2815
2816 if (R.isAmbiguous())
2817 return ExprError();
2818
2819 // This could be an implicitly declared function reference if the language
2820 // mode allows it as a feature.
2821 if (R.empty() && HasTrailingLParen && II &&
2822 getLangOpts().implicitFunctionsAllowed()) {
2823 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2824 if (D) R.addDecl(D);
2825 }
2826
2827 // Determine whether this name might be a candidate for
2828 // argument-dependent lookup.
2829 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2830
2831 if (R.empty() && !ADL) {
2832 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2833 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2834 TemplateKWLoc, TemplateArgs))
2835 return E;
2836 }
2837
2838 // Don't diagnose an empty lookup for inline assembly.
2839 if (IsInlineAsmIdentifier)
2840 return ExprError();
2841
2842 // If this name wasn't predeclared and if this is not a function
2843 // call, diagnose the problem.
2844 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2845 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2846 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2847 "Typo correction callback misconfigured");
2848 if (CCC) {
2849 // Make sure the callback knows what the typo being diagnosed is.
2850 CCC->setTypoName(II);
2851 if (SS.isValid())
2852 CCC->setTypoNNS(SS.getScopeRep());
2853 }
2854 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2855 // a template name, but we happen to have always already looked up the name
2856 // before we get here if it must be a template name.
2857 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2858 {}, nullptr))
2859 return ExprError();
2860
2861 assert(!R.empty() &&
2862 "DiagnoseEmptyLookup returned false but added no results");
2863
2864 // If we found an Objective-C instance variable, let
2865 // LookupInObjCMethod build the appropriate expression to
2866 // reference the ivar.
2867 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2868 R.clear();
2869 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2870 // In a hopelessly buggy code, Objective-C instance variable
2871 // lookup fails and no expression will be built to reference it.
2872 if (!E.isInvalid() && !E.get())
2873 return ExprError();
2874 return E;
2875 }
2876 }
2877
2878 // This is guaranteed from this point on.
2879 assert(!R.empty() || ADL);
2880
2881 // Check whether this might be a C++ implicit instance member access.
2882 // C++ [class.mfct.non-static]p3:
2883 // When an id-expression that is not part of a class member access
2884 // syntax and not used to form a pointer to member is used in the
2885 // body of a non-static member function of class X, if name lookup
2886 // resolves the name in the id-expression to a non-static non-type
2887 // member of some class C, the id-expression is transformed into a
2888 // class member access expression using (*this) as the
2889 // postfix-expression to the left of the . operator.
2890 //
2891 // But we don't actually need to do this for '&' operands if R
2892 // resolved to a function or overloaded function set, because the
2893 // expression is ill-formed if it actually works out to be a
2894 // non-static member function:
2895 //
2896 // C++ [expr.ref]p4:
2897 // Otherwise, if E1.E2 refers to a non-static member function. . .
2898 // [t]he expression can be used only as the left-hand operand of a
2899 // member function call.
2900 //
2901 // There are other safeguards against such uses, but it's important
2902 // to get this right here so that we don't end up making a
2903 // spuriously dependent expression if we're inside a dependent
2904 // instance method.
2905 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2906 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2907 S);
2908
2909 if (TemplateArgs || TemplateKWLoc.isValid()) {
2910
2911 // In C++1y, if this is a variable template id, then check it
2912 // in BuildTemplateIdExpr().
2913 // The single lookup result must be a variable template declaration.
2914 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2915 (Id.TemplateId->Kind == TNK_Var_template ||
2916 Id.TemplateId->Kind == TNK_Concept_template)) {
2917 assert(R.getAsSingle<TemplateDecl>() &&
2918 "There should only be one declaration found.");
2919 }
2920
2921 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2922 }
2923
2924 return BuildDeclarationNameExpr(SS, R, ADL);
2925 }
2926
2927 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2928 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2929 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2930 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2931 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2932
2933 if (R.isAmbiguous())
2934 return ExprError();
2935
2936 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2937 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2938 NameInfo, /*TemplateArgs=*/nullptr);
2939
2940 if (R.empty()) {
2941 // Don't diagnose problems with invalid record decl, the secondary no_member
2942 // diagnostic during template instantiation is likely bogus, e.g. if a class
2943 // is invalid because it's derived from an invalid base class, then missing
2944 // members were likely supposed to be inherited.
2945 DeclContext *DC = computeDeclContext(SS);
2946 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2947 if (CD->isInvalidDecl() || CD->isBeingDefined())
2948 return ExprError();
2949 Diag(NameInfo.getLoc(), diag::err_no_member)
2950 << NameInfo.getName() << DC << SS.getRange();
2951 return ExprError();
2952 }
2953
2954 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2955 QualType ET;
2956 TypeLocBuilder TLB;
2957 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
2958 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
2959 SS.getScopeRep(), TagD,
2960 /*OwnsTag=*/false);
2961 auto TL = TLB.push<TagTypeLoc>(ET);
2962 TL.setElaboratedKeywordLoc(SourceLocation());
2963 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2964 TL.setNameLoc(NameInfo.getLoc());
2965 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
2966 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
2967 SS.getScopeRep(), TypedefD);
2968 TLB.push<TypedefTypeLoc>(ET).set(
2969 /*ElaboratedKeywordLoc=*/SourceLocation(),
2970 SS.getWithLocInContext(Context), NameInfo.getLoc());
2971 } else {
2972 // FIXME: What else can appear here?
2973 ET = SemaRef.Context.getTypeDeclType(TD);
2974 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
2975 assert(SS.isEmpty());
2976 }
2977
2978 // Diagnose a missing typename if this resolved unambiguously to a type in
2979 // a dependent context. If we can recover with a type, downgrade this to
2980 // a warning in Microsoft compatibility mode.
2981 unsigned DiagID = diag::err_typename_missing;
2982 if (RecoveryTSI && getLangOpts().MSVCCompat)
2983 DiagID = diag::ext_typename_missing;
2984 SourceLocation Loc = SS.getBeginLoc();
2985 auto D = Diag(Loc, DiagID);
2986 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2987
2988 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2989 // context.
2990 if (!RecoveryTSI)
2991 return ExprError();
2992
2993 // Only issue the fixit if we're prepared to recover.
2994 D << FixItHint::CreateInsertion(Loc, "typename ");
2995
2996 // Recover by pretending this was an elaborated type.
2997 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2998
2999 return ExprEmpty();
3000 }
3001
3002 // If necessary, build an implicit class member access.
3003 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3004 return BuildPossibleImplicitMemberExpr(SS,
3005 /*TemplateKWLoc=*/SourceLocation(),
3006 R, /*TemplateArgs=*/nullptr,
3007 /*S=*/nullptr);
3008
3009 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3010 }
3011
3012 ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3013 NestedNameSpecifier Qualifier,
3014 NamedDecl *FoundDecl,
3015 NamedDecl *Member) {
3016 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3017 if (!RD)
3018 return From;
3019
3020 QualType DestRecordType;
3021 QualType DestType;
3022 QualType FromRecordType;
3023 QualType FromType = From->getType();
3024 bool PointerConversions = false;
3025 if (isa<FieldDecl>(Member)) {
3026 DestRecordType = Context.getCanonicalTagType(RD);
3027 auto FromPtrType = FromType->getAs<PointerType>();
3028 DestRecordType = Context.getAddrSpaceQualType(
3029 DestRecordType, FromPtrType
3030 ? FromType->getPointeeType().getAddressSpace()
3031 : FromType.getAddressSpace());
3032
3033 if (FromPtrType) {
3034 DestType = Context.getPointerType(DestRecordType);
3035 FromRecordType = FromPtrType->getPointeeType();
3036 PointerConversions = true;
3037 } else {
3038 DestType = DestRecordType;
3039 FromRecordType = FromType;
3040 }
3041 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3042 if (!Method->isImplicitObjectMemberFunction())
3043 return From;
3044
3045 DestType = Method->getThisType().getNonReferenceType();
3046 DestRecordType = Method->getFunctionObjectParameterType();
3047
3048 if (FromType->getAs<PointerType>()) {
3049 FromRecordType = FromType->getPointeeType();
3050 PointerConversions = true;
3051 } else {
3052 FromRecordType = FromType;
3053 DestType = DestRecordType;
3054 }
3055
3056 LangAS FromAS = FromRecordType.getAddressSpace();
3057 LangAS DestAS = DestRecordType.getAddressSpace();
3058 if (FromAS != DestAS) {
3059 QualType FromRecordTypeWithoutAS =
3060 Context.removeAddrSpaceQualType(FromRecordType);
3061 QualType FromTypeWithDestAS =
3062 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3063 if (PointerConversions)
3064 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3065 From = ImpCastExprToType(From, FromTypeWithDestAS,
3066 CK_AddressSpaceConversion, From->getValueKind())
3067 .get();
3068 }
3069 } else {
3070 // No conversion necessary.
3071 return From;
3072 }
3073
3074 if (DestType->isDependentType() || FromType->isDependentType())
3075 return From;
3076
3077 // If the unqualified types are the same, no conversion is necessary.
3078 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3079 return From;
3080
3081 SourceRange FromRange = From->getSourceRange();
3082 SourceLocation FromLoc = FromRange.getBegin();
3083
3084 ExprValueKind VK = From->getValueKind();
3085
3086 // C++ [class.member.lookup]p8:
3087 // [...] Ambiguities can often be resolved by qualifying a name with its
3088 // class name.
3089 //
3090 // If the member was a qualified name and the qualified referred to a
3091 // specific base subobject type, we'll cast to that intermediate type
3092 // first and then to the object in which the member is declared. That allows
3093 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3094 //
3095 // class Base { public: int x; };
3096 // class Derived1 : public Base { };
3097 // class Derived2 : public Base { };
3098 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3099 //
3100 // void VeryDerived::f() {
3101 // x = 17; // error: ambiguous base subobjects
3102 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3103 // }
3104 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3105 QualType QType = QualType(Qualifier.getAsType(), 0);
3106 assert(QType->isRecordType() && "lookup done with non-record type");
3107
3108 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3109
3110 // In C++98, the qualifier type doesn't actually have to be a base
3111 // type of the object type, in which case we just ignore it.
3112 // Otherwise build the appropriate casts.
3113 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3114 CXXCastPath BasePath;
3115 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3116 FromLoc, FromRange, &BasePath))
3117 return ExprError();
3118
3119 if (PointerConversions)
3120 QType = Context.getPointerType(QType);
3121 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3122 VK, &BasePath).get();
3123
3124 FromType = QType;
3125 FromRecordType = QRecordType;
3126
3127 // If the qualifier type was the same as the destination type,
3128 // we're done.
3129 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3130 return From;
3131 }
3132 }
3133
3134 CXXCastPath BasePath;
3135 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3136 FromLoc, FromRange, &BasePath,
3137 /*IgnoreAccess=*/true))
3138 return ExprError();
3139
3140 // Propagate qualifiers to base subobjects as per:
3141 // C++ [basic.type.qualifier]p1.2:
3142 // A volatile object is [...] a subobject of a volatile object.
3143 Qualifiers FromTypeQuals = FromType.getQualifiers();
3144 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3145 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3146
3147 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3148 &BasePath);
3149 }
3150
3151 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3152 const LookupResult &R,
3153 bool HasTrailingLParen) {
3154 // Only when used directly as the postfix-expression of a call.
3155 if (!HasTrailingLParen)
3156 return false;
3157
3158 // Never if a scope specifier was provided.
3159 if (SS.isNotEmpty())
3160 return false;
3161
3162 // Only in C++ or ObjC++.
3163 if (!getLangOpts().CPlusPlus)
3164 return false;
3165
3166 // Turn off ADL when we find certain kinds of declarations during
3167 // normal lookup:
3168 for (const NamedDecl *D : R) {
3169 // C++0x [basic.lookup.argdep]p3:
3170 // -- a declaration of a class member
3171 // Since using decls preserve this property, we check this on the
3172 // original decl.
3173 if (D->isCXXClassMember())
3174 return false;
3175
3176 // C++0x [basic.lookup.argdep]p3:
3177 // -- a block-scope function declaration that is not a
3178 // using-declaration
3179 // NOTE: we also trigger this for function templates (in fact, we
3180 // don't check the decl type at all, since all other decl types
3181 // turn off ADL anyway).
3182 if (isa<UsingShadowDecl>(D))
3183 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3184 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3185 return false;
3186
3187 // C++0x [basic.lookup.argdep]p3:
3188 // -- a declaration that is neither a function or a function
3189 // template
3190 // And also for builtin functions.
3191 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3192 // But also builtin functions.
3193 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3194 return false;
3195 } else if (!isa<FunctionTemplateDecl>(D))
3196 return false;
3197 }
3198
3199 return true;
3200 }
3201
3202
3203 /// Diagnoses obvious problems with the use of the given declaration
3204 /// as an expression. This is only actually called for lookups that
3205 /// were not overloaded, and it doesn't promise that the declaration
3206 /// will in fact be used.
3207 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3208 bool AcceptInvalid) {
3209 if (D->isInvalidDecl() && !AcceptInvalid)
3210 return true;
3211
3212 if (isa<TypedefNameDecl>(D)) {
3213 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3214 return true;
3215 }
3216
3217 if (isa<ObjCInterfaceDecl>(D)) {
3218 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3219 return true;
3220 }
3221
3222 if (isa<NamespaceDecl>(D)) {
3223 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3224 return true;
3225 }
3226
3227 return false;
3228 }
3229
3230 // Certain multiversion types should be treated as overloaded even when there is
3231 // only one result.
3232 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3233 assert(R.isSingleResult() && "Expected only a single result");
3234 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3235 return FD &&
3236 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3237 }
3238
3239 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3240 LookupResult &R, bool NeedsADL,
3241 bool AcceptInvalidDecl) {
3242 // If this is a single, fully-resolved result and we don't need ADL,
3243 // just build an ordinary singleton decl ref.
3244 if (!NeedsADL && R.isSingleResult() &&
3245 !R.getAsSingle<FunctionTemplateDecl>() &&
3246 !ShouldLookupResultBeMultiVersionOverload(R))
3247 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3248 R.getRepresentativeDecl(), nullptr,
3249 AcceptInvalidDecl);
3250
3251 // We only need to check the declaration if there's exactly one
3252 // result, because in the overloaded case the results can only be
3253 // functions and function templates.
3254 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3255 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3256 AcceptInvalidDecl))
3257 return ExprError();
3258
3259 // Otherwise, just build an unresolved lookup expression. Suppress
3260 // any lookup-related diagnostics; we'll hash these out later, when
3261 // we've picked a target.
3262 R.suppressDiagnostics();
3263
3264 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3265 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3266 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3267 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3268
3269 return ULE;
3270 }
3271
3272 ExprResult Sema::BuildDeclarationNameExpr(
3273 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3274 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3275 bool AcceptInvalidDecl) {
3276 assert(D && "Cannot refer to a NULL declaration");
3277 assert(!isa<FunctionTemplateDecl>(D) &&
3278 "Cannot refer unambiguously to a function template");
3279
3280 SourceLocation Loc = NameInfo.getLoc();
3281 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3282 // Recovery from invalid cases (e.g. D is an invalid Decl).
3283 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3284 // diagnostics, as invalid decls use int as a fallback type.
3285 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3286 }
3287
3288 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3289 // Specifically diagnose references to class templates that are missing
3290 // a template argument list.
3291 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3292 return ExprError();
3293 }
3294
3295 // Make sure that we're referring to a value.
3296 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3297 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3298 Diag(D->getLocation(), diag::note_declared_at);
3299 return ExprError();
3300 }
3301
3302 // Check whether this declaration can be used. Note that we suppress
3303 // this check when we're going to perform argument-dependent lookup
3304 // on this function name, because this might not be the function
3305 // that overload resolution actually selects.
3306 if (DiagnoseUseOfDecl(D, Loc))
3307 return ExprError();
3308
3309 auto *VD = cast<ValueDecl>(D);
3310
3311 // Only create DeclRefExpr's for valid Decl's.
3312 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3313 return ExprError();
3314
3315 // Handle members of anonymous structs and unions. If we got here,
3316 // and the reference is to a class member indirect field, then this
3317 // must be the subject of a pointer-to-member expression.
3318 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3319 IndirectField && !IndirectField->isCXXClassMember())
3320 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3321 IndirectField);
3322
3323 QualType type = VD->getType();
3324 if (type.isNull())
3325 return ExprError();
3326 ExprValueKind valueKind = VK_PRValue;
3327
3328 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3329 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3330 // is expanded by some outer '...' in the context of the use.
3331 type = type.getNonPackExpansionType();
3332
3333 switch (D->getKind()) {
3334 // Ignore all the non-ValueDecl kinds.
3335 #define ABSTRACT_DECL(kind)
3336 #define VALUE(type, base)
3337 #define DECL(type, base) case Decl::type:
3338 #include "clang/AST/DeclNodes.inc"
3339 llvm_unreachable("invalid value decl kind");
3340
3341 // These shouldn't make it here.
3342 case Decl::ObjCAtDefsField:
3343 llvm_unreachable("forming non-member reference to ivar?");
3344
3345 // Enum constants are always r-values and never references.
3346 // Unresolved using declarations are dependent.
3347 case Decl::EnumConstant:
3348 case Decl::UnresolvedUsingValue:
3349 case Decl::OMPDeclareReduction:
3350 case Decl::OMPDeclareMapper:
3351 valueKind = VK_PRValue;
3352 break;
3353
3354 // Fields and indirect fields that got here must be for
3355 // pointer-to-member expressions; we just call them l-values for
3356 // internal consistency, because this subexpression doesn't really
3357 // exist in the high-level semantics.
3358 case Decl::Field:
3359 case Decl::IndirectField:
3360 case Decl::ObjCIvar:
3361 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3362 "building reference to field in C?");
3363
3364 // These can't have reference type in well-formed programs, but
3365 // for internal consistency we do this anyway.
3366 type = type.getNonReferenceType();
3367 valueKind = VK_LValue;
3368 break;
3369
3370 // Non-type template parameters are either l-values or r-values
3371 // depending on the type.
3372 case Decl::NonTypeTemplateParm: {
3373 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3374 type = reftype->getPointeeType();
3375 valueKind = VK_LValue; // even if the parameter is an r-value reference
3376 break;
3377 }
3378
3379 // [expr.prim.id.unqual]p2:
3380 // If the entity is a template parameter object for a template
3381 // parameter of type T, the type of the expression is const T.
3382 // [...] The expression is an lvalue if the entity is a [...] template
3383 // parameter object.
3384 if (type->isRecordType()) {
3385 type = type.getUnqualifiedType().withConst();
3386 valueKind = VK_LValue;
3387 break;
3388 }
3389
3390 // For non-references, we need to strip qualifiers just in case
3391 // the template parameter was declared as 'const int' or whatever.
3392 valueKind = VK_PRValue;
3393 type = type.getUnqualifiedType();
3394 break;
3395 }
3396
3397 case Decl::Var:
3398 case Decl::VarTemplateSpecialization:
3399 case Decl::VarTemplatePartialSpecialization:
3400 case Decl::Decomposition:
3401 case Decl::Binding:
3402 case Decl::OMPCapturedExpr:
3403 // In C, "extern void blah;" is valid and is an r-value.
3404 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3405 type->isVoidType()) {
3406 valueKind = VK_PRValue;
3407 break;
3408 }
3409 [[fallthrough]];
3410
3411 case Decl::ImplicitParam:
3412 case Decl::ParmVar: {
3413 // These are always l-values.
3414 valueKind = VK_LValue;
3415 type = type.getNonReferenceType();
3416
3417 // FIXME: Does the addition of const really only apply in
3418 // potentially-evaluated contexts? Since the variable isn't actually
3419 // captured in an unevaluated context, it seems that the answer is no.
3420 if (!isUnevaluatedContext()) {
3421 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3422 if (!CapturedType.isNull())
3423 type = CapturedType;
3424 }
3425 break;
3426 }
3427
3428 case Decl::Function: {
3429 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3430 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3431 type = Context.BuiltinFnTy;
3432 valueKind = VK_PRValue;
3433 break;
3434 }
3435 }
3436
3437 const FunctionType *fty = type->castAs<FunctionType>();
3438
3439 // If we're referring to a function with an __unknown_anytype
3440 // result type, make the entire expression __unknown_anytype.
3441 if (fty->getReturnType() == Context.UnknownAnyTy) {
3442 type = Context.UnknownAnyTy;
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 // Functions are l-values in C++.
3448 if (getLangOpts().CPlusPlus) {
3449 valueKind = VK_LValue;
3450 break;
3451 }
3452
3453 // C99 DR 316 says that, if a function type comes from a
3454 // function definition (without a prototype), that type is only
3455 // used for checking compatibility. Therefore, when referencing
3456 // the function, we pretend that we don't have the full function
3457 // type.
3458 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3459 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3460 fty->getExtInfo());
3461
3462 // Functions are r-values in C.
3463 valueKind = VK_PRValue;
3464 break;
3465 }
3466
3467 case Decl::CXXDeductionGuide:
3468 llvm_unreachable("building reference to deduction guide");
3469
3470 case Decl::MSProperty:
3471 case Decl::MSGuid:
3472 case Decl::TemplateParamObject:
3473 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3474 // capture in OpenMP, or duplicated between host and device?
3475 valueKind = VK_LValue;
3476 break;
3477
3478 case Decl::UnnamedGlobalConstant:
3479 valueKind = VK_LValue;
3480 break;
3481
3482 case Decl::CXXMethod:
3483 // If we're referring to a method with an __unknown_anytype
3484 // result type, make the entire expression __unknown_anytype.
3485 // This should only be possible with a type written directly.
3486 if (const FunctionProtoType *proto =
3487 dyn_cast<FunctionProtoType>(VD->getType()))
3488 if (proto->getReturnType() == Context.UnknownAnyTy) {
3489 type = Context.UnknownAnyTy;
3490 valueKind = VK_PRValue;
3491 break;
3492 }
3493
3494 // C++ methods are l-values if static, r-values if non-static.
3495 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3496 valueKind = VK_LValue;
3497 break;
3498 }
3499 [[fallthrough]];
3500
3501 case Decl::CXXConversion:
3502 case Decl::CXXDestructor:
3503 case Decl::CXXConstructor:
3504 valueKind = VK_PRValue;
3505 break;
3506 }
3507
3508 auto *E =
3509 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3510 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3511 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3512 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3513 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3514 // diagnostics).
3515 if (VD->isInvalidDecl() && E)
3516 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3517 return E;
3518 }
3519
3520 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3521 SmallString<32> &Target) {
3522 Target.resize(CharByteWidth * (Source.size() + 1));
3523 char *ResultPtr = &Target[0];
3524 const llvm::UTF8 *ErrorPtr;
3525 bool success =
3526 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3527 (void)success;
3528 assert(success);
3529 Target.resize(ResultPtr - &Target[0]);
3530 }
3531
3532 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3533 PredefinedIdentKind IK) {
3534 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3535 if (!currentDecl) {
3536 Diag(Loc, diag::ext_predef_outside_function);
3537 currentDecl = Context.getTranslationUnitDecl();
3538 }
3539
3540 QualType ResTy;
3541 StringLiteral *SL = nullptr;
3542 if (cast<DeclContext>(currentDecl)->isDependentContext())
3543 ResTy = Context.DependentTy;
3544 else {
3545 // Pre-defined identifiers are of type char[x], where x is the length of
3546 // the string.
3547 bool ForceElaboratedPrinting =
3548 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3549 auto Str =
3550 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3551 unsigned Length = Str.length();
3552
3553 llvm::APInt LengthI(32, Length + 1);
3554 if (IK == PredefinedIdentKind::LFunction ||
3555 IK == PredefinedIdentKind::LFuncSig) {
3556 ResTy =
3557 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3558 SmallString<32> RawChars;
3559 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3560 Str, RawChars);
3561 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3562 ArraySizeModifier::Normal,
3563 /*IndexTypeQuals*/ 0);
3564 SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,
3565 /*Pascal*/ false, ResTy, Loc);
3566 } else {
3567 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3568 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3569 ArraySizeModifier::Normal,
3570 /*IndexTypeQuals*/ 0);
3571 SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,
3572 /*Pascal*/ false, ResTy, Loc);
3573 }
3574 }
3575
3576 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3577 SL);
3578 }
3579
3580 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3581 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3582 }
3583
3584 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3585 SmallString<16> CharBuffer;
3586 bool Invalid = false;
3587 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3588 if (Invalid)
3589 return ExprError();
3590
3591 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3592 PP, Tok.getKind());
3593 if (Literal.hadError())
3594 return ExprError();
3595
3596 QualType Ty;
3597 if (Literal.isWide())
3598 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3599 else if (Literal.isUTF8() && getLangOpts().C23)
3600 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3601 else if (Literal.isUTF8() && getLangOpts().Char8)
3602 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3603 else if (Literal.isUTF16())
3604 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3605 else if (Literal.isUTF32())
3606 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3607 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3608 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3609 else
3610 Ty = Context.CharTy; // 'x' -> char in C++;
3611 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3612
3613 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3614 if (Literal.isWide())
3615 Kind = CharacterLiteralKind::Wide;
3616 else if (Literal.isUTF16())
3617 Kind = CharacterLiteralKind::UTF16;
3618 else if (Literal.isUTF32())
3619 Kind = CharacterLiteralKind::UTF32;
3620 else if (Literal.isUTF8())
3621 Kind = CharacterLiteralKind::UTF8;
3622
3623 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3624 Tok.getLocation());
3625
3626 if (Literal.getUDSuffix().empty())
3627 return Lit;
3628
3629 // We're building a user-defined literal.
3630 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3631 SourceLocation UDSuffixLoc =
3632 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3633
3634 // Make sure we're allowed user-defined literals here.
3635 if (!UDLScope)
3636 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3637
3638 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3639 // operator "" X (ch)
3640 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3641 Lit, Tok.getLocation());
3642 }
3643
3644 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3645 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3646 return IntegerLiteral::Create(Context,
3647 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3648 Context.IntTy, Loc);
3649 }
3650
3651 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3652 QualType Ty, SourceLocation Loc) {
3653 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3654
3655 using llvm::APFloat;
3656 APFloat Val(Format);
3657
3658 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3659 if (RM == llvm::RoundingMode::Dynamic)
3660 RM = llvm::RoundingMode::NearestTiesToEven;
3661 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3662
3663 // Overflow is always an error, but underflow is only an error if
3664 // we underflowed to zero (APFloat reports denormals as underflow).
3665 if ((result & APFloat::opOverflow) ||
3666 ((result & APFloat::opUnderflow) && Val.isZero())) {
3667 unsigned diagnostic;
3668 SmallString<20> buffer;
3669 if (result & APFloat::opOverflow) {
3670 diagnostic = diag::warn_float_overflow;
3671 APFloat::getLargest(Format).toString(buffer);
3672 } else {
3673 diagnostic = diag::warn_float_underflow;
3674 APFloat::getSmallest(Format).toString(buffer);
3675 }
3676
3677 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3678 }
3679
3680 bool isExact = (result == APFloat::opOK);
3681 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3682 }
3683
3684 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3685 assert(E && "Invalid expression");
3686
3687 if (E->isValueDependent())
3688 return false;
3689
3690 QualType QT = E->getType();
3691 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3692 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3693 return true;
3694 }
3695
3696 llvm::APSInt ValueAPS;
3697 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3698
3699 if (R.isInvalid())
3700 return true;
3701
3702 // GCC allows the value of unroll count to be 0.
3703 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3704 // "The values of 0 and 1 block any unrolling of the loop."
3705 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3706 // '#pragma unroll' cases.
3707 bool ValueIsPositive =
3708 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3709 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3710 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3711 << toString(ValueAPS, 10) << ValueIsPositive;
3712 return true;
3713 }
3714
3715 return false;
3716 }
3717
3718 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3719 // Fast path for a single digit (which is quite common). A single digit
3720 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3721 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3722 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3723 return ActOnIntegerConstant(Tok.getLocation(), Val);
3724 }
3725
3726 SmallString<128> SpellingBuffer;
3727 // NumericLiteralParser wants to overread by one character. Add padding to
3728 // the buffer in case the token is copied to the buffer. If getSpelling()
3729 // returns a StringRef to the memory buffer, it should have a null char at
3730 // the EOF, so it is also safe.
3731 SpellingBuffer.resize(Tok.getLength() + 1);
3732
3733 // Get the spelling of the token, which eliminates trigraphs, etc.
3734 bool Invalid = false;
3735 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3736 if (Invalid)
3737 return ExprError();
3738
3739 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3740 PP.getSourceManager(), PP.getLangOpts(),
3741 PP.getTargetInfo(), PP.getDiagnostics());
3742 if (Literal.hadError)
3743 return ExprError();
3744
3745 if (Literal.hasUDSuffix()) {
3746 // We're building a user-defined literal.
3747 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3748 SourceLocation UDSuffixLoc =
3749 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3750
3751 // Make sure we're allowed user-defined literals here.
3752 if (!UDLScope)
3753 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3754
3755 QualType CookedTy;
3756 if (Literal.isFloatingLiteral()) {
3757 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3758 // long double, the literal is treated as a call of the form
3759 // operator "" X (f L)
3760 CookedTy = Context.LongDoubleTy;
3761 } else {
3762 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3763 // unsigned long long, the literal is treated as a call of the form
3764 // operator "" X (n ULL)
3765 CookedTy = Context.UnsignedLongLongTy;
3766 }
3767
3768 DeclarationName OpName =
3769 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3770 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3771 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3772
3773 SourceLocation TokLoc = Tok.getLocation();
3774
3775 // Perform literal operator lookup to determine if we're building a raw
3776 // literal or a cooked one.
3777 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3778 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3779 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3780 /*AllowStringTemplatePack*/ false,
3781 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3782 case LOLR_ErrorNoDiagnostic:
3783 // Lookup failure for imaginary constants isn't fatal, there's still the
3784 // GNU extension producing _Complex types.
3785 break;
3786 case LOLR_Error:
3787 return ExprError();
3788 case LOLR_Cooked: {
3789 Expr *Lit;
3790 if (Literal.isFloatingLiteral()) {
3791 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3792 } else {
3793 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3794 if (Literal.GetIntegerValue(ResultVal))
3795 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3796 << /* Unsigned */ 1;
3797 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3798 Tok.getLocation());
3799 }
3800 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3801 }
3802
3803 case LOLR_Raw: {
3804 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3805 // literal is treated as a call of the form
3806 // operator "" X ("n")
3807 unsigned Length = Literal.getUDSuffixOffset();
3808 QualType StrTy = Context.getConstantArrayType(
3809 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3810 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3811 Expr *Lit =
3812 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3813 StringLiteralKind::Ordinary,
3814 /*Pascal*/ false, StrTy, TokLoc);
3815 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3816 }
3817
3818 case LOLR_Template: {
3819 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3820 // template), L is treated as a call fo the form
3821 // operator "" X <'c1', 'c2', ... 'ck'>()
3822 // where n is the source character sequence c1 c2 ... ck.
3823 TemplateArgumentListInfo ExplicitArgs;
3824 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3825 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3826 llvm::APSInt Value(CharBits, CharIsUnsigned);
3827 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3828 Value = TokSpelling[I];
3829 TemplateArgument Arg(Context, Value, Context.CharTy);
3830 TemplateArgumentLocInfo ArgInfo;
3831 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3832 }
3833 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3834 }
3835 case LOLR_StringTemplatePack:
3836 llvm_unreachable("unexpected literal operator lookup result");
3837 }
3838 }
3839
3840 Expr *Res;
3841
3842 if (Literal.isFixedPointLiteral()) {
3843 QualType Ty;
3844
3845 if (Literal.isAccum) {
3846 if (Literal.isHalf) {
3847 Ty = Context.ShortAccumTy;
3848 } else if (Literal.isLong) {
3849 Ty = Context.LongAccumTy;
3850 } else {
3851 Ty = Context.AccumTy;
3852 }
3853 } else if (Literal.isFract) {
3854 if (Literal.isHalf) {
3855 Ty = Context.ShortFractTy;
3856 } else if (Literal.isLong) {
3857 Ty = Context.LongFractTy;
3858 } else {
3859 Ty = Context.FractTy;
3860 }
3861 }
3862
3863 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3864
3865 bool isSigned = !Literal.isUnsigned;
3866 unsigned scale = Context.getFixedPointScale(Ty);
3867 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3868
3869 llvm::APInt Val(bit_width, 0, isSigned);
3870 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3871 bool ValIsZero = Val.isZero() && !Overflowed;
3872
3873 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3874 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3875 // Clause 6.4.4 - The value of a constant shall be in the range of
3876 // representable values for its type, with exception for constants of a
3877 // fract type with a value of exactly 1; such a constant shall denote
3878 // the maximal value for the type.
3879 --Val;
3880 else if (Val.ugt(MaxVal) || Overflowed)
3881 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3882
3883 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3884 Tok.getLocation(), scale);
3885 } else if (Literal.isFloatingLiteral()) {
3886 QualType Ty;
3887 if (Literal.isHalf){
3888 if (getLangOpts().HLSL ||
3889 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3890 Ty = Context.HalfTy;
3891 else {
3892 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3893 return ExprError();
3894 }
3895 } else if (Literal.isFloat)
3896 Ty = Context.FloatTy;
3897 else if (Literal.isLong)
3898 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3899 else if (Literal.isFloat16)
3900 Ty = Context.Float16Ty;
3901 else if (Literal.isFloat128)
3902 Ty = Context.Float128Ty;
3903 else if (getLangOpts().HLSL)
3904 Ty = Context.FloatTy;
3905 else
3906 Ty = Context.DoubleTy;
3907
3908 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3909
3910 if (Ty == Context.DoubleTy) {
3911 if (getLangOpts().SinglePrecisionConstants) {
3912 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3913 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3914 }
3915 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3916 "cl_khr_fp64", getLangOpts())) {
3917 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3918 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3919 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3920 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3921 }
3922 }
3923 } else if (!Literal.isIntegerLiteral()) {
3924 return ExprError();
3925 } else {
3926 QualType Ty;
3927
3928 // 'z/uz' literals are a C++23 feature.
3929 if (Literal.isSizeT)
3930 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3931 ? getLangOpts().CPlusPlus23
3932 ? diag::warn_cxx20_compat_size_t_suffix
3933 : diag::ext_cxx23_size_t_suffix
3934 : diag::err_cxx23_size_t_suffix);
3935
3936 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3937 // but we do not currently support the suffix in C++ mode because it's not
3938 // entirely clear whether WG21 will prefer this suffix to return a library
3939 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3940 // literals are a C++ extension.
3941 if (Literal.isBitInt)
3942 PP.Diag(Tok.getLocation(),
3943 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3944 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3945 : diag::ext_c23_bitint_suffix);
3946
3947 // Get the value in the widest-possible width. What is "widest" depends on
3948 // whether the literal is a bit-precise integer or not. For a bit-precise
3949 // integer type, try to scan the source to determine how many bits are
3950 // needed to represent the value. This may seem a bit expensive, but trying
3951 // to get the integer value from an overly-wide APInt is *extremely*
3952 // expensive, so the naive approach of assuming
3953 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3954 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3955 if (Literal.isBitInt)
3956 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3957 Literal.getLiteralDigits(), Literal.getRadix());
3958 if (Literal.MicrosoftInteger) {
3959 if (Literal.MicrosoftInteger == 128 &&
3960 !Context.getTargetInfo().hasInt128Type())
3961 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3962 << Literal.isUnsigned;
3963 BitsNeeded = Literal.MicrosoftInteger;
3964 }
3965
3966 llvm::APInt ResultVal(BitsNeeded, 0);
3967
3968 if (Literal.GetIntegerValue(ResultVal)) {
3969 // If this value didn't fit into uintmax_t, error and force to ull.
3970 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3971 << /* Unsigned */ 1;
3972 Ty = Context.UnsignedLongLongTy;
3973 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3974 "long long is not intmax_t?");
3975 } else {
3976 // If this value fits into a ULL, try to figure out what else it fits into
3977 // according to the rules of C99 6.4.4.1p5.
3978
3979 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3980 // be an unsigned int.
3981 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3982
3983 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3984 // suffix for portability of code with C++, but both `l` and `ll` are
3985 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3986 // same.
3987 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3988 Literal.isLong = true;
3989 Literal.isLongLong = false;
3990 }
3991
3992 // Check from smallest to largest, picking the smallest type we can.
3993 unsigned Width = 0;
3994
3995 // Microsoft specific integer suffixes are explicitly sized.
3996 if (Literal.MicrosoftInteger) {
3997 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3998 Width = 8;
3999 Ty = Context.CharTy;
4000 } else {
4001 Width = Literal.MicrosoftInteger;
4002 Ty = Context.getIntTypeForBitwidth(Width,
4003 /*Signed=*/!Literal.isUnsigned);
4004 }
4005 }
4006
4007 // Bit-precise integer literals are automagically-sized based on the
4008 // width required by the literal.
4009 if (Literal.isBitInt) {
4010 // The signed version has one more bit for the sign value. There are no
4011 // zero-width bit-precise integers, even if the literal value is 0.
4012 Width = std::max(ResultVal.getActiveBits(), 1u) +
4013 (Literal.isUnsigned ? 0u : 1u);
4014
4015 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4016 // and reset the type to the largest supported width.
4017 unsigned int MaxBitIntWidth =
4018 Context.getTargetInfo().getMaxBitIntWidth();
4019 if (Width > MaxBitIntWidth) {
4020 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4021 << Literal.isUnsigned;
4022 Width = MaxBitIntWidth;
4023 }
4024
4025 // Reset the result value to the smaller APInt and select the correct
4026 // type to be used. Note, we zext even for signed values because the
4027 // literal itself is always an unsigned value (a preceeding - is a
4028 // unary operator, not part of the literal).
4029 ResultVal = ResultVal.zextOrTrunc(Width);
4030 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4031 }
4032
4033 // Check C++23 size_t literals.
4034 if (Literal.isSizeT) {
4035 assert(!Literal.MicrosoftInteger &&
4036 "size_t literals can't be Microsoft literals");
4037 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4038 Context.getTargetInfo().getSizeType());
4039
4040 // Does it fit in size_t?
4041 if (ResultVal.isIntN(SizeTSize)) {
4042 // Does it fit in ssize_t?
4043 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4044 Ty = Context.getSignedSizeType();
4045 else if (AllowUnsigned)
4046 Ty = Context.getSizeType();
4047 Width = SizeTSize;
4048 }
4049 }
4050
4051 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4052 !Literal.isSizeT) {
4053 // Are int/unsigned possibilities?
4054 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4055
4056 // Does it fit in a unsigned int?
4057 if (ResultVal.isIntN(IntSize)) {
4058 // Does it fit in a signed int?
4059 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4060 Ty = Context.IntTy;
4061 else if (AllowUnsigned)
4062 Ty = Context.UnsignedIntTy;
4063 Width = IntSize;
4064 }
4065 }
4066
4067 // Are long/unsigned long possibilities?
4068 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4069 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4070
4071 // Does it fit in a unsigned long?
4072 if (ResultVal.isIntN(LongSize)) {
4073 // Does it fit in a signed long?
4074 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4075 Ty = Context.LongTy;
4076 else if (AllowUnsigned)
4077 Ty = Context.UnsignedLongTy;
4078 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4079 // is compatible.
4080 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4081 const unsigned LongLongSize =
4082 Context.getTargetInfo().getLongLongWidth();
4083 Diag(Tok.getLocation(),
4084 getLangOpts().CPlusPlus
4085 ? Literal.isLong
4086 ? diag::warn_old_implicitly_unsigned_long_cxx
4087 : /*C++98 UB*/ diag::
4088 ext_old_implicitly_unsigned_long_cxx
4089 : diag::warn_old_implicitly_unsigned_long)
4090 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4091 : /*will be ill-formed*/ 1);
4092 Ty = Context.UnsignedLongTy;
4093 }
4094 Width = LongSize;
4095 }
4096 }
4097
4098 // Check long long if needed.
4099 if (Ty.isNull() && !Literal.isSizeT) {
4100 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4101
4102 // Does it fit in a unsigned long long?
4103 if (ResultVal.isIntN(LongLongSize)) {
4104 // Does it fit in a signed long long?
4105 // To be compatible with MSVC, hex integer literals ending with the
4106 // LL or i64 suffix are always signed in Microsoft mode.
4107 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4108 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4109 Ty = Context.LongLongTy;
4110 else if (AllowUnsigned)
4111 Ty = Context.UnsignedLongLongTy;
4112 Width = LongLongSize;
4113
4114 // 'long long' is a C99 or C++11 feature, whether the literal
4115 // explicitly specified 'long long' or we needed the extra width.
4116 if (getLangOpts().CPlusPlus)
4117 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4118 ? diag::warn_cxx98_compat_longlong
4119 : diag::ext_cxx11_longlong);
4120 else if (!getLangOpts().C99)
4121 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4122 }
4123 }
4124
4125 // If we still couldn't decide a type, we either have 'size_t' literal
4126 // that is out of range, or a decimal literal that does not fit in a
4127 // signed long long and has no U suffix.
4128 if (Ty.isNull()) {
4129 if (Literal.isSizeT)
4130 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4131 << Literal.isUnsigned;
4132 else
4133 Diag(Tok.getLocation(),
4134 diag::ext_integer_literal_too_large_for_signed);
4135 Ty = Context.UnsignedLongLongTy;
4136 Width = Context.getTargetInfo().getLongLongWidth();
4137 }
4138
4139 if (ResultVal.getBitWidth() != Width)
4140 ResultVal = ResultVal.trunc(Width);
4141 }
4142 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4143 }
4144
4145 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4146 if (Literal.isImaginary) {
4147 Res = new (Context) ImaginaryLiteral(Res,
4148 Context.getComplexType(Res->getType()));
4149
4150 // In C++, this is a GNU extension. In C, it's a C2y extension.
4151 unsigned DiagId;
4152 if (getLangOpts().CPlusPlus)
4153 DiagId = diag::ext_gnu_imaginary_constant;
4154 else if (getLangOpts().C2y)
4155 DiagId = diag::warn_c23_compat_imaginary_constant;
4156 else
4157 DiagId = diag::ext_c2y_imaginary_constant;
4158 Diag(Tok.getLocation(), DiagId);
4159 }
4160 return Res;
4161 }
4162
4163 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4164 assert(E && "ActOnParenExpr() missing expr");
4165 QualType ExprTy = E->getType();
4166 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4167 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4168 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4169 return new (Context) ParenExpr(L, R, E);
4170 }
4171
4172 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4173 SourceLocation Loc,
4174 SourceRange ArgRange) {
4175 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4176 // scalar or vector data type argument..."
4177 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4178 // type (C99 6.2.5p18) or void.
4179 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4180 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4181 << T << ArgRange;
4182 return true;
4183 }
4184
4185 assert((T->isVoidType() || !T->isIncompleteType()) &&
4186 "Scalar types should always be complete");
4187 return false;
4188 }
4189
4190 static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4191 SourceLocation Loc,
4192 SourceRange ArgRange) {
4193 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4194 if (!T->isVectorType() && !T->isSizelessVectorType())
4195 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4196 << ""
4197 << "__builtin_vectorelements" << T << ArgRange;
4198
4199 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4200 if (T->isSVESizelessBuiltinType()) {
4201 llvm::StringMap<bool> CallerFeatureMap;
4202 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4203 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4204 }
4205 }
4206
4207 return false;
4208 }
4209
4210 static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4211 SourceLocation Loc,
4212 SourceRange ArgRange) {
4213 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4214 return true;
4215
4216 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4217 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4218 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4219 return true;
4220 }
4221
4222 return false;
4223 }
4224
4225 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4226 SourceLocation Loc,
4227 SourceRange ArgRange,
4228 UnaryExprOrTypeTrait TraitKind) {
4229 // Invalid types must be hard errors for SFINAE in C++.
4230 if (S.LangOpts.CPlusPlus)
4231 return true;
4232
4233 // C99 6.5.3.4p1:
4234 if (T->isFunctionType() &&
4235 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4236 TraitKind == UETT_PreferredAlignOf)) {
4237 // sizeof(function)/alignof(function) is allowed as an extension.
4238 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4239 << getTraitSpelling(TraitKind) << ArgRange;
4240 return false;
4241 }
4242
4243 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4244 // this is an error (OpenCL v1.1 s6.3.k)
4245 if (T->isVoidType()) {
4246 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4247 : diag::ext_sizeof_alignof_void_type;
4248 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4249 return false;
4250 }
4251
4252 return true;
4253 }
4254
4255 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4256 SourceLocation Loc,
4257 SourceRange ArgRange,
4258 UnaryExprOrTypeTrait TraitKind) {
4259 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4260 // runtime doesn't allow it.
4261 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4262 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4263 << T << (TraitKind == UETT_SizeOf)
4264 << ArgRange;
4265 return true;
4266 }
4267
4268 return false;
4269 }
4270
4271 /// Check whether E is a pointer from a decayed array type (the decayed
4272 /// pointer type is equal to T) and emit a warning if it is.
4273 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4274 const Expr *E) {
4275 // Don't warn if the operation changed the type.
4276 if (T != E->getType())
4277 return;
4278
4279 // Now look for array decays.
4280 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4281 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4282 return;
4283
4284 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4285 << ICE->getType()
4286 << ICE->getSubExpr()->getType();
4287 }
4288
4289 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4290 UnaryExprOrTypeTrait ExprKind) {
4291 QualType ExprTy = E->getType();
4292 assert(!ExprTy->isReferenceType());
4293
4294 bool IsUnevaluatedOperand =
4295 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4296 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4297 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4298 if (IsUnevaluatedOperand) {
4299 ExprResult Result = CheckUnevaluatedOperand(E);
4300 if (Result.isInvalid())
4301 return true;
4302 E = Result.get();
4303 }
4304
4305 // The operand for sizeof and alignof is in an unevaluated expression context,
4306 // so side effects could result in unintended consequences.
4307 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4308 // used to build SFINAE gadgets.
4309 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4310 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4311 !E->isInstantiationDependent() &&
4312 !E->getType()->isVariableArrayType() &&
4313 E->HasSideEffects(Context, false))
4314 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4315
4316 if (ExprKind == UETT_VecStep)
4317 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4318 E->getSourceRange());
4319
4320 if (ExprKind == UETT_VectorElements)
4321 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4322 E->getSourceRange());
4323
4324 // Explicitly list some types as extensions.
4325 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4326 E->getSourceRange(), ExprKind))
4327 return false;
4328
4329 // WebAssembly tables are always illegal operands to unary expressions and
4330 // type traits.
4331 if (Context.getTargetInfo().getTriple().isWasm() &&
4332 E->getType()->isWebAssemblyTableType()) {
4333 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4334 << getTraitSpelling(ExprKind);
4335 return true;
4336 }
4337
4338 // 'alignof' applied to an expression only requires the base element type of
4339 // the expression to be complete. 'sizeof' requires the expression's type to
4340 // be complete (and will attempt to complete it if it's an array of unknown
4341 // bound).
4342 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4343 if (RequireCompleteSizedType(
4344 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4345 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4346 getTraitSpelling(ExprKind), E->getSourceRange()))
4347 return true;
4348 } else {
4349 if (RequireCompleteSizedExprType(
4350 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4351 getTraitSpelling(ExprKind), E->getSourceRange()))
4352 return true;
4353 }
4354
4355 // Completing the expression's type may have changed it.
4356 ExprTy = E->getType();
4357 assert(!ExprTy->isReferenceType());
4358
4359 if (ExprTy->isFunctionType()) {
4360 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4361 << getTraitSpelling(ExprKind) << E->getSourceRange();
4362 return true;
4363 }
4364
4365 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4366 E->getSourceRange(), ExprKind))
4367 return true;
4368
4369 if (ExprKind == UETT_CountOf) {
4370 // The type has to be an array type. We already checked for incomplete
4371 // types above.
4372 QualType ExprType = E->IgnoreParens()->getType();
4373 if (!ExprType->isArrayType()) {
4374 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4375 return true;
4376 }
4377 // FIXME: warn on _Countof on an array parameter. Not warning on it
4378 // currently because there are papers in WG14 about array types which do
4379 // not decay that could impact this behavior, so we want to see if anything
4380 // changes here before coming up with a warning group for _Countof-related
4381 // diagnostics.
4382 }
4383
4384 if (ExprKind == UETT_SizeOf) {
4385 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4386 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4387 QualType OType = PVD->getOriginalType();
4388 QualType Type = PVD->getType();
4389 if (Type->isPointerType() && OType->isArrayType()) {
4390 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4391 << Type << OType;
4392 Diag(PVD->getLocation(), diag::note_declared_at);
4393 }
4394 }
4395 }
4396
4397 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4398 // decays into a pointer and returns an unintended result. This is most
4399 // likely a typo for "sizeof(array) op x".
4400 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4401 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4402 BO->getLHS());
4403 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4404 BO->getRHS());
4405 }
4406 }
4407
4408 return false;
4409 }
4410
4411 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4412 // Cannot know anything else if the expression is dependent.
4413 if (E->isTypeDependent())
4414 return false;
4415
4416 if (E->getObjectKind() == OK_BitField) {
4417 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4418 << 1 << E->getSourceRange();
4419 return true;
4420 }
4421
4422 ValueDecl *D = nullptr;
4423 Expr *Inner = E->IgnoreParens();
4424 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4425 D = DRE->getDecl();
4426 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4427 D = ME->getMemberDecl();
4428 }
4429
4430 // If it's a field, require the containing struct to have a
4431 // complete definition so that we can compute the layout.
4432 //
4433 // This can happen in C++11 onwards, either by naming the member
4434 // in a way that is not transformed into a member access expression
4435 // (in an unevaluated operand, for instance), or by naming the member
4436 // in a trailing-return-type.
4437 //
4438 // For the record, since __alignof__ on expressions is a GCC
4439 // extension, GCC seems to permit this but always gives the
4440 // nonsensical answer 0.
4441 //
4442 // We don't really need the layout here --- we could instead just
4443 // directly check for all the appropriate alignment-lowing
4444 // attributes --- but that would require duplicating a lot of
4445 // logic that just isn't worth duplicating for such a marginal
4446 // use-case.
4447 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4448 // Fast path this check, since we at least know the record has a
4449 // definition if we can find a member of it.
4450 if (!FD->getParent()->isCompleteDefinition()) {
4451 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4452 << E->getSourceRange();
4453 return true;
4454 }
4455
4456 // Otherwise, if it's a field, and the field doesn't have
4457 // reference type, then it must have a complete type (or be a
4458 // flexible array member, which we explicitly want to
4459 // white-list anyway), which makes the following checks trivial.
4460 if (!FD->getType()->isReferenceType())
4461 return false;
4462 }
4463
4464 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4465 }
4466
4467 bool Sema::CheckVecStepExpr(Expr *E) {
4468 E = E->IgnoreParens();
4469
4470 // Cannot know anything else if the expression is dependent.
4471 if (E->isTypeDependent())
4472 return false;
4473
4474 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4475 }
4476
4477 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4478 CapturingScopeInfo *CSI) {
4479 assert(T->isVariablyModifiedType());
4480 assert(CSI != nullptr);
4481
4482 // We're going to walk down into the type and look for VLA expressions.
4483 do {
4484 const Type *Ty = T.getTypePtr();
4485 switch (Ty->getTypeClass()) {
4486 #define TYPE(Class, Base)
4487 #define ABSTRACT_TYPE(Class, Base)
4488 #define NON_CANONICAL_TYPE(Class, Base)
4489 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4490 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4491 #include "clang/AST/TypeNodes.inc"
4492 T = QualType();
4493 break;
4494 // These types are never variably-modified.
4495 case Type::Builtin:
4496 case Type::Complex:
4497 case Type::Vector:
4498 case Type::ExtVector:
4499 case Type::ConstantMatrix:
4500 case Type::Record:
4501 case Type::Enum:
4502 case Type::TemplateSpecialization:
4503 case Type::ObjCObject:
4504 case Type::ObjCInterface:
4505 case Type::ObjCObjectPointer:
4506 case Type::ObjCTypeParam:
4507 case Type::Pipe:
4508 case Type::BitInt:
4509 case Type::HLSLInlineSpirv:
4510 llvm_unreachable("type class is never variably-modified!");
4511 case Type::Adjusted:
4512 T = cast<AdjustedType>(Ty)->getOriginalType();
4513 break;
4514 case Type::Decayed:
4515 T = cast<DecayedType>(Ty)->getPointeeType();
4516 break;
4517 case Type::ArrayParameter:
4518 T = cast<ArrayParameterType>(Ty)->getElementType();
4519 break;
4520 case Type::Pointer:
4521 T = cast<PointerType>(Ty)->getPointeeType();
4522 break;
4523 case Type::BlockPointer:
4524 T = cast<BlockPointerType>(Ty)->getPointeeType();
4525 break;
4526 case Type::LValueReference:
4527 case Type::RValueReference:
4528 T = cast<ReferenceType>(Ty)->getPointeeType();
4529 break;
4530 case Type::MemberPointer:
4531 T = cast<MemberPointerType>(Ty)->getPointeeType();
4532 break;
4533 case Type::ConstantArray:
4534 case Type::IncompleteArray:
4535 // Losing element qualification here is fine.
4536 T = cast<ArrayType>(Ty)->getElementType();
4537 break;
4538 case Type::VariableArray: {
4539 // Losing element qualification here is fine.
4540 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4541
4542 // Unknown size indication requires no size computation.
4543 // Otherwise, evaluate and record it.
4544 auto Size = VAT->getSizeExpr();
4545 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4546 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4547 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4548
4549 T = VAT->getElementType();
4550 break;
4551 }
4552 case Type::FunctionProto:
4553 case Type::FunctionNoProto:
4554 T = cast<FunctionType>(Ty)->getReturnType();
4555 break;
4556 case Type::Paren:
4557 case Type::TypeOf:
4558 case Type::UnaryTransform:
4559 case Type::Attributed:
4560 case Type::BTFTagAttributed:
4561 case Type::HLSLAttributedResource:
4562 case Type::SubstTemplateTypeParm:
4563 case Type::MacroQualified:
4564 case Type::CountAttributed:
4565 // Keep walking after single level desugaring.
4566 T = T.getSingleStepDesugaredType(Context);
4567 break;
4568 case Type::Typedef:
4569 T = cast<TypedefType>(Ty)->desugar();
4570 break;
4571 case Type::Decltype:
4572 T = cast<DecltypeType>(Ty)->desugar();
4573 break;
4574 case Type::PackIndexing:
4575 T = cast<PackIndexingType>(Ty)->desugar();
4576 break;
4577 case Type::Using:
4578 T = cast<UsingType>(Ty)->desugar();
4579 break;
4580 case Type::Auto:
4581 case Type::DeducedTemplateSpecialization:
4582 T = cast<DeducedType>(Ty)->getDeducedType();
4583 break;
4584 case Type::TypeOfExpr:
4585 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4586 break;
4587 case Type::Atomic:
4588 T = cast<AtomicType>(Ty)->getValueType();
4589 break;
4590 case Type::PredefinedSugar:
4591 T = cast<PredefinedSugarType>(Ty)->desugar();
4592 break;
4593 }
4594 } while (!T.isNull() && T->isVariablyModifiedType());
4595 }
4596
4597 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4598 SourceLocation OpLoc,
4599 SourceRange ExprRange,
4600 UnaryExprOrTypeTrait ExprKind,
4601 StringRef KWName) {
4602 if (ExprType->isDependentType())
4603 return false;
4604
4605 // C++ [expr.sizeof]p2:
4606 // When applied to a reference or a reference type, the result
4607 // is the size of the referenced type.
4608 // C++11 [expr.alignof]p3:
4609 // When alignof is applied to a reference type, the result
4610 // shall be the alignment of the referenced type.
4611 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4612 ExprType = Ref->getPointeeType();
4613
4614 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4615 // When alignof or _Alignof is applied to an array type, the result
4616 // is the alignment of the element type.
4617 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4618 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4619 // If the trait is 'alignof' in C before C2y, the ability to apply the
4620 // trait to an incomplete array is an extension.
4621 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4622 ExprType->isIncompleteArrayType())
4623 Diag(OpLoc, getLangOpts().C2y
4624 ? diag::warn_c2y_compat_alignof_incomplete_array
4625 : diag::ext_c2y_alignof_incomplete_array);
4626 ExprType = Context.getBaseElementType(ExprType);
4627 }
4628
4629 if (ExprKind == UETT_VecStep)
4630 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4631
4632 if (ExprKind == UETT_VectorElements)
4633 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4634 ExprRange);
4635
4636 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4637 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4638 ExprRange);
4639
4640 // Explicitly list some types as extensions.
4641 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4642 ExprKind))
4643 return false;
4644
4645 if (RequireCompleteSizedType(
4646 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4647 KWName, ExprRange))
4648 return true;
4649
4650 if (ExprType->isFunctionType()) {
4651 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4652 return true;
4653 }
4654
4655 if (ExprKind == UETT_CountOf) {
4656 // The type has to be an array type. We already checked for incomplete
4657 // types above.
4658 if (!ExprType->isArrayType()) {
4659 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4660 return true;
4661 }
4662 }
4663
4664 // WebAssembly tables are always illegal operands to unary expressions and
4665 // type traits.
4666 if (Context.getTargetInfo().getTriple().isWasm() &&
4667 ExprType->isWebAssemblyTableType()) {
4668 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4669 << getTraitSpelling(ExprKind);
4670 return true;
4671 }
4672
4673 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4674 ExprKind))
4675 return true;
4676
4677 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4678 if (auto *TT = ExprType->getAs<TypedefType>()) {
4679 for (auto I = FunctionScopes.rbegin(),
4680 E = std::prev(FunctionScopes.rend());
4681 I != E; ++I) {
4682 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4683 if (CSI == nullptr)
4684 break;
4685 DeclContext *DC = nullptr;
4686 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4687 DC = LSI->CallOperator;
4688 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4689 DC = CRSI->TheCapturedDecl;
4690 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4691 DC = BSI->TheDecl;
4692 if (DC) {
4693 if (DC->containsDecl(TT->getDecl()))
4694 break;
4695 captureVariablyModifiedType(Context, ExprType, CSI);
4696 }
4697 }
4698 }
4699 }
4700
4701 return false;
4702 }
4703
4704 ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4705 SourceLocation OpLoc,
4706 UnaryExprOrTypeTrait ExprKind,
4707 SourceRange R) {
4708 if (!TInfo)
4709 return ExprError();
4710
4711 QualType T = TInfo->getType();
4712
4713 if (!T->isDependentType() &&
4714 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4715 getTraitSpelling(ExprKind)))
4716 return ExprError();
4717
4718 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4719 // properly deal with VLAs in nested calls of sizeof and typeof.
4720 if (currentEvaluationContext().isUnevaluated() &&
4721 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4722 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4723 TInfo->getType()->isVariablyModifiedType())
4724 TInfo = TransformToPotentiallyEvaluated(TInfo);
4725
4726 // It's possible that the transformation above failed.
4727 if (!TInfo)
4728 return ExprError();
4729
4730 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4731 return new (Context) UnaryExprOrTypeTraitExpr(
4732 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4733 }
4734
4735 ExprResult
4736 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4737 UnaryExprOrTypeTrait ExprKind) {
4738 ExprResult PE = CheckPlaceholderExpr(E);
4739 if (PE.isInvalid())
4740 return ExprError();
4741
4742 E = PE.get();
4743
4744 // Verify that the operand is valid.
4745 bool isInvalid = false;
4746 if (E->isTypeDependent()) {
4747 // Delay type-checking for type-dependent expressions.
4748 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4749 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4750 } else if (ExprKind == UETT_VecStep) {
4751 isInvalid = CheckVecStepExpr(E);
4752 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4753 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4754 isInvalid = true;
4755 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4756 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4757 isInvalid = true;
4758 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4759 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4760 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4761 }
4762
4763 if (isInvalid)
4764 return ExprError();
4765
4766 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4767 E->getType()->isVariableArrayType()) {
4768 PE = TransformToPotentiallyEvaluated(E);
4769 if (PE.isInvalid()) return ExprError();
4770 E = PE.get();
4771 }
4772
4773 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4774 return new (Context) UnaryExprOrTypeTraitExpr(
4775 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4776 }
4777
4778 ExprResult
4779 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4780 UnaryExprOrTypeTrait ExprKind, bool IsType,
4781 void *TyOrEx, SourceRange ArgRange) {
4782 // If error parsing type, ignore.
4783 if (!TyOrEx) return ExprError();
4784
4785 if (IsType) {
4786 TypeSourceInfo *TInfo;
4787 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4788 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4789 }
4790
4791 Expr *ArgEx = (Expr *)TyOrEx;
4792 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4793 return Result;
4794 }
4795
4796 bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4797 SourceLocation OpLoc, SourceRange R) {
4798 if (!TInfo)
4799 return true;
4800 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4801 UETT_AlignOf, KWName);
4802 }
4803
4804 bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4805 SourceLocation OpLoc, SourceRange R) {
4806 TypeSourceInfo *TInfo;
4807 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4808 &TInfo);
4809 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4810 }
4811
4812 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4813 bool IsReal) {
4814 if (V.get()->isTypeDependent())
4815 return S.Context.DependentTy;
4816
4817 // _Real and _Imag are only l-values for normal l-values.
4818 if (V.get()->getObjectKind() != OK_Ordinary) {
4819 V = S.DefaultLvalueConversion(V.get());
4820 if (V.isInvalid())
4821 return QualType();
4822 }
4823
4824 // These operators return the element type of a complex type.
4825 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4826 return CT->getElementType();
4827
4828 // Otherwise they pass through real integer and floating point types here.
4829 if (V.get()->getType()->isArithmeticType())
4830 return V.get()->getType();
4831
4832 // Test for placeholders.
4833 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4834 if (PR.isInvalid()) return QualType();
4835 if (PR.get() != V.get()) {
4836 V = PR;
4837 return CheckRealImagOperand(S, V, Loc, IsReal);
4838 }
4839
4840 // Reject anything else.
4841 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4842 << (IsReal ? "__real" : "__imag");
4843 return QualType();
4844 }
4845
4846
4847
4848 ExprResult
4849 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4850 tok::TokenKind Kind, Expr *Input) {
4851 UnaryOperatorKind Opc;
4852 switch (Kind) {
4853 default: llvm_unreachable("Unknown unary op!");
4854 case tok::plusplus: Opc = UO_PostInc; break;
4855 case tok::minusminus: Opc = UO_PostDec; break;
4856 }
4857
4858 // Since this might is a postfix expression, get rid of ParenListExprs.
4859 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4860 if (Result.isInvalid()) return ExprError();
4861 Input = Result.get();
4862
4863 return BuildUnaryOp(S, OpLoc, Opc, Input);
4864 }
4865
4866 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4867 ///
4868 /// \return true on error
4869 static bool checkArithmeticOnObjCPointer(Sema &S,
4870 SourceLocation opLoc,
4871 Expr *op) {
4872 assert(op->getType()->isObjCObjectPointerType());
4873 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4874 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4875 return false;
4876
4877 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4878 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4879 << op->getSourceRange();
4880 return true;
4881 }
4882
4883 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4884 auto *BaseNoParens = Base->IgnoreParens();
4885 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4886 return MSProp->getPropertyDecl()->getType()->isArrayType();
4887 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4888 }
4889
4890 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4891 // Typically this is DependentTy, but can sometimes be more precise.
4892 //
4893 // There are cases when we could determine a non-dependent type:
4894 // - LHS and RHS may have non-dependent types despite being type-dependent
4895 // (e.g. unbounded array static members of the current instantiation)
4896 // - one may be a dependent-sized array with known element type
4897 // - one may be a dependent-typed valid index (enum in current instantiation)
4898 //
4899 // We *always* return a dependent type, in such cases it is DependentTy.
4900 // This avoids creating type-dependent expressions with non-dependent types.
4901 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4902 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4903 const ASTContext &Ctx) {
4904 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4905 QualType LTy = LHS->getType(), RTy = RHS->getType();
4906 QualType Result = Ctx.DependentTy;
4907 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4908 if (const PointerType *PT = LTy->getAs<PointerType>())
4909 Result = PT->getPointeeType();
4910 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4911 Result = AT->getElementType();
4912 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4913 if (const PointerType *PT = RTy->getAs<PointerType>())
4914 Result = PT->getPointeeType();
4915 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4916 Result = AT->getElementType();
4917 }
4918 // Ensure we return a dependent type.
4919 return Result->isDependentType() ? Result : Ctx.DependentTy;
4920 }
4921
4922 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4923 SourceLocation lbLoc,
4924 MultiExprArg ArgExprs,
4925 SourceLocation rbLoc) {
4926
4927 if (base && !base->getType().isNull() &&
4928 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4929 auto *AS = cast<ArraySectionExpr>(base);
4930 if (AS->isOMPArraySection())
4931 return OpenMP().ActOnOMPArraySectionExpr(
4932 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4933 /*Length*/ nullptr,
4934 /*Stride=*/nullptr, rbLoc);
4935
4936 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4937 SourceLocation(), /*Length*/ nullptr,
4938 rbLoc);
4939 }
4940
4941 // Since this might be a postfix expression, get rid of ParenListExprs.
4942 if (isa<ParenListExpr>(base)) {
4943 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4944 if (result.isInvalid())
4945 return ExprError();
4946 base = result.get();
4947 }
4948
4949 // Check if base and idx form a MatrixSubscriptExpr.
4950 //
4951 // Helper to check for comma expressions, which are not allowed as indices for
4952 // matrix subscript expressions.
4953 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4954 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4955 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4956 << SourceRange(base->getBeginLoc(), rbLoc);
4957 return true;
4958 }
4959 return false;
4960 };
4961 // The matrix subscript operator ([][])is considered a single operator.
4962 // Separating the index expressions by parenthesis is not allowed.
4963 if (base && !base->getType().isNull() &&
4964 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4965 !isa<MatrixSubscriptExpr>(base)) {
4966 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4967 << SourceRange(base->getBeginLoc(), rbLoc);
4968 return ExprError();
4969 }
4970 // If the base is a MatrixSubscriptExpr, try to create a new
4971 // MatrixSubscriptExpr.
4972 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4973 if (matSubscriptE) {
4974 assert(ArgExprs.size() == 1);
4975 if (CheckAndReportCommaError(ArgExprs.front()))
4976 return ExprError();
4977
4978 assert(matSubscriptE->isIncomplete() &&
4979 "base has to be an incomplete matrix subscript");
4980 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4981 matSubscriptE->getRowIdx(),
4982 ArgExprs.front(), rbLoc);
4983 }
4984 if (base->getType()->isWebAssemblyTableType()) {
4985 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4986 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4987 return ExprError();
4988 }
4989
4990 CheckInvalidBuiltinCountedByRef(base,
4991 BuiltinCountedByRefKind::ArraySubscript);
4992
4993 // Handle any non-overload placeholder types in the base and index
4994 // expressions. We can't handle overloads here because the other
4995 // operand might be an overloadable type, in which case the overload
4996 // resolution for the operator overload should get the first crack
4997 // at the overload.
4998 bool IsMSPropertySubscript = false;
4999 if (base->getType()->isNonOverloadPlaceholderType()) {
5000 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5001 if (!IsMSPropertySubscript) {
5002 ExprResult result = CheckPlaceholderExpr(base);
5003 if (result.isInvalid())
5004 return ExprError();
5005 base = result.get();
5006 }
5007 }
5008
5009 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5010 if (base->getType()->isMatrixType()) {
5011 assert(ArgExprs.size() == 1);
5012 if (CheckAndReportCommaError(ArgExprs.front()))
5013 return ExprError();
5014
5015 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5016 rbLoc);
5017 }
5018
5019 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5020 Expr *idx = ArgExprs[0];
5021 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5022 (isa<CXXOperatorCallExpr>(idx) &&
5023 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5024 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5025 << SourceRange(base->getBeginLoc(), rbLoc);
5026 }
5027 }
5028
5029 if (ArgExprs.size() == 1 &&
5030 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5031 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5032 if (result.isInvalid())
5033 return ExprError();
5034 ArgExprs[0] = result.get();
5035 } else {
5036 if (CheckArgsForPlaceholders(ArgExprs))
5037 return ExprError();
5038 }
5039
5040 // Build an unanalyzed expression if either operand is type-dependent.
5041 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5042 (base->isTypeDependent() ||
5043 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
5044 !isa<PackExpansionExpr>(ArgExprs[0])) {
5045 return new (Context) ArraySubscriptExpr(
5046 base, ArgExprs.front(),
5047 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5048 VK_LValue, OK_Ordinary, rbLoc);
5049 }
5050
5051 // MSDN, property (C++)
5052 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5053 // This attribute can also be used in the declaration of an empty array in a
5054 // class or structure definition. For example:
5055 // __declspec(property(get=GetX, put=PutX)) int x[];
5056 // The above statement indicates that x[] can be used with one or more array
5057 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5058 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5059 if (IsMSPropertySubscript) {
5060 assert(ArgExprs.size() == 1);
5061 // Build MS property subscript expression if base is MS property reference
5062 // or MS property subscript.
5063 return new (Context)
5064 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5065 VK_LValue, OK_Ordinary, rbLoc);
5066 }
5067
5068 // Use C++ overloaded-operator rules if either operand has record
5069 // type. The spec says to do this if either type is *overloadable*,
5070 // but enum types can't declare subscript operators or conversion
5071 // operators, so there's nothing interesting for overload resolution
5072 // to do if there aren't any record types involved.
5073 //
5074 // ObjC pointers have their own subscripting logic that is not tied
5075 // to overload resolution and so should not take this path.
5076 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5077 ((base->getType()->isRecordType() ||
5078 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5079 ArgExprs[0]->getType()->isRecordType())))) {
5080 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5081 }
5082
5083 ExprResult Res =
5084 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5085
5086 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5087 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5088
5089 return Res;
5090 }
5091
5092 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5093 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
5094 InitializationKind Kind =
5095 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
5096 InitializationSequence InitSeq(*this, Entity, Kind, E);
5097 return InitSeq.Perform(*this, Entity, Kind, E);
5098 }
5099
5100 ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5101 Expr *RowIdx,
5102 SourceLocation RBLoc) {
5103 ExprResult BaseR = CheckPlaceholderExpr(Base);
5104 if (BaseR.isInvalid())
5105 return BaseR;
5106 Base = BaseR.get();
5107
5108 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5109 if (RowR.isInvalid())
5110 return RowR;
5111 RowIdx = RowR.get();
5112
5113 // Build an unanalyzed expression if any of the operands is type-dependent.
5114 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5115 return new (Context)
5116 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5117
5118 // Check that IndexExpr is an integer expression. If it is a constant
5119 // expression, check that it is less than Dim (= the number of elements in the
5120 // corresponding dimension).
5121 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5122 bool IsColumnIdx) -> Expr * {
5123 if (!IndexExpr->getType()->isIntegerType() &&
5124 !IndexExpr->isTypeDependent()) {
5125 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5126 << IsColumnIdx;
5127 return nullptr;
5128 }
5129
5130 if (std::optional<llvm::APSInt> Idx =
5131 IndexExpr->getIntegerConstantExpr(Context)) {
5132 if ((*Idx < 0 || *Idx >= Dim)) {
5133 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5134 << IsColumnIdx << Dim;
5135 return nullptr;
5136 }
5137 }
5138
5139 ExprResult ConvExpr = IndexExpr;
5140 assert(!ConvExpr.isInvalid() &&
5141 "should be able to convert any integer type to size type");
5142 return ConvExpr.get();
5143 };
5144
5145 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5146 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5147 if (!RowIdx)
5148 return ExprError();
5149
5150 QualType RowVecQT =
5151 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5152
5153 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5154 }
5155
5156 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5157 Expr *ColumnIdx,
5158 SourceLocation RBLoc) {
5159 ExprResult BaseR = CheckPlaceholderExpr(Base);
5160 if (BaseR.isInvalid())
5161 return BaseR;
5162 Base = BaseR.get();
5163
5164 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5165 if (RowR.isInvalid())
5166 return RowR;
5167 RowIdx = RowR.get();
5168
5169 if (!ColumnIdx)
5170 return new (Context) MatrixSubscriptExpr(
5171 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5172
5173 // Build an unanalyzed expression if any of the operands is type-dependent.
5174 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5175 ColumnIdx->isTypeDependent())
5176 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5177 Context.DependentTy, RBLoc);
5178
5179 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5180 if (ColumnR.isInvalid())
5181 return ColumnR;
5182 ColumnIdx = ColumnR.get();
5183
5184 // Check that IndexExpr is an integer expression. If it is a constant
5185 // expression, check that it is less than Dim (= the number of elements in the
5186 // corresponding dimension).
5187 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5188 bool IsColumnIdx) -> Expr * {
5189 if (!IndexExpr->getType()->isIntegerType() &&
5190 !IndexExpr->isTypeDependent()) {
5191 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5192 << IsColumnIdx;
5193 return nullptr;
5194 }
5195
5196 if (std::optional<llvm::APSInt> Idx =
5197 IndexExpr->getIntegerConstantExpr(Context)) {
5198 if ((*Idx < 0 || *Idx >= Dim)) {
5199 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5200 << IsColumnIdx << Dim;
5201 return nullptr;
5202 }
5203 }
5204
5205 ExprResult ConvExpr = IndexExpr;
5206 assert(!ConvExpr.isInvalid() &&
5207 "should be able to convert any integer type to size type");
5208 return ConvExpr.get();
5209 };
5210
5211 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5212 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5213 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5214 if (!RowIdx || !ColumnIdx)
5215 return ExprError();
5216
5217 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5218 MTy->getElementType(), RBLoc);
5219 }
5220
5221 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5222 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5223 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5224
5225 // For expressions like `&(*s).b`, the base is recorded and what should be
5226 // checked.
5227 const MemberExpr *Member = nullptr;
5228 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5229 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5230
5231 LastRecord.PossibleDerefs.erase(StrippedExpr);
5232 }
5233
5234 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5235 if (isUnevaluatedContext())
5236 return;
5237
5238 QualType ResultTy = E->getType();
5239 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5240
5241 // Bail if the element is an array since it is not memory access.
5242 if (isa<ArrayType>(ResultTy))
5243 return;
5244
5245 if (ResultTy->hasAttr(attr::NoDeref)) {
5246 LastRecord.PossibleDerefs.insert(E);
5247 return;
5248 }
5249
5250 // Check if the base type is a pointer to a member access of a struct
5251 // marked with noderef.
5252 const Expr *Base = E->getBase();
5253 QualType BaseTy = Base->getType();
5254 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5255 // Not a pointer access
5256 return;
5257
5258 const MemberExpr *Member = nullptr;
5259 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5260 Member->isArrow())
5261 Base = Member->getBase();
5262
5263 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5264 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5265 LastRecord.PossibleDerefs.insert(E);
5266 }
5267 }
5268
5269 ExprResult
5270 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5271 Expr *Idx, SourceLocation RLoc) {
5272 Expr *LHSExp = Base;
5273 Expr *RHSExp = Idx;
5274
5275 ExprValueKind VK = VK_LValue;
5276 ExprObjectKind OK = OK_Ordinary;
5277
5278 // Per C++ core issue 1213, the result is an xvalue if either operand is
5279 // a non-lvalue array, and an lvalue otherwise.
5280 if (getLangOpts().CPlusPlus11) {
5281 for (auto *Op : {LHSExp, RHSExp}) {
5282 Op = Op->IgnoreImplicit();
5283 if (Op->getType()->isArrayType() && !Op->isLValue())
5284 VK = VK_XValue;
5285 }
5286 }
5287
5288 // Perform default conversions.
5289 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5290 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5291 if (Result.isInvalid())
5292 return ExprError();
5293 LHSExp = Result.get();
5294 }
5295 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5296 if (Result.isInvalid())
5297 return ExprError();
5298 RHSExp = Result.get();
5299
5300 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5301
5302 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5303 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5304 // in the subscript position. As a result, we need to derive the array base
5305 // and index from the expression types.
5306 Expr *BaseExpr, *IndexExpr;
5307 QualType ResultType;
5308 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5309 BaseExpr = LHSExp;
5310 IndexExpr = RHSExp;
5311 ResultType =
5312 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5313 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5314 BaseExpr = LHSExp;
5315 IndexExpr = RHSExp;
5316 ResultType = PTy->getPointeeType();
5317 } else if (const ObjCObjectPointerType *PTy =
5318 LHSTy->getAs<ObjCObjectPointerType>()) {
5319 BaseExpr = LHSExp;
5320 IndexExpr = RHSExp;
5321
5322 // Use custom logic if this should be the pseudo-object subscript
5323 // expression.
5324 if (!LangOpts.isSubscriptPointerArithmetic())
5325 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5326 nullptr, nullptr);
5327
5328 ResultType = PTy->getPointeeType();
5329 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5330 // Handle the uncommon case of "123[Ptr]".
5331 BaseExpr = RHSExp;
5332 IndexExpr = LHSExp;
5333 ResultType = PTy->getPointeeType();
5334 } else if (const ObjCObjectPointerType *PTy =
5335 RHSTy->getAs<ObjCObjectPointerType>()) {
5336 // Handle the uncommon case of "123[Ptr]".
5337 BaseExpr = RHSExp;
5338 IndexExpr = LHSExp;
5339 ResultType = PTy->getPointeeType();
5340 if (!LangOpts.isSubscriptPointerArithmetic()) {
5341 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5342 << ResultType << BaseExpr->getSourceRange();
5343 return ExprError();
5344 }
5345 } else if (LHSTy->isSubscriptableVectorType()) {
5346 if (LHSTy->isBuiltinType() &&
5347 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5348 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5349 if (BTy->isSVEBool())
5350 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5351 << LHSExp->getSourceRange()
5352 << RHSExp->getSourceRange());
5353 ResultType = BTy->getSveEltType(Context);
5354 } else {
5355 const VectorType *VTy = LHSTy->getAs<VectorType>();
5356 ResultType = VTy->getElementType();
5357 }
5358 BaseExpr = LHSExp; // vectors: V[123]
5359 IndexExpr = RHSExp;
5360 // We apply C++ DR1213 to vector subscripting too.
5361 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5362 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5363 if (Materialized.isInvalid())
5364 return ExprError();
5365 LHSExp = Materialized.get();
5366 }
5367 VK = LHSExp->getValueKind();
5368 if (VK != VK_PRValue)
5369 OK = OK_VectorComponent;
5370
5371 QualType BaseType = BaseExpr->getType();
5372 Qualifiers BaseQuals = BaseType.getQualifiers();
5373 Qualifiers MemberQuals = ResultType.getQualifiers();
5374 Qualifiers Combined = BaseQuals + MemberQuals;
5375 if (Combined != MemberQuals)
5376 ResultType = Context.getQualifiedType(ResultType, Combined);
5377 } else if (LHSTy->isArrayType()) {
5378 // If we see an array that wasn't promoted by
5379 // DefaultFunctionArrayLvalueConversion, it must be an array that
5380 // wasn't promoted because of the C90 rule that doesn't
5381 // allow promoting non-lvalue arrays. Warn, then
5382 // force the promotion here.
5383 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5384 << LHSExp->getSourceRange();
5385 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5386 CK_ArrayToPointerDecay).get();
5387 LHSTy = LHSExp->getType();
5388
5389 BaseExpr = LHSExp;
5390 IndexExpr = RHSExp;
5391 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5392 } else if (RHSTy->isArrayType()) {
5393 // Same as previous, except for 123[f().a] case
5394 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5395 << RHSExp->getSourceRange();
5396 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5397 CK_ArrayToPointerDecay).get();
5398 RHSTy = RHSExp->getType();
5399
5400 BaseExpr = RHSExp;
5401 IndexExpr = LHSExp;
5402 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5403 } else {
5404 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5405 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5406 }
5407 // C99 6.5.2.1p1
5408 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5409 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5410 << IndexExpr->getSourceRange());
5411
5412 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5413 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5414 !IndexExpr->isTypeDependent()) {
5415 std::optional<llvm::APSInt> IntegerContantExpr =
5416 IndexExpr->getIntegerConstantExpr(getASTContext());
5417 if (!IntegerContantExpr.has_value() ||
5418 IntegerContantExpr.value().isNegative())
5419 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5420 }
5421
5422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5424 // type. Note that Functions are not objects, and that (in C99 parlance)
5425 // incomplete types are not object types.
5426 if (ResultType->isFunctionType()) {
5427 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5428 << ResultType << BaseExpr->getSourceRange();
5429 return ExprError();
5430 }
5431
5432 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5433 // GNU extension: subscripting on pointer to void
5434 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5435 << BaseExpr->getSourceRange();
5436
5437 // C forbids expressions of unqualified void type from being l-values.
5438 // See IsCForbiddenLValueType.
5439 if (!ResultType.hasQualifiers())
5440 VK = VK_PRValue;
5441 } else if (!ResultType->isDependentType() &&
5442 !ResultType.isWebAssemblyReferenceType() &&
5443 RequireCompleteSizedType(
5444 LLoc, ResultType,
5445 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5446 return ExprError();
5447
5448 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5449 !ResultType.isCForbiddenLValueType());
5450
5451 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5452 FunctionScopes.size() > 1) {
5453 if (auto *TT =
5454 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5455 for (auto I = FunctionScopes.rbegin(),
5456 E = std::prev(FunctionScopes.rend());
5457 I != E; ++I) {
5458 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5459 if (CSI == nullptr)
5460 break;
5461 DeclContext *DC = nullptr;
5462 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5463 DC = LSI->CallOperator;
5464 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5465 DC = CRSI->TheCapturedDecl;
5466 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5467 DC = BSI->TheDecl;
5468 if (DC) {
5469 if (DC->containsDecl(TT->getDecl()))
5470 break;
5471 captureVariablyModifiedType(
5472 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5473 }
5474 }
5475 }
5476 }
5477
5478 return new (Context)
5479 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5480 }
5481
5482 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5483 ParmVarDecl *Param, Expr *RewrittenInit,
5484 bool SkipImmediateInvocations) {
5485 if (Param->hasUnparsedDefaultArg()) {
5486 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5487 // If we've already cleared out the location for the default argument,
5488 // that means we're parsing it right now.
5489 if (!UnparsedDefaultArgLocs.count(Param)) {
5490 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5491 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5492 Param->setInvalidDecl();
5493 return true;
5494 }
5495
5496 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5497 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5498 Diag(UnparsedDefaultArgLocs[Param],
5499 diag::note_default_argument_declared_here);
5500 return true;
5501 }
5502
5503 if (Param->hasUninstantiatedDefaultArg()) {
5504 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5505 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5506 return true;
5507 }
5508
5509 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5510 assert(Init && "default argument but no initializer?");
5511
5512 // If the default expression creates temporaries, we need to
5513 // push them to the current stack of expression temporaries so they'll
5514 // be properly destroyed.
5515 // FIXME: We should really be rebuilding the default argument with new
5516 // bound temporaries; see the comment in PR5810.
5517 // We don't need to do that with block decls, though, because
5518 // blocks in default argument expression can never capture anything.
5519 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5520 // Set the "needs cleanups" bit regardless of whether there are
5521 // any explicit objects.
5522 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5523 // Append all the objects to the cleanup list. Right now, this
5524 // should always be a no-op, because blocks in default argument
5525 // expressions should never be able to capture anything.
5526 assert(!InitWithCleanup->getNumObjects() &&
5527 "default argument expression has capturing blocks?");
5528 }
5529 // C++ [expr.const]p15.1:
5530 // An expression or conversion is in an immediate function context if it is
5531 // potentially evaluated and [...] its innermost enclosing non-block scope
5532 // is a function parameter scope of an immediate function.
5533 EnterExpressionEvaluationContext EvalContext(
5534 *this,
5535 FD->isImmediateFunction()
5536 ? ExpressionEvaluationContext::ImmediateFunctionContext
5537 : ExpressionEvaluationContext::PotentiallyEvaluated,
5538 Param);
5539 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5540 SkipImmediateInvocations;
5541 runWithSufficientStackSpace(CallLoc, [&] {
5542 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5543 });
5544 return false;
5545 }
5546
5547 struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5548 const ASTContext &Context;
5549 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5550 ShouldVisitImplicitCode = true;
5551 }
5552
5553 bool HasImmediateCalls = false;
5554
5555 bool VisitCallExpr(CallExpr *E) override {
5556 if (const FunctionDecl *FD = E->getDirectCallee())
5557 HasImmediateCalls |= FD->isImmediateFunction();
5558 return DynamicRecursiveASTVisitor::VisitStmt(E);
5559 }
5560
5561 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5562 if (const FunctionDecl *FD = E->getConstructor())
5563 HasImmediateCalls |= FD->isImmediateFunction();
5564 return DynamicRecursiveASTVisitor::VisitStmt(E);
5565 }
5566
5567 // SourceLocExpr are not immediate invocations
5568 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5569 // need to be rebuilt so that they refer to the correct SourceLocation and
5570 // DeclContext.
5571 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5572 HasImmediateCalls = true;
5573 return DynamicRecursiveASTVisitor::VisitStmt(E);
5574 }
5575
5576 // A nested lambda might have parameters with immediate invocations
5577 // in their default arguments.
5578 // The compound statement is not visited (as it does not constitute a
5579 // subexpression).
5580 // FIXME: We should consider visiting and transforming captures
5581 // with init expressions.
5582 bool VisitLambdaExpr(LambdaExpr *E) override {
5583 return VisitCXXMethodDecl(E->getCallOperator());
5584 }
5585
5586 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5587 return TraverseStmt(E->getExpr());
5588 }
5589
5590 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5591 return TraverseStmt(E->getExpr());
5592 }
5593 };
5594
5595 struct EnsureImmediateInvocationInDefaultArgs
5596 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5597 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5598 : TreeTransform(SemaRef) {}
5599
5600 bool AlwaysRebuild() { return true; }
5601
5602 // Lambda can only have immediate invocations in the default
5603 // args of their parameters, which is transformed upon calling the closure.
5604 // The body is not a subexpression, so we have nothing to do.
5605 // FIXME: Immediate calls in capture initializers should be transformed.
5606 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5607 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5608
5609 // Make sure we don't rebuild the this pointer as it would
5610 // cause it to incorrectly point it to the outermost class
5611 // in the case of nested struct initialization.
5612 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5613
5614 // Rewrite to source location to refer to the context in which they are used.
5615 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5616 DeclContext *DC = E->getParentContext();
5617 if (DC == SemaRef.CurContext)
5618 return E;
5619
5620 // FIXME: During instantiation, because the rebuild of defaults arguments
5621 // is not always done in the context of the template instantiator,
5622 // we run the risk of producing a dependent source location
5623 // that would never be rebuilt.
5624 // This usually happens during overload resolution, or in contexts
5625 // where the value of the source location does not matter.
5626 // However, we should find a better way to deal with source location
5627 // of function templates.
5628 if (!SemaRef.CurrentInstantiationScope ||
5629 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5630 DC = SemaRef.CurContext;
5631
5632 return getDerived().RebuildSourceLocExpr(
5633 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5634 }
5635 };
5636
5637 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5638 FunctionDecl *FD, ParmVarDecl *Param,
5639 Expr *Init) {
5640 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5641
5642 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5643 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5644 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5645 InitializationContext =
5646 OutermostDeclarationWithDelayedImmediateInvocations();
5647 if (!InitializationContext.has_value())
5648 InitializationContext.emplace(CallLoc, Param, CurContext);
5649
5650 if (!Init && !Param->hasUnparsedDefaultArg()) {
5651 // Mark that we are replacing a default argument first.
5652 // If we are instantiating a template we won't have to
5653 // retransform immediate calls.
5654 // C++ [expr.const]p15.1:
5655 // An expression or conversion is in an immediate function context if it
5656 // is potentially evaluated and [...] its innermost enclosing non-block
5657 // scope is a function parameter scope of an immediate function.
5658 EnterExpressionEvaluationContext EvalContext(
5659 *this,
5660 FD->isImmediateFunction()
5661 ? ExpressionEvaluationContext::ImmediateFunctionContext
5662 : ExpressionEvaluationContext::PotentiallyEvaluated,
5663 Param);
5664
5665 if (Param->hasUninstantiatedDefaultArg()) {
5666 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5667 return ExprError();
5668 }
5669 // CWG2631
5670 // An immediate invocation that is not evaluated where it appears is
5671 // evaluated and checked for whether it is a constant expression at the
5672 // point where the enclosing initializer is used in a function call.
5673 ImmediateCallVisitor V(getASTContext());
5674 if (!NestedDefaultChecking)
5675 V.TraverseDecl(Param);
5676
5677 // Rewrite the call argument that was created from the corresponding
5678 // parameter's default argument.
5679 if (V.HasImmediateCalls ||
5680 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5681 if (V.HasImmediateCalls)
5682 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5683 CallLoc, Param, CurContext};
5684 // Pass down lifetime extending flag, and collect temporaries in
5685 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5686 currentEvaluationContext().InLifetimeExtendingContext =
5687 parentEvaluationContext().InLifetimeExtendingContext;
5688 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5689 ExprResult Res;
5690 runWithSufficientStackSpace(CallLoc, [&] {
5691 Res = Immediate.TransformInitializer(Param->getInit(),
5692 /*NotCopy=*/false);
5693 });
5694 if (Res.isInvalid())
5695 return ExprError();
5696 Res = ConvertParamDefaultArgument(Param, Res.get(),
5697 Res.get()->getBeginLoc());
5698 if (Res.isInvalid())
5699 return ExprError();
5700 Init = Res.get();
5701 }
5702 }
5703
5704 if (CheckCXXDefaultArgExpr(
5705 CallLoc, FD, Param, Init,
5706 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5707 return ExprError();
5708
5709 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5710 Init, InitializationContext->Context);
5711 }
5712
5713 static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5714 FieldDecl *Field) {
5715 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5716 return Pattern;
5717 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5718 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5719 DeclContext::lookup_result Lookup =
5720 ClassPattern->lookup(Field->getDeclName());
5721 auto Rng = llvm::make_filter_range(
5722 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5723 if (Rng.empty())
5724 return nullptr;
5725 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5726 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5727 // && "Duplicated instantiation pattern for field decl");
5728 return cast<FieldDecl>(*Rng.begin());
5729 }
5730
5731 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5732 assert(Field->hasInClassInitializer());
5733
5734 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5735
5736 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5737
5738 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5739 InitializationContext =
5740 OutermostDeclarationWithDelayedImmediateInvocations();
5741 if (!InitializationContext.has_value())
5742 InitializationContext.emplace(Loc, Field, CurContext);
5743
5744 Expr *Init = nullptr;
5745
5746 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5747 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5748 EnterExpressionEvaluationContext EvalContext(
5749 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5750
5751 if (!Field->getInClassInitializer()) {
5752 // Maybe we haven't instantiated the in-class initializer. Go check the
5753 // pattern FieldDecl to see if it has one.
5754 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5755 FieldDecl *Pattern =
5756 FindFieldDeclInstantiationPattern(getASTContext(), Field);
5757 assert(Pattern && "We must have set the Pattern!");
5758 if (!Pattern->hasInClassInitializer() ||
5759 InstantiateInClassInitializer(Loc, Field, Pattern,
5760 getTemplateInstantiationArgs(Field))) {
5761 Field->setInvalidDecl();
5762 return ExprError();
5763 }
5764 }
5765 }
5766
5767 // CWG2631
5768 // An immediate invocation that is not evaluated where it appears is
5769 // evaluated and checked for whether it is a constant expression at the
5770 // point where the enclosing initializer is used in a [...] a constructor
5771 // definition, or an aggregate initialization.
5772 ImmediateCallVisitor V(getASTContext());
5773 if (!NestedDefaultChecking)
5774 V.TraverseDecl(Field);
5775
5776 // CWG1815
5777 // Support lifetime extension of temporary created by aggregate
5778 // initialization using a default member initializer. We should rebuild
5779 // the initializer in a lifetime extension context if the initializer
5780 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5781 // extension code recurses into the default initializer and does lifetime
5782 // extension when warranted.
5783 bool ContainsAnyTemporaries =
5784 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5785 if (Field->getInClassInitializer() &&
5786 !Field->getInClassInitializer()->containsErrors() &&
5787 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5788 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5789 CurContext};
5790 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5791 NestedDefaultChecking;
5792 // Pass down lifetime extending flag, and collect temporaries in
5793 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5794 currentEvaluationContext().InLifetimeExtendingContext =
5795 parentEvaluationContext().InLifetimeExtendingContext;
5796 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5797 ExprResult Res;
5798 runWithSufficientStackSpace(Loc, [&] {
5799 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5800 /*CXXDirectInit=*/false);
5801 });
5802 if (!Res.isInvalid())
5803 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5804 if (Res.isInvalid()) {
5805 Field->setInvalidDecl();
5806 return ExprError();
5807 }
5808 Init = Res.get();
5809 }
5810
5811 if (Field->getInClassInitializer()) {
5812 Expr *E = Init ? Init : Field->getInClassInitializer();
5813 if (!NestedDefaultChecking)
5814 runWithSufficientStackSpace(Loc, [&] {
5815 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5816 });
5817 if (isInLifetimeExtendingContext())
5818 DiscardCleanupsInEvaluationContext();
5819 // C++11 [class.base.init]p7:
5820 // The initialization of each base and member constitutes a
5821 // full-expression.
5822 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5823 if (Res.isInvalid()) {
5824 Field->setInvalidDecl();
5825 return ExprError();
5826 }
5827 Init = Res.get();
5828
5829 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5830 Field, InitializationContext->Context,
5831 Init);
5832 }
5833
5834 // DR1351:
5835 // If the brace-or-equal-initializer of a non-static data member
5836 // invokes a defaulted default constructor of its class or of an
5837 // enclosing class in a potentially evaluated subexpression, the
5838 // program is ill-formed.
5839 //
5840 // This resolution is unworkable: the exception specification of the
5841 // default constructor can be needed in an unevaluated context, in
5842 // particular, in the operand of a noexcept-expression, and we can be
5843 // unable to compute an exception specification for an enclosed class.
5844 //
5845 // Any attempt to resolve the exception specification of a defaulted default
5846 // constructor before the initializer is lexically complete will ultimately
5847 // come here at which point we can diagnose it.
5848 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5849 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5850 << OutermostClass << Field;
5851 Diag(Field->getEndLoc(),
5852 diag::note_default_member_initializer_not_yet_parsed);
5853 // Recover by marking the field invalid, unless we're in a SFINAE context.
5854 if (!isSFINAEContext())
5855 Field->setInvalidDecl();
5856 return ExprError();
5857 }
5858
5859 VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5860 const FunctionProtoType *Proto,
5861 Expr *Fn) {
5862 if (Proto && Proto->isVariadic()) {
5863 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5864 return VariadicCallType::Constructor;
5865 else if (Fn && Fn->getType()->isBlockPointerType())
5866 return VariadicCallType::Block;
5867 else if (FDecl) {
5868 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5869 if (Method->isInstance())
5870 return VariadicCallType::Method;
5871 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5872 return VariadicCallType::Method;
5873 return VariadicCallType::Function;
5874 }
5875 return VariadicCallType::DoesNotApply;
5876 }
5877
5878 namespace {
5879 class FunctionCallCCC final : public FunctionCallFilterCCC {
5880 public:
5881 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5882 unsigned NumArgs, MemberExpr *ME)
5883 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5884 FunctionName(FuncName) {}
5885
5886 bool ValidateCandidate(const TypoCorrection &candidate) override {
5887 if (!candidate.getCorrectionSpecifier() ||
5888 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5889 return false;
5890 }
5891
5892 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5893 }
5894
5895 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5896 return std::make_unique<FunctionCallCCC>(*this);
5897 }
5898
5899 private:
5900 const IdentifierInfo *const FunctionName;
5901 };
5902 }
5903
5904 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5905 FunctionDecl *FDecl,
5906 ArrayRef<Expr *> Args) {
5907 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5908 DeclarationName FuncName = FDecl->getDeclName();
5909 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5910
5911 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5912 if (TypoCorrection Corrected = S.CorrectTypo(
5913 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5914 S.getScopeForContext(S.CurContext), nullptr, CCC,
5915 CorrectTypoKind::ErrorRecovery)) {
5916 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5917 if (Corrected.isOverloaded()) {
5918 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5919 OverloadCandidateSet::iterator Best;
5920 for (NamedDecl *CD : Corrected) {
5921 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5922 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5923 OCS);
5924 }
5925 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5926 case OR_Success:
5927 ND = Best->FoundDecl;
5928 Corrected.setCorrectionDecl(ND);
5929 break;
5930 default:
5931 break;
5932 }
5933 }
5934 ND = ND->getUnderlyingDecl();
5935 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5936 return Corrected;
5937 }
5938 }
5939 return TypoCorrection();
5940 }
5941
5942 // [C++26][[expr.unary.op]/p4
5943 // A pointer to member is only formed when an explicit &
5944 // is used and its operand is a qualified-id not enclosed in parentheses.
5945 static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
5946 if (!isa<ParenExpr>(Fn))
5947 return false;
5948
5949 Fn = Fn->IgnoreParens();
5950
5951 auto *UO = dyn_cast<UnaryOperator>(Fn);
5952 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5953 return false;
5954 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5955 return DRE->hasQualifier();
5956 }
5957 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5958 return bool(OVL->getQualifier());
5959 return false;
5960 }
5961
5962 bool
5963 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5964 FunctionDecl *FDecl,
5965 const FunctionProtoType *Proto,
5966 ArrayRef<Expr *> Args,
5967 SourceLocation RParenLoc,
5968 bool IsExecConfig) {
5969 // Bail out early if calling a builtin with custom typechecking.
5970 if (FDecl)
5971 if (unsigned ID = FDecl->getBuiltinID())
5972 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5973 return false;
5974
5975 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5976 // assignment, to the types of the corresponding parameter, ...
5977
5978 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5979 bool HasExplicitObjectParameter =
5980 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5981 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5982 unsigned NumParams = Proto->getNumParams();
5983 bool Invalid = false;
5984 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5985 unsigned FnKind = Fn->getType()->isBlockPointerType()
5986 ? 1 /* block */
5987 : (IsExecConfig ? 3 /* kernel function (exec config) */
5988 : 0 /* function */);
5989
5990 // If too few arguments are available (and we don't have default
5991 // arguments for the remaining parameters), don't make the call.
5992 if (Args.size() < NumParams) {
5993 if (Args.size() < MinArgs) {
5994 TypoCorrection TC;
5995 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5996 unsigned diag_id =
5997 MinArgs == NumParams && !Proto->isVariadic()
5998 ? diag::err_typecheck_call_too_few_args_suggest
5999 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6000 diagnoseTypo(
6001 TC, PDiag(diag_id)
6002 << FnKind << MinArgs - ExplicitObjectParameterOffset
6003 << static_cast<unsigned>(Args.size()) -
6004 ExplicitObjectParameterOffset
6005 << HasExplicitObjectParameter << TC.getCorrectionRange());
6006 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6007 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6008 ->getDeclName())
6009 Diag(RParenLoc,
6010 MinArgs == NumParams && !Proto->isVariadic()
6011 ? diag::err_typecheck_call_too_few_args_one
6012 : diag::err_typecheck_call_too_few_args_at_least_one)
6013 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6014 << HasExplicitObjectParameter << Fn->getSourceRange();
6015 else
6016 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6017 ? diag::err_typecheck_call_too_few_args
6018 : diag::err_typecheck_call_too_few_args_at_least)
6019 << FnKind << MinArgs - ExplicitObjectParameterOffset
6020 << static_cast<unsigned>(Args.size()) -
6021 ExplicitObjectParameterOffset
6022 << HasExplicitObjectParameter << Fn->getSourceRange();
6023
6024 // Emit the location of the prototype.
6025 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6026 Diag(FDecl->getLocation(), diag::note_callee_decl)
6027 << FDecl << FDecl->getParametersSourceRange();
6028
6029 return true;
6030 }
6031 // We reserve space for the default arguments when we create
6032 // the call expression, before calling ConvertArgumentsForCall.
6033 assert((Call->getNumArgs() == NumParams) &&
6034 "We should have reserved space for the default arguments before!");
6035 }
6036
6037 // If too many are passed and not variadic, error on the extras and drop
6038 // them.
6039 if (Args.size() > NumParams) {
6040 if (!Proto->isVariadic()) {
6041 TypoCorrection TC;
6042 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6043 unsigned diag_id =
6044 MinArgs == NumParams && !Proto->isVariadic()
6045 ? diag::err_typecheck_call_too_many_args_suggest
6046 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6047 diagnoseTypo(
6048 TC, PDiag(diag_id)
6049 << FnKind << NumParams - ExplicitObjectParameterOffset
6050 << static_cast<unsigned>(Args.size()) -
6051 ExplicitObjectParameterOffset
6052 << HasExplicitObjectParameter << TC.getCorrectionRange());
6053 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6054 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6055 ->getDeclName())
6056 Diag(Args[NumParams]->getBeginLoc(),
6057 MinArgs == NumParams
6058 ? diag::err_typecheck_call_too_many_args_one
6059 : diag::err_typecheck_call_too_many_args_at_most_one)
6060 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6061 << static_cast<unsigned>(Args.size()) -
6062 ExplicitObjectParameterOffset
6063 << HasExplicitObjectParameter << Fn->getSourceRange()
6064 << SourceRange(Args[NumParams]->getBeginLoc(),
6065 Args.back()->getEndLoc());
6066 else
6067 Diag(Args[NumParams]->getBeginLoc(),
6068 MinArgs == NumParams
6069 ? diag::err_typecheck_call_too_many_args
6070 : diag::err_typecheck_call_too_many_args_at_most)
6071 << FnKind << NumParams - ExplicitObjectParameterOffset
6072 << static_cast<unsigned>(Args.size()) -
6073 ExplicitObjectParameterOffset
6074 << HasExplicitObjectParameter << Fn->getSourceRange()
6075 << SourceRange(Args[NumParams]->getBeginLoc(),
6076 Args.back()->getEndLoc());
6077
6078 // Emit the location of the prototype.
6079 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6080 Diag(FDecl->getLocation(), diag::note_callee_decl)
6081 << FDecl << FDecl->getParametersSourceRange();
6082
6083 // This deletes the extra arguments.
6084 Call->shrinkNumArgs(NumParams);
6085 return true;
6086 }
6087 }
6088 SmallVector<Expr *, 8> AllArgs;
6089 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6090
6091 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6092 AllArgs, CallType);
6093 if (Invalid)
6094 return true;
6095 unsigned TotalNumArgs = AllArgs.size();
6096 for (unsigned i = 0; i < TotalNumArgs; ++i)
6097 Call->setArg(i, AllArgs[i]);
6098
6099 Call->computeDependence();
6100 return false;
6101 }
6102
6103 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6104 const FunctionProtoType *Proto,
6105 unsigned FirstParam, ArrayRef<Expr *> Args,
6106 SmallVectorImpl<Expr *> &AllArgs,
6107 VariadicCallType CallType, bool AllowExplicit,
6108 bool IsListInitialization) {
6109 unsigned NumParams = Proto->getNumParams();
6110 bool Invalid = false;
6111 size_t ArgIx = 0;
6112 // Continue to check argument types (even if we have too few/many args).
6113 for (unsigned i = FirstParam; i < NumParams; i++) {
6114 QualType ProtoArgType = Proto->getParamType(i);
6115
6116 Expr *Arg;
6117 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6118 if (ArgIx < Args.size()) {
6119 Arg = Args[ArgIx++];
6120
6121 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6122 diag::err_call_incomplete_argument, Arg))
6123 return true;
6124
6125 // Strip the unbridged-cast placeholder expression off, if applicable.
6126 bool CFAudited = false;
6127 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6128 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6129 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6130 Arg = ObjC().stripARCUnbridgedCast(Arg);
6131 else if (getLangOpts().ObjCAutoRefCount &&
6132 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6133 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6134 CFAudited = true;
6135
6136 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6137 ProtoArgType->isBlockPointerType())
6138 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6139 BE->getBlockDecl()->setDoesNotEscape();
6140 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6141 Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLInOut)) {
6142 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6143 if (ArgExpr.isInvalid())
6144 return true;
6145 Arg = ArgExpr.getAs<Expr>();
6146 }
6147
6148 InitializedEntity Entity =
6149 Param ? InitializedEntity::InitializeParameter(Context, Param,
6150 ProtoArgType)
6151 : InitializedEntity::InitializeParameter(
6152 Context, ProtoArgType, Proto->isParamConsumed(i));
6153
6154 // Remember that parameter belongs to a CF audited API.
6155 if (CFAudited)
6156 Entity.setParameterCFAudited();
6157
6158 ExprResult ArgE = PerformCopyInitialization(
6159 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6160 if (ArgE.isInvalid())
6161 return true;
6162
6163 Arg = ArgE.getAs<Expr>();
6164 } else {
6165 assert(Param && "can't use default arguments without a known callee");
6166
6167 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6168 if (ArgExpr.isInvalid())
6169 return true;
6170
6171 Arg = ArgExpr.getAs<Expr>();
6172 }
6173
6174 // Check for array bounds violations for each argument to the call. This
6175 // check only triggers warnings when the argument isn't a more complex Expr
6176 // with its own checking, such as a BinaryOperator.
6177 CheckArrayAccess(Arg);
6178
6179 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6180 CheckStaticArrayArgument(CallLoc, Param, Arg);
6181
6182 AllArgs.push_back(Arg);
6183 }
6184
6185 // If this is a variadic call, handle args passed through "...".
6186 if (CallType != VariadicCallType::DoesNotApply) {
6187 // Assume that extern "C" functions with variadic arguments that
6188 // return __unknown_anytype aren't *really* variadic.
6189 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6190 FDecl->isExternC()) {
6191 for (Expr *A : Args.slice(ArgIx)) {
6192 QualType paramType; // ignored
6193 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6194 Invalid |= arg.isInvalid();
6195 AllArgs.push_back(arg.get());
6196 }
6197
6198 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6199 } else {
6200 for (Expr *A : Args.slice(ArgIx)) {
6201 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6202 Invalid |= Arg.isInvalid();
6203 AllArgs.push_back(Arg.get());
6204 }
6205 }
6206
6207 // Check for array bounds violations.
6208 for (Expr *A : Args.slice(ArgIx))
6209 CheckArrayAccess(A);
6210 }
6211 return Invalid;
6212 }
6213
6214 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6215 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6216 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6217 TL = DTL.getOriginalLoc();
6218 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6219 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6220 << ATL.getLocalSourceRange();
6221 }
6222
6223 void
6224 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6225 ParmVarDecl *Param,
6226 const Expr *ArgExpr) {
6227 // Static array parameters are not supported in C++.
6228 if (!Param || getLangOpts().CPlusPlus)
6229 return;
6230
6231 QualType OrigTy = Param->getOriginalType();
6232
6233 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6234 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6235 return;
6236
6237 if (ArgExpr->isNullPointerConstant(Context,
6238 Expr::NPC_NeverValueDependent)) {
6239 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6240 DiagnoseCalleeStaticArrayParam(*this, Param);
6241 return;
6242 }
6243
6244 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6245 if (!CAT)
6246 return;
6247
6248 const ConstantArrayType *ArgCAT =
6249 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6250 if (!ArgCAT)
6251 return;
6252
6253 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6254 ArgCAT->getElementType())) {
6255 if (ArgCAT->getSize().ult(CAT->getSize())) {
6256 Diag(CallLoc, diag::warn_static_array_too_small)
6257 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6258 << (unsigned)CAT->getZExtSize() << 0;
6259 DiagnoseCalleeStaticArrayParam(*this, Param);
6260 }
6261 return;
6262 }
6263
6264 std::optional<CharUnits> ArgSize =
6265 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6266 std::optional<CharUnits> ParmSize =
6267 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6268 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6269 Diag(CallLoc, diag::warn_static_array_too_small)
6270 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6271 << (unsigned)ParmSize->getQuantity() << 1;
6272 DiagnoseCalleeStaticArrayParam(*this, Param);
6273 }
6274 }
6275
6276 /// Given a function expression of unknown-any type, try to rebuild it
6277 /// to have a function type.
6278 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6279
6280 /// Is the given type a placeholder that we need to lower out
6281 /// immediately during argument processing?
6282 static bool isPlaceholderToRemoveAsArg(QualType type) {
6283 // Placeholders are never sugared.
6284 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6285 if (!placeholder) return false;
6286
6287 switch (placeholder->getKind()) {
6288 // Ignore all the non-placeholder types.
6289 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6290 case BuiltinType::Id:
6291 #include "clang/Basic/OpenCLImageTypes.def"
6292 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6293 case BuiltinType::Id:
6294 #include "clang/Basic/OpenCLExtensionTypes.def"
6295 // In practice we'll never use this, since all SVE types are sugared
6296 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6297 #define SVE_TYPE(Name, Id, SingletonId) \
6298 case BuiltinType::Id:
6299 #include "clang/Basic/AArch64ACLETypes.def"
6300 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6301 case BuiltinType::Id:
6302 #include "clang/Basic/PPCTypes.def"
6303 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6304 #include "clang/Basic/RISCVVTypes.def"
6305 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6306 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6307 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6308 #include "clang/Basic/AMDGPUTypes.def"
6309 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6310 #include "clang/Basic/HLSLIntangibleTypes.def"
6311 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6312 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6313 #include "clang/AST/BuiltinTypes.def"
6314 return false;
6315
6316 case BuiltinType::UnresolvedTemplate:
6317 // We cannot lower out overload sets; they might validly be resolved
6318 // by the call machinery.
6319 case BuiltinType::Overload:
6320 return false;
6321
6322 // Unbridged casts in ARC can be handled in some call positions and
6323 // should be left in place.
6324 case BuiltinType::ARCUnbridgedCast:
6325 return false;
6326
6327 // Pseudo-objects should be converted as soon as possible.
6328 case BuiltinType::PseudoObject:
6329 return true;
6330
6331 // The debugger mode could theoretically but currently does not try
6332 // to resolve unknown-typed arguments based on known parameter types.
6333 case BuiltinType::UnknownAny:
6334 return true;
6335
6336 // These are always invalid as call arguments and should be reported.
6337 case BuiltinType::BoundMember:
6338 case BuiltinType::BuiltinFn:
6339 case BuiltinType::IncompleteMatrixIdx:
6340 case BuiltinType::ArraySection:
6341 case BuiltinType::OMPArrayShaping:
6342 case BuiltinType::OMPIterator:
6343 return true;
6344
6345 }
6346 llvm_unreachable("bad builtin type kind");
6347 }
6348
6349 bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6350 // Apply this processing to all the arguments at once instead of
6351 // dying at the first failure.
6352 bool hasInvalid = false;
6353 for (size_t i = 0, e = args.size(); i != e; i++) {
6354 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6355 ExprResult result = CheckPlaceholderExpr(args[i]);
6356 if (result.isInvalid()) hasInvalid = true;
6357 else args[i] = result.get();
6358 }
6359 }
6360 return hasInvalid;
6361 }
6362
6363 /// If a builtin function has a pointer argument with no explicit address
6364 /// space, then it should be able to accept a pointer to any address
6365 /// space as input. In order to do this, we need to replace the
6366 /// standard builtin declaration with one that uses the same address space
6367 /// as the call.
6368 ///
6369 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6370 /// it does not contain any pointer arguments without
6371 /// an address space qualifer. Otherwise the rewritten
6372 /// FunctionDecl is returned.
6373 /// TODO: Handle pointer return types.
6374 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6375 FunctionDecl *FDecl,
6376 MultiExprArg ArgExprs) {
6377
6378 QualType DeclType = FDecl->getType();
6379 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6380
6381 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6382 ArgExprs.size() < FT->getNumParams())
6383 return nullptr;
6384
6385 bool NeedsNewDecl = false;
6386 unsigned i = 0;
6387 SmallVector<QualType, 8> OverloadParams;
6388
6389 {
6390 // The lvalue conversions in this loop are only for type resolution and
6391 // don't actually occur.
6392 EnterExpressionEvaluationContext Unevaluated(
6393 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6394 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6395
6396 for (QualType ParamType : FT->param_types()) {
6397
6398 // Convert array arguments to pointer to simplify type lookup.
6399 ExprResult ArgRes =
6400 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6401 if (ArgRes.isInvalid())
6402 return nullptr;
6403 Expr *Arg = ArgRes.get();
6404 QualType ArgType = Arg->getType();
6405 if (!ParamType->isPointerType() ||
6406 ParamType->getPointeeType().hasAddressSpace() ||
6407 !ArgType->isPointerType() ||
6408 !ArgType->getPointeeType().hasAddressSpace() ||
6409 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6410 OverloadParams.push_back(ParamType);
6411 continue;
6412 }
6413
6414 QualType PointeeType = ParamType->getPointeeType();
6415 NeedsNewDecl = true;
6416 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6417
6418 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6419 OverloadParams.push_back(Context.getPointerType(PointeeType));
6420 }
6421 }
6422
6423 if (!NeedsNewDecl)
6424 return nullptr;
6425
6426 FunctionProtoType::ExtProtoInfo EPI;
6427 EPI.Variadic = FT->isVariadic();
6428 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6429 OverloadParams, EPI);
6430 DeclContext *Parent = FDecl->getParent();
6431 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6432 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6433 FDecl->getIdentifier(), OverloadTy,
6434 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6435 false,
6436 /*hasPrototype=*/true);
6437 SmallVector<ParmVarDecl*, 16> Params;
6438 FT = cast<FunctionProtoType>(OverloadTy);
6439 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6440 QualType ParamType = FT->getParamType(i);
6441 ParmVarDecl *Parm =
6442 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6443 SourceLocation(), nullptr, ParamType,
6444 /*TInfo=*/nullptr, SC_None, nullptr);
6445 Parm->setScopeInfo(0, i);
6446 Params.push_back(Parm);
6447 }
6448 OverloadDecl->setParams(Params);
6449 // We cannot merge host/device attributes of redeclarations. They have to
6450 // be consistent when created.
6451 if (Sema->LangOpts.CUDA) {
6452 if (FDecl->hasAttr<CUDAHostAttr>())
6453 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6454 if (FDecl->hasAttr<CUDADeviceAttr>())
6455 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6456 }
6457 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6458 return OverloadDecl;
6459 }
6460
6461 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6462 FunctionDecl *Callee,
6463 MultiExprArg ArgExprs) {
6464 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6465 // similar attributes) really don't like it when functions are called with an
6466 // invalid number of args.
6467 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6468 /*PartialOverloading=*/false) &&
6469 !Callee->isVariadic())
6470 return;
6471 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6472 return;
6473
6474 if (const EnableIfAttr *Attr =
6475 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6476 S.Diag(Fn->getBeginLoc(),
6477 isa<CXXMethodDecl>(Callee)
6478 ? diag::err_ovl_no_viable_member_function_in_call
6479 : diag::err_ovl_no_viable_function_in_call)
6480 << Callee << Callee->getSourceRange();
6481 S.Diag(Callee->getLocation(),
6482 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6483 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6484 return;
6485 }
6486 }
6487
6488 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6489 const UnresolvedMemberExpr *const UME, Sema &S) {
6490
6491 const auto GetFunctionLevelDCIfCXXClass =
6492 [](Sema &S) -> const CXXRecordDecl * {
6493 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6494 if (!DC || !DC->getParent())
6495 return nullptr;
6496
6497 // If the call to some member function was made from within a member
6498 // function body 'M' return return 'M's parent.
6499 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6500 return MD->getParent()->getCanonicalDecl();
6501 // else the call was made from within a default member initializer of a
6502 // class, so return the class.
6503 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6504 return RD->getCanonicalDecl();
6505 return nullptr;
6506 };
6507 // If our DeclContext is neither a member function nor a class (in the
6508 // case of a lambda in a default member initializer), we can't have an
6509 // enclosing 'this'.
6510
6511 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6512 if (!CurParentClass)
6513 return false;
6514
6515 // The naming class for implicit member functions call is the class in which
6516 // name lookup starts.
6517 const CXXRecordDecl *const NamingClass =
6518 UME->getNamingClass()->getCanonicalDecl();
6519 assert(NamingClass && "Must have naming class even for implicit access");
6520
6521 // If the unresolved member functions were found in a 'naming class' that is
6522 // related (either the same or derived from) to the class that contains the
6523 // member function that itself contained the implicit member access.
6524
6525 return CurParentClass == NamingClass ||
6526 CurParentClass->isDerivedFrom(NamingClass);
6527 }
6528
6529 static void
6530 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6531 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6532
6533 if (!UME)
6534 return;
6535
6536 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6537 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6538 // already been captured, or if this is an implicit member function call (if
6539 // it isn't, an attempt to capture 'this' should already have been made).
6540 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6541 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6542 return;
6543
6544 // Check if the naming class in which the unresolved members were found is
6545 // related (same as or is a base of) to the enclosing class.
6546
6547 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6548 return;
6549
6550
6551 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6552 // If the enclosing function is not dependent, then this lambda is
6553 // capture ready, so if we can capture this, do so.
6554 if (!EnclosingFunctionCtx->isDependentContext()) {
6555 // If the current lambda and all enclosing lambdas can capture 'this' -
6556 // then go ahead and capture 'this' (since our unresolved overload set
6557 // contains at least one non-static member function).
6558 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6559 S.CheckCXXThisCapture(CallLoc);
6560 } else if (S.CurContext->isDependentContext()) {
6561 // ... since this is an implicit member reference, that might potentially
6562 // involve a 'this' capture, mark 'this' for potential capture in
6563 // enclosing lambdas.
6564 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6565 CurLSI->addPotentialThisCapture(CallLoc);
6566 }
6567 }
6568
6569 // Once a call is fully resolved, warn for unqualified calls to specific
6570 // C++ standard functions, like move and forward.
6571 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6572 const CallExpr *Call) {
6573 // We are only checking unary move and forward so exit early here.
6574 if (Call->getNumArgs() != 1)
6575 return;
6576
6577 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6578 if (!E || isa<UnresolvedLookupExpr>(E))
6579 return;
6580 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6581 if (!DRE || !DRE->getLocation().isValid())
6582 return;
6583
6584 if (DRE->getQualifier())
6585 return;
6586
6587 const FunctionDecl *FD = Call->getDirectCallee();
6588 if (!FD)
6589 return;
6590
6591 // Only warn for some functions deemed more frequent or problematic.
6592 unsigned BuiltinID = FD->getBuiltinID();
6593 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6594 return;
6595
6596 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6597 << FD->getQualifiedNameAsString()
6598 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6599 }
6600
6601 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6602 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6603 Expr *ExecConfig) {
6604 ExprResult Call =
6605 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6606 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6607 if (Call.isInvalid())
6608 return Call;
6609
6610 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6611 // language modes.
6612 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6613 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6614 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6615 << ULE->getName();
6616 }
6617
6618 if (LangOpts.OpenMP)
6619 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6620 ExecConfig);
6621 if (LangOpts.CPlusPlus) {
6622 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6623 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6624
6625 // If we previously found that the id-expression of this call refers to a
6626 // consteval function but the call is dependent, we should not treat is an
6627 // an invalid immediate call.
6628 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6629 DRE && Call.get()->isValueDependent()) {
6630 currentEvaluationContext().ReferenceToConsteval.erase(DRE);
6631 }
6632 }
6633 return Call;
6634 }
6635
6636 // Any type that could be used to form a callable expression
6637 static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6638 QualType T = E->getType();
6639 if (T->isDependentType())
6640 return true;
6641
6642 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6643 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6644 T->isFunctionType() || T->isFunctionReferenceType() ||
6645 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6646 T->isBlockPointerType() || T->isRecordType())
6647 return true;
6648
6649 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6650 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(E);
6651 }
6652
6653 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6654 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6655 Expr *ExecConfig, bool IsExecConfig,
6656 bool AllowRecovery) {
6657 // Since this might be a postfix expression, get rid of ParenListExprs.
6658 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6659 if (Result.isInvalid()) return ExprError();
6660 Fn = Result.get();
6661
6662 if (CheckArgsForPlaceholders(ArgExprs))
6663 return ExprError();
6664
6665 // The result of __builtin_counted_by_ref cannot be used as a function
6666 // argument. It allows leaking and modification of bounds safety information.
6667 for (const Expr *Arg : ArgExprs)
6668 if (CheckInvalidBuiltinCountedByRef(Arg,
6669 BuiltinCountedByRefKind::FunctionArg))
6670 return ExprError();
6671
6672 if (getLangOpts().CPlusPlus) {
6673 // If this is a pseudo-destructor expression, build the call immediately.
6674 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6675 if (!ArgExprs.empty()) {
6676 // Pseudo-destructor calls should not have any arguments.
6677 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6678 << FixItHint::CreateRemoval(
6679 SourceRange(ArgExprs.front()->getBeginLoc(),
6680 ArgExprs.back()->getEndLoc()));
6681 }
6682
6683 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6684 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6685 }
6686 if (Fn->getType() == Context.PseudoObjectTy) {
6687 ExprResult result = CheckPlaceholderExpr(Fn);
6688 if (result.isInvalid()) return ExprError();
6689 Fn = result.get();
6690 }
6691
6692 // Determine whether this is a dependent call inside a C++ template,
6693 // in which case we won't do any semantic analysis now.
6694 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6695 if (ExecConfig) {
6696 return CUDAKernelCallExpr::Create(Context, Fn,
6697 cast<CallExpr>(ExecConfig), ArgExprs,
6698 Context.DependentTy, VK_PRValue,
6699 RParenLoc, CurFPFeatureOverrides());
6700 } else {
6701
6702 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6703 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6704 Fn->getBeginLoc());
6705
6706 // If the type of the function itself is not dependent
6707 // check that it is a reasonable as a function, as type deduction
6708 // later assume the CallExpr has a sensible TYPE.
6709 if (!MayBeFunctionType(Context, Fn))
6710 return ExprError(
6711 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6712 << Fn->getType() << Fn->getSourceRange());
6713
6714 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6715 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6716 }
6717 }
6718
6719 // Determine whether this is a call to an object (C++ [over.call.object]).
6720 if (Fn->getType()->isRecordType())
6721 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6722 RParenLoc);
6723
6724 if (Fn->getType() == Context.UnknownAnyTy) {
6725 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6726 if (result.isInvalid()) return ExprError();
6727 Fn = result.get();
6728 }
6729
6730 if (Fn->getType() == Context.BoundMemberTy) {
6731 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6732 RParenLoc, ExecConfig, IsExecConfig,
6733 AllowRecovery);
6734 }
6735 }
6736
6737 // Check for overloaded calls. This can happen even in C due to extensions.
6738 if (Fn->getType() == Context.OverloadTy) {
6739 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6740
6741 // We aren't supposed to apply this logic if there's an '&' involved.
6742 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6743 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6744 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6745 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6746 OverloadExpr *ovl = find.Expression;
6747 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6748 return BuildOverloadedCallExpr(
6749 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6750 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6751 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6752 RParenLoc, ExecConfig, IsExecConfig,
6753 AllowRecovery);
6754 }
6755 }
6756
6757 // If we're directly calling a function, get the appropriate declaration.
6758 if (Fn->getType() == Context.UnknownAnyTy) {
6759 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6760 if (result.isInvalid()) return ExprError();
6761 Fn = result.get();
6762 }
6763
6764 Expr *NakedFn = Fn->IgnoreParens();
6765
6766 bool CallingNDeclIndirectly = false;
6767 NamedDecl *NDecl = nullptr;
6768 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6769 if (UnOp->getOpcode() == UO_AddrOf) {
6770 CallingNDeclIndirectly = true;
6771 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6772 }
6773 }
6774
6775 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6776 NDecl = DRE->getDecl();
6777
6778 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6779 if (FDecl && FDecl->getBuiltinID()) {
6780 // Rewrite the function decl for this builtin by replacing parameters
6781 // with no explicit address space with the address space of the arguments
6782 // in ArgExprs.
6783 if ((FDecl =
6784 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6785 NDecl = FDecl;
6786 Fn = DeclRefExpr::Create(
6787 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6788 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6789 nullptr, DRE->isNonOdrUse());
6790 }
6791 }
6792 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6793 NDecl = ME->getMemberDecl();
6794
6795 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6796 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6797 FD, /*Complain=*/true, Fn->getBeginLoc()))
6798 return ExprError();
6799
6800 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6801
6802 // If this expression is a call to a builtin function in HIP compilation,
6803 // allow a pointer-type argument to default address space to be passed as a
6804 // pointer-type parameter to a non-default address space. If Arg is declared
6805 // in the default address space and Param is declared in a non-default
6806 // address space, perform an implicit address space cast to the parameter
6807 // type.
6808 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6809 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6810 ++Idx) {
6811 ParmVarDecl *Param = FD->getParamDecl(Idx);
6812 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6813 !ArgExprs[Idx]->getType()->isPointerType())
6814 continue;
6815
6816 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6817 auto ArgTy = ArgExprs[Idx]->getType();
6818 auto ArgPtTy = ArgTy->getPointeeType();
6819 auto ArgAS = ArgPtTy.getAddressSpace();
6820
6821 // Add address space cast if target address spaces are different
6822 bool NeedImplicitASC =
6823 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6824 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6825 // or from specific AS which has target AS matching that of Param.
6826 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6827 if (!NeedImplicitASC)
6828 continue;
6829
6830 // First, ensure that the Arg is an RValue.
6831 if (ArgExprs[Idx]->isGLValue()) {
6832 ArgExprs[Idx] = ImplicitCastExpr::Create(
6833 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6834 nullptr, VK_PRValue, FPOptionsOverride());
6835 }
6836
6837 // Construct a new arg type with address space of Param
6838 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6839 ArgPtQuals.setAddressSpace(ParamAS);
6840 auto NewArgPtTy =
6841 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6842 auto NewArgTy =
6843 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6844 ArgTy.getQualifiers());
6845
6846 // Finally perform an implicit address space cast
6847 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6848 CK_AddressSpaceConversion)
6849 .get();
6850 }
6851 }
6852 }
6853
6854 if (Context.isDependenceAllowed() &&
6855 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6856 assert(!getLangOpts().CPlusPlus);
6857 assert((Fn->containsErrors() ||
6858 llvm::any_of(ArgExprs,
6859 [](clang::Expr *E) { return E->containsErrors(); })) &&
6860 "should only occur in error-recovery path.");
6861 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6862 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6863 }
6864 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6865 ExecConfig, IsExecConfig);
6866 }
6867
6868 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6869 MultiExprArg CallArgs) {
6870 std::string Name = Context.BuiltinInfo.getName(Id);
6871 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6872 Sema::LookupOrdinaryName);
6873 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6874
6875 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6876 assert(BuiltInDecl && "failed to find builtin declaration");
6877
6878 ExprResult DeclRef =
6879 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6880 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6881
6882 ExprResult Call =
6883 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6884
6885 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6886 return Call.get();
6887 }
6888
6889 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6890 SourceLocation BuiltinLoc,
6891 SourceLocation RParenLoc) {
6892 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6893 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6894 }
6895
6896 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6897 SourceLocation BuiltinLoc,
6898 SourceLocation RParenLoc) {
6899 ExprValueKind VK = VK_PRValue;
6900 ExprObjectKind OK = OK_Ordinary;
6901 QualType SrcTy = E->getType();
6902 if (!SrcTy->isDependentType() &&
6903 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6904 return ExprError(
6905 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6906 << DestTy << SrcTy << E->getSourceRange());
6907 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6908 }
6909
6910 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6911 SourceLocation BuiltinLoc,
6912 SourceLocation RParenLoc) {
6913 TypeSourceInfo *TInfo;
6914 GetTypeFromParser(ParsedDestTy, &TInfo);
6915 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6916 }
6917
6918 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6919 SourceLocation LParenLoc,
6920 ArrayRef<Expr *> Args,
6921 SourceLocation RParenLoc, Expr *Config,
6922 bool IsExecConfig, ADLCallKind UsesADL) {
6923 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6924 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6925
6926 auto IsSJLJ = [&] {
6927 switch (BuiltinID) {
6928 case Builtin::BI__builtin_longjmp:
6929 case Builtin::BI__builtin_setjmp:
6930 case Builtin::BI__sigsetjmp:
6931 case Builtin::BI_longjmp:
6932 case Builtin::BI_setjmp:
6933 case Builtin::BIlongjmp:
6934 case Builtin::BIsetjmp:
6935 case Builtin::BIsiglongjmp:
6936 case Builtin::BIsigsetjmp:
6937 return true;
6938 default:
6939 return false;
6940 }
6941 };
6942
6943 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
6944 if (!CurrentDefer.empty() && IsSJLJ()) {
6945 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
6946 // for more than just blocks (e.g. lambdas, nested classes...).
6947 Scope *DeferParent = CurrentDefer.back().first;
6948 Scope *Block = CurScope->getBlockParent();
6949 if (DeferParent->Contains(*CurScope) &&
6950 (!Block || !DeferParent->Contains(*Block)))
6951 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
6952 }
6953
6954 // Functions with 'interrupt' attribute cannot be called directly.
6955 if (FDecl) {
6956 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6957 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6958 return ExprError();
6959 }
6960 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6961 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6962 return ExprError();
6963 }
6964 }
6965
6966 // X86 interrupt handlers may only call routines with attribute
6967 // no_caller_saved_registers since there is no efficient way to
6968 // save and restore the non-GPR state.
6969 if (auto *Caller = getCurFunctionDecl()) {
6970 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6971 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6972 const TargetInfo &TI = Context.getTargetInfo();
6973 bool HasNonGPRRegisters =
6974 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6975 if (HasNonGPRRegisters &&
6976 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6977 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6978 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6979 if (FDecl)
6980 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6981 }
6982 }
6983 }
6984
6985 // Promote the function operand.
6986 // We special-case function promotion here because we only allow promoting
6987 // builtin functions to function pointers in the callee of a call.
6988 ExprResult Result;
6989 QualType ResultTy;
6990 if (BuiltinID &&
6991 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6992 // Extract the return type from the (builtin) function pointer type.
6993 // FIXME Several builtins still have setType in
6994 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6995 // Builtins.td to ensure they are correct before removing setType calls.
6996 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6997 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6998 ResultTy = FDecl->getCallResultType();
6999 } else {
7000 Result = CallExprUnaryConversions(Fn);
7001 ResultTy = Context.BoolTy;
7002 }
7003 if (Result.isInvalid())
7004 return ExprError();
7005 Fn = Result.get();
7006
7007 // Check for a valid function type, but only if it is not a builtin which
7008 // requires custom type checking. These will be handled by
7009 // CheckBuiltinFunctionCall below just after creation of the call expression.
7010 const FunctionType *FuncT = nullptr;
7011 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7012 retry:
7013 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7014 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7015 // have type pointer to function".
7016 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7017 if (!FuncT)
7018 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7019 << Fn->getType() << Fn->getSourceRange());
7020 } else if (const BlockPointerType *BPT =
7021 Fn->getType()->getAs<BlockPointerType>()) {
7022 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7023 } else {
7024 // Handle calls to expressions of unknown-any type.
7025 if (Fn->getType() == Context.UnknownAnyTy) {
7026 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7027 if (rewrite.isInvalid())
7028 return ExprError();
7029 Fn = rewrite.get();
7030 goto retry;
7031 }
7032
7033 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7034 << Fn->getType() << Fn->getSourceRange());
7035 }
7036 }
7037
7038 // Get the number of parameters in the function prototype, if any.
7039 // We will allocate space for max(Args.size(), NumParams) arguments
7040 // in the call expression.
7041 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7042 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7043
7044 CallExpr *TheCall;
7045 if (Config) {
7046 assert(UsesADL == ADLCallKind::NotADL &&
7047 "CUDAKernelCallExpr should not use ADL");
7048 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7049 Args, ResultTy, VK_PRValue, RParenLoc,
7050 CurFPFeatureOverrides(), NumParams);
7051 } else {
7052 TheCall =
7053 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7054 CurFPFeatureOverrides(), NumParams, UsesADL);
7055 }
7056
7057 // Bail out early if calling a builtin with custom type checking.
7058 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7059 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7060 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7061 E = CheckForImmediateInvocation(E, FDecl);
7062 return E;
7063 }
7064
7065 if (getLangOpts().CUDA) {
7066 if (Config) {
7067 // CUDA: Kernel calls must be to global functions
7068 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7069 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7070 << FDecl << Fn->getSourceRange());
7071
7072 // CUDA: Kernel function must have 'void' return type
7073 if (!FuncT->getReturnType()->isVoidType() &&
7074 !FuncT->getReturnType()->getAs<AutoType>() &&
7075 !FuncT->getReturnType()->isInstantiationDependentType())
7076 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7077 << Fn->getType() << Fn->getSourceRange());
7078 } else {
7079 // CUDA: Calls to global functions must be configured
7080 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7081 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7082 << FDecl << Fn->getSourceRange());
7083 }
7084 }
7085
7086 // Check for a valid return type
7087 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7088 FDecl))
7089 return ExprError();
7090
7091 // We know the result type of the call, set it.
7092 TheCall->setType(FuncT->getCallResultType(Context));
7093 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7094
7095 // WebAssembly tables can't be used as arguments.
7096 if (Context.getTargetInfo().getTriple().isWasm()) {
7097 for (const Expr *Arg : Args) {
7098 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7099 return ExprError(Diag(Arg->getExprLoc(),
7100 diag::err_wasm_table_as_function_parameter));
7101 }
7102 }
7103 }
7104
7105 if (Proto) {
7106 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7107 IsExecConfig))
7108 return ExprError();
7109 } else {
7110 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7111
7112 if (FDecl) {
7113 // Check if we have too few/too many template arguments, based
7114 // on our knowledge of the function definition.
7115 const FunctionDecl *Def = nullptr;
7116 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7117 Proto = Def->getType()->getAs<FunctionProtoType>();
7118 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7119 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7120 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7121 }
7122
7123 // If the function we're calling isn't a function prototype, but we have
7124 // a function prototype from a prior declaratiom, use that prototype.
7125 if (!FDecl->hasPrototype())
7126 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7127 }
7128
7129 // If we still haven't found a prototype to use but there are arguments to
7130 // the call, diagnose this as calling a function without a prototype.
7131 // However, if we found a function declaration, check to see if
7132 // -Wdeprecated-non-prototype was disabled where the function was declared.
7133 // If so, we will silence the diagnostic here on the assumption that this
7134 // interface is intentional and the user knows what they're doing. We will
7135 // also silence the diagnostic if there is a function declaration but it
7136 // was implicitly defined (the user already gets diagnostics about the
7137 // creation of the implicit function declaration, so the additional warning
7138 // is not helpful).
7139 if (!Proto && !Args.empty() &&
7140 (!FDecl || (!FDecl->isImplicit() &&
7141 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7142 FDecl->getLocation()))))
7143 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7144 << (FDecl != nullptr) << FDecl;
7145
7146 // Promote the arguments (C99 6.5.2.2p6).
7147 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7148 Expr *Arg = Args[i];
7149
7150 if (Proto && i < Proto->getNumParams()) {
7151 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7152 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7153 ExprResult ArgE =
7154 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7155 if (ArgE.isInvalid())
7156 return true;
7157
7158 Arg = ArgE.getAs<Expr>();
7159
7160 } else {
7161 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7162
7163 if (ArgE.isInvalid())
7164 return true;
7165
7166 Arg = ArgE.getAs<Expr>();
7167 }
7168
7169 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7170 diag::err_call_incomplete_argument, Arg))
7171 return ExprError();
7172
7173 TheCall->setArg(i, Arg);
7174 }
7175 TheCall->computeDependence();
7176 }
7177
7178 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7179 if (Method->isImplicitObjectMemberFunction())
7180 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7181 << Fn->getSourceRange() << 0);
7182
7183 // Check for sentinels
7184 if (NDecl)
7185 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7186
7187 // Warn for unions passing across security boundary (CMSE).
7188 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7189 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7190 if (const auto *RT =
7191 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7192 if (RT->getDecl()->isOrContainsUnion())
7193 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7194 << 0 << i;
7195 }
7196 }
7197 }
7198
7199 // Do special checking on direct calls to functions.
7200 if (FDecl) {
7201 if (CheckFunctionCall(FDecl, TheCall, Proto))
7202 return ExprError();
7203
7204 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7205
7206 if (BuiltinID)
7207 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7208 } else if (NDecl) {
7209 if (CheckPointerCall(NDecl, TheCall, Proto))
7210 return ExprError();
7211 } else {
7212 if (CheckOtherCall(TheCall, Proto))
7213 return ExprError();
7214 }
7215
7216 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7217 }
7218
7219 ExprResult
7220 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7221 SourceLocation RParenLoc, Expr *InitExpr) {
7222 assert(Ty && "ActOnCompoundLiteral(): missing type");
7223 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7224
7225 TypeSourceInfo *TInfo;
7226 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7227 if (!TInfo)
7228 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7229
7230 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7231 }
7232
7233 ExprResult
7234 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7235 SourceLocation RParenLoc, Expr *LiteralExpr) {
7236 QualType literalType = TInfo->getType();
7237
7238 if (literalType->isArrayType()) {
7239 if (RequireCompleteSizedType(
7240 LParenLoc, Context.getBaseElementType(literalType),
7241 diag::err_array_incomplete_or_sizeless_type,
7242 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7243 return ExprError();
7244 if (literalType->isVariableArrayType()) {
7245 // C23 6.7.10p4: An entity of variable length array type shall not be
7246 // initialized except by an empty initializer.
7247 //
7248 // The C extension warnings are issued from ParseBraceInitializer() and
7249 // do not need to be issued here. However, we continue to issue an error
7250 // in the case there are initializers or we are compiling C++. We allow
7251 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7252 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7253 // FIXME: should we allow this construct in C++ when it makes sense to do
7254 // so?
7255 //
7256 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7257 // shall specify an object type or an array of unknown size, but not a
7258 // variable length array type. This seems odd, as it allows 'int a[size] =
7259 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7260 // says, this is what's implemented here for C (except for the extension
7261 // that permits constant foldable size arrays)
7262
7263 auto diagID = LangOpts.CPlusPlus
7264 ? diag::err_variable_object_no_init
7265 : diag::err_compound_literal_with_vla_type;
7266 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7267 diagID))
7268 return ExprError();
7269 }
7270 } else if (!literalType->isDependentType() &&
7271 RequireCompleteType(LParenLoc, literalType,
7272 diag::err_typecheck_decl_incomplete_type,
7273 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7274 return ExprError();
7275
7276 InitializedEntity Entity
7277 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7278 InitializationKind Kind
7279 = InitializationKind::CreateCStyleCast(LParenLoc,
7280 SourceRange(LParenLoc, RParenLoc),
7281 /*InitList=*/true);
7282 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7283 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7284 &literalType);
7285 if (Result.isInvalid())
7286 return ExprError();
7287 LiteralExpr = Result.get();
7288
7289 // We treat the compound literal as being at file scope if it's not in a
7290 // function or method body, or within the function's prototype scope. This
7291 // means the following compound literal is not at file scope:
7292 // void func(char *para[(int [1]){ 0 }[0]);
7293 const Scope *S = getCurScope();
7294 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7295 !S->isInCFunctionScope() &&
7296 (!S || !S->isFunctionPrototypeScope());
7297
7298 // In C, compound literals are l-values for some reason.
7299 // For GCC compatibility, in C++, file-scope array compound literals with
7300 // constant initializers are also l-values, and compound literals are
7301 // otherwise prvalues.
7302 //
7303 // (GCC also treats C++ list-initialized file-scope array prvalues with
7304 // constant initializers as l-values, but that's non-conforming, so we don't
7305 // follow it there.)
7306 //
7307 // FIXME: It would be better to handle the lvalue cases as materializing and
7308 // lifetime-extending a temporary object, but our materialized temporaries
7309 // representation only supports lifetime extension from a variable, not "out
7310 // of thin air".
7311 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7312 // is bound to the result of applying array-to-pointer decay to the compound
7313 // literal.
7314 // FIXME: GCC supports compound literals of reference type, which should
7315 // obviously have a value kind derived from the kind of reference involved.
7316 ExprValueKind VK =
7317 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7318 ? VK_PRValue
7319 : VK_LValue;
7320
7321 // C99 6.5.2.5
7322 // "If the compound literal occurs outside the body of a function, the
7323 // initializer list shall consist of constant expressions."
7324 if (IsFileScope)
7325 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7326 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7327 Expr *Init = ILE->getInit(i);
7328 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7329 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7330 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7331 << Init->getSourceBitField();
7332 return ExprError();
7333 }
7334
7335 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7336 }
7337
7338 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7339 LiteralExpr, IsFileScope);
7340 if (IsFileScope) {
7341 if (!LiteralExpr->isTypeDependent() &&
7342 !LiteralExpr->isValueDependent() &&
7343 !literalType->isDependentType()) // C99 6.5.2.5p3
7344 if (CheckForConstantInitializer(LiteralExpr))
7345 return ExprError();
7346 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7347 literalType.getAddressSpace() != LangAS::Default) {
7348 // Embedded-C extensions to C99 6.5.2.5:
7349 // "If the compound literal occurs inside the body of a function, the
7350 // type name shall not be qualified by an address-space qualifier."
7351 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7352 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7353 return ExprError();
7354 }
7355
7356 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7357 // Compound literals that have automatic storage duration are destroyed at
7358 // the end of the scope in C; in C++, they're just temporaries.
7359
7360 // Emit diagnostics if it is or contains a C union type that is non-trivial
7361 // to destruct.
7362 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7363 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7364 NonTrivialCUnionContext::CompoundLiteral,
7365 NTCUK_Destruct);
7366
7367 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7368 if (literalType.isDestructedType()) {
7369 Cleanup.setExprNeedsCleanups(true);
7370 ExprCleanupObjects.push_back(E);
7371 getCurFunction()->setHasBranchProtectedScope();
7372 }
7373 }
7374
7375 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7376 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7377 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7378 E->getInitializer()->getExprLoc());
7379
7380 return MaybeBindToTemporary(E);
7381 }
7382
7383 ExprResult
7384 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7385 SourceLocation RBraceLoc) {
7386 // Only produce each kind of designated initialization diagnostic once.
7387 SourceLocation FirstDesignator;
7388 bool DiagnosedArrayDesignator = false;
7389 bool DiagnosedNestedDesignator = false;
7390 bool DiagnosedMixedDesignator = false;
7391
7392 // Check that any designated initializers are syntactically valid in the
7393 // current language mode.
7394 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7395 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7396 if (FirstDesignator.isInvalid())
7397 FirstDesignator = DIE->getBeginLoc();
7398
7399 if (!getLangOpts().CPlusPlus)
7400 break;
7401
7402 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7403 DiagnosedNestedDesignator = true;
7404 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7405 << DIE->getDesignatorsSourceRange();
7406 }
7407
7408 for (auto &Desig : DIE->designators()) {
7409 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7410 DiagnosedArrayDesignator = true;
7411 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7412 << Desig.getSourceRange();
7413 }
7414 }
7415
7416 if (!DiagnosedMixedDesignator &&
7417 !isa<DesignatedInitExpr>(InitArgList[0])) {
7418 DiagnosedMixedDesignator = true;
7419 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7420 << DIE->getSourceRange();
7421 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7422 << InitArgList[0]->getSourceRange();
7423 }
7424 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7425 isa<DesignatedInitExpr>(InitArgList[0])) {
7426 DiagnosedMixedDesignator = true;
7427 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7428 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7429 << DIE->getSourceRange();
7430 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7431 << InitArgList[I]->getSourceRange();
7432 }
7433 }
7434
7435 if (FirstDesignator.isValid()) {
7436 // Only diagnose designated initiaization as a C++20 extension if we didn't
7437 // already diagnose use of (non-C++20) C99 designator syntax.
7438 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7439 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7440 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7441 ? diag::warn_cxx17_compat_designated_init
7442 : diag::ext_cxx_designated_init);
7443 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7444 Diag(FirstDesignator, diag::ext_designated_init);
7445 }
7446 }
7447
7448 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7449 }
7450
7451 ExprResult
7452 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7453 SourceLocation RBraceLoc) {
7454 // Semantic analysis for initializers is done by ActOnDeclarator() and
7455 // CheckInitializer() - it requires knowledge of the object being initialized.
7456
7457 // Immediately handle non-overload placeholders. Overloads can be
7458 // resolved contextually, but everything else here can't.
7459 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7460 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7461 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7462
7463 // Ignore failures; dropping the entire initializer list because
7464 // of one failure would be terrible for indexing/etc.
7465 if (result.isInvalid()) continue;
7466
7467 InitArgList[I] = result.get();
7468 }
7469 }
7470
7471 InitListExpr *E =
7472 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7473 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7474 return E;
7475 }
7476
7477 void Sema::maybeExtendBlockObject(ExprResult &E) {
7478 assert(E.get()->getType()->isBlockPointerType());
7479 assert(E.get()->isPRValue());
7480
7481 // Only do this in an r-value context.
7482 if (!getLangOpts().ObjCAutoRefCount) return;
7483
7484 E = ImplicitCastExpr::Create(
7485 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7486 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7487 Cleanup.setExprNeedsCleanups(true);
7488 }
7489
7490 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7491 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7492 // Also, callers should have filtered out the invalid cases with
7493 // pointers. Everything else should be possible.
7494
7495 QualType SrcTy = Src.get()->getType();
7496 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7497 return CK_NoOp;
7498
7499 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7500 case Type::STK_MemberPointer:
7501 llvm_unreachable("member pointer type in C");
7502
7503 case Type::STK_CPointer:
7504 case Type::STK_BlockPointer:
7505 case Type::STK_ObjCObjectPointer:
7506 switch (DestTy->getScalarTypeKind()) {
7507 case Type::STK_CPointer: {
7508 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7509 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7510 if (SrcAS != DestAS)
7511 return CK_AddressSpaceConversion;
7512 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7513 return CK_NoOp;
7514 return CK_BitCast;
7515 }
7516 case Type::STK_BlockPointer:
7517 return (SrcKind == Type::STK_BlockPointer
7518 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7519 case Type::STK_ObjCObjectPointer:
7520 if (SrcKind == Type::STK_ObjCObjectPointer)
7521 return CK_BitCast;
7522 if (SrcKind == Type::STK_CPointer)
7523 return CK_CPointerToObjCPointerCast;
7524 maybeExtendBlockObject(Src);
7525 return CK_BlockPointerToObjCPointerCast;
7526 case Type::STK_Bool:
7527 return CK_PointerToBoolean;
7528 case Type::STK_Integral:
7529 return CK_PointerToIntegral;
7530 case Type::STK_Floating:
7531 case Type::STK_FloatingComplex:
7532 case Type::STK_IntegralComplex:
7533 case Type::STK_MemberPointer:
7534 case Type::STK_FixedPoint:
7535 llvm_unreachable("illegal cast from pointer");
7536 }
7537 llvm_unreachable("Should have returned before this");
7538
7539 case Type::STK_FixedPoint:
7540 switch (DestTy->getScalarTypeKind()) {
7541 case Type::STK_FixedPoint:
7542 return CK_FixedPointCast;
7543 case Type::STK_Bool:
7544 return CK_FixedPointToBoolean;
7545 case Type::STK_Integral:
7546 return CK_FixedPointToIntegral;
7547 case Type::STK_Floating:
7548 return CK_FixedPointToFloating;
7549 case Type::STK_IntegralComplex:
7550 case Type::STK_FloatingComplex:
7551 Diag(Src.get()->getExprLoc(),
7552 diag::err_unimplemented_conversion_with_fixed_point_type)
7553 << DestTy;
7554 return CK_IntegralCast;
7555 case Type::STK_CPointer:
7556 case Type::STK_ObjCObjectPointer:
7557 case Type::STK_BlockPointer:
7558 case Type::STK_MemberPointer:
7559 llvm_unreachable("illegal cast to pointer type");
7560 }
7561 llvm_unreachable("Should have returned before this");
7562
7563 case Type::STK_Bool: // casting from bool is like casting from an integer
7564 case Type::STK_Integral:
7565 switch (DestTy->getScalarTypeKind()) {
7566 case Type::STK_CPointer:
7567 case Type::STK_ObjCObjectPointer:
7568 case Type::STK_BlockPointer:
7569 if (Src.get()->isNullPointerConstant(Context,
7570 Expr::NPC_ValueDependentIsNull))
7571 return CK_NullToPointer;
7572 return CK_IntegralToPointer;
7573 case Type::STK_Bool:
7574 return CK_IntegralToBoolean;
7575 case Type::STK_Integral:
7576 return CK_IntegralCast;
7577 case Type::STK_Floating:
7578 return CK_IntegralToFloating;
7579 case Type::STK_IntegralComplex:
7580 Src = ImpCastExprToType(Src.get(),
7581 DestTy->castAs<ComplexType>()->getElementType(),
7582 CK_IntegralCast);
7583 return CK_IntegralRealToComplex;
7584 case Type::STK_FloatingComplex:
7585 Src = ImpCastExprToType(Src.get(),
7586 DestTy->castAs<ComplexType>()->getElementType(),
7587 CK_IntegralToFloating);
7588 return CK_FloatingRealToComplex;
7589 case Type::STK_MemberPointer:
7590 llvm_unreachable("member pointer type in C");
7591 case Type::STK_FixedPoint:
7592 return CK_IntegralToFixedPoint;
7593 }
7594 llvm_unreachable("Should have returned before this");
7595
7596 case Type::STK_Floating:
7597 switch (DestTy->getScalarTypeKind()) {
7598 case Type::STK_Floating:
7599 return CK_FloatingCast;
7600 case Type::STK_Bool:
7601 return CK_FloatingToBoolean;
7602 case Type::STK_Integral:
7603 return CK_FloatingToIntegral;
7604 case Type::STK_FloatingComplex:
7605 Src = ImpCastExprToType(Src.get(),
7606 DestTy->castAs<ComplexType>()->getElementType(),
7607 CK_FloatingCast);
7608 return CK_FloatingRealToComplex;
7609 case Type::STK_IntegralComplex:
7610 Src = ImpCastExprToType(Src.get(),
7611 DestTy->castAs<ComplexType>()->getElementType(),
7612 CK_FloatingToIntegral);
7613 return CK_IntegralRealToComplex;
7614 case Type::STK_CPointer:
7615 case Type::STK_ObjCObjectPointer:
7616 case Type::STK_BlockPointer:
7617 llvm_unreachable("valid float->pointer cast?");
7618 case Type::STK_MemberPointer:
7619 llvm_unreachable("member pointer type in C");
7620 case Type::STK_FixedPoint:
7621 return CK_FloatingToFixedPoint;
7622 }
7623 llvm_unreachable("Should have returned before this");
7624
7625 case Type::STK_FloatingComplex:
7626 switch (DestTy->getScalarTypeKind()) {
7627 case Type::STK_FloatingComplex:
7628 return CK_FloatingComplexCast;
7629 case Type::STK_IntegralComplex:
7630 return CK_FloatingComplexToIntegralComplex;
7631 case Type::STK_Floating: {
7632 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7633 if (Context.hasSameType(ET, DestTy))
7634 return CK_FloatingComplexToReal;
7635 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7636 return CK_FloatingCast;
7637 }
7638 case Type::STK_Bool:
7639 return CK_FloatingComplexToBoolean;
7640 case Type::STK_Integral:
7641 Src = ImpCastExprToType(Src.get(),
7642 SrcTy->castAs<ComplexType>()->getElementType(),
7643 CK_FloatingComplexToReal);
7644 return CK_FloatingToIntegral;
7645 case Type::STK_CPointer:
7646 case Type::STK_ObjCObjectPointer:
7647 case Type::STK_BlockPointer:
7648 llvm_unreachable("valid complex float->pointer cast?");
7649 case Type::STK_MemberPointer:
7650 llvm_unreachable("member pointer type in C");
7651 case Type::STK_FixedPoint:
7652 Diag(Src.get()->getExprLoc(),
7653 diag::err_unimplemented_conversion_with_fixed_point_type)
7654 << SrcTy;
7655 return CK_IntegralCast;
7656 }
7657 llvm_unreachable("Should have returned before this");
7658
7659 case Type::STK_IntegralComplex:
7660 switch (DestTy->getScalarTypeKind()) {
7661 case Type::STK_FloatingComplex:
7662 return CK_IntegralComplexToFloatingComplex;
7663 case Type::STK_IntegralComplex:
7664 return CK_IntegralComplexCast;
7665 case Type::STK_Integral: {
7666 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7667 if (Context.hasSameType(ET, DestTy))
7668 return CK_IntegralComplexToReal;
7669 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7670 return CK_IntegralCast;
7671 }
7672 case Type::STK_Bool:
7673 return CK_IntegralComplexToBoolean;
7674 case Type::STK_Floating:
7675 Src = ImpCastExprToType(Src.get(),
7676 SrcTy->castAs<ComplexType>()->getElementType(),
7677 CK_IntegralComplexToReal);
7678 return CK_IntegralToFloating;
7679 case Type::STK_CPointer:
7680 case Type::STK_ObjCObjectPointer:
7681 case Type::STK_BlockPointer:
7682 llvm_unreachable("valid complex int->pointer cast?");
7683 case Type::STK_MemberPointer:
7684 llvm_unreachable("member pointer type in C");
7685 case Type::STK_FixedPoint:
7686 Diag(Src.get()->getExprLoc(),
7687 diag::err_unimplemented_conversion_with_fixed_point_type)
7688 << SrcTy;
7689 return CK_IntegralCast;
7690 }
7691 llvm_unreachable("Should have returned before this");
7692 }
7693
7694 llvm_unreachable("Unhandled scalar cast");
7695 }
7696
7697 static bool breakDownVectorType(QualType type, uint64_t &len,
7698 QualType &eltType) {
7699 // Vectors are simple.
7700 if (const VectorType *vecType = type->getAs<VectorType>()) {
7701 len = vecType->getNumElements();
7702 eltType = vecType->getElementType();
7703 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7704 return true;
7705 }
7706
7707 // We allow lax conversion to and from non-vector types, but only if
7708 // they're real types (i.e. non-complex, non-pointer scalar types).
7709 if (!type->isRealType()) return false;
7710
7711 len = 1;
7712 eltType = type;
7713 return true;
7714 }
7715
7716 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7717 assert(srcTy->isVectorType() || destTy->isVectorType());
7718
7719 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7720 if (!FirstType->isSVESizelessBuiltinType())
7721 return false;
7722
7723 const auto *VecTy = SecondType->getAs<VectorType>();
7724 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7725 };
7726
7727 return ValidScalableConversion(srcTy, destTy) ||
7728 ValidScalableConversion(destTy, srcTy);
7729 }
7730
7731 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7732 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7733 return false;
7734
7735 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7736 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7737
7738 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7739 matSrcType->getNumColumns() == matDestType->getNumColumns();
7740 }
7741
7742 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7743 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7744
7745 uint64_t SrcLen, DestLen;
7746 QualType SrcEltTy, DestEltTy;
7747 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7748 return false;
7749 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7750 return false;
7751
7752 // ASTContext::getTypeSize will return the size rounded up to a
7753 // power of 2, so instead of using that, we need to use the raw
7754 // element size multiplied by the element count.
7755 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7756 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7757
7758 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7759 }
7760
7761 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7762 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7763 "expected at least one type to be a vector here");
7764
7765 bool IsSrcTyAltivec =
7766 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7767 VectorKind::AltiVecVector) ||
7768 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7769 VectorKind::AltiVecBool) ||
7770 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7771 VectorKind::AltiVecPixel));
7772
7773 bool IsDestTyAltivec = DestTy->isVectorType() &&
7774 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7775 VectorKind::AltiVecVector) ||
7776 (DestTy->castAs<VectorType>()->getVectorKind() ==
7777 VectorKind::AltiVecBool) ||
7778 (DestTy->castAs<VectorType>()->getVectorKind() ==
7779 VectorKind::AltiVecPixel));
7780
7781 return (IsSrcTyAltivec || IsDestTyAltivec);
7782 }
7783
7784 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7785 assert(destTy->isVectorType() || srcTy->isVectorType());
7786
7787 // Disallow lax conversions between scalars and ExtVectors (these
7788 // conversions are allowed for other vector types because common headers
7789 // depend on them). Most scalar OP ExtVector cases are handled by the
7790 // splat path anyway, which does what we want (convert, not bitcast).
7791 // What this rules out for ExtVectors is crazy things like char4*float.
7792 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7793 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7794
7795 return areVectorTypesSameSize(srcTy, destTy);
7796 }
7797
7798 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7799 assert(destTy->isVectorType() || srcTy->isVectorType());
7800
7801 switch (Context.getLangOpts().getLaxVectorConversions()) {
7802 case LangOptions::LaxVectorConversionKind::None:
7803 return false;
7804
7805 case LangOptions::LaxVectorConversionKind::Integer:
7806 if (!srcTy->isIntegralOrEnumerationType()) {
7807 auto *Vec = srcTy->getAs<VectorType>();
7808 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7809 return false;
7810 }
7811 if (!destTy->isIntegralOrEnumerationType()) {
7812 auto *Vec = destTy->getAs<VectorType>();
7813 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7814 return false;
7815 }
7816 // OK, integer (vector) -> integer (vector) bitcast.
7817 break;
7818
7819 case LangOptions::LaxVectorConversionKind::All:
7820 break;
7821 }
7822
7823 return areLaxCompatibleVectorTypes(srcTy, destTy);
7824 }
7825
7826 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7827 CastKind &Kind) {
7828 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7829 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7830 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7831 << DestTy << SrcTy << R;
7832 }
7833 } else if (SrcTy->isMatrixType()) {
7834 return Diag(R.getBegin(),
7835 diag::err_invalid_conversion_between_matrix_and_type)
7836 << SrcTy << DestTy << R;
7837 } else if (DestTy->isMatrixType()) {
7838 return Diag(R.getBegin(),
7839 diag::err_invalid_conversion_between_matrix_and_type)
7840 << DestTy << SrcTy << R;
7841 }
7842
7843 Kind = CK_MatrixCast;
7844 return false;
7845 }
7846
7847 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7848 CastKind &Kind) {
7849 assert(VectorTy->isVectorType() && "Not a vector type!");
7850
7851 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7852 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7853 return Diag(R.getBegin(),
7854 Ty->isVectorType() ?
7855 diag::err_invalid_conversion_between_vectors :
7856 diag::err_invalid_conversion_between_vector_and_integer)
7857 << VectorTy << Ty << R;
7858 } else
7859 return Diag(R.getBegin(),
7860 diag::err_invalid_conversion_between_vector_and_scalar)
7861 << VectorTy << Ty << R;
7862
7863 Kind = CK_BitCast;
7864 return false;
7865 }
7866
7867 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7868 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7869
7870 if (DestElemTy == SplattedExpr->getType())
7871 return SplattedExpr;
7872
7873 assert(DestElemTy->isFloatingType() ||
7874 DestElemTy->isIntegralOrEnumerationType());
7875
7876 CastKind CK;
7877 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7878 // OpenCL requires that we convert `true` boolean expressions to -1, but
7879 // only when splatting vectors.
7880 if (DestElemTy->isFloatingType()) {
7881 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7882 // in two steps: boolean to signed integral, then to floating.
7883 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7884 CK_BooleanToSignedIntegral);
7885 SplattedExpr = CastExprRes.get();
7886 CK = CK_IntegralToFloating;
7887 } else {
7888 CK = CK_BooleanToSignedIntegral;
7889 }
7890 } else {
7891 ExprResult CastExprRes = SplattedExpr;
7892 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7893 if (CastExprRes.isInvalid())
7894 return ExprError();
7895 SplattedExpr = CastExprRes.get();
7896 }
7897 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7898 }
7899
7900 ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
7901 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
7902
7903 if (DestElemTy == SplattedExpr->getType())
7904 return SplattedExpr;
7905
7906 assert(DestElemTy->isFloatingType() ||
7907 DestElemTy->isIntegralOrEnumerationType());
7908
7909 // TODO: Add support for boolean matrix once exposed
7910 // https://github.com/llvm/llvm-project/issues/170920
7911 ExprResult CastExprRes = SplattedExpr;
7912 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
7913 if (CastExprRes.isInvalid())
7914 return ExprError();
7915 SplattedExpr = CastExprRes.get();
7916
7917 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7918 }
7919
7920 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7921 Expr *CastExpr, CastKind &Kind) {
7922 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7923
7924 QualType SrcTy = CastExpr->getType();
7925
7926 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7927 // an ExtVectorType.
7928 // In OpenCL, casts between vectors of different types are not allowed.
7929 // (See OpenCL 6.2).
7930 if (SrcTy->isVectorType()) {
7931 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7932 (getLangOpts().OpenCL &&
7933 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
7934 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
7935 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7936 << DestTy << SrcTy << R;
7937 return ExprError();
7938 }
7939 Kind = CK_BitCast;
7940 return CastExpr;
7941 }
7942
7943 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7944 // conversion will take place first from scalar to elt type, and then
7945 // splat from elt type to vector.
7946 if (SrcTy->isPointerType())
7947 return Diag(R.getBegin(),
7948 diag::err_invalid_conversion_between_vector_and_scalar)
7949 << DestTy << SrcTy << R;
7950
7951 Kind = CK_VectorSplat;
7952 return prepareVectorSplat(DestTy, CastExpr);
7953 }
7954
7955 /// Check that a call to alloc_size function specifies sufficient space for the
7956 /// destination type.
7957 static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7958 const Expr *E) {
7959 QualType SourceType = E->getType();
7960 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7961 DestType == SourceType)
7962 return;
7963
7964 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
7965 if (!CE)
7966 return;
7967
7968 // Find the total size allocated by the function call.
7969 if (!CE->getCalleeAllocSizeAttr())
7970 return;
7971 std::optional<llvm::APInt> AllocSize =
7972 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
7973 // Allocations of size zero are permitted as a special case. They are usually
7974 // done intentionally.
7975 if (!AllocSize || AllocSize->isZero())
7976 return;
7977 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
7978
7979 QualType TargetType = DestType->getPointeeType();
7980 // Find the destination size. As a special case function types have size of
7981 // one byte to match the sizeof operator behavior.
7982 auto LhsSize = TargetType->isFunctionType()
7983 ? CharUnits::One()
7984 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
7985 if (LhsSize && Size < LhsSize)
7986 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
7987 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7988 }
7989
7990 ExprResult
7991 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7992 Declarator &D, ParsedType &Ty,
7993 SourceLocation RParenLoc, Expr *CastExpr) {
7994 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7995 "ActOnCastExpr(): missing type or expr");
7996
7997 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7998 if (D.isInvalidType())
7999 return ExprError();
8000
8001 if (getLangOpts().CPlusPlus) {
8002 // Check that there are no default arguments (C++ only).
8003 CheckExtraCXXDefaultArguments(D);
8004 }
8005
8006 checkUnusedDeclAttributes(D);
8007
8008 QualType castType = castTInfo->getType();
8009 Ty = CreateParsedType(castType, castTInfo);
8010
8011 bool isVectorLiteral = false;
8012
8013 // Check for an altivec or OpenCL literal,
8014 // i.e. all the elements are integer constants.
8015 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8016 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8017 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8018 && castType->isVectorType() && (PE || PLE)) {
8019 if (PLE && PLE->getNumExprs() == 0) {
8020 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8021 return ExprError();
8022 }
8023 if (PE || PLE->getNumExprs() == 1) {
8024 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8025 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8026 isVectorLiteral = true;
8027 }
8028 else
8029 isVectorLiteral = true;
8030 }
8031
8032 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8033 // then handle it as such.
8034 if (isVectorLiteral)
8035 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8036
8037 // If the Expr being casted is a ParenListExpr, handle it specially.
8038 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8039 // sequence of BinOp comma operators.
8040 if (isa<ParenListExpr>(CastExpr)) {
8041 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8042 if (Result.isInvalid()) return ExprError();
8043 CastExpr = Result.get();
8044 }
8045
8046 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8047 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8048
8049 ObjC().CheckTollFreeBridgeCast(castType, CastExpr);
8050
8051 ObjC().CheckObjCBridgeRelatedCast(castType, CastExpr);
8052
8053 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8054
8055 CheckSufficientAllocSize(*this, castType, CastExpr);
8056
8057 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8058 }
8059
8060 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8061 SourceLocation RParenLoc, Expr *E,
8062 TypeSourceInfo *TInfo) {
8063 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8064 "Expected paren or paren list expression");
8065
8066 Expr **exprs;
8067 unsigned numExprs;
8068 Expr *subExpr;
8069 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8070 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8071 LiteralLParenLoc = PE->getLParenLoc();
8072 LiteralRParenLoc = PE->getRParenLoc();
8073 exprs = PE->getExprs();
8074 numExprs = PE->getNumExprs();
8075 } else { // isa<ParenExpr> by assertion at function entrance
8076 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8077 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8078 subExpr = cast<ParenExpr>(E)->getSubExpr();
8079 exprs = &subExpr;
8080 numExprs = 1;
8081 }
8082
8083 QualType Ty = TInfo->getType();
8084 assert(Ty->isVectorType() && "Expected vector type");
8085
8086 SmallVector<Expr *, 8> initExprs;
8087 const VectorType *VTy = Ty->castAs<VectorType>();
8088 unsigned numElems = VTy->getNumElements();
8089
8090 // '(...)' form of vector initialization in AltiVec: the number of
8091 // initializers must be one or must match the size of the vector.
8092 // If a single value is specified in the initializer then it will be
8093 // replicated to all the components of the vector
8094 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8095 VTy->getElementType()))
8096 return ExprError();
8097 if (ShouldSplatAltivecScalarInCast(VTy)) {
8098 // The number of initializers must be one or must match the size of the
8099 // vector. If a single value is specified in the initializer then it will
8100 // be replicated to all the components of the vector
8101 if (numExprs == 1) {
8102 QualType ElemTy = VTy->getElementType();
8103 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8104 if (Literal.isInvalid())
8105 return ExprError();
8106 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8107 PrepareScalarCast(Literal, ElemTy));
8108 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8109 }
8110 else if (numExprs < numElems) {
8111 Diag(E->getExprLoc(),
8112 diag::err_incorrect_number_of_vector_initializers);
8113 return ExprError();
8114 }
8115 else
8116 initExprs.append(exprs, exprs + numExprs);
8117 }
8118 else {
8119 // For OpenCL, when the number of initializers is a single value,
8120 // it will be replicated to all components of the vector.
8121 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8122 numExprs == 1) {
8123 QualType ElemTy = VTy->getElementType();
8124 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8125 if (Literal.isInvalid())
8126 return ExprError();
8127 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8128 PrepareScalarCast(Literal, ElemTy));
8129 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8130 }
8131
8132 initExprs.append(exprs, exprs + numExprs);
8133 }
8134 // FIXME: This means that pretty-printing the final AST will produce curly
8135 // braces instead of the original commas.
8136 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8137 initExprs, LiteralRParenLoc);
8138 initE->setType(Ty);
8139 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8140 }
8141
8142 ExprResult
8143 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8144 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8145 if (!E)
8146 return OrigExpr;
8147
8148 ExprResult Result(E->getExpr(0));
8149
8150 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8151 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8152 E->getExpr(i));
8153
8154 if (Result.isInvalid()) return ExprError();
8155
8156 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8157 }
8158
8159 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8160 SourceLocation R,
8161 MultiExprArg Val) {
8162 return ParenListExpr::Create(Context, L, Val, R);
8163 }
8164
8165 ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8166 unsigned NumUserSpecifiedExprs,
8167 SourceLocation InitLoc,
8168 SourceLocation LParenLoc,
8169 SourceLocation RParenLoc) {
8170 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8171 InitLoc, LParenLoc, RParenLoc);
8172 }
8173
8174 bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8175 SourceLocation QuestionLoc) {
8176 const Expr *NullExpr = LHSExpr;
8177 const Expr *NonPointerExpr = RHSExpr;
8178 Expr::NullPointerConstantKind NullKind =
8179 NullExpr->isNullPointerConstant(Context,
8180 Expr::NPC_ValueDependentIsNotNull);
8181
8182 if (NullKind == Expr::NPCK_NotNull) {
8183 NullExpr = RHSExpr;
8184 NonPointerExpr = LHSExpr;
8185 NullKind =
8186 NullExpr->isNullPointerConstant(Context,
8187 Expr::NPC_ValueDependentIsNotNull);
8188 }
8189
8190 if (NullKind == Expr::NPCK_NotNull)
8191 return false;
8192
8193 if (NullKind == Expr::NPCK_ZeroExpression)
8194 return false;
8195
8196 if (NullKind == Expr::NPCK_ZeroLiteral) {
8197 // In this case, check to make sure that we got here from a "NULL"
8198 // string in the source code.
8199 NullExpr = NullExpr->IgnoreParenImpCasts();
8200 SourceLocation loc = NullExpr->getExprLoc();
8201 if (!findMacroSpelling(loc, "NULL"))
8202 return false;
8203 }
8204
8205 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8206 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8207 << NonPointerExpr->getType() << DiagType
8208 << NonPointerExpr->getSourceRange();
8209 return true;
8210 }
8211
8212 /// Return false if the condition expression is valid, true otherwise.
8213 static bool checkCondition(Sema &S, const Expr *Cond,
8214 SourceLocation QuestionLoc) {
8215 QualType CondTy = Cond->getType();
8216
8217 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8218 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8219 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8220 << CondTy << Cond->getSourceRange();
8221 return true;
8222 }
8223
8224 // C99 6.5.15p2
8225 if (CondTy->isScalarType()) return false;
8226
8227 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8228 << CondTy << Cond->getSourceRange();
8229 return true;
8230 }
8231
8232 /// Return false if the NullExpr can be promoted to PointerTy,
8233 /// true otherwise.
8234 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8235 QualType PointerTy) {
8236 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8237 !NullExpr.get()->isNullPointerConstant(S.Context,
8238 Expr::NPC_ValueDependentIsNull))
8239 return true;
8240
8241 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8242 return false;
8243 }
8244
8245 /// Checks compatibility between two pointers and return the resulting
8246 /// type.
8247 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8248 ExprResult &RHS,
8249 SourceLocation Loc) {
8250 QualType LHSTy = LHS.get()->getType();
8251 QualType RHSTy = RHS.get()->getType();
8252
8253 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8254 // Two identical pointers types are always compatible.
8255 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8256 }
8257
8258 QualType lhptee, rhptee;
8259
8260 // Get the pointee types.
8261 bool IsBlockPointer = false;
8262 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8263 lhptee = LHSBTy->getPointeeType();
8264 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8265 IsBlockPointer = true;
8266 } else {
8267 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8268 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8269 }
8270
8271 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8272 // differently qualified versions of compatible types, the result type is
8273 // a pointer to an appropriately qualified version of the composite
8274 // type.
8275
8276 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8277 // clause doesn't make sense for our extensions. E.g. address space 2 should
8278 // be incompatible with address space 3: they may live on different devices or
8279 // anything.
8280 Qualifiers lhQual = lhptee.getQualifiers();
8281 Qualifiers rhQual = rhptee.getQualifiers();
8282
8283 LangAS ResultAddrSpace = LangAS::Default;
8284 LangAS LAddrSpace = lhQual.getAddressSpace();
8285 LangAS RAddrSpace = rhQual.getAddressSpace();
8286
8287 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8288 // spaces is disallowed.
8289 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8290 ResultAddrSpace = LAddrSpace;
8291 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8292 ResultAddrSpace = RAddrSpace;
8293 else {
8294 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8295 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8296 << RHS.get()->getSourceRange();
8297 return QualType();
8298 }
8299
8300 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8301 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8302 lhQual.removeCVRQualifiers();
8303 rhQual.removeCVRQualifiers();
8304
8305 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8306 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8307 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8308 << RHS.get()->getSourceRange();
8309 return QualType();
8310 }
8311
8312 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8313 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8314 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8315 // qual types are compatible iff
8316 // * corresponded types are compatible
8317 // * CVR qualifiers are equal
8318 // * address spaces are equal
8319 // Thus for conditional operator we merge CVR and address space unqualified
8320 // pointees and if there is a composite type we return a pointer to it with
8321 // merged qualifiers.
8322 LHSCastKind =
8323 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8324 RHSCastKind =
8325 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8326 lhQual.removeAddressSpace();
8327 rhQual.removeAddressSpace();
8328
8329 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8330 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8331
8332 QualType CompositeTy = S.Context.mergeTypes(
8333 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8334 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8335
8336 if (CompositeTy.isNull()) {
8337 // In this situation, we assume void* type. No especially good
8338 // reason, but this is what gcc does, and we do have to pick
8339 // to get a consistent AST.
8340 QualType incompatTy;
8341 incompatTy = S.Context.getPointerType(
8342 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8343 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8344 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8345
8346 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8347 // for casts between types with incompatible address space qualifiers.
8348 // For the following code the compiler produces casts between global and
8349 // local address spaces of the corresponded innermost pointees:
8350 // local int *global *a;
8351 // global int *global *b;
8352 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8353 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8354 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8355 << RHS.get()->getSourceRange();
8356
8357 return incompatTy;
8358 }
8359
8360 // The pointer types are compatible.
8361 // In case of OpenCL ResultTy should have the address space qualifier
8362 // which is a superset of address spaces of both the 2nd and the 3rd
8363 // operands of the conditional operator.
8364 QualType ResultTy = [&, ResultAddrSpace]() {
8365 if (S.getLangOpts().OpenCL) {
8366 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8367 CompositeQuals.setAddressSpace(ResultAddrSpace);
8368 return S.Context
8369 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8370 .withCVRQualifiers(MergedCVRQual);
8371 }
8372 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8373 }();
8374 if (IsBlockPointer)
8375 ResultTy = S.Context.getBlockPointerType(ResultTy);
8376 else
8377 ResultTy = S.Context.getPointerType(ResultTy);
8378
8379 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8380 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8381 return ResultTy;
8382 }
8383
8384 /// Return the resulting type when the operands are both block pointers.
8385 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8386 ExprResult &LHS,
8387 ExprResult &RHS,
8388 SourceLocation Loc) {
8389 QualType LHSTy = LHS.get()->getType();
8390 QualType RHSTy = RHS.get()->getType();
8391
8392 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8393 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8394 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8395 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8396 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8397 return destType;
8398 }
8399 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8400 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8401 << RHS.get()->getSourceRange();
8402 return QualType();
8403 }
8404
8405 // We have 2 block pointer types.
8406 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8407 }
8408
8409 /// Return the resulting type when the operands are both pointers.
8410 static QualType
8411 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8412 ExprResult &RHS,
8413 SourceLocation Loc) {
8414 // get the pointer types
8415 QualType LHSTy = LHS.get()->getType();
8416 QualType RHSTy = RHS.get()->getType();
8417
8418 // get the "pointed to" types
8419 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8420 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8421
8422 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8423 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8424 // Figure out necessary qualifiers (C99 6.5.15p6)
8425 QualType destPointee
8426 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8427 QualType destType = S.Context.getPointerType(destPointee);
8428 // Add qualifiers if necessary.
8429 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8430 // Promote to void*.
8431 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8432 return destType;
8433 }
8434 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8435 QualType destPointee
8436 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8437 QualType destType = S.Context.getPointerType(destPointee);
8438 // Add qualifiers if necessary.
8439 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8440 // Promote to void*.
8441 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8442 return destType;
8443 }
8444
8445 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8446 }
8447
8448 /// Return false if the first expression is not an integer and the second
8449 /// expression is not a pointer, true otherwise.
8450 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8451 Expr* PointerExpr, SourceLocation Loc,
8452 bool IsIntFirstExpr) {
8453 if (!PointerExpr->getType()->isPointerType() ||
8454 !Int.get()->getType()->isIntegerType())
8455 return false;
8456
8457 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8458 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8459
8460 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8461 << Expr1->getType() << Expr2->getType()
8462 << Expr1->getSourceRange() << Expr2->getSourceRange();
8463 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8464 CK_IntegralToPointer);
8465 return true;
8466 }
8467
8468 /// Simple conversion between integer and floating point types.
8469 ///
8470 /// Used when handling the OpenCL conditional operator where the
8471 /// condition is a vector while the other operands are scalar.
8472 ///
8473 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8474 /// types are either integer or floating type. Between the two
8475 /// operands, the type with the higher rank is defined as the "result
8476 /// type". The other operand needs to be promoted to the same type. No
8477 /// other type promotion is allowed. We cannot use
8478 /// UsualArithmeticConversions() for this purpose, since it always
8479 /// promotes promotable types.
8480 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8481 ExprResult &RHS,
8482 SourceLocation QuestionLoc) {
8483 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8484 if (LHS.isInvalid())
8485 return QualType();
8486 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8487 if (RHS.isInvalid())
8488 return QualType();
8489
8490 // For conversion purposes, we ignore any qualifiers.
8491 // For example, "const float" and "float" are equivalent.
8492 QualType LHSType =
8493 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8494 QualType RHSType =
8495 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8496
8497 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8498 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8499 << LHSType << LHS.get()->getSourceRange();
8500 return QualType();
8501 }
8502
8503 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8504 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8505 << RHSType << RHS.get()->getSourceRange();
8506 return QualType();
8507 }
8508
8509 // If both types are identical, no conversion is needed.
8510 if (LHSType == RHSType)
8511 return LHSType;
8512
8513 // Now handle "real" floating types (i.e. float, double, long double).
8514 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8515 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8516 /*IsCompAssign = */ false);
8517
8518 // Finally, we have two differing integer types.
8519 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8520 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8521 }
8522
8523 /// Convert scalar operands to a vector that matches the
8524 /// condition in length.
8525 ///
8526 /// Used when handling the OpenCL conditional operator where the
8527 /// condition is a vector while the other operands are scalar.
8528 ///
8529 /// We first compute the "result type" for the scalar operands
8530 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8531 /// into a vector of that type where the length matches the condition
8532 /// vector type. s6.11.6 requires that the element types of the result
8533 /// and the condition must have the same number of bits.
8534 static QualType
8535 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8536 QualType CondTy, SourceLocation QuestionLoc) {
8537 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8538 if (ResTy.isNull()) return QualType();
8539
8540 const VectorType *CV = CondTy->getAs<VectorType>();
8541 assert(CV);
8542
8543 // Determine the vector result type
8544 unsigned NumElements = CV->getNumElements();
8545 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8546
8547 // Ensure that all types have the same number of bits
8548 if (S.Context.getTypeSize(CV->getElementType())
8549 != S.Context.getTypeSize(ResTy)) {
8550 // Since VectorTy is created internally, it does not pretty print
8551 // with an OpenCL name. Instead, we just print a description.
8552 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8553 SmallString<64> Str;
8554 llvm::raw_svector_ostream OS(Str);
8555 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8556 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8557 << CondTy << OS.str();
8558 return QualType();
8559 }
8560
8561 // Convert operands to the vector result type
8562 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8563 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8564
8565 return VectorTy;
8566 }
8567
8568 /// Return false if this is a valid OpenCL condition vector
8569 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8570 SourceLocation QuestionLoc) {
8571 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8572 // integral type.
8573 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8574 assert(CondTy);
8575 QualType EleTy = CondTy->getElementType();
8576 if (EleTy->isIntegerType()) return false;
8577
8578 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8579 << Cond->getType() << Cond->getSourceRange();
8580 return true;
8581 }
8582
8583 /// Return false if the vector condition type and the vector
8584 /// result type are compatible.
8585 ///
8586 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8587 /// number of elements, and their element types have the same number
8588 /// of bits.
8589 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8590 SourceLocation QuestionLoc) {
8591 const VectorType *CV = CondTy->getAs<VectorType>();
8592 const VectorType *RV = VecResTy->getAs<VectorType>();
8593 assert(CV && RV);
8594
8595 if (CV->getNumElements() != RV->getNumElements()) {
8596 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8597 << CondTy << VecResTy;
8598 return true;
8599 }
8600
8601 QualType CVE = CV->getElementType();
8602 QualType RVE = RV->getElementType();
8603
8604 // Boolean vectors are permitted outside of OpenCL mode.
8605 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8606 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8607 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8608 << CondTy << VecResTy;
8609 return true;
8610 }
8611
8612 return false;
8613 }
8614
8615 /// Return the resulting type for the conditional operator in
8616 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8617 /// s6.3.i) when the condition is a vector type.
8618 static QualType
8619 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8620 ExprResult &LHS, ExprResult &RHS,
8621 SourceLocation QuestionLoc) {
8622 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8623 if (Cond.isInvalid())
8624 return QualType();
8625 QualType CondTy = Cond.get()->getType();
8626
8627 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8628 return QualType();
8629
8630 // If either operand is a vector then find the vector type of the
8631 // result as specified in OpenCL v1.1 s6.3.i.
8632 if (LHS.get()->getType()->isVectorType() ||
8633 RHS.get()->getType()->isVectorType()) {
8634 bool IsBoolVecLang =
8635 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8636 QualType VecResTy =
8637 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8638 /*isCompAssign*/ false,
8639 /*AllowBothBool*/ true,
8640 /*AllowBoolConversions*/ false,
8641 /*AllowBooleanOperation*/ IsBoolVecLang,
8642 /*ReportInvalid*/ true);
8643 if (VecResTy.isNull())
8644 return QualType();
8645 // The result type must match the condition type as specified in
8646 // OpenCL v1.1 s6.11.6.
8647 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8648 return QualType();
8649 return VecResTy;
8650 }
8651
8652 // Both operands are scalar.
8653 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8654 }
8655
8656 /// Return true if the Expr is block type
8657 static bool checkBlockType(Sema &S, const Expr *E) {
8658 if (E->getType()->isBlockPointerType()) {
8659 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8660 return true;
8661 }
8662
8663 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8664 QualType Ty = CE->getCallee()->getType();
8665 if (Ty->isBlockPointerType()) {
8666 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8667 return true;
8668 }
8669 }
8670 return false;
8671 }
8672
8673 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8674 /// In that case, LHS = cond.
8675 /// C99 6.5.15
8676 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8677 ExprResult &RHS, ExprValueKind &VK,
8678 ExprObjectKind &OK,
8679 SourceLocation QuestionLoc) {
8680
8681 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8682 if (!LHSResult.isUsable()) return QualType();
8683 LHS = LHSResult;
8684
8685 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8686 if (!RHSResult.isUsable()) return QualType();
8687 RHS = RHSResult;
8688
8689 // C++ is sufficiently different to merit its own checker.
8690 if (getLangOpts().CPlusPlus)
8691 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8692
8693 VK = VK_PRValue;
8694 OK = OK_Ordinary;
8695
8696 if (Context.isDependenceAllowed() &&
8697 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8698 RHS.get()->isTypeDependent())) {
8699 assert(!getLangOpts().CPlusPlus);
8700 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8701 RHS.get()->containsErrors()) &&
8702 "should only occur in error-recovery path.");
8703 return Context.DependentTy;
8704 }
8705
8706 // The OpenCL operator with a vector condition is sufficiently
8707 // different to merit its own checker.
8708 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8709 Cond.get()->getType()->isExtVectorType())
8710 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8711
8712 // First, check the condition.
8713 Cond = UsualUnaryConversions(Cond.get());
8714 if (Cond.isInvalid())
8715 return QualType();
8716 if (checkCondition(*this, Cond.get(), QuestionLoc))
8717 return QualType();
8718
8719 // Handle vectors.
8720 if (LHS.get()->getType()->isVectorType() ||
8721 RHS.get()->getType()->isVectorType())
8722 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8723 /*AllowBothBool*/ true,
8724 /*AllowBoolConversions*/ false,
8725 /*AllowBooleanOperation*/ false,
8726 /*ReportInvalid*/ true);
8727
8728 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8729 ArithConvKind::Conditional);
8730 if (LHS.isInvalid() || RHS.isInvalid())
8731 return QualType();
8732
8733 // WebAssembly tables are not allowed as conditional LHS or RHS.
8734 QualType LHSTy = LHS.get()->getType();
8735 QualType RHSTy = RHS.get()->getType();
8736 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8737 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8739 return QualType();
8740 }
8741
8742 // Diagnose attempts to convert between __ibm128, __float128 and long double
8743 // where such conversions currently can't be handled.
8744 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8745 Diag(QuestionLoc,
8746 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8748 return QualType();
8749 }
8750
8751 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8752 // selection operator (?:).
8753 if (getLangOpts().OpenCL &&
8754 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8755 return QualType();
8756 }
8757
8758 // If both operands have arithmetic type, do the usual arithmetic conversions
8759 // to find a common type: C99 6.5.15p3,5.
8760 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8761 // Disallow invalid arithmetic conversions, such as those between bit-
8762 // precise integers types of different sizes, or between a bit-precise
8763 // integer and another type.
8764 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8765 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8766 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8767 << RHS.get()->getSourceRange();
8768 return QualType();
8769 }
8770
8771 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8772 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8773
8774 return ResTy;
8775 }
8776
8777 // If both operands are the same structure or union type, the result is that
8778 // type.
8779 // FIXME: Type of conditional expression must be complete in C mode.
8780 if (LHSTy->isRecordType() &&
8781 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8782 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8783 RHSTy.getUnqualifiedType());
8784
8785 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8786 // The following || allows only one side to be void (a GCC-ism).
8787 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8788 QualType ResTy;
8789 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8790 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8791 } else if (RHSTy->isVoidType()) {
8792 ResTy = RHSTy;
8793 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8794 << RHS.get()->getSourceRange();
8795 } else {
8796 ResTy = LHSTy;
8797 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8798 << LHS.get()->getSourceRange();
8799 }
8800 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8801 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8802 return ResTy;
8803 }
8804
8805 // C23 6.5.15p7:
8806 // ... if both the second and third operands have nullptr_t type, the
8807 // result also has that type.
8808 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8809 return ResTy;
8810
8811 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8812 // the type of the other operand."
8813 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8814 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8815
8816 // All objective-c pointer type analysis is done here.
8817 QualType compositeType =
8818 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8819 if (LHS.isInvalid() || RHS.isInvalid())
8820 return QualType();
8821 if (!compositeType.isNull())
8822 return compositeType;
8823
8824
8825 // Handle block pointer types.
8826 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8827 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8828 QuestionLoc);
8829
8830 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8831 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8832 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8833 QuestionLoc);
8834
8835 // GCC compatibility: soften pointer/integer mismatch. Note that
8836 // null pointers have been filtered out by this point.
8837 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8838 /*IsIntFirstExpr=*/true))
8839 return RHSTy;
8840 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8841 /*IsIntFirstExpr=*/false))
8842 return LHSTy;
8843
8844 // Emit a better diagnostic if one of the expressions is a null pointer
8845 // constant and the other is not a pointer type. In this case, the user most
8846 // likely forgot to take the address of the other expression.
8847 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8848 return QualType();
8849
8850 // Finally, if the LHS and RHS types are canonically the same type, we can
8851 // use the common sugared type.
8852 if (Context.hasSameType(LHSTy, RHSTy))
8853 return Context.getCommonSugaredType(LHSTy, RHSTy);
8854
8855 // Otherwise, the operands are not compatible.
8856 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8857 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8858 << RHS.get()->getSourceRange();
8859 return QualType();
8860 }
8861
8862 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8863 /// ParenRange in parentheses.
8864 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8865 const PartialDiagnostic &Note,
8866 SourceRange ParenRange) {
8867 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8868 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8869 EndLoc.isValid()) {
8870 Self.Diag(Loc, Note)
8871 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8872 << FixItHint::CreateInsertion(EndLoc, ")");
8873 } else {
8874 // We can't display the parentheses, so just show the bare note.
8875 Self.Diag(Loc, Note) << ParenRange;
8876 }
8877 }
8878
8879 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8880 return BinaryOperator::isAdditiveOp(Opc) ||
8881 BinaryOperator::isMultiplicativeOp(Opc) ||
8882 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8883 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8884 // not any of the logical operators. Bitwise-xor is commonly used as a
8885 // logical-xor because there is no logical-xor operator. The logical
8886 // operators, including uses of xor, have a high false positive rate for
8887 // precedence warnings.
8888 }
8889
8890 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8891 /// expression, either using a built-in or overloaded operator,
8892 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8893 /// expression.
8894 static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8895 const Expr **RHSExprs) {
8896 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8897 E = E->IgnoreImpCasts();
8898 E = E->IgnoreConversionOperatorSingleStep();
8899 E = E->IgnoreImpCasts();
8900 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8901 E = MTE->getSubExpr();
8902 E = E->IgnoreImpCasts();
8903 }
8904
8905 // Built-in binary operator.
8906 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8907 OP && IsArithmeticOp(OP->getOpcode())) {
8908 *Opcode = OP->getOpcode();
8909 *RHSExprs = OP->getRHS();
8910 return true;
8911 }
8912
8913 // Overloaded operator.
8914 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8915 if (Call->getNumArgs() != 2)
8916 return false;
8917
8918 // Make sure this is really a binary operator that is safe to pass into
8919 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8920 OverloadedOperatorKind OO = Call->getOperator();
8921 if (OO < OO_Plus || OO > OO_Arrow ||
8922 OO == OO_PlusPlus || OO == OO_MinusMinus)
8923 return false;
8924
8925 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8926 if (IsArithmeticOp(OpKind)) {
8927 *Opcode = OpKind;
8928 *RHSExprs = Call->getArg(1);
8929 return true;
8930 }
8931 }
8932
8933 return false;
8934 }
8935
8936 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8937 /// or is a logical expression such as (x==y) which has int type, but is
8938 /// commonly interpreted as boolean.
8939 static bool ExprLooksBoolean(const Expr *E) {
8940 E = E->IgnoreParenImpCasts();
8941
8942 if (E->getType()->isBooleanType())
8943 return true;
8944 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8945 return OP->isComparisonOp() || OP->isLogicalOp();
8946 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8947 return OP->getOpcode() == UO_LNot;
8948 if (E->getType()->isPointerType())
8949 return true;
8950 // FIXME: What about overloaded operator calls returning "unspecified boolean
8951 // type"s (commonly pointer-to-members)?
8952
8953 return false;
8954 }
8955
8956 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8957 /// and binary operator are mixed in a way that suggests the programmer assumed
8958 /// the conditional operator has higher precedence, for example:
8959 /// "int x = a + someBinaryCondition ? 1 : 2".
8960 static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
8961 Expr *Condition, const Expr *LHSExpr,
8962 const Expr *RHSExpr) {
8963 BinaryOperatorKind CondOpcode;
8964 const Expr *CondRHS;
8965
8966 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8967 return;
8968 if (!ExprLooksBoolean(CondRHS))
8969 return;
8970
8971 // The condition is an arithmetic binary expression, with a right-
8972 // hand side that looks boolean, so warn.
8973
8974 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8975 ? diag::warn_precedence_bitwise_conditional
8976 : diag::warn_precedence_conditional;
8977
8978 Self.Diag(OpLoc, DiagID)
8979 << Condition->getSourceRange()
8980 << BinaryOperator::getOpcodeStr(CondOpcode);
8981
8982 SuggestParentheses(
8983 Self, OpLoc,
8984 Self.PDiag(diag::note_precedence_silence)
8985 << BinaryOperator::getOpcodeStr(CondOpcode),
8986 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8987
8988 SuggestParentheses(Self, OpLoc,
8989 Self.PDiag(diag::note_precedence_conditional_first),
8990 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8991 }
8992
8993 /// Compute the nullability of a conditional expression.
8994 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8995 QualType LHSTy, QualType RHSTy,
8996 ASTContext &Ctx) {
8997 if (!ResTy->isAnyPointerType())
8998 return ResTy;
8999
9000 auto GetNullability = [](QualType Ty) {
9001 std::optional<NullabilityKind> Kind = Ty->getNullability();
9002 if (Kind) {
9003 // For our purposes, treat _Nullable_result as _Nullable.
9004 if (*Kind == NullabilityKind::NullableResult)
9005 return NullabilityKind::Nullable;
9006 return *Kind;
9007 }
9008 return NullabilityKind::Unspecified;
9009 };
9010
9011 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9012 NullabilityKind MergedKind;
9013
9014 // Compute nullability of a binary conditional expression.
9015 if (IsBin) {
9016 if (LHSKind == NullabilityKind::NonNull)
9017 MergedKind = NullabilityKind::NonNull;
9018 else
9019 MergedKind = RHSKind;
9020 // Compute nullability of a normal conditional expression.
9021 } else {
9022 if (LHSKind == NullabilityKind::Nullable ||
9023 RHSKind == NullabilityKind::Nullable)
9024 MergedKind = NullabilityKind::Nullable;
9025 else if (LHSKind == NullabilityKind::NonNull)
9026 MergedKind = RHSKind;
9027 else if (RHSKind == NullabilityKind::NonNull)
9028 MergedKind = LHSKind;
9029 else
9030 MergedKind = NullabilityKind::Unspecified;
9031 }
9032
9033 // Return if ResTy already has the correct nullability.
9034 if (GetNullability(ResTy) == MergedKind)
9035 return ResTy;
9036
9037 // Strip all nullability from ResTy.
9038 while (ResTy->getNullability())
9039 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9040
9041 // Create a new AttributedType with the new nullability kind.
9042 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9043 }
9044
9045 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9046 SourceLocation ColonLoc,
9047 Expr *CondExpr, Expr *LHSExpr,
9048 Expr *RHSExpr) {
9049 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9050 // was the condition.
9051 OpaqueValueExpr *opaqueValue = nullptr;
9052 Expr *commonExpr = nullptr;
9053 if (!LHSExpr) {
9054 commonExpr = CondExpr;
9055 // Lower out placeholder types first. This is important so that we don't
9056 // try to capture a placeholder. This happens in few cases in C++; such
9057 // as Objective-C++'s dictionary subscripting syntax.
9058 if (commonExpr->hasPlaceholderType()) {
9059 ExprResult result = CheckPlaceholderExpr(commonExpr);
9060 if (!result.isUsable()) return ExprError();
9061 commonExpr = result.get();
9062 }
9063 // We usually want to apply unary conversions *before* saving, except
9064 // in the special case of a C++ l-value conditional.
9065 if (!(getLangOpts().CPlusPlus
9066 && !commonExpr->isTypeDependent()
9067 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9068 && commonExpr->isGLValue()
9069 && commonExpr->isOrdinaryOrBitFieldObject()
9070 && RHSExpr->isOrdinaryOrBitFieldObject()
9071 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9072 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9073 if (commonRes.isInvalid())
9074 return ExprError();
9075 commonExpr = commonRes.get();
9076 }
9077
9078 // If the common expression is a class or array prvalue, materialize it
9079 // so that we can safely refer to it multiple times.
9080 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9081 commonExpr->getType()->isArrayType())) {
9082 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9083 if (MatExpr.isInvalid())
9084 return ExprError();
9085 commonExpr = MatExpr.get();
9086 }
9087
9088 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9089 commonExpr->getType(),
9090 commonExpr->getValueKind(),
9091 commonExpr->getObjectKind(),
9092 commonExpr);
9093 LHSExpr = CondExpr = opaqueValue;
9094 }
9095
9096 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9097 ExprValueKind VK = VK_PRValue;
9098 ExprObjectKind OK = OK_Ordinary;
9099 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9100 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9101 VK, OK, QuestionLoc);
9102 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9103 RHS.isInvalid())
9104 return ExprError();
9105
9106 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9107 RHS.get());
9108
9109 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9110
9111 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9112 Context);
9113
9114 if (!commonExpr)
9115 return new (Context)
9116 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9117 RHS.get(), result, VK, OK);
9118
9119 return new (Context) BinaryConditionalOperator(
9120 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9121 ColonLoc, result, VK, OK);
9122 }
9123
9124 bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9125 unsigned FromAttributes = 0, ToAttributes = 0;
9126 if (const auto *FromFn =
9127 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9128 FromAttributes =
9129 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9130 if (const auto *ToFn =
9131 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9132 ToAttributes =
9133 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9134
9135 return FromAttributes != ToAttributes;
9136 }
9137
9138 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9139 // being closely modeled after the C99 spec:-). The odd characteristic of this
9140 // routine is it effectively iqnores the qualifiers on the top level pointee.
9141 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9142 // FIXME: add a couple examples in this comment.
9143 static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9144 QualType LHSType,
9145 QualType RHSType,
9146 SourceLocation Loc) {
9147 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9148 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9149
9150 // get the "pointed to" type (ignoring qualifiers at the top level)
9151 const Type *lhptee, *rhptee;
9152 Qualifiers lhq, rhq;
9153 std::tie(lhptee, lhq) =
9154 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9155 std::tie(rhptee, rhq) =
9156 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9157
9158 AssignConvertType ConvTy = AssignConvertType::Compatible;
9159
9160 // C99 6.5.16.1p1: This following citation is common to constraints
9161 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9162 // qualifiers of the type *pointed to* by the right;
9163
9164 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9165 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9166 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9167 // Ignore lifetime for further calculation.
9168 lhq.removeObjCLifetime();
9169 rhq.removeObjCLifetime();
9170 }
9171
9172 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9173 // Treat address-space mismatches as fatal.
9174 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9175 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9176
9177 // It's okay to add or remove GC or lifetime qualifiers when converting to
9178 // and from void*.
9179 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9180 rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9181 S.getASTContext()) &&
9182 (lhptee->isVoidType() || rhptee->isVoidType()))
9183 ; // keep old
9184
9185 // Treat lifetime mismatches as fatal.
9186 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9187 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9188
9189 // Treat pointer-auth mismatches as fatal.
9190 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9191 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9192
9193 // For GCC/MS compatibility, other qualifier mismatches are treated
9194 // as still compatible in C.
9195 else
9196 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9197 }
9198
9199 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9200 // incomplete type and the other is a pointer to a qualified or unqualified
9201 // version of void...
9202 if (lhptee->isVoidType()) {
9203 if (rhptee->isIncompleteOrObjectType())
9204 return ConvTy;
9205
9206 // As an extension, we allow cast to/from void* to function pointer.
9207 assert(rhptee->isFunctionType());
9208 return AssignConvertType::FunctionVoidPointer;
9209 }
9210
9211 if (rhptee->isVoidType()) {
9212 // In C, void * to another pointer type is compatible, but we want to note
9213 // that there will be an implicit conversion happening here.
9214 if (lhptee->isIncompleteOrObjectType())
9215 return ConvTy == AssignConvertType::Compatible &&
9216 !S.getLangOpts().CPlusPlus
9217 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9218 : ConvTy;
9219
9220 // As an extension, we allow cast to/from void* to function pointer.
9221 assert(lhptee->isFunctionType());
9222 return AssignConvertType::FunctionVoidPointer;
9223 }
9224
9225 if (!S.Diags.isIgnored(
9226 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9227 Loc) &&
9228 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9229 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9230 return AssignConvertType::IncompatibleFunctionPointerStrict;
9231
9232 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9233 // unqualified versions of compatible types, ...
9234 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9235 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9236 // Check if the pointee types are compatible ignoring the sign.
9237 // We explicitly check for char so that we catch "char" vs
9238 // "unsigned char" on systems where "char" is unsigned.
9239 if (lhptee->isCharType())
9240 ltrans = S.Context.UnsignedCharTy;
9241 else if (lhptee->hasSignedIntegerRepresentation())
9242 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9243
9244 if (rhptee->isCharType())
9245 rtrans = S.Context.UnsignedCharTy;
9246 else if (rhptee->hasSignedIntegerRepresentation())
9247 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9248
9249 if (ltrans == rtrans) {
9250 // Types are compatible ignoring the sign. Qualifier incompatibility
9251 // takes priority over sign incompatibility because the sign
9252 // warning can be disabled.
9253 if (!S.IsAssignConvertCompatible(ConvTy))
9254 return ConvTy;
9255
9256 return AssignConvertType::IncompatiblePointerSign;
9257 }
9258
9259 // If we are a multi-level pointer, it's possible that our issue is simply
9260 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9261 // the eventual target type is the same and the pointers have the same
9262 // level of indirection, this must be the issue.
9263 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9264 do {
9265 std::tie(lhptee, lhq) =
9266 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9267 std::tie(rhptee, rhq) =
9268 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9269
9270 // Inconsistent address spaces at this point is invalid, even if the
9271 // address spaces would be compatible.
9272 // FIXME: This doesn't catch address space mismatches for pointers of
9273 // different nesting levels, like:
9274 // __local int *** a;
9275 // int ** b = a;
9276 // It's not clear how to actually determine when such pointers are
9277 // invalidly incompatible.
9278 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9279 return AssignConvertType::
9280 IncompatibleNestedPointerAddressSpaceMismatch;
9281
9282 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9283
9284 if (lhptee == rhptee)
9285 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9286 }
9287
9288 // General pointer incompatibility takes priority over qualifiers.
9289 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9290 return AssignConvertType::IncompatibleFunctionPointer;
9291 return AssignConvertType::IncompatiblePointer;
9292 }
9293 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9294 // hasSameType, so we can skip further checks.
9295 const auto *LFT = ltrans->getAs<FunctionType>();
9296 const auto *RFT = rtrans->getAs<FunctionType>();
9297 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9298 // The invocation of IsFunctionConversion below will try to transform rtrans
9299 // to obtain an exact match for ltrans. This should not fail because of
9300 // mismatches in result type and parameter types, they were already checked
9301 // by typesAreCompatible above. So we will recreate rtrans (or where
9302 // appropriate ltrans) using the result type and parameter types from ltrans
9303 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9304 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9305 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9306 if (LFPT && RFPT) {
9307 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9308 LFPT->getParamTypes(),
9309 RFPT->getExtProtoInfo());
9310 } else if (LFPT) {
9311 FunctionProtoType::ExtProtoInfo EPI;
9312 EPI.ExtInfo = RFT->getExtInfo();
9313 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9314 LFPT->getParamTypes(), EPI);
9315 } else if (RFPT) {
9316 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9317 // all of its ExtProtoInfo. Transform ltrans instead.
9318 FunctionProtoType::ExtProtoInfo EPI;
9319 EPI.ExtInfo = LFT->getExtInfo();
9320 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9321 RFPT->getParamTypes(), EPI);
9322 } else {
9323 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9324 RFT->getExtInfo());
9325 }
9326 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9327 !S.IsFunctionConversion(rtrans, ltrans))
9328 return AssignConvertType::IncompatibleFunctionPointer;
9329 }
9330 return ConvTy;
9331 }
9332
9333 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9334 /// block pointer types are compatible or whether a block and normal pointer
9335 /// are compatible. It is more restrict than comparing two function pointer
9336 // types.
9337 static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9338 QualType LHSType,
9339 QualType RHSType) {
9340 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9341 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9342
9343 QualType lhptee, rhptee;
9344
9345 // get the "pointed to" type (ignoring qualifiers at the top level)
9346 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9347 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9348
9349 // In C++, the types have to match exactly.
9350 if (S.getLangOpts().CPlusPlus)
9351 return AssignConvertType::IncompatibleBlockPointer;
9352
9353 AssignConvertType ConvTy = AssignConvertType::Compatible;
9354
9355 // For blocks we enforce that qualifiers are identical.
9356 Qualifiers LQuals = lhptee.getLocalQualifiers();
9357 Qualifiers RQuals = rhptee.getLocalQualifiers();
9358 if (S.getLangOpts().OpenCL) {
9359 LQuals.removeAddressSpace();
9360 RQuals.removeAddressSpace();
9361 }
9362 if (LQuals != RQuals)
9363 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9364
9365 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9366 // assignment.
9367 // The current behavior is similar to C++ lambdas. A block might be
9368 // assigned to a variable iff its return type and parameters are compatible
9369 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9370 // an assignment. Presumably it should behave in way that a function pointer
9371 // assignment does in C, so for each parameter and return type:
9372 // * CVR and address space of LHS should be a superset of CVR and address
9373 // space of RHS.
9374 // * unqualified types should be compatible.
9375 if (S.getLangOpts().OpenCL) {
9376 if (!S.Context.typesAreBlockPointerCompatible(
9377 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9378 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9379 return AssignConvertType::IncompatibleBlockPointer;
9380 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9381 return AssignConvertType::IncompatibleBlockPointer;
9382
9383 return ConvTy;
9384 }
9385
9386 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9387 /// for assignment compatibility.
9388 static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9389 QualType LHSType,
9390 QualType RHSType) {
9391 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9392 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9393
9394 if (LHSType->isObjCBuiltinType()) {
9395 // Class is not compatible with ObjC object pointers.
9396 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9397 !RHSType->isObjCQualifiedClassType())
9398 return AssignConvertType::IncompatiblePointer;
9399 return AssignConvertType::Compatible;
9400 }
9401 if (RHSType->isObjCBuiltinType()) {
9402 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9403 !LHSType->isObjCQualifiedClassType())
9404 return AssignConvertType::IncompatiblePointer;
9405 return AssignConvertType::Compatible;
9406 }
9407 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9408 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9409
9410 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9411 // make an exception for id<P>
9412 !LHSType->isObjCQualifiedIdType())
9413 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9414
9415 if (S.Context.typesAreCompatible(LHSType, RHSType))
9416 return AssignConvertType::Compatible;
9417 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9418 return AssignConvertType::IncompatibleObjCQualifiedId;
9419 return AssignConvertType::IncompatiblePointer;
9420 }
9421
9422 AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9423 QualType LHSType,
9424 QualType RHSType) {
9425 // Fake up an opaque expression. We don't actually care about what
9426 // cast operations are required, so if CheckAssignmentConstraints
9427 // adds casts to this they'll be wasted, but fortunately that doesn't
9428 // usually happen on valid code.
9429 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9430 ExprResult RHSPtr = &RHSExpr;
9431 CastKind K;
9432
9433 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9434 }
9435
9436 /// This helper function returns true if QT is a vector type that has element
9437 /// type ElementType.
9438 static bool isVector(QualType QT, QualType ElementType) {
9439 if (const VectorType *VT = QT->getAs<VectorType>())
9440 return VT->getElementType().getCanonicalType() == ElementType;
9441 return false;
9442 }
9443
9444 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9445 /// has code to accommodate several GCC extensions when type checking
9446 /// pointers. Here are some objectionable examples that GCC considers warnings:
9447 ///
9448 /// int a, *pint;
9449 /// short *pshort;
9450 /// struct foo *pfoo;
9451 ///
9452 /// pint = pshort; // warning: assignment from incompatible pointer type
9453 /// a = pint; // warning: assignment makes integer from pointer without a cast
9454 /// pint = a; // warning: assignment makes pointer from integer without a cast
9455 /// pint = pfoo; // warning: assignment from incompatible pointer type
9456 ///
9457 /// As a result, the code for dealing with pointers is more complex than the
9458 /// C99 spec dictates.
9459 ///
9460 /// Sets 'Kind' for any result kind except Incompatible.
9461 AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9462 ExprResult &RHS,
9463 CastKind &Kind,
9464 bool ConvertRHS) {
9465 QualType RHSType = RHS.get()->getType();
9466 QualType OrigLHSType = LHSType;
9467
9468 // Get canonical types. We're not formatting these types, just comparing
9469 // them.
9470 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9471 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9472
9473 // Common case: no conversion required.
9474 if (LHSType == RHSType) {
9475 Kind = CK_NoOp;
9476 return AssignConvertType::Compatible;
9477 }
9478
9479 // If the LHS has an __auto_type, there are no additional type constraints
9480 // to be worried about.
9481 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9482 if (AT->isGNUAutoType()) {
9483 Kind = CK_NoOp;
9484 return AssignConvertType::Compatible;
9485 }
9486 }
9487
9488 // If we have an atomic type, try a non-atomic assignment, then just add an
9489 // atomic qualification step.
9490 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9491 AssignConvertType Result =
9492 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9493 if (!IsAssignConvertCompatible(Result))
9494 return Result;
9495 if (Kind != CK_NoOp && ConvertRHS)
9496 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9497 Kind = CK_NonAtomicToAtomic;
9498 return Result;
9499 }
9500
9501 // If the left-hand side is a reference type, then we are in a
9502 // (rare!) case where we've allowed the use of references in C,
9503 // e.g., as a parameter type in a built-in function. In this case,
9504 // just make sure that the type referenced is compatible with the
9505 // right-hand side type. The caller is responsible for adjusting
9506 // LHSType so that the resulting expression does not have reference
9507 // type.
9508 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9509 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9510 Kind = CK_LValueBitCast;
9511 return AssignConvertType::Compatible;
9512 }
9513 return AssignConvertType::Incompatible;
9514 }
9515
9516 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9517 // of an ExtVector type to the same ExtVector type.
9518 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9519 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9520 // Implicit conversions require the same number of elements.
9521 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9522 return AssignConvertType::Incompatible;
9523
9524 if (LHSType->isExtVectorBoolType() &&
9525 RHSExtType->getElementType()->isIntegerType()) {
9526 Kind = CK_IntegralToBoolean;
9527 return AssignConvertType::Compatible;
9528 }
9529 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9530 if (Context.getLangOpts().OpenCL &&
9531 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9532 Kind = CK_BitCast;
9533 return AssignConvertType::Compatible;
9534 }
9535 return AssignConvertType::Incompatible;
9536 }
9537 if (RHSType->isArithmeticType()) {
9538 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9539 if (ConvertRHS)
9540 RHS = prepareVectorSplat(LHSType, RHS.get());
9541 Kind = CK_VectorSplat;
9542 return AssignConvertType::Compatible;
9543 }
9544 }
9545
9546 // Conversions to or from vector type.
9547 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9548 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9549 // Allow assignments of an AltiVec vector type to an equivalent GCC
9550 // vector type and vice versa
9551 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9552 Kind = CK_BitCast;
9553 return AssignConvertType::Compatible;
9554 }
9555
9556 // If we are allowing lax vector conversions, and LHS and RHS are both
9557 // vectors, the total size only needs to be the same. This is a bitcast;
9558 // no bits are changed but the result type is different.
9559 if (isLaxVectorConversion(RHSType, LHSType)) {
9560 // The default for lax vector conversions with Altivec vectors will
9561 // change, so if we are converting between vector types where
9562 // at least one is an Altivec vector, emit a warning.
9563 if (Context.getTargetInfo().getTriple().isPPC() &&
9564 anyAltivecTypes(RHSType, LHSType) &&
9565 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9566 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9567 << RHSType << LHSType;
9568 Kind = CK_BitCast;
9569 return AssignConvertType::IncompatibleVectors;
9570 }
9571 }
9572
9573 // When the RHS comes from another lax conversion (e.g. binops between
9574 // scalars and vectors) the result is canonicalized as a vector. When the
9575 // LHS is also a vector, the lax is allowed by the condition above. Handle
9576 // the case where LHS is a scalar.
9577 if (LHSType->isScalarType()) {
9578 const VectorType *VecType = RHSType->getAs<VectorType>();
9579 if (VecType && VecType->getNumElements() == 1 &&
9580 isLaxVectorConversion(RHSType, LHSType)) {
9581 if (Context.getTargetInfo().getTriple().isPPC() &&
9582 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9583 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9584 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9585 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9586 << RHSType << LHSType;
9587 ExprResult *VecExpr = &RHS;
9588 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9589 Kind = CK_BitCast;
9590 return AssignConvertType::Compatible;
9591 }
9592 }
9593
9594 // Allow assignments between fixed-length and sizeless SVE vectors.
9595 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9596 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9597 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9598 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9599 Kind = CK_BitCast;
9600 return AssignConvertType::Compatible;
9601 }
9602
9603 // Allow assignments between fixed-length and sizeless RVV vectors.
9604 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9605 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9606 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9607 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9608 Kind = CK_BitCast;
9609 return AssignConvertType::Compatible;
9610 }
9611 }
9612
9613 return AssignConvertType::Incompatible;
9614 }
9615
9616 // Diagnose attempts to convert between __ibm128, __float128 and long double
9617 // where such conversions currently can't be handled.
9618 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9619 return AssignConvertType::Incompatible;
9620
9621 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9622 // discards the imaginary part.
9623 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9624 !LHSType->getAs<ComplexType>())
9625 return AssignConvertType::Incompatible;
9626
9627 // Arithmetic conversions.
9628 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9629 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9630 if (ConvertRHS)
9631 Kind = PrepareScalarCast(RHS, LHSType);
9632 return AssignConvertType::Compatible;
9633 }
9634
9635 // Conversions to normal pointers.
9636 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9637 // U* -> T*
9638 if (isa<PointerType>(RHSType)) {
9639 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9640 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9641 if (AddrSpaceL != AddrSpaceR)
9642 Kind = CK_AddressSpaceConversion;
9643 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9644 Kind = CK_NoOp;
9645 else
9646 Kind = CK_BitCast;
9647 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9648 RHS.get()->getBeginLoc());
9649 }
9650
9651 // int -> T*
9652 if (RHSType->isIntegerType()) {
9653 Kind = CK_IntegralToPointer; // FIXME: null?
9654 return AssignConvertType::IntToPointer;
9655 }
9656
9657 // C pointers are not compatible with ObjC object pointers,
9658 // with two exceptions:
9659 if (isa<ObjCObjectPointerType>(RHSType)) {
9660 // - conversions to void*
9661 if (LHSPointer->getPointeeType()->isVoidType()) {
9662 Kind = CK_BitCast;
9663 return AssignConvertType::Compatible;
9664 }
9665
9666 // - conversions from 'Class' to the redefinition type
9667 if (RHSType->isObjCClassType() &&
9668 Context.hasSameType(LHSType,
9669 Context.getObjCClassRedefinitionType())) {
9670 Kind = CK_BitCast;
9671 return AssignConvertType::Compatible;
9672 }
9673
9674 Kind = CK_BitCast;
9675 return AssignConvertType::IncompatiblePointer;
9676 }
9677
9678 // U^ -> void*
9679 if (RHSType->getAs<BlockPointerType>()) {
9680 if (LHSPointer->getPointeeType()->isVoidType()) {
9681 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9682 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9683 ->getPointeeType()
9684 .getAddressSpace();
9685 Kind =
9686 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9687 return AssignConvertType::Compatible;
9688 }
9689 }
9690
9691 return AssignConvertType::Incompatible;
9692 }
9693
9694 // Conversions to block pointers.
9695 if (isa<BlockPointerType>(LHSType)) {
9696 // U^ -> T^
9697 if (RHSType->isBlockPointerType()) {
9698 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9699 ->getPointeeType()
9700 .getAddressSpace();
9701 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9702 ->getPointeeType()
9703 .getAddressSpace();
9704 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9705 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9706 }
9707
9708 // int or null -> T^
9709 if (RHSType->isIntegerType()) {
9710 Kind = CK_IntegralToPointer; // FIXME: null
9711 return AssignConvertType::IntToBlockPointer;
9712 }
9713
9714 // id -> T^
9715 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9716 Kind = CK_AnyPointerToBlockPointerCast;
9717 return AssignConvertType::Compatible;
9718 }
9719
9720 // void* -> T^
9721 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9722 if (RHSPT->getPointeeType()->isVoidType()) {
9723 Kind = CK_AnyPointerToBlockPointerCast;
9724 return AssignConvertType::Compatible;
9725 }
9726
9727 return AssignConvertType::Incompatible;
9728 }
9729
9730 // Conversions to Objective-C pointers.
9731 if (isa<ObjCObjectPointerType>(LHSType)) {
9732 // A* -> B*
9733 if (RHSType->isObjCObjectPointerType()) {
9734 Kind = CK_BitCast;
9735 AssignConvertType result =
9736 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9737 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9738 result == AssignConvertType::Compatible &&
9739 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9740 result = AssignConvertType::IncompatibleObjCWeakRef;
9741 return result;
9742 }
9743
9744 // int or null -> A*
9745 if (RHSType->isIntegerType()) {
9746 Kind = CK_IntegralToPointer; // FIXME: null
9747 return AssignConvertType::IntToPointer;
9748 }
9749
9750 // In general, C pointers are not compatible with ObjC object pointers,
9751 // with two exceptions:
9752 if (isa<PointerType>(RHSType)) {
9753 Kind = CK_CPointerToObjCPointerCast;
9754
9755 // - conversions from 'void*'
9756 if (RHSType->isVoidPointerType()) {
9757 return AssignConvertType::Compatible;
9758 }
9759
9760 // - conversions to 'Class' from its redefinition type
9761 if (LHSType->isObjCClassType() &&
9762 Context.hasSameType(RHSType,
9763 Context.getObjCClassRedefinitionType())) {
9764 return AssignConvertType::Compatible;
9765 }
9766
9767 return AssignConvertType::IncompatiblePointer;
9768 }
9769
9770 // Only under strict condition T^ is compatible with an Objective-C pointer.
9771 if (RHSType->isBlockPointerType() &&
9772 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9773 if (ConvertRHS)
9774 maybeExtendBlockObject(RHS);
9775 Kind = CK_BlockPointerToObjCPointerCast;
9776 return AssignConvertType::Compatible;
9777 }
9778
9779 return AssignConvertType::Incompatible;
9780 }
9781
9782 // Conversion to nullptr_t (C23 only)
9783 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9784 RHS.get()->isNullPointerConstant(Context,
9785 Expr::NPC_ValueDependentIsNull)) {
9786 // null -> nullptr_t
9787 Kind = CK_NullToPointer;
9788 return AssignConvertType::Compatible;
9789 }
9790
9791 // Conversions from pointers that are not covered by the above.
9792 if (isa<PointerType>(RHSType)) {
9793 // T* -> _Bool
9794 if (LHSType == Context.BoolTy) {
9795 Kind = CK_PointerToBoolean;
9796 return AssignConvertType::Compatible;
9797 }
9798
9799 // T* -> int
9800 if (LHSType->isIntegerType()) {
9801 Kind = CK_PointerToIntegral;
9802 return AssignConvertType::PointerToInt;
9803 }
9804
9805 return AssignConvertType::Incompatible;
9806 }
9807
9808 // Conversions from Objective-C pointers that are not covered by the above.
9809 if (isa<ObjCObjectPointerType>(RHSType)) {
9810 // T* -> _Bool
9811 if (LHSType == Context.BoolTy) {
9812 Kind = CK_PointerToBoolean;
9813 return AssignConvertType::Compatible;
9814 }
9815
9816 // T* -> int
9817 if (LHSType->isIntegerType()) {
9818 Kind = CK_PointerToIntegral;
9819 return AssignConvertType::PointerToInt;
9820 }
9821
9822 return AssignConvertType::Incompatible;
9823 }
9824
9825 // struct A -> struct B
9826 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9827 if (Context.typesAreCompatible(LHSType, RHSType)) {
9828 Kind = CK_NoOp;
9829 return AssignConvertType::Compatible;
9830 }
9831 }
9832
9833 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9834 Kind = CK_IntToOCLSampler;
9835 return AssignConvertType::Compatible;
9836 }
9837
9838 return AssignConvertType::Incompatible;
9839 }
9840
9841 /// Constructs a transparent union from an expression that is
9842 /// used to initialize the transparent union.
9843 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9844 ExprResult &EResult, QualType UnionType,
9845 FieldDecl *Field) {
9846 // Build an initializer list that designates the appropriate member
9847 // of the transparent union.
9848 Expr *E = EResult.get();
9849 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9850 E, SourceLocation());
9851 Initializer->setType(UnionType);
9852 Initializer->setInitializedFieldInUnion(Field);
9853
9854 // Build a compound literal constructing a value of the transparent
9855 // union type from this initializer list.
9856 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9857 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9858 VK_PRValue, Initializer, false);
9859 }
9860
9861 AssignConvertType
9862 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9863 ExprResult &RHS) {
9864 QualType RHSType = RHS.get()->getType();
9865
9866 // If the ArgType is a Union type, we want to handle a potential
9867 // transparent_union GCC extension.
9868 const RecordType *UT = ArgType->getAsUnionType();
9869 if (!UT)
9870 return AssignConvertType::Incompatible;
9871
9872 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
9873 if (!UD->hasAttr<TransparentUnionAttr>())
9874 return AssignConvertType::Incompatible;
9875
9876 // The field to initialize within the transparent union.
9877 FieldDecl *InitField = nullptr;
9878 // It's compatible if the expression matches any of the fields.
9879 for (auto *it : UD->fields()) {
9880 if (it->getType()->isPointerType()) {
9881 // If the transparent union contains a pointer type, we allow:
9882 // 1) void pointer
9883 // 2) null pointer constant
9884 if (RHSType->isPointerType())
9885 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9886 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9887 InitField = it;
9888 break;
9889 }
9890
9891 if (RHS.get()->isNullPointerConstant(Context,
9892 Expr::NPC_ValueDependentIsNull)) {
9893 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9894 CK_NullToPointer);
9895 InitField = it;
9896 break;
9897 }
9898 }
9899
9900 CastKind Kind;
9901 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
9902 AssignConvertType::Compatible) {
9903 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9904 InitField = it;
9905 break;
9906 }
9907 }
9908
9909 if (!InitField)
9910 return AssignConvertType::Incompatible;
9911
9912 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9913 return AssignConvertType::Compatible;
9914 }
9915
9916 AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
9917 ExprResult &CallerRHS,
9918 bool Diagnose,
9919 bool DiagnoseCFAudited,
9920 bool ConvertRHS) {
9921 // We need to be able to tell the caller whether we diagnosed a problem, if
9922 // they ask us to issue diagnostics.
9923 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9924
9925 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9926 // we can't avoid *all* modifications at the moment, so we need some somewhere
9927 // to put the updated value.
9928 ExprResult LocalRHS = CallerRHS;
9929 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9930
9931 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9932 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9933 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9934 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9935 Diag(RHS.get()->getExprLoc(),
9936 diag::warn_noderef_to_dereferenceable_pointer)
9937 << RHS.get()->getSourceRange();
9938 }
9939 }
9940 }
9941
9942 if (getLangOpts().CPlusPlus) {
9943 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9944 // C++ 5.17p3: If the left operand is not of class type, the
9945 // expression is implicitly converted (C++ 4) to the
9946 // cv-unqualified type of the left operand.
9947 QualType RHSType = RHS.get()->getType();
9948 if (Diagnose) {
9949 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9950 AssignmentAction::Assigning);
9951 } else {
9952 ImplicitConversionSequence ICS =
9953 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9954 /*SuppressUserConversions=*/false,
9955 AllowedExplicit::None,
9956 /*InOverloadResolution=*/false,
9957 /*CStyle=*/false,
9958 /*AllowObjCWritebackConversion=*/false);
9959 if (ICS.isFailure())
9960 return AssignConvertType::Incompatible;
9961 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9962 ICS, AssignmentAction::Assigning);
9963 }
9964 if (RHS.isInvalid())
9965 return AssignConvertType::Incompatible;
9966 AssignConvertType result = AssignConvertType::Compatible;
9967 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9968 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9969 result = AssignConvertType::IncompatibleObjCWeakRef;
9970 return result;
9971 }
9972
9973 // FIXME: Currently, we fall through and treat C++ classes like C
9974 // structures.
9975 // FIXME: We also fall through for atomics; not sure what should
9976 // happen there, though.
9977 } else if (RHS.get()->getType() == Context.OverloadTy) {
9978 // As a set of extensions to C, we support overloading on functions. These
9979 // functions need to be resolved here.
9980 DeclAccessPair DAP;
9981 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9982 RHS.get(), LHSType, /*Complain=*/false, DAP))
9983 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9984 else
9985 return AssignConvertType::Incompatible;
9986 }
9987
9988 // This check seems unnatural, however it is necessary to ensure the proper
9989 // conversion of functions/arrays. If the conversion were done for all
9990 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9991 // expressions that suppress this implicit conversion (&, sizeof). This needs
9992 // to happen before we check for null pointer conversions because C does not
9993 // undergo the same implicit conversions as C++ does above (by the calls to
9994 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9995 // lvalue to rvalue cast before checking for null pointer constraints. This
9996 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9997 //
9998 // Suppress this for references: C++ 8.5.3p5.
9999 if (!LHSType->isReferenceType()) {
10000 // FIXME: We potentially allocate here even if ConvertRHS is false.
10001 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10002 if (RHS.isInvalid())
10003 return AssignConvertType::Incompatible;
10004 }
10005
10006 // The constraints are expressed in terms of the atomic, qualified, or
10007 // unqualified type of the LHS.
10008 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10009
10010 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10011 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10012 if ((LHSTypeAfterConversion->isPointerType() ||
10013 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10014 LHSTypeAfterConversion->isBlockPointerType()) &&
10015 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10016 RHS.get()->isNullPointerConstant(Context,
10017 Expr::NPC_ValueDependentIsNull))) {
10018 AssignConvertType Ret = AssignConvertType::Compatible;
10019 if (Diagnose || ConvertRHS) {
10020 CastKind Kind;
10021 CXXCastPath Path;
10022 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10023 /*IgnoreBaseAccess=*/false, Diagnose);
10024
10025 // If there is a conversion of some kind, check to see what kind of
10026 // pointer conversion happened so we can diagnose a C++ compatibility
10027 // diagnostic if the conversion is invalid. This only matters if the RHS
10028 // is some kind of void pointer. We have a carve-out when the RHS is from
10029 // a macro expansion because the use of a macro may indicate different
10030 // code between C and C++. Consider: char *s = NULL; where NULL is
10031 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10032 // C++, which is valid in C++.
10033 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10034 !RHS.get()->getBeginLoc().isMacroID()) {
10035 QualType CanRHS =
10036 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10037 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10038 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10039 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10040 RHS.get()->getExprLoc());
10041 // Anything that's not considered perfectly compatible would be
10042 // incompatible in C++.
10043 if (Ret != AssignConvertType::Compatible)
10044 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10045 }
10046 }
10047
10048 if (ConvertRHS)
10049 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10050 }
10051 return Ret;
10052 }
10053 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10054 // unqualified bool, and the right operand is a pointer or its type is
10055 // nullptr_t.
10056 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10057 RHS.get()->getType()->isNullPtrType()) {
10058 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10059 // only handles nullptr -> _Bool due to needing an extra conversion
10060 // step.
10061 // We model this by converting from nullptr -> void * and then let the
10062 // conversion from void * -> _Bool happen naturally.
10063 if (Diagnose || ConvertRHS) {
10064 CastKind Kind;
10065 CXXCastPath Path;
10066 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10067 /*IgnoreBaseAccess=*/false, Diagnose);
10068 if (ConvertRHS)
10069 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10070 &Path);
10071 }
10072 }
10073
10074 // OpenCL queue_t type assignment.
10075 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10076 Context, Expr::NPC_ValueDependentIsNull)) {
10077 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10078 return AssignConvertType::Compatible;
10079 }
10080
10081 CastKind Kind;
10082 AssignConvertType result =
10083 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10084
10085 // If assigning a void * created by an allocation function call to some other
10086 // type, check that the allocated size is sufficient for that type.
10087 if (result != AssignConvertType::Incompatible &&
10088 RHS.get()->getType()->isVoidPointerType())
10089 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10090
10091 // C99 6.5.16.1p2: The value of the right operand is converted to the
10092 // type of the assignment expression.
10093 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10094 // so that we can use references in built-in functions even in C.
10095 // The getNonReferenceType() call makes sure that the resulting expression
10096 // does not have reference type.
10097 if (result != AssignConvertType::Incompatible &&
10098 RHS.get()->getType() != LHSType) {
10099 QualType Ty = LHSType.getNonLValueExprType(Context);
10100 Expr *E = RHS.get();
10101
10102 // Check for various Objective-C errors. If we are not reporting
10103 // diagnostics and just checking for errors, e.g., during overload
10104 // resolution, return Incompatible to indicate the failure.
10105 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10106 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10107 CheckedConversionKind::Implicit, Diagnose,
10108 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10109 if (!Diagnose)
10110 return AssignConvertType::Incompatible;
10111 }
10112 if (getLangOpts().ObjC &&
10113 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10114 E->getType(), E, Diagnose) ||
10115 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10116 if (!Diagnose)
10117 return AssignConvertType::Incompatible;
10118 // Replace the expression with a corrected version and continue so we
10119 // can find further errors.
10120 RHS = E;
10121 return AssignConvertType::Compatible;
10122 }
10123
10124 if (ConvertRHS)
10125 RHS = ImpCastExprToType(E, Ty, Kind);
10126 }
10127
10128 return result;
10129 }
10130
10131 namespace {
10132 /// The original operand to an operator, prior to the application of the usual
10133 /// arithmetic conversions and converting the arguments of a builtin operator
10134 /// candidate.
10135 struct OriginalOperand {
10136 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10137 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10138 Op = MTE->getSubExpr();
10139 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10140 Op = BTE->getSubExpr();
10141 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10142 Orig = ICE->getSubExprAsWritten();
10143 Conversion = ICE->getConversionFunction();
10144 }
10145 }
10146
10147 QualType getType() const { return Orig->getType(); }
10148
10149 Expr *Orig;
10150 NamedDecl *Conversion;
10151 };
10152 }
10153
10154 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10155 ExprResult &RHS) {
10156 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10157
10158 Diag(Loc, diag::err_typecheck_invalid_operands)
10159 << OrigLHS.getType() << OrigRHS.getType()
10160 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10161
10162 // If a user-defined conversion was applied to either of the operands prior
10163 // to applying the built-in operator rules, tell the user about it.
10164 if (OrigLHS.Conversion) {
10165 Diag(OrigLHS.Conversion->getLocation(),
10166 diag::note_typecheck_invalid_operands_converted)
10167 << 0 << LHS.get()->getType();
10168 }
10169 if (OrigRHS.Conversion) {
10170 Diag(OrigRHS.Conversion->getLocation(),
10171 diag::note_typecheck_invalid_operands_converted)
10172 << 1 << RHS.get()->getType();
10173 }
10174
10175 return QualType();
10176 }
10177
10178 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10179 ExprResult &RHS) {
10180 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10181 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10182
10183 bool LHSNatVec = LHSType->isVectorType();
10184 bool RHSNatVec = RHSType->isVectorType();
10185
10186 if (!(LHSNatVec && RHSNatVec)) {
10187 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10188 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10189 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10190 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10191 << Vector->getSourceRange();
10192 return QualType();
10193 }
10194
10195 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10196 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10197 << RHS.get()->getSourceRange();
10198
10199 return QualType();
10200 }
10201
10202 /// Try to convert a value of non-vector type to a vector type by converting
10203 /// the type to the element type of the vector and then performing a splat.
10204 /// If the language is OpenCL, we only use conversions that promote scalar
10205 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10206 /// for float->int.
10207 ///
10208 /// OpenCL V2.0 6.2.6.p2:
10209 /// An error shall occur if any scalar operand type has greater rank
10210 /// than the type of the vector element.
10211 ///
10212 /// \param scalar - if non-null, actually perform the conversions
10213 /// \return true if the operation fails (but without diagnosing the failure)
10214 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10215 QualType scalarTy,
10216 QualType vectorEltTy,
10217 QualType vectorTy,
10218 unsigned &DiagID) {
10219 // The conversion to apply to the scalar before splatting it,
10220 // if necessary.
10221 CastKind scalarCast = CK_NoOp;
10222
10223 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10224 scalarCast = CK_IntegralToBoolean;
10225 } else if (vectorEltTy->isIntegralType(S.Context)) {
10226 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10227 (scalarTy->isIntegerType() &&
10228 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10229 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10230 return true;
10231 }
10232 if (!scalarTy->isIntegralType(S.Context))
10233 return true;
10234 scalarCast = CK_IntegralCast;
10235 } else if (vectorEltTy->isRealFloatingType()) {
10236 if (scalarTy->isRealFloatingType()) {
10237 if (S.getLangOpts().OpenCL &&
10238 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10239 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10240 return true;
10241 }
10242 scalarCast = CK_FloatingCast;
10243 }
10244 else if (scalarTy->isIntegralType(S.Context))
10245 scalarCast = CK_IntegralToFloating;
10246 else
10247 return true;
10248 } else {
10249 return true;
10250 }
10251
10252 // Adjust scalar if desired.
10253 if (scalar) {
10254 if (scalarCast != CK_NoOp)
10255 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10256 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10257 }
10258 return false;
10259 }
10260
10261 /// Convert vector E to a vector with the same number of elements but different
10262 /// element type.
10263 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10264 const auto *VecTy = E->getType()->getAs<VectorType>();
10265 assert(VecTy && "Expression E must be a vector");
10266 QualType NewVecTy =
10267 VecTy->isExtVectorType()
10268 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10269 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10270 VecTy->getVectorKind());
10271
10272 // Look through the implicit cast. Return the subexpression if its type is
10273 // NewVecTy.
10274 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10275 if (ICE->getSubExpr()->getType() == NewVecTy)
10276 return ICE->getSubExpr();
10277
10278 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10279 return S.ImpCastExprToType(E, NewVecTy, Cast);
10280 }
10281
10282 /// Test if a (constant) integer Int can be casted to another integer type
10283 /// IntTy without losing precision.
10284 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10285 QualType OtherIntTy) {
10286 Expr *E = Int->get();
10287 if (E->containsErrors() || E->isInstantiationDependent())
10288 return false;
10289
10290 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10291
10292 // Reject cases where the value of the Int is unknown as that would
10293 // possibly cause truncation, but accept cases where the scalar can be
10294 // demoted without loss of precision.
10295 Expr::EvalResult EVResult;
10296 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10297 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10298 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10299 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10300
10301 if (CstInt) {
10302 // If the scalar is constant and is of a higher order and has more active
10303 // bits that the vector element type, reject it.
10304 llvm::APSInt Result = EVResult.Val.getInt();
10305 unsigned NumBits = IntSigned
10306 ? (Result.isNegative() ? Result.getSignificantBits()
10307 : Result.getActiveBits())
10308 : Result.getActiveBits();
10309 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10310 return true;
10311
10312 // If the signedness of the scalar type and the vector element type
10313 // differs and the number of bits is greater than that of the vector
10314 // element reject it.
10315 return (IntSigned != OtherIntSigned &&
10316 NumBits > S.Context.getIntWidth(OtherIntTy));
10317 }
10318
10319 // Reject cases where the value of the scalar is not constant and it's
10320 // order is greater than that of the vector element type.
10321 return (Order < 0);
10322 }
10323
10324 /// Test if a (constant) integer Int can be casted to floating point type
10325 /// FloatTy without losing precision.
10326 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10327 QualType FloatTy) {
10328 if (Int->get()->containsErrors())
10329 return false;
10330
10331 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10332
10333 // Determine if the integer constant can be expressed as a floating point
10334 // number of the appropriate type.
10335 Expr::EvalResult EVResult;
10336 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10337
10338 uint64_t Bits = 0;
10339 if (CstInt) {
10340 // Reject constants that would be truncated if they were converted to
10341 // the floating point type. Test by simple to/from conversion.
10342 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10343 // could be avoided if there was a convertFromAPInt method
10344 // which could signal back if implicit truncation occurred.
10345 llvm::APSInt Result = EVResult.Val.getInt();
10346 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10347 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10348 llvm::APFloat::rmTowardZero);
10349 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10350 !IntTy->hasSignedIntegerRepresentation());
10351 bool Ignored = false;
10352 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10353 &Ignored);
10354 if (Result != ConvertBack)
10355 return true;
10356 } else {
10357 // Reject types that cannot be fully encoded into the mantissa of
10358 // the float.
10359 Bits = S.Context.getTypeSize(IntTy);
10360 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10361 S.Context.getFloatTypeSemantics(FloatTy));
10362 if (Bits > FloatPrec)
10363 return true;
10364 }
10365
10366 return false;
10367 }
10368
10369 /// Attempt to convert and splat Scalar into a vector whose types matches
10370 /// Vector following GCC conversion rules. The rule is that implicit
10371 /// conversion can occur when Scalar can be casted to match Vector's element
10372 /// type without causing truncation of Scalar.
10373 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10374 ExprResult *Vector) {
10375 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10376 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10377 QualType VectorEltTy;
10378
10379 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10380 assert(!isa<ExtVectorType>(VT) &&
10381 "ExtVectorTypes should not be handled here!");
10382 VectorEltTy = VT->getElementType();
10383 } else if (VectorTy->isSveVLSBuiltinType()) {
10384 VectorEltTy =
10385 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10386 } else {
10387 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10388 }
10389
10390 // Reject cases where the vector element type or the scalar element type are
10391 // not integral or floating point types.
10392 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10393 return true;
10394
10395 // The conversion to apply to the scalar before splatting it,
10396 // if necessary.
10397 CastKind ScalarCast = CK_NoOp;
10398
10399 // Accept cases where the vector elements are integers and the scalar is
10400 // an integer.
10401 // FIXME: Notionally if the scalar was a floating point value with a precise
10402 // integral representation, we could cast it to an appropriate integer
10403 // type and then perform the rest of the checks here. GCC will perform
10404 // this conversion in some cases as determined by the input language.
10405 // We should accept it on a language independent basis.
10406 if (VectorEltTy->isIntegralType(S.Context) &&
10407 ScalarTy->isIntegralType(S.Context) &&
10408 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10409
10410 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10411 return true;
10412
10413 ScalarCast = CK_IntegralCast;
10414 } else if (VectorEltTy->isIntegralType(S.Context) &&
10415 ScalarTy->isRealFloatingType()) {
10416 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10417 ScalarCast = CK_FloatingToIntegral;
10418 else
10419 return true;
10420 } else if (VectorEltTy->isRealFloatingType()) {
10421 if (ScalarTy->isRealFloatingType()) {
10422
10423 // Reject cases where the scalar type is not a constant and has a higher
10424 // Order than the vector element type.
10425 llvm::APFloat Result(0.0);
10426
10427 // Determine whether this is a constant scalar. In the event that the
10428 // value is dependent (and thus cannot be evaluated by the constant
10429 // evaluator), skip the evaluation. This will then diagnose once the
10430 // expression is instantiated.
10431 bool CstScalar = Scalar->get()->isValueDependent() ||
10432 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10433 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10434 if (!CstScalar && Order < 0)
10435 return true;
10436
10437 // If the scalar cannot be safely casted to the vector element type,
10438 // reject it.
10439 if (CstScalar) {
10440 bool Truncated = false;
10441 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10442 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10443 if (Truncated)
10444 return true;
10445 }
10446
10447 ScalarCast = CK_FloatingCast;
10448 } else if (ScalarTy->isIntegralType(S.Context)) {
10449 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10450 return true;
10451
10452 ScalarCast = CK_IntegralToFloating;
10453 } else
10454 return true;
10455 } else if (ScalarTy->isEnumeralType())
10456 return true;
10457
10458 // Adjust scalar if desired.
10459 if (ScalarCast != CK_NoOp)
10460 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10461 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10462 return false;
10463 }
10464
10465 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10466 SourceLocation Loc, bool IsCompAssign,
10467 bool AllowBothBool,
10468 bool AllowBoolConversions,
10469 bool AllowBoolOperation,
10470 bool ReportInvalid) {
10471 if (!IsCompAssign) {
10472 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10473 if (LHS.isInvalid())
10474 return QualType();
10475 }
10476 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10477 if (RHS.isInvalid())
10478 return QualType();
10479
10480 // For conversion purposes, we ignore any qualifiers.
10481 // For example, "const float" and "float" are equivalent.
10482 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10483 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10484
10485 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10486 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10487 assert(LHSVecType || RHSVecType);
10488
10489 if (getLangOpts().HLSL)
10490 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10491 IsCompAssign);
10492
10493 // Any operation with MFloat8 type is only possible with C intrinsics
10494 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10495 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10496 return InvalidOperands(Loc, LHS, RHS);
10497
10498 // AltiVec-style "vector bool op vector bool" combinations are allowed
10499 // for some operators but not others.
10500 if (!AllowBothBool && LHSVecType &&
10501 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10502 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10503 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10504
10505 // This operation may not be performed on boolean vectors.
10506 if (!AllowBoolOperation &&
10507 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10508 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10509
10510 // If the vector types are identical, return.
10511 if (Context.hasSameType(LHSType, RHSType))
10512 return Context.getCommonSugaredType(LHSType, RHSType);
10513
10514 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10515 if (LHSVecType && RHSVecType &&
10516 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10517 if (isa<ExtVectorType>(LHSVecType)) {
10518 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10519 return LHSType;
10520 }
10521
10522 if (!IsCompAssign)
10523 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10524 return RHSType;
10525 }
10526
10527 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10528 // can be mixed, with the result being the non-bool type. The non-bool
10529 // operand must have integer element type.
10530 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10531 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10532 (Context.getTypeSize(LHSVecType->getElementType()) ==
10533 Context.getTypeSize(RHSVecType->getElementType()))) {
10534 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10535 LHSVecType->getElementType()->isIntegerType() &&
10536 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10537 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10538 return LHSType;
10539 }
10540 if (!IsCompAssign &&
10541 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10542 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10543 RHSVecType->getElementType()->isIntegerType()) {
10544 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10545 return RHSType;
10546 }
10547 }
10548
10549 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10550 // invalid since the ambiguity can affect the ABI.
10551 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10552 unsigned &SVEorRVV) {
10553 const VectorType *VecType = SecondType->getAs<VectorType>();
10554 SVEorRVV = 0;
10555 if (FirstType->isSizelessBuiltinType() && VecType) {
10556 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10557 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10558 return true;
10559 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10560 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10561 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10562 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10563 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10564 SVEorRVV = 1;
10565 return true;
10566 }
10567 }
10568
10569 return false;
10570 };
10571
10572 unsigned SVEorRVV;
10573 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10574 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10575 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10576 << SVEorRVV << LHSType << RHSType;
10577 return QualType();
10578 }
10579
10580 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10581 // invalid since the ambiguity can affect the ABI.
10582 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10583 unsigned &SVEorRVV) {
10584 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10585 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10586
10587 SVEorRVV = 0;
10588 if (FirstVecType && SecondVecType) {
10589 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10590 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10591 SecondVecType->getVectorKind() ==
10592 VectorKind::SveFixedLengthPredicate)
10593 return true;
10594 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10595 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10596 SecondVecType->getVectorKind() ==
10597 VectorKind::RVVFixedLengthMask_1 ||
10598 SecondVecType->getVectorKind() ==
10599 VectorKind::RVVFixedLengthMask_2 ||
10600 SecondVecType->getVectorKind() ==
10601 VectorKind::RVVFixedLengthMask_4) {
10602 SVEorRVV = 1;
10603 return true;
10604 }
10605 }
10606 return false;
10607 }
10608
10609 if (SecondVecType &&
10610 SecondVecType->getVectorKind() == VectorKind::Generic) {
10611 if (FirstType->isSVESizelessBuiltinType())
10612 return true;
10613 if (FirstType->isRVVSizelessBuiltinType()) {
10614 SVEorRVV = 1;
10615 return true;
10616 }
10617 }
10618
10619 return false;
10620 };
10621
10622 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10623 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10624 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10625 << SVEorRVV << LHSType << RHSType;
10626 return QualType();
10627 }
10628
10629 // If there's a vector type and a scalar, try to convert the scalar to
10630 // the vector element type and splat.
10631 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10632 if (!RHSVecType) {
10633 if (isa<ExtVectorType>(LHSVecType)) {
10634 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10635 LHSVecType->getElementType(), LHSType,
10636 DiagID))
10637 return LHSType;
10638 } else {
10639 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10640 return LHSType;
10641 }
10642 }
10643 if (!LHSVecType) {
10644 if (isa<ExtVectorType>(RHSVecType)) {
10645 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10646 LHSType, RHSVecType->getElementType(),
10647 RHSType, DiagID))
10648 return RHSType;
10649 } else {
10650 if (LHS.get()->isLValue() ||
10651 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10652 return RHSType;
10653 }
10654 }
10655
10656 // FIXME: The code below also handles conversion between vectors and
10657 // non-scalars, we should break this down into fine grained specific checks
10658 // and emit proper diagnostics.
10659 QualType VecType = LHSVecType ? LHSType : RHSType;
10660 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10661 QualType OtherType = LHSVecType ? RHSType : LHSType;
10662 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10663 if (isLaxVectorConversion(OtherType, VecType)) {
10664 if (Context.getTargetInfo().getTriple().isPPC() &&
10665 anyAltivecTypes(RHSType, LHSType) &&
10666 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10667 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10668 // If we're allowing lax vector conversions, only the total (data) size
10669 // needs to be the same. For non compound assignment, if one of the types is
10670 // scalar, the result is always the vector type.
10671 if (!IsCompAssign) {
10672 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10673 return VecType;
10674 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10675 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10676 // type. Note that this is already done by non-compound assignments in
10677 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10678 // <1 x T> -> T. The result is also a vector type.
10679 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10680 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10681 ExprResult *RHSExpr = &RHS;
10682 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10683 return VecType;
10684 }
10685 }
10686
10687 // Okay, the expression is invalid.
10688
10689 // If there's a non-vector, non-real operand, diagnose that.
10690 if ((!RHSVecType && !RHSType->isRealType()) ||
10691 (!LHSVecType && !LHSType->isRealType())) {
10692 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10693 << LHSType << RHSType
10694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10695 return QualType();
10696 }
10697
10698 // OpenCL V1.1 6.2.6.p1:
10699 // If the operands are of more than one vector type, then an error shall
10700 // occur. Implicit conversions between vector types are not permitted, per
10701 // section 6.2.1.
10702 if (getLangOpts().OpenCL &&
10703 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10704 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10705 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10706 << RHSType;
10707 return QualType();
10708 }
10709
10710
10711 // If there is a vector type that is not a ExtVector and a scalar, we reach
10712 // this point if scalar could not be converted to the vector's element type
10713 // without truncation.
10714 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10715 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10716 QualType Scalar = LHSVecType ? RHSType : LHSType;
10717 QualType Vector = LHSVecType ? LHSType : RHSType;
10718 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10719 Diag(Loc,
10720 diag::err_typecheck_vector_not_convertable_implict_truncation)
10721 << ScalarOrVector << Scalar << Vector;
10722
10723 return QualType();
10724 }
10725
10726 // Otherwise, use the generic diagnostic.
10727 Diag(Loc, DiagID)
10728 << LHSType << RHSType
10729 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10730 return QualType();
10731 }
10732
10733 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10734 SourceLocation Loc,
10735 bool IsCompAssign,
10736 ArithConvKind OperationKind) {
10737 if (!IsCompAssign) {
10738 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10739 if (LHS.isInvalid())
10740 return QualType();
10741 }
10742 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10743 if (RHS.isInvalid())
10744 return QualType();
10745
10746 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10747 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10748
10749 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10750 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10751
10752 unsigned DiagID = diag::err_typecheck_invalid_operands;
10753 if ((OperationKind == ArithConvKind::Arithmetic) &&
10754 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10755 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10756 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10757 << RHS.get()->getSourceRange();
10758 return QualType();
10759 }
10760
10761 if (Context.hasSameType(LHSType, RHSType))
10762 return LHSType;
10763
10764 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10765 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10766 return LHSType;
10767 }
10768 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10769 if (LHS.get()->isLValue() ||
10770 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10771 return RHSType;
10772 }
10773
10774 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10775 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10776 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10777 << LHSType << RHSType << LHS.get()->getSourceRange()
10778 << RHS.get()->getSourceRange();
10779 return QualType();
10780 }
10781
10782 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10783 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10784 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10785 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10786 << LHSType << RHSType << LHS.get()->getSourceRange()
10787 << RHS.get()->getSourceRange();
10788 return QualType();
10789 }
10790
10791 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10792 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10793 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10794 bool ScalarOrVector =
10795 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10796
10797 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10798 << ScalarOrVector << Scalar << Vector;
10799
10800 return QualType();
10801 }
10802
10803 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10804 << RHS.get()->getSourceRange();
10805 return QualType();
10806 }
10807
10808 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10809 // expression. These are mainly cases where the null pointer is used as an
10810 // integer instead of a pointer.
10811 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10812 SourceLocation Loc, bool IsCompare) {
10813 // The canonical way to check for a GNU null is with isNullPointerConstant,
10814 // but we use a bit of a hack here for speed; this is a relatively
10815 // hot path, and isNullPointerConstant is slow.
10816 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10817 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10818
10819 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10820
10821 // Avoid analyzing cases where the result will either be invalid (and
10822 // diagnosed as such) or entirely valid and not something to warn about.
10823 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10824 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10825 return;
10826
10827 // Comparison operations would not make sense with a null pointer no matter
10828 // what the other expression is.
10829 if (!IsCompare) {
10830 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10831 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10832 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10833 return;
10834 }
10835
10836 // The rest of the operations only make sense with a null pointer
10837 // if the other expression is a pointer.
10838 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10839 NonNullType->canDecayToPointerType())
10840 return;
10841
10842 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10843 << LHSNull /* LHS is NULL */ << NonNullType
10844 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10845 }
10846
10847 static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
10848 SourceLocation OpLoc) {
10849 // If the divisor is real, then this is real/real or complex/real division.
10850 // Either way there can be no precision loss.
10851 auto *CT = DivisorTy->getAs<ComplexType>();
10852 if (!CT)
10853 return;
10854
10855 QualType ElementType = CT->getElementType().getCanonicalType();
10856 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10857 LangOptions::ComplexRangeKind::CX_Promoted;
10858 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10859 return;
10860
10861 ASTContext &Ctx = S.getASTContext();
10862 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10863 const llvm::fltSemantics &ElementTypeSemantics =
10864 Ctx.getFloatTypeSemantics(ElementType);
10865 const llvm::fltSemantics &HigherElementTypeSemantics =
10866 Ctx.getFloatTypeSemantics(HigherElementType);
10867
10868 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10869 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10870 (HigherElementType == Ctx.LongDoubleTy &&
10871 !Ctx.getTargetInfo().hasLongDoubleType())) {
10872 // Retain the location of the first use of higher precision type.
10873 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
10874 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
10875 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10876 if (Type == HigherElementType) {
10877 Num++;
10878 return;
10879 }
10880 }
10881 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
10882 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
10883 }
10884 }
10885
10886 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10887 SourceLocation Loc) {
10888 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10889 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10890 if (!LUE || !RUE)
10891 return;
10892 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10893 RUE->getKind() != UETT_SizeOf)
10894 return;
10895
10896 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10897 QualType LHSTy = LHSArg->getType();
10898 QualType RHSTy;
10899
10900 if (RUE->isArgumentType())
10901 RHSTy = RUE->getArgumentType().getNonReferenceType();
10902 else
10903 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10904
10905 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10906 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10907 return;
10908
10909 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10910 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10911 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10912 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10913 << LHSArgDecl;
10914 }
10915 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10916 QualType ArrayElemTy = ArrayTy->getElementType();
10917 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10918 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10919 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10920 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10921 return;
10922 S.Diag(Loc, diag::warn_division_sizeof_array)
10923 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10924 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10925 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10926 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10927 << LHSArgDecl;
10928 }
10929
10930 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10931 }
10932 }
10933
10934 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10935 ExprResult &RHS,
10936 SourceLocation Loc, bool IsDiv) {
10937 // Check for division/remainder by zero.
10938 Expr::EvalResult RHSValue;
10939 if (!RHS.get()->isValueDependent() &&
10940 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10941 RHSValue.Val.getInt() == 0)
10942 S.DiagRuntimeBehavior(Loc, RHS.get(),
10943 S.PDiag(diag::warn_remainder_division_by_zero)
10944 << IsDiv << RHS.get()->getSourceRange());
10945 }
10946
10947 static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
10948 const ExprResult &LHS, const ExprResult &RHS,
10949 BinaryOperatorKind Opc) {
10950 if (!LHS.isUsable() || !RHS.isUsable())
10951 return;
10952 const Expr *LHSExpr = LHS.get();
10953 const Expr *RHSExpr = RHS.get();
10954 const QualType LHSType = LHSExpr->getType();
10955 const QualType RHSType = RHSExpr->getType();
10956 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10957 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10958 if (!LHSIsScoped && !RHSIsScoped)
10959 return;
10960 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10961 return;
10962 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10963 return;
10964 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10965 return;
10966 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10967 SourceLocation BeginLoc = expr->getBeginLoc();
10968 QualType IntType = type->castAs<EnumType>()
10969 ->getDecl()
10970 ->getDefinitionOrSelf()
10971 ->getIntegerType();
10972 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10973 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
10974 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
10975 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
10976 };
10977 if (LHSIsScoped) {
10978 DiagnosticHelper(LHSExpr, LHSType);
10979 }
10980 if (RHSIsScoped) {
10981 DiagnosticHelper(RHSExpr, RHSType);
10982 }
10983 }
10984
10985 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10986 SourceLocation Loc,
10987 BinaryOperatorKind Opc) {
10988 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10989 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10990
10991 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10992
10993 QualType LHSTy = LHS.get()->getType();
10994 QualType RHSTy = RHS.get()->getType();
10995 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10996 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10997 /*AllowBothBool*/ getLangOpts().AltiVec,
10998 /*AllowBoolConversions*/ false,
10999 /*AllowBooleanOperation*/ false,
11000 /*ReportInvalid*/ true);
11001 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11002 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11003 ArithConvKind::Arithmetic);
11004 if (!IsDiv &&
11005 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11006 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11007 // For division, only matrix-by-scalar is supported. Other combinations with
11008 // matrix types are invalid.
11009 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11010 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11011
11012 QualType compType = UsualArithmeticConversions(
11013 LHS, RHS, Loc,
11014 IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11015 if (LHS.isInvalid() || RHS.isInvalid())
11016 return QualType();
11017
11018 if (compType.isNull() || !compType->isArithmeticType()) {
11019 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11020 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11021 return ResultTy;
11022 }
11023 if (IsDiv) {
11024 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11025 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11026 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11027 }
11028 return compType;
11029 }
11030
11031 QualType Sema::CheckRemainderOperands(
11032 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11033 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11034
11035 // Note: This check is here to simplify the double exclusions of
11036 // scalar and vector HLSL checks. No getLangOpts().HLSL
11037 // is needed since all languages exlcude doubles.
11038 if (LHS.get()->getType()->isDoubleType() ||
11039 RHS.get()->getType()->isDoubleType() ||
11040 (LHS.get()->getType()->isVectorType() && LHS.get()
11041 ->getType()
11042 ->getAs<VectorType>()
11043 ->getElementType()
11044 ->isDoubleType()) ||
11045 (RHS.get()->getType()->isVectorType() && RHS.get()
11046 ->getType()
11047 ->getAs<VectorType>()
11048 ->getElementType()
11049 ->isDoubleType()))
11050 return InvalidOperands(Loc, LHS, RHS);
11051
11052 if (LHS.get()->getType()->isVectorType() ||
11053 RHS.get()->getType()->isVectorType()) {
11054 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11055 RHS.get()->getType()->hasIntegerRepresentation()) ||
11056 (getLangOpts().HLSL &&
11057 (LHS.get()->getType()->hasFloatingRepresentation() ||
11058 RHS.get()->getType()->hasFloatingRepresentation())))
11059 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11060 /*AllowBothBool*/ getLangOpts().AltiVec,
11061 /*AllowBoolConversions*/ false,
11062 /*AllowBooleanOperation*/ false,
11063 /*ReportInvalid*/ true);
11064 return InvalidOperands(Loc, LHS, RHS);
11065 }
11066
11067 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11068 RHS.get()->getType()->isSveVLSBuiltinType()) {
11069 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11070 RHS.get()->getType()->hasIntegerRepresentation())
11071 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11072 ArithConvKind::Arithmetic);
11073
11074 return InvalidOperands(Loc, LHS, RHS);
11075 }
11076
11077 QualType compType = UsualArithmeticConversions(
11078 LHS, RHS, Loc,
11079 IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11080 if (LHS.isInvalid() || RHS.isInvalid())
11081 return QualType();
11082
11083 if (compType.isNull() ||
11084 (!compType->isIntegerType() &&
11085 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11086 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11087 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11088 IsCompAssign ? BO_RemAssign : BO_Rem);
11089 return ResultTy;
11090 }
11091 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11092 return compType;
11093 }
11094
11095 /// Diagnose invalid arithmetic on two void pointers.
11096 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11097 Expr *LHSExpr, Expr *RHSExpr) {
11098 S.Diag(Loc, S.getLangOpts().CPlusPlus
11099 ? diag::err_typecheck_pointer_arith_void_type
11100 : diag::ext_gnu_void_ptr)
11101 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11102 << RHSExpr->getSourceRange();
11103 }
11104
11105 /// Diagnose invalid arithmetic on a void pointer.
11106 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11107 Expr *Pointer) {
11108 S.Diag(Loc, S.getLangOpts().CPlusPlus
11109 ? diag::err_typecheck_pointer_arith_void_type
11110 : diag::ext_gnu_void_ptr)
11111 << 0 /* one pointer */ << Pointer->getSourceRange();
11112 }
11113
11114 /// Diagnose invalid arithmetic on a null pointer.
11115 ///
11116 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11117 /// idiom, which we recognize as a GNU extension.
11118 ///
11119 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11120 Expr *Pointer, bool IsGNUIdiom) {
11121 if (IsGNUIdiom)
11122 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11123 << Pointer->getSourceRange();
11124 else
11125 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11126 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11127 }
11128
11129 /// Diagnose invalid subraction on a null pointer.
11130 ///
11131 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11132 Expr *Pointer, bool BothNull) {
11133 // Null - null is valid in C++ [expr.add]p7
11134 if (BothNull && S.getLangOpts().CPlusPlus)
11135 return;
11136
11137 // Is this s a macro from a system header?
11138 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11139 return;
11140
11141 S.DiagRuntimeBehavior(Loc, Pointer,
11142 S.PDiag(diag::warn_pointer_sub_null_ptr)
11143 << S.getLangOpts().CPlusPlus
11144 << Pointer->getSourceRange());
11145 }
11146
11147 /// Diagnose invalid arithmetic on two function pointers.
11148 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11149 Expr *LHS, Expr *RHS) {
11150 assert(LHS->getType()->isAnyPointerType());
11151 assert(RHS->getType()->isAnyPointerType());
11152 S.Diag(Loc, S.getLangOpts().CPlusPlus
11153 ? diag::err_typecheck_pointer_arith_function_type
11154 : diag::ext_gnu_ptr_func_arith)
11155 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11156 // We only show the second type if it differs from the first.
11157 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11158 RHS->getType())
11159 << RHS->getType()->getPointeeType()
11160 << LHS->getSourceRange() << RHS->getSourceRange();
11161 }
11162
11163 /// Diagnose invalid arithmetic on a function pointer.
11164 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11165 Expr *Pointer) {
11166 assert(Pointer->getType()->isAnyPointerType());
11167 S.Diag(Loc, S.getLangOpts().CPlusPlus
11168 ? diag::err_typecheck_pointer_arith_function_type
11169 : diag::ext_gnu_ptr_func_arith)
11170 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11171 << 0 /* one pointer, so only one type */
11172 << Pointer->getSourceRange();
11173 }
11174
11175 /// Emit error if Operand is incomplete pointer type
11176 ///
11177 /// \returns True if pointer has incomplete type
11178 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11179 Expr *Operand) {
11180 QualType ResType = Operand->getType();
11181 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11182 ResType = ResAtomicType->getValueType();
11183
11184 assert(ResType->isAnyPointerType());
11185 QualType PointeeTy = ResType->getPointeeType();
11186 return S.RequireCompleteSizedType(
11187 Loc, PointeeTy,
11188 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11189 Operand->getSourceRange());
11190 }
11191
11192 /// Check the validity of an arithmetic pointer operand.
11193 ///
11194 /// If the operand has pointer type, this code will check for pointer types
11195 /// which are invalid in arithmetic operations. These will be diagnosed
11196 /// appropriately, including whether or not the use is supported as an
11197 /// extension.
11198 ///
11199 /// \returns True when the operand is valid to use (even if as an extension).
11200 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11201 Expr *Operand) {
11202 QualType ResType = Operand->getType();
11203 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11204 ResType = ResAtomicType->getValueType();
11205
11206 if (!ResType->isAnyPointerType()) return true;
11207
11208 QualType PointeeTy = ResType->getPointeeType();
11209 if (PointeeTy->isVoidType()) {
11210 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11211 return !S.getLangOpts().CPlusPlus;
11212 }
11213 if (PointeeTy->isFunctionType()) {
11214 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11215 return !S.getLangOpts().CPlusPlus;
11216 }
11217
11218 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11219
11220 return true;
11221 }
11222
11223 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11224 /// operands.
11225 ///
11226 /// This routine will diagnose any invalid arithmetic on pointer operands much
11227 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11228 /// for emitting a single diagnostic even for operations where both LHS and RHS
11229 /// are (potentially problematic) pointers.
11230 ///
11231 /// \returns True when the operand is valid to use (even if as an extension).
11232 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11233 Expr *LHSExpr, Expr *RHSExpr) {
11234 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11235 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11236 if (!isLHSPointer && !isRHSPointer) return true;
11237
11238 QualType LHSPointeeTy, RHSPointeeTy;
11239 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11240 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11241
11242 // if both are pointers check if operation is valid wrt address spaces
11243 if (isLHSPointer && isRHSPointer) {
11244 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11245 S.getASTContext())) {
11246 S.Diag(Loc,
11247 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11248 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11249 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11250 return false;
11251 }
11252 }
11253
11254 // Check for arithmetic on pointers to incomplete types.
11255 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11256 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11257 if (isLHSVoidPtr || isRHSVoidPtr) {
11258 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11259 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11260 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11261
11262 return !S.getLangOpts().CPlusPlus;
11263 }
11264
11265 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11266 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11267 if (isLHSFuncPtr || isRHSFuncPtr) {
11268 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11269 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11270 RHSExpr);
11271 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11272
11273 return !S.getLangOpts().CPlusPlus;
11274 }
11275
11276 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11277 return false;
11278 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11279 return false;
11280
11281 return true;
11282 }
11283
11284 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11285 /// literal.
11286 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11287 Expr *LHSExpr, Expr *RHSExpr) {
11288 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11289 Expr* IndexExpr = RHSExpr;
11290 if (!StrExpr) {
11291 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11292 IndexExpr = LHSExpr;
11293 }
11294
11295 bool IsStringPlusInt = StrExpr &&
11296 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11297 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11298 return;
11299
11300 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11301 Self.Diag(OpLoc, diag::warn_string_plus_int)
11302 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11303
11304 // Only print a fixit for "str" + int, not for int + "str".
11305 if (IndexExpr == RHSExpr) {
11306 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11307 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11308 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11309 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11310 << FixItHint::CreateInsertion(EndLoc, "]");
11311 } else
11312 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11313 }
11314
11315 /// Emit a warning when adding a char literal to a string.
11316 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11317 Expr *LHSExpr, Expr *RHSExpr) {
11318 const Expr *StringRefExpr = LHSExpr;
11319 const CharacterLiteral *CharExpr =
11320 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11321
11322 if (!CharExpr) {
11323 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11324 StringRefExpr = RHSExpr;
11325 }
11326
11327 if (!CharExpr || !StringRefExpr)
11328 return;
11329
11330 const QualType StringType = StringRefExpr->getType();
11331
11332 // Return if not a PointerType.
11333 if (!StringType->isAnyPointerType())
11334 return;
11335
11336 // Return if not a CharacterType.
11337 if (!StringType->getPointeeType()->isAnyCharacterType())
11338 return;
11339
11340 ASTContext &Ctx = Self.getASTContext();
11341 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11342
11343 const QualType CharType = CharExpr->getType();
11344 if (!CharType->isAnyCharacterType() &&
11345 CharType->isIntegerType() &&
11346 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11347 Self.Diag(OpLoc, diag::warn_string_plus_char)
11348 << DiagRange << Ctx.CharTy;
11349 } else {
11350 Self.Diag(OpLoc, diag::warn_string_plus_char)
11351 << DiagRange << CharExpr->getType();
11352 }
11353
11354 // Only print a fixit for str + char, not for char + str.
11355 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11356 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11357 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11358 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11359 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11360 << FixItHint::CreateInsertion(EndLoc, "]");
11361 } else {
11362 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11363 }
11364 }
11365
11366 /// Emit error when two pointers are incompatible.
11367 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11368 Expr *LHSExpr, Expr *RHSExpr) {
11369 assert(LHSExpr->getType()->isAnyPointerType());
11370 assert(RHSExpr->getType()->isAnyPointerType());
11371 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11372 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11373 << RHSExpr->getSourceRange();
11374 }
11375
11376 // C99 6.5.6
11377 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11378 SourceLocation Loc, BinaryOperatorKind Opc,
11379 QualType* CompLHSTy) {
11380 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11381
11382 if (LHS.get()->getType()->isVectorType() ||
11383 RHS.get()->getType()->isVectorType()) {
11384 QualType compType =
11385 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11386 /*AllowBothBool*/ getLangOpts().AltiVec,
11387 /*AllowBoolConversions*/ getLangOpts().ZVector,
11388 /*AllowBooleanOperation*/ false,
11389 /*ReportInvalid*/ true);
11390 if (CompLHSTy) *CompLHSTy = compType;
11391 return compType;
11392 }
11393
11394 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11395 RHS.get()->getType()->isSveVLSBuiltinType()) {
11396 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11397 ArithConvKind::Arithmetic);
11398 if (CompLHSTy)
11399 *CompLHSTy = compType;
11400 return compType;
11401 }
11402
11403 if (LHS.get()->getType()->isConstantMatrixType() ||
11404 RHS.get()->getType()->isConstantMatrixType()) {
11405 QualType compType =
11406 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11407 if (CompLHSTy)
11408 *CompLHSTy = compType;
11409 return compType;
11410 }
11411
11412 QualType compType = UsualArithmeticConversions(
11413 LHS, RHS, Loc,
11414 CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11415 if (LHS.isInvalid() || RHS.isInvalid())
11416 return QualType();
11417
11418 // Diagnose "string literal" '+' int and string '+' "char literal".
11419 if (Opc == BO_Add) {
11420 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11421 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11422 }
11423
11424 // handle the common case first (both operands are arithmetic).
11425 if (!compType.isNull() && compType->isArithmeticType()) {
11426 if (CompLHSTy) *CompLHSTy = compType;
11427 return compType;
11428 }
11429
11430 // Type-checking. Ultimately the pointer's going to be in PExp;
11431 // note that we bias towards the LHS being the pointer.
11432 Expr *PExp = LHS.get(), *IExp = RHS.get();
11433
11434 bool isObjCPointer;
11435 if (PExp->getType()->isPointerType()) {
11436 isObjCPointer = false;
11437 } else if (PExp->getType()->isObjCObjectPointerType()) {
11438 isObjCPointer = true;
11439 } else {
11440 std::swap(PExp, IExp);
11441 if (PExp->getType()->isPointerType()) {
11442 isObjCPointer = false;
11443 } else if (PExp->getType()->isObjCObjectPointerType()) {
11444 isObjCPointer = true;
11445 } else {
11446 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11447 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11448 return ResultTy;
11449 }
11450 }
11451 assert(PExp->getType()->isAnyPointerType());
11452
11453 if (!IExp->getType()->isIntegerType())
11454 return InvalidOperands(Loc, LHS, RHS);
11455
11456 // Adding to a null pointer results in undefined behavior.
11457 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11458 Context, Expr::NPC_ValueDependentIsNotNull)) {
11459 // In C++ adding zero to a null pointer is defined.
11460 Expr::EvalResult KnownVal;
11461 if (!getLangOpts().CPlusPlus ||
11462 (!IExp->isValueDependent() &&
11463 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11464 KnownVal.Val.getInt() != 0))) {
11465 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11466 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11467 Context, BO_Add, PExp, IExp);
11468 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11469 }
11470 }
11471
11472 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11473 return QualType();
11474
11475 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11476 return QualType();
11477
11478 // Arithmetic on label addresses is normally allowed, except when we add
11479 // a ptrauth signature to the addresses.
11480 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11481 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11482 << /*addition*/ 1;
11483 return QualType();
11484 }
11485
11486 // Check array bounds for pointer arithemtic
11487 CheckArrayAccess(PExp, IExp);
11488
11489 if (CompLHSTy) {
11490 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11491 if (LHSTy.isNull()) {
11492 LHSTy = LHS.get()->getType();
11493 if (Context.isPromotableIntegerType(LHSTy))
11494 LHSTy = Context.getPromotedIntegerType(LHSTy);
11495 }
11496 *CompLHSTy = LHSTy;
11497 }
11498
11499 return PExp->getType();
11500 }
11501
11502 // C99 6.5.6
11503 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11504 SourceLocation Loc,
11505 BinaryOperatorKind Opc,
11506 QualType *CompLHSTy) {
11507 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11508
11509 if (LHS.get()->getType()->isVectorType() ||
11510 RHS.get()->getType()->isVectorType()) {
11511 QualType compType =
11512 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11513 /*AllowBothBool*/ getLangOpts().AltiVec,
11514 /*AllowBoolConversions*/ getLangOpts().ZVector,
11515 /*AllowBooleanOperation*/ false,
11516 /*ReportInvalid*/ true);
11517 if (CompLHSTy) *CompLHSTy = compType;
11518 return compType;
11519 }
11520
11521 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11522 RHS.get()->getType()->isSveVLSBuiltinType()) {
11523 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11524 ArithConvKind::Arithmetic);
11525 if (CompLHSTy)
11526 *CompLHSTy = compType;
11527 return compType;
11528 }
11529
11530 if (LHS.get()->getType()->isConstantMatrixType() ||
11531 RHS.get()->getType()->isConstantMatrixType()) {
11532 QualType compType =
11533 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11534 if (CompLHSTy)
11535 *CompLHSTy = compType;
11536 return compType;
11537 }
11538
11539 QualType compType = UsualArithmeticConversions(
11540 LHS, RHS, Loc,
11541 CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11542 if (LHS.isInvalid() || RHS.isInvalid())
11543 return QualType();
11544
11545 // Enforce type constraints: C99 6.5.6p3.
11546
11547 // Handle the common case first (both operands are arithmetic).
11548 if (!compType.isNull() && compType->isArithmeticType()) {
11549 if (CompLHSTy) *CompLHSTy = compType;
11550 return compType;
11551 }
11552
11553 // Either ptr - int or ptr - ptr.
11554 if (LHS.get()->getType()->isAnyPointerType()) {
11555 QualType lpointee = LHS.get()->getType()->getPointeeType();
11556
11557 // Diagnose bad cases where we step over interface counts.
11558 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11559 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11560 return QualType();
11561
11562 // Arithmetic on label addresses is normally allowed, except when we add
11563 // a ptrauth signature to the addresses.
11564 if (isa<AddrLabelExpr>(LHS.get()) &&
11565 getLangOpts().PointerAuthIndirectGotos) {
11566 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11567 << /*subtraction*/ 0;
11568 return QualType();
11569 }
11570
11571 // The result type of a pointer-int computation is the pointer type.
11572 if (RHS.get()->getType()->isIntegerType()) {
11573 // Subtracting from a null pointer should produce a warning.
11574 // The last argument to the diagnose call says this doesn't match the
11575 // GNU int-to-pointer idiom.
11576 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11577 Expr::NPC_ValueDependentIsNotNull)) {
11578 // In C++ adding zero to a null pointer is defined.
11579 Expr::EvalResult KnownVal;
11580 if (!getLangOpts().CPlusPlus ||
11581 (!RHS.get()->isValueDependent() &&
11582 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11583 KnownVal.Val.getInt() != 0))) {
11584 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11585 }
11586 }
11587
11588 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11589 return QualType();
11590
11591 // Check array bounds for pointer arithemtic
11592 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11593 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11594
11595 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11596 return LHS.get()->getType();
11597 }
11598
11599 // Handle pointer-pointer subtractions.
11600 if (const PointerType *RHSPTy
11601 = RHS.get()->getType()->getAs<PointerType>()) {
11602 QualType rpointee = RHSPTy->getPointeeType();
11603
11604 if (getLangOpts().CPlusPlus) {
11605 // Pointee types must be the same: C++ [expr.add]
11606 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11607 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11608 }
11609 } else {
11610 // Pointee types must be compatible C99 6.5.6p3
11611 if (!Context.typesAreCompatible(
11612 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11613 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11614 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11615 return QualType();
11616 }
11617 }
11618
11619 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11620 LHS.get(), RHS.get()))
11621 return QualType();
11622
11623 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11624 Context, Expr::NPC_ValueDependentIsNotNull);
11625 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11626 Context, Expr::NPC_ValueDependentIsNotNull);
11627
11628 // Subtracting nullptr or from nullptr is suspect
11629 if (LHSIsNullPtr)
11630 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11631 if (RHSIsNullPtr)
11632 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11633
11634 // The pointee type may have zero size. As an extension, a structure or
11635 // union may have zero size or an array may have zero length. In this
11636 // case subtraction does not make sense.
11637 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11638 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11639 if (ElementSize.isZero()) {
11640 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11641 << rpointee.getUnqualifiedType()
11642 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11643 }
11644 }
11645
11646 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11647 return Context.getPointerDiffType();
11648 }
11649 }
11650
11651 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11652 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11653 return ResultTy;
11654 }
11655
11656 static bool isScopedEnumerationType(QualType T) {
11657 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11658 return ET->getDecl()->isScoped();
11659 return false;
11660 }
11661
11662 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11663 SourceLocation Loc, BinaryOperatorKind Opc,
11664 QualType LHSType) {
11665 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11666 // so skip remaining warnings as we don't want to modify values within Sema.
11667 if (S.getLangOpts().OpenCL)
11668 return;
11669
11670 if (Opc == BO_Shr &&
11671 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11672 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11673
11674 // Check right/shifter operand
11675 Expr::EvalResult RHSResult;
11676 if (RHS.get()->isValueDependent() ||
11677 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11678 return;
11679 llvm::APSInt Right = RHSResult.Val.getInt();
11680
11681 if (Right.isNegative()) {
11682 S.DiagRuntimeBehavior(Loc, RHS.get(),
11683 S.PDiag(diag::warn_shift_negative)
11684 << RHS.get()->getSourceRange());
11685 return;
11686 }
11687
11688 QualType LHSExprType = LHS.get()->getType();
11689 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11690 if (LHSExprType->isBitIntType())
11691 LeftSize = S.Context.getIntWidth(LHSExprType);
11692 else if (LHSExprType->isFixedPointType()) {
11693 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11694 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11695 }
11696 if (Right.uge(LeftSize)) {
11697 S.DiagRuntimeBehavior(Loc, RHS.get(),
11698 S.PDiag(diag::warn_shift_gt_typewidth)
11699 << RHS.get()->getSourceRange());
11700 return;
11701 }
11702
11703 // FIXME: We probably need to handle fixed point types specially here.
11704 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11705 return;
11706
11707 // When left shifting an ICE which is signed, we can check for overflow which
11708 // according to C++ standards prior to C++2a has undefined behavior
11709 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11710 // more than the maximum value representable in the result type, so never
11711 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11712 // expression is still probably a bug.)
11713 Expr::EvalResult LHSResult;
11714 if (LHS.get()->isValueDependent() ||
11715 LHSType->hasUnsignedIntegerRepresentation() ||
11716 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11717 return;
11718 llvm::APSInt Left = LHSResult.Val.getInt();
11719
11720 // Don't warn if signed overflow is defined, then all the rest of the
11721 // diagnostics will not be triggered because the behavior is defined.
11722 // Also don't warn in C++20 mode (and newer), as signed left shifts
11723 // always wrap and never overflow.
11724 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11725 return;
11726
11727 // If LHS does not have a non-negative value then, the
11728 // behavior is undefined before C++2a. Warn about it.
11729 if (Left.isNegative()) {
11730 S.DiagRuntimeBehavior(Loc, LHS.get(),
11731 S.PDiag(diag::warn_shift_lhs_negative)
11732 << LHS.get()->getSourceRange());
11733 return;
11734 }
11735
11736 llvm::APInt ResultBits =
11737 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11738 if (ResultBits.ule(LeftSize))
11739 return;
11740 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11741 Result = Result.shl(Right);
11742
11743 // Print the bit representation of the signed integer as an unsigned
11744 // hexadecimal number.
11745 SmallString<40> HexResult;
11746 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11747
11748 // If we are only missing a sign bit, this is less likely to result in actual
11749 // bugs -- if the result is cast back to an unsigned type, it will have the
11750 // expected value. Thus we place this behind a different warning that can be
11751 // turned off separately if needed.
11752 if (ResultBits - 1 == LeftSize) {
11753 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11754 << HexResult << LHSType
11755 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11756 return;
11757 }
11758
11759 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11760 << HexResult.str() << Result.getSignificantBits() << LHSType
11761 << Left.getBitWidth() << LHS.get()->getSourceRange()
11762 << RHS.get()->getSourceRange();
11763 }
11764
11765 /// Return the resulting type when a vector is shifted
11766 /// by a scalar or vector shift amount.
11767 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11768 SourceLocation Loc, bool IsCompAssign) {
11769 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11770 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11771 !LHS.get()->getType()->isVectorType()) {
11772 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11773 << RHS.get()->getType() << LHS.get()->getType()
11774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11775 return QualType();
11776 }
11777
11778 if (!IsCompAssign) {
11779 LHS = S.UsualUnaryConversions(LHS.get());
11780 if (LHS.isInvalid()) return QualType();
11781 }
11782
11783 RHS = S.UsualUnaryConversions(RHS.get());
11784 if (RHS.isInvalid()) return QualType();
11785
11786 QualType LHSType = LHS.get()->getType();
11787 // Note that LHS might be a scalar because the routine calls not only in
11788 // OpenCL case.
11789 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11790 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11791
11792 // Note that RHS might not be a vector.
11793 QualType RHSType = RHS.get()->getType();
11794 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11795 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11796
11797 // Do not allow shifts for boolean vectors.
11798 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11799 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11800 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11801 << LHS.get()->getType() << RHS.get()->getType()
11802 << LHS.get()->getSourceRange();
11803 return QualType();
11804 }
11805
11806 // The operands need to be integers.
11807 if (!LHSEleType->isIntegerType()) {
11808 S.Diag(Loc, diag::err_typecheck_expect_int)
11809 << LHS.get()->getType() << LHS.get()->getSourceRange();
11810 return QualType();
11811 }
11812
11813 if (!RHSEleType->isIntegerType()) {
11814 S.Diag(Loc, diag::err_typecheck_expect_int)
11815 << RHS.get()->getType() << RHS.get()->getSourceRange();
11816 return QualType();
11817 }
11818
11819 if (!LHSVecTy) {
11820 assert(RHSVecTy);
11821 if (IsCompAssign)
11822 return RHSType;
11823 if (LHSEleType != RHSEleType) {
11824 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11825 LHSEleType = RHSEleType;
11826 }
11827 QualType VecTy =
11828 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11829 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11830 LHSType = VecTy;
11831 } else if (RHSVecTy) {
11832 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11833 // are applied component-wise. So if RHS is a vector, then ensure
11834 // that the number of elements is the same as LHS...
11835 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11836 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11837 << LHS.get()->getType() << RHS.get()->getType()
11838 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11839 return QualType();
11840 }
11841 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11842 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11843 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11844 if (LHSBT != RHSBT &&
11845 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11846 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11847 << LHS.get()->getType() << RHS.get()->getType()
11848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11849 }
11850 }
11851 } else {
11852 // ...else expand RHS to match the number of elements in LHS.
11853 QualType VecTy =
11854 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11855 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11856 }
11857
11858 return LHSType;
11859 }
11860
11861 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11862 ExprResult &RHS, SourceLocation Loc,
11863 bool IsCompAssign) {
11864 if (!IsCompAssign) {
11865 LHS = S.UsualUnaryConversions(LHS.get());
11866 if (LHS.isInvalid())
11867 return QualType();
11868 }
11869
11870 RHS = S.UsualUnaryConversions(RHS.get());
11871 if (RHS.isInvalid())
11872 return QualType();
11873
11874 QualType LHSType = LHS.get()->getType();
11875 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11876 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11877 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11878 : LHSType;
11879
11880 // Note that RHS might not be a vector
11881 QualType RHSType = RHS.get()->getType();
11882 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11883 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11884 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11885 : RHSType;
11886
11887 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11888 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11889 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11890 << LHSType << RHSType << LHS.get()->getSourceRange();
11891 return QualType();
11892 }
11893
11894 if (!LHSEleType->isIntegerType()) {
11895 S.Diag(Loc, diag::err_typecheck_expect_int)
11896 << LHS.get()->getType() << LHS.get()->getSourceRange();
11897 return QualType();
11898 }
11899
11900 if (!RHSEleType->isIntegerType()) {
11901 S.Diag(Loc, diag::err_typecheck_expect_int)
11902 << RHS.get()->getType() << RHS.get()->getSourceRange();
11903 return QualType();
11904 }
11905
11906 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11907 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11908 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11909 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11910 << LHSType << RHSType << LHS.get()->getSourceRange()
11911 << RHS.get()->getSourceRange();
11912 return QualType();
11913 }
11914
11915 if (!LHSType->isSveVLSBuiltinType()) {
11916 assert(RHSType->isSveVLSBuiltinType());
11917 if (IsCompAssign)
11918 return RHSType;
11919 if (LHSEleType != RHSEleType) {
11920 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11921 LHSEleType = RHSEleType;
11922 }
11923 const llvm::ElementCount VecSize =
11924 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11925 QualType VecTy =
11926 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11927 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11928 LHSType = VecTy;
11929 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11930 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11931 S.Context.getTypeSize(LHSBuiltinTy)) {
11932 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11933 << LHSType << RHSType << LHS.get()->getSourceRange()
11934 << RHS.get()->getSourceRange();
11935 return QualType();
11936 }
11937 } else {
11938 const llvm::ElementCount VecSize =
11939 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11940 if (LHSEleType != RHSEleType) {
11941 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11942 RHSEleType = LHSEleType;
11943 }
11944 QualType VecTy =
11945 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11946 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11947 }
11948
11949 return LHSType;
11950 }
11951
11952 // C99 6.5.7
11953 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11954 SourceLocation Loc, BinaryOperatorKind Opc,
11955 bool IsCompAssign) {
11956 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11957
11958 // Vector shifts promote their scalar inputs to vector type.
11959 if (LHS.get()->getType()->isVectorType() ||
11960 RHS.get()->getType()->isVectorType()) {
11961 if (LangOpts.ZVector) {
11962 // The shift operators for the z vector extensions work basically
11963 // like general shifts, except that neither the LHS nor the RHS is
11964 // allowed to be a "vector bool".
11965 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11966 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11967 return InvalidOperands(Loc, LHS, RHS);
11968 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11969 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11970 return InvalidOperands(Loc, LHS, RHS);
11971 }
11972 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11973 }
11974
11975 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11976 RHS.get()->getType()->isSveVLSBuiltinType())
11977 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11978
11979 // Shifts don't perform usual arithmetic conversions, they just do integer
11980 // promotions on each operand. C99 6.5.7p3
11981
11982 // For the LHS, do usual unary conversions, but then reset them away
11983 // if this is a compound assignment.
11984 ExprResult OldLHS = LHS;
11985 LHS = UsualUnaryConversions(LHS.get());
11986 if (LHS.isInvalid())
11987 return QualType();
11988 QualType LHSType = LHS.get()->getType();
11989 if (IsCompAssign) LHS = OldLHS;
11990
11991 // The RHS is simpler.
11992 RHS = UsualUnaryConversions(RHS.get());
11993 if (RHS.isInvalid())
11994 return QualType();
11995 QualType RHSType = RHS.get()->getType();
11996
11997 // C99 6.5.7p2: Each of the operands shall have integer type.
11998 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11999 if ((!LHSType->isFixedPointOrIntegerType() &&
12000 !LHSType->hasIntegerRepresentation()) ||
12001 !RHSType->hasIntegerRepresentation()) {
12002 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12003 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12004 return ResultTy;
12005 }
12006
12007 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12008
12009 // "The type of the result is that of the promoted left operand."
12010 return LHSType;
12011 }
12012
12013 /// Diagnose bad pointer comparisons.
12014 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12015 ExprResult &LHS, ExprResult &RHS,
12016 bool IsError) {
12017 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12018 : diag::ext_typecheck_comparison_of_distinct_pointers)
12019 << LHS.get()->getType() << RHS.get()->getType()
12020 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12021 }
12022
12023 /// Returns false if the pointers are converted to a composite type,
12024 /// true otherwise.
12025 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12026 ExprResult &LHS, ExprResult &RHS) {
12027 // C++ [expr.rel]p2:
12028 // [...] Pointer conversions (4.10) and qualification
12029 // conversions (4.4) are performed on pointer operands (or on
12030 // a pointer operand and a null pointer constant) to bring
12031 // them to their composite pointer type. [...]
12032 //
12033 // C++ [expr.eq]p1 uses the same notion for (in)equality
12034 // comparisons of pointers.
12035
12036 QualType LHSType = LHS.get()->getType();
12037 QualType RHSType = RHS.get()->getType();
12038 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12039 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12040
12041 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12042 if (T.isNull()) {
12043 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12044 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12045 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12046 else
12047 S.InvalidOperands(Loc, LHS, RHS);
12048 return true;
12049 }
12050
12051 return false;
12052 }
12053
12054 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12055 ExprResult &LHS,
12056 ExprResult &RHS,
12057 bool IsError) {
12058 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12059 : diag::ext_typecheck_comparison_of_fptr_to_void)
12060 << LHS.get()->getType() << RHS.get()->getType()
12061 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12062 }
12063
12064 static bool isObjCObjectLiteral(ExprResult &E) {
12065 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12066 case Stmt::ObjCArrayLiteralClass:
12067 case Stmt::ObjCDictionaryLiteralClass:
12068 case Stmt::ObjCStringLiteralClass:
12069 case Stmt::ObjCBoxedExprClass:
12070 return true;
12071 default:
12072 // Note that ObjCBoolLiteral is NOT an object literal!
12073 return false;
12074 }
12075 }
12076
12077 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12078 const ObjCObjectPointerType *Type =
12079 LHS->getType()->getAs<ObjCObjectPointerType>();
12080
12081 // If this is not actually an Objective-C object, bail out.
12082 if (!Type)
12083 return false;
12084
12085 // Get the LHS object's interface type.
12086 QualType InterfaceType = Type->getPointeeType();
12087
12088 // If the RHS isn't an Objective-C object, bail out.
12089 if (!RHS->getType()->isObjCObjectPointerType())
12090 return false;
12091
12092 // Try to find the -isEqual: method.
12093 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12094 ObjCMethodDecl *Method =
12095 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12096 /*IsInstance=*/true);
12097 if (!Method) {
12098 if (Type->isObjCIdType()) {
12099 // For 'id', just check the global pool.
12100 Method =
12101 S.ObjC().LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12102 /*receiverId=*/true);
12103 } else {
12104 // Check protocols.
12105 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12106 /*IsInstance=*/true);
12107 }
12108 }
12109
12110 if (!Method)
12111 return false;
12112
12113 QualType T = Method->parameters()[0]->getType();
12114 if (!T->isObjCObjectPointerType())
12115 return false;
12116
12117 QualType R = Method->getReturnType();
12118 if (!R->isScalarType())
12119 return false;
12120
12121 return true;
12122 }
12123
12124 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12125 ExprResult &LHS, ExprResult &RHS,
12126 BinaryOperator::Opcode Opc){
12127 Expr *Literal;
12128 Expr *Other;
12129 if (isObjCObjectLiteral(LHS)) {
12130 Literal = LHS.get();
12131 Other = RHS.get();
12132 } else {
12133 Literal = RHS.get();
12134 Other = LHS.get();
12135 }
12136
12137 // Don't warn on comparisons against nil.
12138 Other = Other->IgnoreParenCasts();
12139 if (Other->isNullPointerConstant(S.getASTContext(),
12140 Expr::NPC_ValueDependentIsNotNull))
12141 return;
12142
12143 // This should be kept in sync with warn_objc_literal_comparison.
12144 // LK_String should always be after the other literals, since it has its own
12145 // warning flag.
12146 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12147 assert(LiteralKind != SemaObjC::LK_Block);
12148 if (LiteralKind == SemaObjC::LK_None) {
12149 llvm_unreachable("Unknown Objective-C object literal kind");
12150 }
12151
12152 if (LiteralKind == SemaObjC::LK_String)
12153 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12154 << Literal->getSourceRange();
12155 else
12156 S.Diag(Loc, diag::warn_objc_literal_comparison)
12157 << LiteralKind << Literal->getSourceRange();
12158
12159 if (BinaryOperator::isEqualityOp(Opc) &&
12160 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12161 SourceLocation Start = LHS.get()->getBeginLoc();
12162 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12163 CharSourceRange OpRange =
12164 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12165
12166 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12167 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12168 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12169 << FixItHint::CreateInsertion(End, "]");
12170 }
12171 }
12172
12173 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12174 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12175 ExprResult &RHS, SourceLocation Loc,
12176 BinaryOperatorKind Opc) {
12177 // Check that left hand side is !something.
12178 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12179 if (!UO || UO->getOpcode() != UO_LNot) return;
12180
12181 // Only check if the right hand side is non-bool arithmetic type.
12182 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12183
12184 // Make sure that the something in !something is not bool.
12185 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12186 if (SubExpr->isKnownToHaveBooleanValue()) return;
12187
12188 // Emit warning.
12189 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12190 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12191 << Loc << IsBitwiseOp;
12192
12193 // First note suggest !(x < y)
12194 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12195 SourceLocation FirstClose = RHS.get()->getEndLoc();
12196 FirstClose = S.getLocForEndOfToken(FirstClose);
12197 if (FirstClose.isInvalid())
12198 FirstOpen = SourceLocation();
12199 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12200 << IsBitwiseOp
12201 << FixItHint::CreateInsertion(FirstOpen, "(")
12202 << FixItHint::CreateInsertion(FirstClose, ")");
12203
12204 // Second note suggests (!x) < y
12205 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12206 SourceLocation SecondClose = LHS.get()->getEndLoc();
12207 SecondClose = S.getLocForEndOfToken(SecondClose);
12208 if (SecondClose.isInvalid())
12209 SecondOpen = SourceLocation();
12210 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12211 << FixItHint::CreateInsertion(SecondOpen, "(")
12212 << FixItHint::CreateInsertion(SecondClose, ")");
12213 }
12214
12215 // Returns true if E refers to a non-weak array.
12216 static bool checkForArray(const Expr *E) {
12217 const ValueDecl *D = nullptr;
12218 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12219 D = DR->getDecl();
12220 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12221 if (Mem->isImplicitAccess())
12222 D = Mem->getMemberDecl();
12223 }
12224 if (!D)
12225 return false;
12226 return D->getType()->isArrayType() && !D->isWeak();
12227 }
12228
12229 /// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12230 /// pointer and size is an unsigned integer. Return whether the result is
12231 /// always true/false.
12232 static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12233 const Expr *RHS,
12234 BinaryOperatorKind Opc) {
12235 if (!LHS->getType()->isPointerType() ||
12236 S.getLangOpts().PointerOverflowDefined)
12237 return std::nullopt;
12238
12239 // Canonicalize to >= or < predicate.
12240 switch (Opc) {
12241 case BO_GE:
12242 case BO_LT:
12243 break;
12244 case BO_GT:
12245 std::swap(LHS, RHS);
12246 Opc = BO_LT;
12247 break;
12248 case BO_LE:
12249 std::swap(LHS, RHS);
12250 Opc = BO_GE;
12251 break;
12252 default:
12253 return std::nullopt;
12254 }
12255
12256 auto *BO = dyn_cast<BinaryOperator>(LHS);
12257 if (!BO || BO->getOpcode() != BO_Add)
12258 return std::nullopt;
12259
12260 Expr *Other;
12261 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12262 Other = BO->getRHS();
12263 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12264 Other = BO->getLHS();
12265 else
12266 return std::nullopt;
12267
12268 if (!Other->getType()->isUnsignedIntegerType())
12269 return std::nullopt;
12270
12271 return Opc == BO_GE;
12272 }
12273
12274 /// Diagnose some forms of syntactically-obvious tautological comparison.
12275 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12276 Expr *LHS, Expr *RHS,
12277 BinaryOperatorKind Opc) {
12278 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12279 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12280
12281 QualType LHSType = LHS->getType();
12282 QualType RHSType = RHS->getType();
12283 if (LHSType->hasFloatingRepresentation() ||
12284 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12285 S.inTemplateInstantiation())
12286 return;
12287
12288 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12289 // Tautological diagnostics.
12290 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12291 return;
12292
12293 // Comparisons between two array types are ill-formed for operator<=>, so
12294 // we shouldn't emit any additional warnings about it.
12295 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12296 return;
12297
12298 // For non-floating point types, check for self-comparisons of the form
12299 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12300 // often indicate logic errors in the program.
12301 //
12302 // NOTE: Don't warn about comparison expressions resulting from macro
12303 // expansion. Also don't warn about comparisons which are only self
12304 // comparisons within a template instantiation. The warnings should catch
12305 // obvious cases in the definition of the template anyways. The idea is to
12306 // warn when the typed comparison operator will always evaluate to the same
12307 // result.
12308
12309 // Used for indexing into %select in warn_comparison_always
12310 enum {
12311 AlwaysConstant,
12312 AlwaysTrue,
12313 AlwaysFalse,
12314 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12315 };
12316
12317 // C++1a [array.comp]:
12318 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12319 // operands of array type.
12320 // C++2a [depr.array.comp]:
12321 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12322 // operands of array type are deprecated.
12323 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12324 RHSStripped->getType()->isArrayType()) {
12325 auto IsDeprArrayComparionIgnored =
12326 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12327 auto DiagID = S.getLangOpts().CPlusPlus26
12328 ? diag::warn_array_comparison_cxx26
12329 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12330 ? diag::warn_array_comparison
12331 : diag::warn_depr_array_comparison;
12332 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12333 << LHSStripped->getType() << RHSStripped->getType();
12334 // Carry on to produce the tautological comparison warning, if this
12335 // expression is potentially-evaluated, we can resolve the array to a
12336 // non-weak declaration, and so on.
12337 }
12338
12339 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12340 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12341 unsigned Result;
12342 switch (Opc) {
12343 case BO_EQ:
12344 case BO_LE:
12345 case BO_GE:
12346 Result = AlwaysTrue;
12347 break;
12348 case BO_NE:
12349 case BO_LT:
12350 case BO_GT:
12351 Result = AlwaysFalse;
12352 break;
12353 case BO_Cmp:
12354 Result = AlwaysEqual;
12355 break;
12356 default:
12357 Result = AlwaysConstant;
12358 break;
12359 }
12360 S.DiagRuntimeBehavior(Loc, nullptr,
12361 S.PDiag(diag::warn_comparison_always)
12362 << 0 /*self-comparison*/
12363 << Result);
12364 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12365 // What is it always going to evaluate to?
12366 unsigned Result;
12367 switch (Opc) {
12368 case BO_EQ: // e.g. array1 == array2
12369 Result = AlwaysFalse;
12370 break;
12371 case BO_NE: // e.g. array1 != array2
12372 Result = AlwaysTrue;
12373 break;
12374 default: // e.g. array1 <= array2
12375 // The best we can say is 'a constant'
12376 Result = AlwaysConstant;
12377 break;
12378 }
12379 S.DiagRuntimeBehavior(Loc, nullptr,
12380 S.PDiag(diag::warn_comparison_always)
12381 << 1 /*array comparison*/
12382 << Result);
12383 } else if (std::optional<bool> Res =
12384 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12385 S.DiagRuntimeBehavior(Loc, nullptr,
12386 S.PDiag(diag::warn_comparison_always)
12387 << 2 /*pointer comparison*/
12388 << (*Res ? AlwaysTrue : AlwaysFalse));
12389 }
12390 }
12391
12392 if (isa<CastExpr>(LHSStripped))
12393 LHSStripped = LHSStripped->IgnoreParenCasts();
12394 if (isa<CastExpr>(RHSStripped))
12395 RHSStripped = RHSStripped->IgnoreParenCasts();
12396
12397 // Warn about comparisons against a string constant (unless the other
12398 // operand is null); the user probably wants string comparison function.
12399 Expr *LiteralString = nullptr;
12400 Expr *LiteralStringStripped = nullptr;
12401 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12402 !RHSStripped->isNullPointerConstant(S.Context,
12403 Expr::NPC_ValueDependentIsNull)) {
12404 LiteralString = LHS;
12405 LiteralStringStripped = LHSStripped;
12406 } else if ((isa<StringLiteral>(RHSStripped) ||
12407 isa<ObjCEncodeExpr>(RHSStripped)) &&
12408 !LHSStripped->isNullPointerConstant(S.Context,
12409 Expr::NPC_ValueDependentIsNull)) {
12410 LiteralString = RHS;
12411 LiteralStringStripped = RHSStripped;
12412 }
12413
12414 if (LiteralString) {
12415 S.DiagRuntimeBehavior(Loc, nullptr,
12416 S.PDiag(diag::warn_stringcompare)
12417 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12418 << LiteralString->getSourceRange());
12419 }
12420 }
12421
12422 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12423 switch (CK) {
12424 default: {
12425 #ifndef NDEBUG
12426 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12427 << "\n";
12428 #endif
12429 llvm_unreachable("unhandled cast kind");
12430 }
12431 case CK_UserDefinedConversion:
12432 return ICK_Identity;
12433 case CK_LValueToRValue:
12434 return ICK_Lvalue_To_Rvalue;
12435 case CK_ArrayToPointerDecay:
12436 return ICK_Array_To_Pointer;
12437 case CK_FunctionToPointerDecay:
12438 return ICK_Function_To_Pointer;
12439 case CK_IntegralCast:
12440 return ICK_Integral_Conversion;
12441 case CK_FloatingCast:
12442 return ICK_Floating_Conversion;
12443 case CK_IntegralToFloating:
12444 case CK_FloatingToIntegral:
12445 return ICK_Floating_Integral;
12446 case CK_IntegralComplexCast:
12447 case CK_FloatingComplexCast:
12448 case CK_FloatingComplexToIntegralComplex:
12449 case CK_IntegralComplexToFloatingComplex:
12450 return ICK_Complex_Conversion;
12451 case CK_FloatingComplexToReal:
12452 case CK_FloatingRealToComplex:
12453 case CK_IntegralComplexToReal:
12454 case CK_IntegralRealToComplex:
12455 return ICK_Complex_Real;
12456 case CK_HLSLArrayRValue:
12457 return ICK_HLSL_Array_RValue;
12458 }
12459 }
12460
12461 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12462 QualType FromType,
12463 SourceLocation Loc) {
12464 // Check for a narrowing implicit conversion.
12465 StandardConversionSequence SCS;
12466 SCS.setAsIdentityConversion();
12467 SCS.setToType(0, FromType);
12468 SCS.setToType(1, ToType);
12469 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12470 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12471
12472 APValue PreNarrowingValue;
12473 QualType PreNarrowingType;
12474 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12475 PreNarrowingType,
12476 /*IgnoreFloatToIntegralConversion*/ true)) {
12477 case NK_Dependent_Narrowing:
12478 // Implicit conversion to a narrower type, but the expression is
12479 // value-dependent so we can't tell whether it's actually narrowing.
12480 case NK_Not_Narrowing:
12481 return false;
12482
12483 case NK_Constant_Narrowing:
12484 // Implicit conversion to a narrower type, and the value is not a constant
12485 // expression.
12486 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12487 << /*Constant*/ 1
12488 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12489 return true;
12490
12491 case NK_Variable_Narrowing:
12492 // Implicit conversion to a narrower type, and the value is not a constant
12493 // expression.
12494 case NK_Type_Narrowing:
12495 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12496 << /*Constant*/ 0 << FromType << ToType;
12497 // TODO: It's not a constant expression, but what if the user intended it
12498 // to be? Can we produce notes to help them figure out why it isn't?
12499 return true;
12500 }
12501 llvm_unreachable("unhandled case in switch");
12502 }
12503
12504 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12505 ExprResult &LHS,
12506 ExprResult &RHS,
12507 SourceLocation Loc) {
12508 QualType LHSType = LHS.get()->getType();
12509 QualType RHSType = RHS.get()->getType();
12510 // Dig out the original argument type and expression before implicit casts
12511 // were applied. These are the types/expressions we need to check the
12512 // [expr.spaceship] requirements against.
12513 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12514 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12515 QualType LHSStrippedType = LHSStripped.get()->getType();
12516 QualType RHSStrippedType = RHSStripped.get()->getType();
12517
12518 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12519 // other is not, the program is ill-formed.
12520 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12521 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12522 return QualType();
12523 }
12524
12525 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12526 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12527 RHSStrippedType->isEnumeralType();
12528 if (NumEnumArgs == 1) {
12529 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12530 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12531 if (OtherTy->hasFloatingRepresentation()) {
12532 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12533 return QualType();
12534 }
12535 }
12536 if (NumEnumArgs == 2) {
12537 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12538 // type E, the operator yields the result of converting the operands
12539 // to the underlying type of E and applying <=> to the converted operands.
12540 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12541 S.InvalidOperands(Loc, LHS, RHS);
12542 return QualType();
12543 }
12544 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12545 assert(IntType->isArithmeticType());
12546
12547 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12548 // promote the boolean type, and all other promotable integer types, to
12549 // avoid this.
12550 if (S.Context.isPromotableIntegerType(IntType))
12551 IntType = S.Context.getPromotedIntegerType(IntType);
12552
12553 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12554 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12555 LHSType = RHSType = IntType;
12556 }
12557
12558 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12559 // usual arithmetic conversions are applied to the operands.
12560 QualType Type =
12561 S.UsualArithmeticConversions(LHS, RHS, Loc, ArithConvKind::Comparison);
12562 if (LHS.isInvalid() || RHS.isInvalid())
12563 return QualType();
12564 if (Type.isNull()) {
12565 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12566 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12567 return ResultTy;
12568 }
12569
12570 std::optional<ComparisonCategoryType> CCT =
12571 getComparisonCategoryForBuiltinCmp(Type);
12572 if (!CCT)
12573 return S.InvalidOperands(Loc, LHS, RHS);
12574
12575 bool HasNarrowing = checkThreeWayNarrowingConversion(
12576 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12577 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12578 RHS.get()->getBeginLoc());
12579 if (HasNarrowing)
12580 return QualType();
12581
12582 assert(!Type.isNull() && "composite type for <=> has not been set");
12583
12584 return S.CheckComparisonCategoryType(
12585 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12586 }
12587
12588 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12589 ExprResult &RHS,
12590 SourceLocation Loc,
12591 BinaryOperatorKind Opc) {
12592 if (Opc == BO_Cmp)
12593 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12594
12595 // C99 6.5.8p3 / C99 6.5.9p4
12596 QualType Type =
12597 S.UsualArithmeticConversions(LHS, RHS, Loc, ArithConvKind::Comparison);
12598 if (LHS.isInvalid() || RHS.isInvalid())
12599 return QualType();
12600 if (Type.isNull()) {
12601 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12602 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12603 return ResultTy;
12604 }
12605 assert(Type->isArithmeticType() || Type->isEnumeralType());
12606
12607 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12608 return S.InvalidOperands(Loc, LHS, RHS);
12609
12610 // Check for comparisons of floating point operands using != and ==.
12611 if (Type->hasFloatingRepresentation())
12612 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12613
12614 // The result of comparisons is 'bool' in C++, 'int' in C.
12615 return S.Context.getLogicalOperationType();
12616 }
12617
12618 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12619 if (!NullE.get()->getType()->isAnyPointerType())
12620 return;
12621 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12622 if (!E.get()->getType()->isAnyPointerType() &&
12623 E.get()->isNullPointerConstant(Context,
12624 Expr::NPC_ValueDependentIsNotNull) ==
12625 Expr::NPCK_ZeroExpression) {
12626 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12627 if (CL->getValue() == 0)
12628 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12629 << NullValue
12630 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12631 NullValue ? "NULL" : "(void *)0");
12632 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12633 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12634 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12635 if (T == Context.CharTy)
12636 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12637 << NullValue
12638 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12639 NullValue ? "NULL" : "(void *)0");
12640 }
12641 }
12642 }
12643
12644 // C99 6.5.8, C++ [expr.rel]
12645 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12646 SourceLocation Loc,
12647 BinaryOperatorKind Opc) {
12648 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12649 bool IsThreeWay = Opc == BO_Cmp;
12650 bool IsOrdered = IsRelational || IsThreeWay;
12651 auto IsAnyPointerType = [](ExprResult E) {
12652 QualType Ty = E.get()->getType();
12653 return Ty->isPointerType() || Ty->isMemberPointerType();
12654 };
12655
12656 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12657 // type, array-to-pointer, ..., conversions are performed on both operands to
12658 // bring them to their composite type.
12659 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12660 // any type-related checks.
12661 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12662 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12663 if (LHS.isInvalid())
12664 return QualType();
12665 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12666 if (RHS.isInvalid())
12667 return QualType();
12668 } else {
12669 LHS = DefaultLvalueConversion(LHS.get());
12670 if (LHS.isInvalid())
12671 return QualType();
12672 RHS = DefaultLvalueConversion(RHS.get());
12673 if (RHS.isInvalid())
12674 return QualType();
12675 }
12676
12677 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12678 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12679 CheckPtrComparisonWithNullChar(LHS, RHS);
12680 CheckPtrComparisonWithNullChar(RHS, LHS);
12681 }
12682
12683 // Handle vector comparisons separately.
12684 if (LHS.get()->getType()->isVectorType() ||
12685 RHS.get()->getType()->isVectorType())
12686 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12687
12688 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12689 RHS.get()->getType()->isSveVLSBuiltinType())
12690 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12691
12692 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12693 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12694
12695 QualType LHSType = LHS.get()->getType();
12696 QualType RHSType = RHS.get()->getType();
12697 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12698 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12699 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12700
12701 if ((LHSType->isPointerType() &&
12702 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12703 (RHSType->isPointerType() &&
12704 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12705 return InvalidOperands(Loc, LHS, RHS);
12706
12707 const Expr::NullPointerConstantKind LHSNullKind =
12708 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12709 const Expr::NullPointerConstantKind RHSNullKind =
12710 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12711 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12712 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12713
12714 auto computeResultTy = [&]() {
12715 if (Opc != BO_Cmp)
12716 return QualType(Context.getLogicalOperationType());
12717 assert(getLangOpts().CPlusPlus);
12718 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12719
12720 QualType CompositeTy = LHS.get()->getType();
12721 assert(!CompositeTy->isReferenceType());
12722
12723 std::optional<ComparisonCategoryType> CCT =
12724 getComparisonCategoryForBuiltinCmp(CompositeTy);
12725 if (!CCT)
12726 return InvalidOperands(Loc, LHS, RHS);
12727
12728 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12729 // P0946R0: Comparisons between a null pointer constant and an object
12730 // pointer result in std::strong_equality, which is ill-formed under
12731 // P1959R0.
12732 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12733 << (LHSIsNull ? LHS.get()->getSourceRange()
12734 : RHS.get()->getSourceRange());
12735 return QualType();
12736 }
12737
12738 return CheckComparisonCategoryType(
12739 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12740 };
12741
12742 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12743 bool IsEquality = Opc == BO_EQ;
12744 if (RHSIsNull)
12745 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12746 RHS.get()->getSourceRange());
12747 else
12748 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12749 LHS.get()->getSourceRange());
12750 }
12751
12752 if (IsOrdered && LHSType->isFunctionPointerType() &&
12753 RHSType->isFunctionPointerType()) {
12754 // Valid unless a relational comparison of function pointers
12755 bool IsError = Opc == BO_Cmp;
12756 auto DiagID =
12757 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12758 : getLangOpts().CPlusPlus
12759 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12760 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12761 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12762 << RHS.get()->getSourceRange();
12763 if (IsError)
12764 return QualType();
12765 }
12766
12767 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12768 (RHSType->isIntegerType() && !RHSIsNull)) {
12769 // Skip normal pointer conversion checks in this case; we have better
12770 // diagnostics for this below.
12771 } else if (getLangOpts().CPlusPlus) {
12772 // Equality comparison of a function pointer to a void pointer is invalid,
12773 // but we allow it as an extension.
12774 // FIXME: If we really want to allow this, should it be part of composite
12775 // pointer type computation so it works in conditionals too?
12776 if (!IsOrdered &&
12777 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12778 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12779 // This is a gcc extension compatibility comparison.
12780 // In a SFINAE context, we treat this as a hard error to maintain
12781 // conformance with the C++ standard.
12782 bool IsError = isSFINAEContext();
12783 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
12784
12785 if (IsError)
12786 return QualType();
12787
12788 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12789 return computeResultTy();
12790 }
12791
12792 // C++ [expr.eq]p2:
12793 // If at least one operand is a pointer [...] bring them to their
12794 // composite pointer type.
12795 // C++ [expr.spaceship]p6
12796 // If at least one of the operands is of pointer type, [...] bring them
12797 // to their composite pointer type.
12798 // C++ [expr.rel]p2:
12799 // If both operands are pointers, [...] bring them to their composite
12800 // pointer type.
12801 // For <=>, the only valid non-pointer types are arrays and functions, and
12802 // we already decayed those, so this is really the same as the relational
12803 // comparison rule.
12804 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12805 (IsOrdered ? 2 : 1) &&
12806 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12807 RHSType->isObjCObjectPointerType()))) {
12808 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12809 return QualType();
12810 return computeResultTy();
12811 }
12812 } else if (LHSType->isPointerType() &&
12813 RHSType->isPointerType()) { // C99 6.5.8p2
12814 // All of the following pointer-related warnings are GCC extensions, except
12815 // when handling null pointer constants.
12816 QualType LCanPointeeTy =
12817 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12818 QualType RCanPointeeTy =
12819 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12820
12821 // C99 6.5.9p2 and C99 6.5.8p2
12822 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12823 RCanPointeeTy.getUnqualifiedType())) {
12824 if (IsRelational) {
12825 // Pointers both need to point to complete or incomplete types
12826 if ((LCanPointeeTy->isIncompleteType() !=
12827 RCanPointeeTy->isIncompleteType()) &&
12828 !getLangOpts().C11) {
12829 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12831 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12832 << RCanPointeeTy->isIncompleteType();
12833 }
12834 }
12835 } else if (!IsRelational &&
12836 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12837 // Valid unless comparison between non-null pointer and function pointer
12838 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12839 && !LHSIsNull && !RHSIsNull)
12840 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12841 /*isError*/false);
12842 } else {
12843 // Invalid
12844 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12845 }
12846 if (LCanPointeeTy != RCanPointeeTy) {
12847 // Treat NULL constant as a special case in OpenCL.
12848 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12849 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12850 getASTContext())) {
12851 Diag(Loc,
12852 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12853 << LHSType << RHSType << 0 /* comparison */
12854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12855 }
12856 }
12857 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12858 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12859 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12860 : CK_BitCast;
12861
12862 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12863 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12864 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12865 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12866 bool ChangingCFIUncheckedCallee =
12867 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12868
12869 if (LHSIsNull && !RHSIsNull)
12870 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12871 else if (!ChangingCFIUncheckedCallee)
12872 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12873 }
12874 return computeResultTy();
12875 }
12876
12877
12878 // C++ [expr.eq]p4:
12879 // Two operands of type std::nullptr_t or one operand of type
12880 // std::nullptr_t and the other a null pointer constant compare
12881 // equal.
12882 // C23 6.5.9p5:
12883 // If both operands have type nullptr_t or one operand has type nullptr_t
12884 // and the other is a null pointer constant, they compare equal if the
12885 // former is a null pointer.
12886 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12887 if (LHSType->isNullPtrType()) {
12888 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12889 return computeResultTy();
12890 }
12891 if (RHSType->isNullPtrType()) {
12892 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12893 return computeResultTy();
12894 }
12895 }
12896
12897 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12898 // C23 6.5.9p6:
12899 // Otherwise, at least one operand is a pointer. If one is a pointer and
12900 // the other is a null pointer constant or has type nullptr_t, they
12901 // compare equal
12902 if (LHSIsNull && RHSType->isPointerType()) {
12903 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12904 return computeResultTy();
12905 }
12906 if (RHSIsNull && LHSType->isPointerType()) {
12907 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12908 return computeResultTy();
12909 }
12910 }
12911
12912 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12913 // These aren't covered by the composite pointer type rules.
12914 if (!IsOrdered && RHSType->isNullPtrType() &&
12915 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12916 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12917 return computeResultTy();
12918 }
12919 if (!IsOrdered && LHSType->isNullPtrType() &&
12920 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12921 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12922 return computeResultTy();
12923 }
12924
12925 if (getLangOpts().CPlusPlus) {
12926 if (IsRelational &&
12927 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12928 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12929 // HACK: Relational comparison of nullptr_t against a pointer type is
12930 // invalid per DR583, but we allow it within std::less<> and friends,
12931 // since otherwise common uses of it break.
12932 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12933 // friends to have std::nullptr_t overload candidates.
12934 DeclContext *DC = CurContext;
12935 if (isa<FunctionDecl>(DC))
12936 DC = DC->getParent();
12937 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12938 if (CTSD->isInStdNamespace() &&
12939 llvm::StringSwitch<bool>(CTSD->getName())
12940 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
12941 .Default(false)) {
12942 if (RHSType->isNullPtrType())
12943 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12944 else
12945 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12946 return computeResultTy();
12947 }
12948 }
12949 }
12950
12951 // C++ [expr.eq]p2:
12952 // If at least one operand is a pointer to member, [...] bring them to
12953 // their composite pointer type.
12954 if (!IsOrdered &&
12955 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12956 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12957 return QualType();
12958 else
12959 return computeResultTy();
12960 }
12961 }
12962
12963 // Handle block pointer types.
12964 if (!IsOrdered && LHSType->isBlockPointerType() &&
12965 RHSType->isBlockPointerType()) {
12966 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12967 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12968
12969 if (!LHSIsNull && !RHSIsNull &&
12970 !Context.typesAreCompatible(lpointee, rpointee)) {
12971 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12972 << LHSType << RHSType << LHS.get()->getSourceRange()
12973 << RHS.get()->getSourceRange();
12974 }
12975 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12976 return computeResultTy();
12977 }
12978
12979 // Allow block pointers to be compared with null pointer constants.
12980 if (!IsOrdered
12981 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12982 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12983 if (!LHSIsNull && !RHSIsNull) {
12984 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12985 ->getPointeeType()->isVoidType())
12986 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12987 ->getPointeeType()->isVoidType())))
12988 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12989 << LHSType << RHSType << LHS.get()->getSourceRange()
12990 << RHS.get()->getSourceRange();
12991 }
12992 if (LHSIsNull && !RHSIsNull)
12993 LHS = ImpCastExprToType(LHS.get(), RHSType,
12994 RHSType->isPointerType() ? CK_BitCast
12995 : CK_AnyPointerToBlockPointerCast);
12996 else
12997 RHS = ImpCastExprToType(RHS.get(), LHSType,
12998 LHSType->isPointerType() ? CK_BitCast
12999 : CK_AnyPointerToBlockPointerCast);
13000 return computeResultTy();
13001 }
13002
13003 if (LHSType->isObjCObjectPointerType() ||
13004 RHSType->isObjCObjectPointerType()) {
13005 const PointerType *LPT = LHSType->getAs<PointerType>();
13006 const PointerType *RPT = RHSType->getAs<PointerType>();
13007 if (LPT || RPT) {
13008 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13009 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13010
13011 if (!LPtrToVoid && !RPtrToVoid &&
13012 !Context.typesAreCompatible(LHSType, RHSType)) {
13013 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13014 /*isError*/false);
13015 }
13016 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13017 // the RHS, but we have test coverage for this behavior.
13018 // FIXME: Consider using convertPointersToCompositeType in C++.
13019 if (LHSIsNull && !RHSIsNull) {
13020 Expr *E = LHS.get();
13021 if (getLangOpts().ObjCAutoRefCount)
13022 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13023 CheckedConversionKind::Implicit);
13024 LHS = ImpCastExprToType(E, RHSType,
13025 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13026 }
13027 else {
13028 Expr *E = RHS.get();
13029 if (getLangOpts().ObjCAutoRefCount)
13030 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13031 CheckedConversionKind::Implicit,
13032 /*Diagnose=*/true,
13033 /*DiagnoseCFAudited=*/false, Opc);
13034 RHS = ImpCastExprToType(E, LHSType,
13035 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13036 }
13037 return computeResultTy();
13038 }
13039 if (LHSType->isObjCObjectPointerType() &&
13040 RHSType->isObjCObjectPointerType()) {
13041 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13042 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13043 /*isError*/false);
13044 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13045 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13046
13047 if (LHSIsNull && !RHSIsNull)
13048 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13049 else
13050 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13051 return computeResultTy();
13052 }
13053
13054 if (!IsOrdered && LHSType->isBlockPointerType() &&
13055 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13056 LHS = ImpCastExprToType(LHS.get(), RHSType,
13057 CK_BlockPointerToObjCPointerCast);
13058 return computeResultTy();
13059 } else if (!IsOrdered &&
13060 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13061 RHSType->isBlockPointerType()) {
13062 RHS = ImpCastExprToType(RHS.get(), LHSType,
13063 CK_BlockPointerToObjCPointerCast);
13064 return computeResultTy();
13065 }
13066 }
13067 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13068 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13069 unsigned DiagID = 0;
13070 bool isError = false;
13071 if (LangOpts.DebuggerSupport) {
13072 // Under a debugger, allow the comparison of pointers to integers,
13073 // since users tend to want to compare addresses.
13074 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13075 (RHSIsNull && RHSType->isIntegerType())) {
13076 if (IsOrdered) {
13077 isError = getLangOpts().CPlusPlus;
13078 DiagID =
13079 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13080 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13081 }
13082 } else if (getLangOpts().CPlusPlus) {
13083 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13084 isError = true;
13085 } else if (IsOrdered)
13086 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13087 else
13088 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13089
13090 if (DiagID) {
13091 Diag(Loc, DiagID)
13092 << LHSType << RHSType << LHS.get()->getSourceRange()
13093 << RHS.get()->getSourceRange();
13094 if (isError)
13095 return QualType();
13096 }
13097
13098 if (LHSType->isIntegerType())
13099 LHS = ImpCastExprToType(LHS.get(), RHSType,
13100 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13101 else
13102 RHS = ImpCastExprToType(RHS.get(), LHSType,
13103 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13104 return computeResultTy();
13105 }
13106
13107 // Handle block pointers.
13108 if (!IsOrdered && RHSIsNull
13109 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13110 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13111 return computeResultTy();
13112 }
13113 if (!IsOrdered && LHSIsNull
13114 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13115 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13116 return computeResultTy();
13117 }
13118
13119 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13120 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13121 return computeResultTy();
13122 }
13123
13124 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13125 return computeResultTy();
13126 }
13127
13128 if (LHSIsNull && RHSType->isQueueT()) {
13129 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13130 return computeResultTy();
13131 }
13132
13133 if (LHSType->isQueueT() && RHSIsNull) {
13134 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13135 return computeResultTy();
13136 }
13137 }
13138
13139 return InvalidOperands(Loc, LHS, RHS);
13140 }
13141
13142 QualType Sema::GetSignedVectorType(QualType V) {
13143 const VectorType *VTy = V->castAs<VectorType>();
13144 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13145
13146 if (isa<ExtVectorType>(VTy)) {
13147 if (VTy->isExtVectorBoolType())
13148 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13149 if (TypeSize == Context.getTypeSize(Context.CharTy))
13150 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13151 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13152 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13153 if (TypeSize == Context.getTypeSize(Context.IntTy))
13154 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13155 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13156 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13157 if (TypeSize == Context.getTypeSize(Context.LongTy))
13158 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13159 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13160 "Unhandled vector element size in vector compare");
13161 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13162 }
13163
13164 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13165 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13166 VectorKind::Generic);
13167 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13168 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13169 VectorKind::Generic);
13170 if (TypeSize == Context.getTypeSize(Context.LongTy))
13171 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13172 VectorKind::Generic);
13173 if (TypeSize == Context.getTypeSize(Context.IntTy))
13174 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13175 VectorKind::Generic);
13176 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13177 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13178 VectorKind::Generic);
13179 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13180 "Unhandled vector element size in vector compare");
13181 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13182 VectorKind::Generic);
13183 }
13184
13185 QualType Sema::GetSignedSizelessVectorType(QualType V) {
13186 const BuiltinType *VTy = V->castAs<BuiltinType>();
13187 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13188
13189 const QualType ETy = V->getSveEltType(Context);
13190 const auto TypeSize = Context.getTypeSize(ETy);
13191
13192 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13193 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13194 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13195 }
13196
13197 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13198 SourceLocation Loc,
13199 BinaryOperatorKind Opc) {
13200 if (Opc == BO_Cmp) {
13201 Diag(Loc, diag::err_three_way_vector_comparison);
13202 return QualType();
13203 }
13204
13205 // Check to make sure we're operating on vectors of the same type and width,
13206 // Allowing one side to be a scalar of element type.
13207 QualType vType =
13208 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13209 /*AllowBothBool*/ true,
13210 /*AllowBoolConversions*/ getLangOpts().ZVector,
13211 /*AllowBooleanOperation*/ true,
13212 /*ReportInvalid*/ true);
13213 if (vType.isNull())
13214 return vType;
13215
13216 QualType LHSType = LHS.get()->getType();
13217
13218 // Determine the return type of a vector compare. By default clang will return
13219 // a scalar for all vector compares except vector bool and vector pixel.
13220 // With the gcc compiler we will always return a vector type and with the xl
13221 // compiler we will always return a scalar type. This switch allows choosing
13222 // which behavior is prefered.
13223 if (getLangOpts().AltiVec) {
13224 switch (getLangOpts().getAltivecSrcCompat()) {
13225 case LangOptions::AltivecSrcCompatKind::Mixed:
13226 // If AltiVec, the comparison results in a numeric type, i.e.
13227 // bool for C++, int for C
13228 if (vType->castAs<VectorType>()->getVectorKind() ==
13229 VectorKind::AltiVecVector)
13230 return Context.getLogicalOperationType();
13231 else
13232 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13233 break;
13234 case LangOptions::AltivecSrcCompatKind::GCC:
13235 // For GCC we always return the vector type.
13236 break;
13237 case LangOptions::AltivecSrcCompatKind::XL:
13238 return Context.getLogicalOperationType();
13239 break;
13240 }
13241 }
13242
13243 // For non-floating point types, check for self-comparisons of the form
13244 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13245 // often indicate logic errors in the program.
13246 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13247
13248 // Check for comparisons of floating point operands using != and ==.
13249 if (LHSType->hasFloatingRepresentation()) {
13250 assert(RHS.get()->getType()->hasFloatingRepresentation());
13251 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13252 }
13253
13254 // Return a signed type for the vector.
13255 return GetSignedVectorType(vType);
13256 }
13257
13258 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13259 ExprResult &RHS,
13260 SourceLocation Loc,
13261 BinaryOperatorKind Opc) {
13262 if (Opc == BO_Cmp) {
13263 Diag(Loc, diag::err_three_way_vector_comparison);
13264 return QualType();
13265 }
13266
13267 // Check to make sure we're operating on vectors of the same type and width,
13268 // Allowing one side to be a scalar of element type.
13269 QualType vType = CheckSizelessVectorOperands(
13270 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13271
13272 if (vType.isNull())
13273 return vType;
13274
13275 QualType LHSType = LHS.get()->getType();
13276
13277 // For non-floating point types, check for self-comparisons of the form
13278 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13279 // often indicate logic errors in the program.
13280 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13281
13282 // Check for comparisons of floating point operands using != and ==.
13283 if (LHSType->hasFloatingRepresentation()) {
13284 assert(RHS.get()->getType()->hasFloatingRepresentation());
13285 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13286 }
13287
13288 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13289 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13290
13291 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13292 RHSBuiltinTy->isSVEBool())
13293 return LHSType;
13294
13295 // Return a signed type for the vector.
13296 return GetSignedSizelessVectorType(vType);
13297 }
13298
13299 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13300 const ExprResult &XorRHS,
13301 const SourceLocation Loc) {
13302 // Do not diagnose macros.
13303 if (Loc.isMacroID())
13304 return;
13305
13306 // Do not diagnose if both LHS and RHS are macros.
13307 if (XorLHS.get()->getExprLoc().isMacroID() &&
13308 XorRHS.get()->getExprLoc().isMacroID())
13309 return;
13310
13311 bool Negative = false;
13312 bool ExplicitPlus = false;
13313 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13314 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13315
13316 if (!LHSInt)
13317 return;
13318 if (!RHSInt) {
13319 // Check negative literals.
13320 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13321 UnaryOperatorKind Opc = UO->getOpcode();
13322 if (Opc != UO_Minus && Opc != UO_Plus)
13323 return;
13324 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13325 if (!RHSInt)
13326 return;
13327 Negative = (Opc == UO_Minus);
13328 ExplicitPlus = !Negative;
13329 } else {
13330 return;
13331 }
13332 }
13333
13334 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13335 llvm::APInt RightSideValue = RHSInt->getValue();
13336 if (LeftSideValue != 2 && LeftSideValue != 10)
13337 return;
13338
13339 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13340 return;
13341
13342 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13343 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13344 llvm::StringRef ExprStr =
13345 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13346
13347 CharSourceRange XorRange =
13348 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13349 llvm::StringRef XorStr =
13350 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13351 // Do not diagnose if xor keyword/macro is used.
13352 if (XorStr == "xor")
13353 return;
13354
13355 std::string LHSStr = std::string(Lexer::getSourceText(
13356 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13357 S.getSourceManager(), S.getLangOpts()));
13358 std::string RHSStr = std::string(Lexer::getSourceText(
13359 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13360 S.getSourceManager(), S.getLangOpts()));
13361
13362 if (Negative) {
13363 RightSideValue = -RightSideValue;
13364 RHSStr = "-" + RHSStr;
13365 } else if (ExplicitPlus) {
13366 RHSStr = "+" + RHSStr;
13367 }
13368
13369 StringRef LHSStrRef = LHSStr;
13370 StringRef RHSStrRef = RHSStr;
13371 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13372 // literals.
13373 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13374 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13375 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13376 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13377 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13378 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13379 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13380 return;
13381
13382 bool SuggestXor =
13383 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13384 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13385 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13386 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13387 std::string SuggestedExpr = "1 << " + RHSStr;
13388 bool Overflow = false;
13389 llvm::APInt One = (LeftSideValue - 1);
13390 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13391 if (Overflow) {
13392 if (RightSideIntValue < 64)
13393 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13394 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13395 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13396 else if (RightSideIntValue == 64)
13397 S.Diag(Loc, diag::warn_xor_used_as_pow)
13398 << ExprStr << toString(XorValue, 10, true);
13399 else
13400 return;
13401 } else {
13402 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13403 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13404 << toString(PowValue, 10, true)
13405 << FixItHint::CreateReplacement(
13406 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13407 }
13408
13409 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13410 << ("0x2 ^ " + RHSStr) << SuggestXor;
13411 } else if (LeftSideValue == 10) {
13412 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13413 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13414 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13415 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13416 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13417 << ("0xA ^ " + RHSStr) << SuggestXor;
13418 }
13419 }
13420
13421 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13422 SourceLocation Loc,
13423 BinaryOperatorKind Opc) {
13424 // Ensure that either both operands are of the same vector type, or
13425 // one operand is of a vector type and the other is of its element type.
13426 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13427 /*AllowBothBool*/ true,
13428 /*AllowBoolConversions*/ false,
13429 /*AllowBooleanOperation*/ false,
13430 /*ReportInvalid*/ false);
13431 if (vType.isNull())
13432 return InvalidOperands(Loc, LHS, RHS);
13433 if (getLangOpts().OpenCL &&
13434 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13435 vType->hasFloatingRepresentation())
13436 return InvalidOperands(Loc, LHS, RHS);
13437 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13438 // usage of the logical operators && and || with vectors in C. This
13439 // check could be notionally dropped.
13440 if (!getLangOpts().CPlusPlus &&
13441 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13442 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13443 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13444 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13445 // `select` functions.
13446 if (getLangOpts().HLSL &&
13447 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13448 (void)InvalidOperands(Loc, LHS, RHS);
13449 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13450 return QualType();
13451 }
13452
13453 return GetSignedVectorType(LHS.get()->getType());
13454 }
13455
13456 QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13457 SourceLocation Loc,
13458 BinaryOperatorKind Opc) {
13459
13460 if (!getLangOpts().HLSL) {
13461 assert(false && "Logical operands are not supported in C\\C++");
13462 return QualType();
13463 }
13464
13465 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13466 (void)InvalidOperands(Loc, LHS, RHS);
13467 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13468 return QualType();
13469 }
13470 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13471 << getLangOpts().getHLSLVersion();
13472 return QualType();
13473 }
13474
13475 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13476 SourceLocation Loc,
13477 bool IsCompAssign) {
13478 if (!IsCompAssign) {
13479 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13480 if (LHS.isInvalid())
13481 return QualType();
13482 }
13483 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13484 if (RHS.isInvalid())
13485 return QualType();
13486
13487 // For conversion purposes, we ignore any qualifiers.
13488 // For example, "const float" and "float" are equivalent.
13489 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13490 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13491
13492 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13493 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13494 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13495
13496 if (Context.hasSameType(LHSType, RHSType))
13497 return Context.getCommonSugaredType(LHSType, RHSType);
13498
13499 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13500 // case we have to return InvalidOperands.
13501 ExprResult OriginalLHS = LHS;
13502 ExprResult OriginalRHS = RHS;
13503 if (LHSMatType && !RHSMatType) {
13504 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13505 if (!RHS.isInvalid())
13506 return LHSType;
13507
13508 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13509 }
13510
13511 if (!LHSMatType && RHSMatType) {
13512 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13513 if (!LHS.isInvalid())
13514 return RHSType;
13515 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13516 }
13517
13518 return InvalidOperands(Loc, LHS, RHS);
13519 }
13520
13521 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13522 SourceLocation Loc,
13523 bool IsCompAssign) {
13524 if (!IsCompAssign) {
13525 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13526 if (LHS.isInvalid())
13527 return QualType();
13528 }
13529 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13530 if (RHS.isInvalid())
13531 return QualType();
13532
13533 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13534 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13535 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13536
13537 if (LHSMatType && RHSMatType) {
13538 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13539 return InvalidOperands(Loc, LHS, RHS);
13540
13541 if (Context.hasSameType(LHSMatType, RHSMatType))
13542 return Context.getCommonSugaredType(
13543 LHS.get()->getType().getUnqualifiedType(),
13544 RHS.get()->getType().getUnqualifiedType());
13545
13546 QualType LHSELTy = LHSMatType->getElementType(),
13547 RHSELTy = RHSMatType->getElementType();
13548 if (!Context.hasSameType(LHSELTy, RHSELTy))
13549 return InvalidOperands(Loc, LHS, RHS);
13550
13551 return Context.getConstantMatrixType(
13552 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13553 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13554 }
13555 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13556 }
13557
13558 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13559 switch (Opc) {
13560 default:
13561 return false;
13562 case BO_And:
13563 case BO_AndAssign:
13564 case BO_Or:
13565 case BO_OrAssign:
13566 case BO_Xor:
13567 case BO_XorAssign:
13568 return true;
13569 }
13570 }
13571
13572 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13573 SourceLocation Loc,
13574 BinaryOperatorKind Opc) {
13575 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13576
13577 bool IsCompAssign =
13578 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13579
13580 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13581
13582 if (LHS.get()->getType()->isVectorType() ||
13583 RHS.get()->getType()->isVectorType()) {
13584 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13585 RHS.get()->getType()->hasIntegerRepresentation())
13586 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13587 /*AllowBothBool*/ true,
13588 /*AllowBoolConversions*/ getLangOpts().ZVector,
13589 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13590 /*ReportInvalid*/ true);
13591 return InvalidOperands(Loc, LHS, RHS);
13592 }
13593
13594 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13595 RHS.get()->getType()->isSveVLSBuiltinType()) {
13596 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13597 RHS.get()->getType()->hasIntegerRepresentation())
13598 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13599 ArithConvKind::BitwiseOp);
13600 return InvalidOperands(Loc, LHS, RHS);
13601 }
13602
13603 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13604 RHS.get()->getType()->isSveVLSBuiltinType()) {
13605 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13606 RHS.get()->getType()->hasIntegerRepresentation())
13607 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13608 ArithConvKind::BitwiseOp);
13609 return InvalidOperands(Loc, LHS, RHS);
13610 }
13611
13612 if (Opc == BO_And)
13613 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13614
13615 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13616 RHS.get()->getType()->hasFloatingRepresentation())
13617 return InvalidOperands(Loc, LHS, RHS);
13618
13619 ExprResult LHSResult = LHS, RHSResult = RHS;
13620 QualType compType = UsualArithmeticConversions(
13621 LHSResult, RHSResult, Loc,
13622 IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13623 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13624 return QualType();
13625 LHS = LHSResult.get();
13626 RHS = RHSResult.get();
13627
13628 if (Opc == BO_Xor)
13629 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13630
13631 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13632 return compType;
13633 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13634 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13635 return ResultTy;
13636 }
13637
13638 // C99 6.5.[13,14]
13639 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13640 SourceLocation Loc,
13641 BinaryOperatorKind Opc) {
13642 // Check vector operands differently.
13643 if (LHS.get()->getType()->isVectorType() ||
13644 RHS.get()->getType()->isVectorType())
13645 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13646
13647 if (LHS.get()->getType()->isConstantMatrixType() ||
13648 RHS.get()->getType()->isConstantMatrixType())
13649 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13650
13651 bool EnumConstantInBoolContext = false;
13652 for (const ExprResult &HS : {LHS, RHS}) {
13653 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13654 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13655 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13656 EnumConstantInBoolContext = true;
13657 }
13658 }
13659
13660 if (EnumConstantInBoolContext)
13661 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13662
13663 // WebAssembly tables can't be used with logical operators.
13664 QualType LHSTy = LHS.get()->getType();
13665 QualType RHSTy = RHS.get()->getType();
13666 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13667 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13668 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13669 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13670 return InvalidOperands(Loc, LHS, RHS);
13671 }
13672
13673 // Diagnose cases where the user write a logical and/or but probably meant a
13674 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13675 // is a constant.
13676 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13677 !LHS.get()->getType()->isBooleanType() &&
13678 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13679 // Don't warn in macros or template instantiations.
13680 !Loc.isMacroID() && !inTemplateInstantiation()) {
13681 // If the RHS can be constant folded, and if it constant folds to something
13682 // that isn't 0 or 1 (which indicate a potential logical operation that
13683 // happened to fold to true/false) then warn.
13684 // Parens on the RHS are ignored.
13685 Expr::EvalResult EVResult;
13686 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13687 llvm::APSInt Result = EVResult.Val.getInt();
13688 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13689 !RHS.get()->getExprLoc().isMacroID()) ||
13690 (Result != 0 && Result != 1)) {
13691 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13692 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13693 // Suggest replacing the logical operator with the bitwise version
13694 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13695 << (Opc == BO_LAnd ? "&" : "|")
13696 << FixItHint::CreateReplacement(
13697 SourceRange(Loc, getLocForEndOfToken(Loc)),
13698 Opc == BO_LAnd ? "&" : "|");
13699 if (Opc == BO_LAnd)
13700 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13701 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13702 << FixItHint::CreateRemoval(
13703 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13704 RHS.get()->getEndLoc()));
13705 }
13706 }
13707 }
13708
13709 if (!Context.getLangOpts().CPlusPlus) {
13710 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13711 // not operate on the built-in scalar and vector float types.
13712 if (Context.getLangOpts().OpenCL &&
13713 Context.getLangOpts().OpenCLVersion < 120) {
13714 if (LHS.get()->getType()->isFloatingType() ||
13715 RHS.get()->getType()->isFloatingType())
13716 return InvalidOperands(Loc, LHS, RHS);
13717 }
13718
13719 LHS = UsualUnaryConversions(LHS.get());
13720 if (LHS.isInvalid())
13721 return QualType();
13722
13723 RHS = UsualUnaryConversions(RHS.get());
13724 if (RHS.isInvalid())
13725 return QualType();
13726
13727 if (!LHS.get()->getType()->isScalarType() ||
13728 !RHS.get()->getType()->isScalarType())
13729 return InvalidOperands(Loc, LHS, RHS);
13730
13731 return Context.IntTy;
13732 }
13733
13734 // The following is safe because we only use this method for
13735 // non-overloadable operands.
13736
13737 // C++ [expr.log.and]p1
13738 // C++ [expr.log.or]p1
13739 // The operands are both contextually converted to type bool.
13740 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13741 if (LHSRes.isInvalid()) {
13742 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13743 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13744 return ResultTy;
13745 }
13746 LHS = LHSRes;
13747
13748 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13749 if (RHSRes.isInvalid()) {
13750 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13751 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13752 return ResultTy;
13753 }
13754 RHS = RHSRes;
13755
13756 // C++ [expr.log.and]p2
13757 // C++ [expr.log.or]p2
13758 // The result is a bool.
13759 return Context.BoolTy;
13760 }
13761
13762 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13763 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13764 if (!ME) return false;
13765 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13766 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13767 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13768 if (!Base) return false;
13769 return Base->getMethodDecl() != nullptr;
13770 }
13771
13772 /// Is the given expression (which must be 'const') a reference to a
13773 /// variable which was originally non-const, but which has become
13774 /// 'const' due to being captured within a block?
13775 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13776 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13777 assert(E->isLValue() && E->getType().isConstQualified());
13778 E = E->IgnoreParens();
13779
13780 // Must be a reference to a declaration from an enclosing scope.
13781 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13782 if (!DRE) return NCCK_None;
13783 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13784
13785 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13786
13787 // The declaration must be a value which is not declared 'const'.
13788 if (!Value || Value->getType().isConstQualified())
13789 return NCCK_None;
13790
13791 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13792 if (Binding) {
13793 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13794 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13795 return NCCK_Lambda;
13796 }
13797
13798 VarDecl *Var = dyn_cast<VarDecl>(Value);
13799 if (!Var)
13800 return NCCK_None;
13801 if (Var->getType()->isReferenceType())
13802 return NCCK_None;
13803
13804 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13805
13806 // Decide whether the first capture was for a block or a lambda.
13807 DeclContext *DC = S.CurContext, *Prev = nullptr;
13808 // Decide whether the first capture was for a block or a lambda.
13809 while (DC) {
13810 // For init-capture, it is possible that the variable belongs to the
13811 // template pattern of the current context.
13812 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13813 if (Var->isInitCapture() &&
13814 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13815 break;
13816 if (DC == Var->getDeclContext())
13817 break;
13818 Prev = DC;
13819 DC = DC->getParent();
13820 }
13821 // Unless we have an init-capture, we've gone one step too far.
13822 if (!Var->isInitCapture())
13823 DC = Prev;
13824 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13825 }
13826
13827 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13828 Ty = Ty.getNonReferenceType();
13829 if (IsDereference && Ty->isPointerType())
13830 Ty = Ty->getPointeeType();
13831 return !Ty.isConstQualified();
13832 }
13833
13834 // Update err_typecheck_assign_const and note_typecheck_assign_const
13835 // when this enum is changed.
13836 enum {
13837 ConstFunction,
13838 ConstVariable,
13839 ConstMember,
13840 ConstMethod,
13841 NestedConstMember,
13842 ConstUnknown, // Keep as last element
13843 };
13844
13845 /// Emit the "read-only variable not assignable" error and print notes to give
13846 /// more information about why the variable is not assignable, such as pointing
13847 /// to the declaration of a const variable, showing that a method is const, or
13848 /// that the function is returning a const reference.
13849 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13850 SourceLocation Loc) {
13851 SourceRange ExprRange = E->getSourceRange();
13852
13853 // Only emit one error on the first const found. All other consts will emit
13854 // a note to the error.
13855 bool DiagnosticEmitted = false;
13856
13857 // Track if the current expression is the result of a dereference, and if the
13858 // next checked expression is the result of a dereference.
13859 bool IsDereference = false;
13860 bool NextIsDereference = false;
13861
13862 // Loop to process MemberExpr chains.
13863 while (true) {
13864 IsDereference = NextIsDereference;
13865
13866 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13867 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13868 NextIsDereference = ME->isArrow();
13869 const ValueDecl *VD = ME->getMemberDecl();
13870 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13871 // Mutable fields can be modified even if the class is const.
13872 if (Field->isMutable()) {
13873 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13874 break;
13875 }
13876
13877 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13878 if (!DiagnosticEmitted) {
13879 S.Diag(Loc, diag::err_typecheck_assign_const)
13880 << ExprRange << ConstMember << false /*static*/ << Field
13881 << Field->getType();
13882 DiagnosticEmitted = true;
13883 }
13884 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13885 << ConstMember << false /*static*/ << Field << Field->getType()
13886 << Field->getSourceRange();
13887 }
13888 E = ME->getBase();
13889 continue;
13890 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13891 if (VDecl->getType().isConstQualified()) {
13892 if (!DiagnosticEmitted) {
13893 S.Diag(Loc, diag::err_typecheck_assign_const)
13894 << ExprRange << ConstMember << true /*static*/ << VDecl
13895 << VDecl->getType();
13896 DiagnosticEmitted = true;
13897 }
13898 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13899 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13900 << VDecl->getSourceRange();
13901 }
13902 // Static fields do not inherit constness from parents.
13903 break;
13904 }
13905 break; // End MemberExpr
13906 } else if (const ArraySubscriptExpr *ASE =
13907 dyn_cast<ArraySubscriptExpr>(E)) {
13908 E = ASE->getBase()->IgnoreParenImpCasts();
13909 continue;
13910 } else if (const ExtVectorElementExpr *EVE =
13911 dyn_cast<ExtVectorElementExpr>(E)) {
13912 E = EVE->getBase()->IgnoreParenImpCasts();
13913 continue;
13914 }
13915 break;
13916 }
13917
13918 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13919 // Function calls
13920 const FunctionDecl *FD = CE->getDirectCallee();
13921 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13922 if (!DiagnosticEmitted) {
13923 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13924 << ConstFunction << FD;
13925 DiagnosticEmitted = true;
13926 }
13927 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13928 diag::note_typecheck_assign_const)
13929 << ConstFunction << FD << FD->getReturnType()
13930 << FD->getReturnTypeSourceRange();
13931 }
13932 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13933 // Point to variable declaration.
13934 if (const ValueDecl *VD = DRE->getDecl()) {
13935 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13936 if (!DiagnosticEmitted) {
13937 S.Diag(Loc, diag::err_typecheck_assign_const)
13938 << ExprRange << ConstVariable << VD << VD->getType();
13939 DiagnosticEmitted = true;
13940 }
13941 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13942 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13943 }
13944 }
13945 } else if (isa<CXXThisExpr>(E)) {
13946 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13947 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13948 if (MD->isConst()) {
13949 if (!DiagnosticEmitted) {
13950 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13951 << ConstMethod << MD;
13952 DiagnosticEmitted = true;
13953 }
13954 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13955 << ConstMethod << MD << MD->getSourceRange();
13956 }
13957 }
13958 }
13959 }
13960
13961 if (DiagnosticEmitted)
13962 return;
13963
13964 // Can't determine a more specific message, so display the generic error.
13965 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13966 }
13967
13968 enum OriginalExprKind {
13969 OEK_Variable,
13970 OEK_Member,
13971 OEK_LValue
13972 };
13973
13974 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13975 const RecordType *Ty,
13976 SourceLocation Loc, SourceRange Range,
13977 OriginalExprKind OEK,
13978 bool &DiagnosticEmitted) {
13979 std::vector<const RecordType *> RecordTypeList;
13980 RecordTypeList.push_back(Ty);
13981 unsigned NextToCheckIndex = 0;
13982 // We walk the record hierarchy breadth-first to ensure that we print
13983 // diagnostics in field nesting order.
13984 while (RecordTypeList.size() > NextToCheckIndex) {
13985 bool IsNested = NextToCheckIndex > 0;
13986 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13987 ->getDecl()
13988 ->getDefinitionOrSelf()
13989 ->fields()) {
13990 // First, check every field for constness.
13991 QualType FieldTy = Field->getType();
13992 if (FieldTy.isConstQualified()) {
13993 if (!DiagnosticEmitted) {
13994 S.Diag(Loc, diag::err_typecheck_assign_const)
13995 << Range << NestedConstMember << OEK << VD
13996 << IsNested << Field;
13997 DiagnosticEmitted = true;
13998 }
13999 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14000 << NestedConstMember << IsNested << Field
14001 << FieldTy << Field->getSourceRange();
14002 }
14003
14004 // Then we append it to the list to check next in order.
14005 FieldTy = FieldTy.getCanonicalType();
14006 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14007 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14008 RecordTypeList.push_back(FieldRecTy);
14009 }
14010 }
14011 ++NextToCheckIndex;
14012 }
14013 }
14014
14015 /// Emit an error for the case where a record we are trying to assign to has a
14016 /// const-qualified field somewhere in its hierarchy.
14017 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14018 SourceLocation Loc) {
14019 QualType Ty = E->getType();
14020 assert(Ty->isRecordType() && "lvalue was not record?");
14021 SourceRange Range = E->getSourceRange();
14022 const auto *RTy = Ty->getAsCanonical<RecordType>();
14023 bool DiagEmitted = false;
14024
14025 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14026 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14027 Range, OEK_Member, DiagEmitted);
14028 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14029 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14030 Range, OEK_Variable, DiagEmitted);
14031 else
14032 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14033 Range, OEK_LValue, DiagEmitted);
14034 if (!DiagEmitted)
14035 DiagnoseConstAssignment(S, E, Loc);
14036 }
14037
14038 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14039 /// emit an error and return true. If so, return false.
14040 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14041 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14042
14043 S.CheckShadowingDeclModification(E, Loc);
14044
14045 SourceLocation OrigLoc = Loc;
14046 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14047 &Loc);
14048 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14049 IsLV = Expr::MLV_InvalidMessageExpression;
14050 if (IsLV == Expr::MLV_Valid)
14051 return false;
14052
14053 unsigned DiagID = 0;
14054 bool NeedType = false;
14055 switch (IsLV) { // C99 6.5.16p2
14056 case Expr::MLV_ConstQualified:
14057 // Use a specialized diagnostic when we're assigning to an object
14058 // from an enclosing function or block.
14059 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14060 if (NCCK == NCCK_Block)
14061 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14062 else
14063 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14064 break;
14065 }
14066
14067 // In ARC, use some specialized diagnostics for occasions where we
14068 // infer 'const'. These are always pseudo-strong variables.
14069 if (S.getLangOpts().ObjCAutoRefCount) {
14070 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14071 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14072 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14073
14074 // Use the normal diagnostic if it's pseudo-__strong but the
14075 // user actually wrote 'const'.
14076 if (var->isARCPseudoStrong() &&
14077 (!var->getTypeSourceInfo() ||
14078 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14079 // There are three pseudo-strong cases:
14080 // - self
14081 ObjCMethodDecl *method = S.getCurMethodDecl();
14082 if (method && var == method->getSelfDecl()) {
14083 DiagID = method->isClassMethod()
14084 ? diag::err_typecheck_arc_assign_self_class_method
14085 : diag::err_typecheck_arc_assign_self;
14086
14087 // - Objective-C externally_retained attribute.
14088 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14089 isa<ParmVarDecl>(var)) {
14090 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14091
14092 // - fast enumeration variables
14093 } else {
14094 DiagID = diag::err_typecheck_arr_assign_enumeration;
14095 }
14096
14097 SourceRange Assign;
14098 if (Loc != OrigLoc)
14099 Assign = SourceRange(OrigLoc, OrigLoc);
14100 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14101 // We need to preserve the AST regardless, so migration tool
14102 // can do its job.
14103 return false;
14104 }
14105 }
14106 }
14107
14108 // If none of the special cases above are triggered, then this is a
14109 // simple const assignment.
14110 if (DiagID == 0) {
14111 DiagnoseConstAssignment(S, E, Loc);
14112 return true;
14113 }
14114
14115 break;
14116 case Expr::MLV_ConstAddrSpace:
14117 DiagnoseConstAssignment(S, E, Loc);
14118 return true;
14119 case Expr::MLV_ConstQualifiedField:
14120 DiagnoseRecursiveConstFields(S, E, Loc);
14121 return true;
14122 case Expr::MLV_ArrayType:
14123 case Expr::MLV_ArrayTemporary:
14124 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14125 NeedType = true;
14126 break;
14127 case Expr::MLV_NotObjectType:
14128 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14129 NeedType = true;
14130 break;
14131 case Expr::MLV_LValueCast:
14132 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14133 break;
14134 case Expr::MLV_Valid:
14135 llvm_unreachable("did not take early return for MLV_Valid");
14136 case Expr::MLV_InvalidExpression:
14137 case Expr::MLV_MemberFunction:
14138 case Expr::MLV_ClassTemporary:
14139 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14140 break;
14141 case Expr::MLV_IncompleteType:
14142 case Expr::MLV_IncompleteVoidType:
14143 return S.RequireCompleteType(Loc, E->getType(),
14144 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14145 case Expr::MLV_DuplicateVectorComponents:
14146 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14147 break;
14148 case Expr::MLV_NoSetterProperty:
14149 llvm_unreachable("readonly properties should be processed differently");
14150 case Expr::MLV_InvalidMessageExpression:
14151 DiagID = diag::err_readonly_message_assignment;
14152 break;
14153 case Expr::MLV_SubObjCPropertySetting:
14154 DiagID = diag::err_no_subobject_property_setting;
14155 break;
14156 }
14157
14158 SourceRange Assign;
14159 if (Loc != OrigLoc)
14160 Assign = SourceRange(OrigLoc, OrigLoc);
14161 if (NeedType)
14162 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14163 else
14164 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14165 return true;
14166 }
14167
14168 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14169 SourceLocation Loc,
14170 Sema &Sema) {
14171 if (Sema.inTemplateInstantiation())
14172 return;
14173 if (Sema.isUnevaluatedContext())
14174 return;
14175 if (Loc.isInvalid() || Loc.isMacroID())
14176 return;
14177 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14178 return;
14179
14180 // C / C++ fields
14181 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14182 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14183 if (ML && MR) {
14184 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14185 return;
14186 const ValueDecl *LHSDecl =
14187 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14188 const ValueDecl *RHSDecl =
14189 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14190 if (LHSDecl != RHSDecl)
14191 return;
14192 if (LHSDecl->getType().isVolatileQualified())
14193 return;
14194 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14195 if (RefTy->getPointeeType().isVolatileQualified())
14196 return;
14197
14198 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14199 }
14200
14201 // Objective-C instance variables
14202 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14203 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14204 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14205 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14206 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14207 if (RL && RR && RL->getDecl() == RR->getDecl())
14208 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14209 }
14210 }
14211
14212 // C99 6.5.16.1
14213 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14214 SourceLocation Loc,
14215 QualType CompoundType,
14216 BinaryOperatorKind Opc) {
14217 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14218
14219 // Verify that LHS is a modifiable lvalue, and emit error if not.
14220 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14221 return QualType();
14222
14223 QualType LHSType = LHSExpr->getType();
14224 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14225 CompoundType;
14226
14227 if (RHS.isUsable()) {
14228 // Even if this check fails don't return early to allow the best
14229 // possible error recovery and to allow any subsequent diagnostics to
14230 // work.
14231 const ValueDecl *Assignee = nullptr;
14232 bool ShowFullyQualifiedAssigneeName = false;
14233 // In simple cases describe what is being assigned to
14234 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14235 Assignee = DR->getDecl();
14236 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14237 Assignee = ME->getMemberDecl();
14238 ShowFullyQualifiedAssigneeName = true;
14239 }
14240
14241 BoundsSafetyCheckAssignmentToCountAttrPtr(
14242 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14243 ShowFullyQualifiedAssigneeName);
14244 }
14245
14246 // OpenCL v1.2 s6.1.1.1 p2:
14247 // The half data type can only be used to declare a pointer to a buffer that
14248 // contains half values
14249 if (getLangOpts().OpenCL &&
14250 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14251 LHSType->isHalfType()) {
14252 Diag(Loc, diag::err_opencl_half_load_store) << 1
14253 << LHSType.getUnqualifiedType();
14254 return QualType();
14255 }
14256
14257 // WebAssembly tables can't be used on RHS of an assignment expression.
14258 if (RHSType->isWebAssemblyTableType()) {
14259 Diag(Loc, diag::err_wasm_table_art) << 0;
14260 return QualType();
14261 }
14262
14263 AssignConvertType ConvTy;
14264 if (CompoundType.isNull()) {
14265 Expr *RHSCheck = RHS.get();
14266
14267 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14268
14269 QualType LHSTy(LHSType);
14270 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14271 if (RHS.isInvalid())
14272 return QualType();
14273 // Special case of NSObject attributes on c-style pointer types.
14274 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14275 ((Context.isObjCNSObjectType(LHSType) &&
14276 RHSType->isObjCObjectPointerType()) ||
14277 (Context.isObjCNSObjectType(RHSType) &&
14278 LHSType->isObjCObjectPointerType())))
14279 ConvTy = AssignConvertType::Compatible;
14280
14281 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14282 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14283
14284 // If the RHS is a unary plus or minus, check to see if they = and + are
14285 // right next to each other. If so, the user may have typo'd "x =+ 4"
14286 // instead of "x += 4".
14287 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14288 RHSCheck = ICE->getSubExpr();
14289 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14290 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14291 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14292 // Only if the two operators are exactly adjacent.
14293 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14294 // And there is a space or other character before the subexpr of the
14295 // unary +/-. We don't want to warn on "x=-1".
14296 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14297 UO->getSubExpr()->getBeginLoc().isFileID()) {
14298 Diag(Loc, diag::warn_not_compound_assign)
14299 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14300 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14301 }
14302 }
14303
14304 if (IsAssignConvertCompatible(ConvTy)) {
14305 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14306 // Warn about retain cycles where a block captures the LHS, but
14307 // not if the LHS is a simple variable into which the block is
14308 // being stored...unless that variable can be captured by reference!
14309 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14310 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14311 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14312 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14313 }
14314
14315 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14316 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14317 // It is safe to assign a weak reference into a strong variable.
14318 // Although this code can still have problems:
14319 // id x = self.weakProp;
14320 // id y = self.weakProp;
14321 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14322 // paths through the function. This should be revisited if
14323 // -Wrepeated-use-of-weak is made flow-sensitive.
14324 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14325 // variable, which will be valid for the current autorelease scope.
14326 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14327 RHS.get()->getBeginLoc()))
14328 getCurFunction()->markSafeWeakUse(RHS.get());
14329
14330 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14331 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14332 }
14333 }
14334 } else {
14335 // Compound assignment "x += y"
14336 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14337 }
14338
14339 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14340 AssignmentAction::Assigning))
14341 return QualType();
14342
14343 CheckForNullPointerDereference(*this, LHSExpr);
14344
14345 AssignedEntity AE{LHSExpr};
14346 checkAssignmentLifetime(*this, AE, RHS.get());
14347
14348 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14349 if (CompoundType.isNull()) {
14350 // C++2a [expr.ass]p5:
14351 // A simple-assignment whose left operand is of a volatile-qualified
14352 // type is deprecated unless the assignment is either a discarded-value
14353 // expression or an unevaluated operand
14354 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14355 }
14356 }
14357
14358 // C11 6.5.16p3: The type of an assignment expression is the type of the
14359 // left operand would have after lvalue conversion.
14360 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14361 // qualified type, the value has the unqualified version of the type of the
14362 // lvalue; additionally, if the lvalue has atomic type, the value has the
14363 // non-atomic version of the type of the lvalue.
14364 // C++ 5.17p1: the type of the assignment expression is that of its left
14365 // operand.
14366 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14367 }
14368
14369 // Scenarios to ignore if expression E is:
14370 // 1. an explicit cast expression into void
14371 // 2. a function call expression that returns void
14372 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14373 E = E->IgnoreParens();
14374
14375 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14376 if (CE->getCastKind() == CK_ToVoid) {
14377 return true;
14378 }
14379
14380 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14381 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14382 CE->getSubExpr()->getType()->isDependentType()) {
14383 return true;
14384 }
14385 }
14386
14387 if (const auto *CE = dyn_cast<CallExpr>(E))
14388 return CE->getCallReturnType(Context)->isVoidType();
14389 return false;
14390 }
14391
14392 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14393 // No warnings in macros
14394 if (Loc.isMacroID())
14395 return;
14396
14397 // Don't warn in template instantiations.
14398 if (inTemplateInstantiation())
14399 return;
14400
14401 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14402 // instead, skip more than needed, then call back into here with the
14403 // CommaVisitor in SemaStmt.cpp.
14404 // The listed locations are the initialization and increment portions
14405 // of a for loop. The additional checks are on the condition of
14406 // if statements, do/while loops, and for loops.
14407 // Differences in scope flags for C89 mode requires the extra logic.
14408 const unsigned ForIncrementFlags =
14409 getLangOpts().C99 || getLangOpts().CPlusPlus
14410 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14411 : Scope::ContinueScope | Scope::BreakScope;
14412 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14413 const unsigned ScopeFlags = getCurScope()->getFlags();
14414 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14415 (ScopeFlags & ForInitFlags) == ForInitFlags)
14416 return;
14417
14418 // If there are multiple comma operators used together, get the RHS of the
14419 // of the comma operator as the LHS.
14420 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14421 if (BO->getOpcode() != BO_Comma)
14422 break;
14423 LHS = BO->getRHS();
14424 }
14425
14426 // Only allow some expressions on LHS to not warn.
14427 if (IgnoreCommaOperand(LHS, Context))
14428 return;
14429
14430 Diag(Loc, diag::warn_comma_operator);
14431 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14432 << LHS->getSourceRange()
14433 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14434 LangOpts.CPlusPlus ? "static_cast<void>("
14435 : "(void)(")
14436 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14437 ")");
14438 }
14439
14440 // C99 6.5.17
14441 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14442 SourceLocation Loc) {
14443 LHS = S.CheckPlaceholderExpr(LHS.get());
14444 RHS = S.CheckPlaceholderExpr(RHS.get());
14445 if (LHS.isInvalid() || RHS.isInvalid())
14446 return QualType();
14447
14448 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14449 // operands, but not unary promotions.
14450 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14451
14452 // So we treat the LHS as a ignored value, and in C++ we allow the
14453 // containing site to determine what should be done with the RHS.
14454 LHS = S.IgnoredValueConversions(LHS.get());
14455 if (LHS.isInvalid())
14456 return QualType();
14457
14458 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14459
14460 if (!S.getLangOpts().CPlusPlus) {
14461 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14462 if (RHS.isInvalid())
14463 return QualType();
14464 if (!RHS.get()->getType()->isVoidType())
14465 S.RequireCompleteType(Loc, RHS.get()->getType(),
14466 diag::err_incomplete_type);
14467 }
14468
14469 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14470 S.DiagnoseCommaOperator(LHS.get(), Loc);
14471
14472 return RHS.get()->getType();
14473 }
14474
14475 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14476 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14477 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14478 ExprValueKind &VK,
14479 ExprObjectKind &OK,
14480 SourceLocation OpLoc, bool IsInc,
14481 bool IsPrefix) {
14482 QualType ResType = Op->getType();
14483 // Atomic types can be used for increment / decrement where the non-atomic
14484 // versions can, so ignore the _Atomic() specifier for the purpose of
14485 // checking.
14486 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14487 ResType = ResAtomicType->getValueType();
14488
14489 assert(!ResType.isNull() && "no type for increment/decrement expression");
14490
14491 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14492 // Decrement of bool is not allowed.
14493 if (!IsInc) {
14494 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14495 return QualType();
14496 }
14497 // Increment of bool sets it to true, but is deprecated.
14498 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14499 : diag::warn_increment_bool)
14500 << Op->getSourceRange();
14501 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14502 // Error on enum increments and decrements in C++ mode
14503 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14504 return QualType();
14505 } else if (ResType->isRealType()) {
14506 // OK!
14507 } else if (ResType->isPointerType()) {
14508 // C99 6.5.2.4p2, 6.5.6p2
14509 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14510 return QualType();
14511 } else if (ResType->isObjCObjectPointerType()) {
14512 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14513 // Otherwise, we just need a complete type.
14514 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14515 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14516 return QualType();
14517 } else if (ResType->isAnyComplexType()) {
14518 // C99 does not support ++/-- on complex types, we allow as an extension.
14519 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14520 : diag::ext_c2y_increment_complex)
14521 << IsInc << Op->getSourceRange();
14522 } else if (ResType->isPlaceholderType()) {
14523 ExprResult PR = S.CheckPlaceholderExpr(Op);
14524 if (PR.isInvalid()) return QualType();
14525 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14526 IsInc, IsPrefix);
14527 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14528 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14529 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14530 (ResType->castAs<VectorType>()->getVectorKind() !=
14531 VectorKind::AltiVecBool)) {
14532 // The z vector extensions allow ++ and -- for non-bool vectors.
14533 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14534 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14535 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14536 } else {
14537 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14538 << ResType << int(IsInc) << Op->getSourceRange();
14539 return QualType();
14540 }
14541 // At this point, we know we have a real, complex or pointer type.
14542 // Now make sure the operand is a modifiable lvalue.
14543 if (CheckForModifiableLvalue(Op, OpLoc, S))
14544 return QualType();
14545 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14546 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14547 // An operand with volatile-qualified type is deprecated
14548 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14549 << IsInc << ResType;
14550 }
14551 // In C++, a prefix increment is the same type as the operand. Otherwise
14552 // (in C or with postfix), the increment is the unqualified type of the
14553 // operand.
14554 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14555 VK = VK_LValue;
14556 OK = Op->getObjectKind();
14557 return ResType;
14558 } else {
14559 VK = VK_PRValue;
14560 return ResType.getUnqualifiedType();
14561 }
14562 }
14563
14564 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14565 /// This routine allows us to typecheck complex/recursive expressions
14566 /// where the declaration is needed for type checking. We only need to
14567 /// handle cases when the expression references a function designator
14568 /// or is an lvalue. Here are some examples:
14569 /// - &(x) => x
14570 /// - &*****f => f for f a function designator.
14571 /// - &s.xx => s
14572 /// - &s.zz[1].yy -> s, if zz is an array
14573 /// - *(x + 1) -> x, if x is an array
14574 /// - &"123"[2] -> 0
14575 /// - & __real__ x -> x
14576 ///
14577 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14578 /// members.
14579 static ValueDecl *getPrimaryDecl(Expr *E) {
14580 switch (E->getStmtClass()) {
14581 case Stmt::DeclRefExprClass:
14582 return cast<DeclRefExpr>(E)->getDecl();
14583 case Stmt::MemberExprClass:
14584 // If this is an arrow operator, the address is an offset from
14585 // the base's value, so the object the base refers to is
14586 // irrelevant.
14587 if (cast<MemberExpr>(E)->isArrow())
14588 return nullptr;
14589 // Otherwise, the expression refers to a part of the base
14590 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14591 case Stmt::ArraySubscriptExprClass: {
14592 // FIXME: This code shouldn't be necessary! We should catch the implicit
14593 // promotion of register arrays earlier.
14594 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14595 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14596 if (ICE->getSubExpr()->getType()->isArrayType())
14597 return getPrimaryDecl(ICE->getSubExpr());
14598 }
14599 return nullptr;
14600 }
14601 case Stmt::UnaryOperatorClass: {
14602 UnaryOperator *UO = cast<UnaryOperator>(E);
14603
14604 switch(UO->getOpcode()) {
14605 case UO_Real:
14606 case UO_Imag:
14607 case UO_Extension:
14608 return getPrimaryDecl(UO->getSubExpr());
14609 default:
14610 return nullptr;
14611 }
14612 }
14613 case Stmt::ParenExprClass:
14614 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14615 case Stmt::ImplicitCastExprClass:
14616 // If the result of an implicit cast is an l-value, we care about
14617 // the sub-expression; otherwise, the result here doesn't matter.
14618 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14619 case Stmt::CXXUuidofExprClass:
14620 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14621 default:
14622 return nullptr;
14623 }
14624 }
14625
14626 namespace {
14627 enum {
14628 AO_Bit_Field = 0,
14629 AO_Vector_Element = 1,
14630 AO_Property_Expansion = 2,
14631 AO_Register_Variable = 3,
14632 AO_Matrix_Element = 4,
14633 AO_No_Error = 5
14634 };
14635 }
14636 /// Diagnose invalid operand for address of operations.
14637 ///
14638 /// \param Type The type of operand which cannot have its address taken.
14639 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14640 Expr *E, unsigned Type) {
14641 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14642 }
14643
14644 bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14645 const Expr *Op,
14646 const CXXMethodDecl *MD) {
14647 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14648
14649 if (Op != DRE)
14650 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14651 << Op->getSourceRange();
14652
14653 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14654 if (isa<CXXDestructorDecl>(MD))
14655 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14656 << DRE->getSourceRange();
14657
14658 if (DRE->getQualifier())
14659 return false;
14660
14661 if (MD->getParent()->getName().empty())
14662 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14663 << DRE->getSourceRange();
14664
14665 SmallString<32> Str;
14666 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14667 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14668 << DRE->getSourceRange()
14669 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14670 }
14671
14672 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14673 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14674 if (PTy->getKind() == BuiltinType::Overload) {
14675 Expr *E = OrigOp.get()->IgnoreParens();
14676 if (!isa<OverloadExpr>(E)) {
14677 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14678 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14679 << OrigOp.get()->getSourceRange();
14680 return QualType();
14681 }
14682
14683 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14684 if (isa<UnresolvedMemberExpr>(Ovl))
14685 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14686 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14687 << OrigOp.get()->getSourceRange();
14688 return QualType();
14689 }
14690
14691 return Context.OverloadTy;
14692 }
14693
14694 if (PTy->getKind() == BuiltinType::UnknownAny)
14695 return Context.UnknownAnyTy;
14696
14697 if (PTy->getKind() == BuiltinType::BoundMember) {
14698 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14699 << OrigOp.get()->getSourceRange();
14700 return QualType();
14701 }
14702
14703 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14704 if (OrigOp.isInvalid()) return QualType();
14705 }
14706
14707 if (OrigOp.get()->isTypeDependent())
14708 return Context.DependentTy;
14709
14710 assert(!OrigOp.get()->hasPlaceholderType());
14711
14712 // Make sure to ignore parentheses in subsequent checks
14713 Expr *op = OrigOp.get()->IgnoreParens();
14714
14715 // In OpenCL captures for blocks called as lambda functions
14716 // are located in the private address space. Blocks used in
14717 // enqueue_kernel can be located in a different address space
14718 // depending on a vendor implementation. Thus preventing
14719 // taking an address of the capture to avoid invalid AS casts.
14720 if (LangOpts.OpenCL) {
14721 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14722 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14723 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14724 return QualType();
14725 }
14726 }
14727
14728 if (getLangOpts().C99) {
14729 // Implement C99-only parts of addressof rules.
14730 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14731 if (uOp->getOpcode() == UO_Deref)
14732 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14733 // (assuming the deref expression is valid).
14734 return uOp->getSubExpr()->getType();
14735 }
14736 // Technically, there should be a check for array subscript
14737 // expressions here, but the result of one is always an lvalue anyway.
14738 }
14739 ValueDecl *dcl = getPrimaryDecl(op);
14740
14741 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14742 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14743 op->getBeginLoc()))
14744 return QualType();
14745
14746 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14747 unsigned AddressOfError = AO_No_Error;
14748
14749 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14750 bool IsError = isSFINAEContext();
14751 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14752 : diag::ext_typecheck_addrof_temporary)
14753 << op->getType() << op->getSourceRange();
14754 if (IsError)
14755 return QualType();
14756 // Materialize the temporary as an lvalue so that we can take its address.
14757 OrigOp = op =
14758 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14759 } else if (isa<ObjCSelectorExpr>(op)) {
14760 return Context.getPointerType(op->getType());
14761 } else if (lval == Expr::LV_MemberFunction) {
14762 // If it's an instance method, make a member pointer.
14763 // The expression must have exactly the form &A::foo.
14764
14765 // If the underlying expression isn't a decl ref, give up.
14766 if (!isa<DeclRefExpr>(op)) {
14767 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14768 << OrigOp.get()->getSourceRange();
14769 return QualType();
14770 }
14771 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14772 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14773
14774 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14775 QualType MPTy = Context.getMemberPointerType(
14776 op->getType(), DRE->getQualifier(), MD->getParent());
14777
14778 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14779 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14780 // When pointer authentication is enabled, argument and return types of
14781 // vitual member functions must be complete. This is because vitrual
14782 // member function pointers are implemented using virtual dispatch
14783 // thunks and the thunks cannot be emitted if the argument or return
14784 // types are incomplete.
14785 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14786 SourceLocation DeclRefLoc,
14787 SourceLocation RetArgTypeLoc) {
14788 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14789 Diag(DeclRefLoc,
14790 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14791 Diag(RetArgTypeLoc,
14792 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14793 << T;
14794 return true;
14795 }
14796 return false;
14797 };
14798 QualType RetTy = MD->getReturnType();
14799 bool IsIncomplete =
14800 !RetTy->isVoidType() &&
14801 ReturnOrParamTypeIsIncomplete(
14802 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14803 for (auto *PVD : MD->parameters())
14804 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14805 PVD->getBeginLoc());
14806 if (IsIncomplete)
14807 return QualType();
14808 }
14809
14810 // Under the MS ABI, lock down the inheritance model now.
14811 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14812 (void)isCompleteType(OpLoc, MPTy);
14813 return MPTy;
14814 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14815 // C99 6.5.3.2p1
14816 // The operand must be either an l-value or a function designator
14817 if (!op->getType()->isFunctionType()) {
14818 // Use a special diagnostic for loads from property references.
14819 if (isa<PseudoObjectExpr>(op)) {
14820 AddressOfError = AO_Property_Expansion;
14821 } else {
14822 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14823 << op->getType() << op->getSourceRange();
14824 return QualType();
14825 }
14826 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14827 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14828 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14829 }
14830
14831 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14832 // The operand cannot be a bit-field
14833 AddressOfError = AO_Bit_Field;
14834 } else if (op->getObjectKind() == OK_VectorComponent) {
14835 // The operand cannot be an element of a vector
14836 AddressOfError = AO_Vector_Element;
14837 } else if (op->getObjectKind() == OK_MatrixComponent) {
14838 // The operand cannot be an element of a matrix.
14839 AddressOfError = AO_Matrix_Element;
14840 } else if (dcl) { // C99 6.5.3.2p1
14841 // We have an lvalue with a decl. Make sure the decl is not declared
14842 // with the register storage-class specifier.
14843 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14844 // in C++ it is not error to take address of a register
14845 // variable (c++03 7.1.1P3)
14846 if (vd->getStorageClass() == SC_Register &&
14847 !getLangOpts().CPlusPlus) {
14848 AddressOfError = AO_Register_Variable;
14849 }
14850 } else if (isa<MSPropertyDecl>(dcl)) {
14851 AddressOfError = AO_Property_Expansion;
14852 } else if (isa<FunctionTemplateDecl>(dcl)) {
14853 return Context.OverloadTy;
14854 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14855 // Okay: we can take the address of a field.
14856 // Could be a pointer to member, though, if there is an explicit
14857 // scope qualifier for the class.
14858
14859 // [C++26] [expr.prim.id.general]
14860 // If an id-expression E denotes a non-static non-type member
14861 // of some class C [...] and if E is a qualified-id, E is
14862 // not the un-parenthesized operand of the unary & operator [...]
14863 // the id-expression is transformed into a class member access expression.
14864 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
14865 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
14866 DeclContext *Ctx = dcl->getDeclContext();
14867 if (Ctx && Ctx->isRecord()) {
14868 if (dcl->getType()->isReferenceType()) {
14869 Diag(OpLoc,
14870 diag::err_cannot_form_pointer_to_member_of_reference_type)
14871 << dcl->getDeclName() << dcl->getType();
14872 return QualType();
14873 }
14874
14875 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14876 Ctx = Ctx->getParent();
14877
14878 QualType MPTy = Context.getMemberPointerType(
14879 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
14880 // Under the MS ABI, lock down the inheritance model now.
14881 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14882 (void)isCompleteType(OpLoc, MPTy);
14883 return MPTy;
14884 }
14885 }
14886 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
14887 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
14888 UnnamedGlobalConstantDecl>(dcl))
14889 llvm_unreachable("Unknown/unexpected decl type");
14890 }
14891
14892 if (AddressOfError != AO_No_Error) {
14893 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14894 return QualType();
14895 }
14896
14897 if (lval == Expr::LV_IncompleteVoidType) {
14898 // Taking the address of a void variable is technically illegal, but we
14899 // allow it in cases which are otherwise valid.
14900 // Example: "extern void x; void* y = &x;".
14901 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14902 }
14903
14904 // If the operand has type "type", the result has type "pointer to type".
14905 if (op->getType()->isObjCObjectType())
14906 return Context.getObjCObjectPointerType(op->getType());
14907
14908 // Cannot take the address of WebAssembly references or tables.
14909 if (Context.getTargetInfo().getTriple().isWasm()) {
14910 QualType OpTy = op->getType();
14911 if (OpTy.isWebAssemblyReferenceType()) {
14912 Diag(OpLoc, diag::err_wasm_ca_reference)
14913 << 1 << OrigOp.get()->getSourceRange();
14914 return QualType();
14915 }
14916 if (OpTy->isWebAssemblyTableType()) {
14917 Diag(OpLoc, diag::err_wasm_table_pr)
14918 << 1 << OrigOp.get()->getSourceRange();
14919 return QualType();
14920 }
14921 }
14922
14923 CheckAddressOfPackedMember(op);
14924
14925 return Context.getPointerType(op->getType());
14926 }
14927
14928 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14929 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14930 if (!DRE)
14931 return;
14932 const Decl *D = DRE->getDecl();
14933 if (!D)
14934 return;
14935 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14936 if (!Param)
14937 return;
14938 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14939 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14940 return;
14941 if (FunctionScopeInfo *FD = S.getCurFunction())
14942 FD->ModifiedNonNullParams.insert(Param);
14943 }
14944
14945 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14946 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14947 SourceLocation OpLoc,
14948 bool IsAfterAmp = false) {
14949 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14950 if (ConvResult.isInvalid())
14951 return QualType();
14952 Op = ConvResult.get();
14953 QualType OpTy = Op->getType();
14954 QualType Result;
14955
14956 if (isa<CXXReinterpretCastExpr>(Op->IgnoreParens())) {
14957 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14958 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14959 Op->getSourceRange());
14960 }
14961
14962 if (const PointerType *PT = OpTy->getAs<PointerType>())
14963 {
14964 Result = PT->getPointeeType();
14965 }
14966 else if (const ObjCObjectPointerType *OPT =
14967 OpTy->getAs<ObjCObjectPointerType>())
14968 Result = OPT->getPointeeType();
14969 else {
14970 ExprResult PR = S.CheckPlaceholderExpr(Op);
14971 if (PR.isInvalid()) return QualType();
14972 if (PR.get() != Op)
14973 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14974 }
14975
14976 if (Result.isNull()) {
14977 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14978 << OpTy << Op->getSourceRange();
14979 return QualType();
14980 }
14981
14982 if (Result->isVoidType()) {
14983 // C++ [expr.unary.op]p1:
14984 // [...] the expression to which [the unary * operator] is applied shall
14985 // be a pointer to an object type, or a pointer to a function type
14986 LangOptions LO = S.getLangOpts();
14987 if (LO.CPlusPlus)
14988 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14989 << OpTy << Op->getSourceRange();
14990 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14991 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14992 << OpTy << Op->getSourceRange();
14993 }
14994
14995 // Dereferences are usually l-values...
14996 VK = VK_LValue;
14997
14998 // ...except that certain expressions are never l-values in C.
14999 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15000 VK = VK_PRValue;
15001
15002 return Result;
15003 }
15004
15005 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15006 BinaryOperatorKind Opc;
15007 switch (Kind) {
15008 default: llvm_unreachable("Unknown binop!");
15009 case tok::periodstar: Opc = BO_PtrMemD; break;
15010 case tok::arrowstar: Opc = BO_PtrMemI; break;
15011 case tok::star: Opc = BO_Mul; break;
15012 case tok::slash: Opc = BO_Div; break;
15013 case tok::percent: Opc = BO_Rem; break;
15014 case tok::plus: Opc = BO_Add; break;
15015 case tok::minus: Opc = BO_Sub; break;
15016 case tok::lessless: Opc = BO_Shl; break;
15017 case tok::greatergreater: Opc = BO_Shr; break;
15018 case tok::lessequal: Opc = BO_LE; break;
15019 case tok::less: Opc = BO_LT; break;
15020 case tok::greaterequal: Opc = BO_GE; break;
15021 case tok::greater: Opc = BO_GT; break;
15022 case tok::exclaimequal: Opc = BO_NE; break;
15023 case tok::equalequal: Opc = BO_EQ; break;
15024 case tok::spaceship: Opc = BO_Cmp; break;
15025 case tok::amp: Opc = BO_And; break;
15026 case tok::caret: Opc = BO_Xor; break;
15027 case tok::pipe: Opc = BO_Or; break;
15028 case tok::ampamp: Opc = BO_LAnd; break;
15029 case tok::pipepipe: Opc = BO_LOr; break;
15030 case tok::equal: Opc = BO_Assign; break;
15031 case tok::starequal: Opc = BO_MulAssign; break;
15032 case tok::slashequal: Opc = BO_DivAssign; break;
15033 case tok::percentequal: Opc = BO_RemAssign; break;
15034 case tok::plusequal: Opc = BO_AddAssign; break;
15035 case tok::minusequal: Opc = BO_SubAssign; break;
15036 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15037 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15038 case tok::ampequal: Opc = BO_AndAssign; break;
15039 case tok::caretequal: Opc = BO_XorAssign; break;
15040 case tok::pipeequal: Opc = BO_OrAssign; break;
15041 case tok::comma: Opc = BO_Comma; break;
15042 }
15043 return Opc;
15044 }
15045
15046 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15047 tok::TokenKind Kind) {
15048 UnaryOperatorKind Opc;
15049 switch (Kind) {
15050 default: llvm_unreachable("Unknown unary op!");
15051 case tok::plusplus: Opc = UO_PreInc; break;
15052 case tok::minusminus: Opc = UO_PreDec; break;
15053 case tok::amp: Opc = UO_AddrOf; break;
15054 case tok::star: Opc = UO_Deref; break;
15055 case tok::plus: Opc = UO_Plus; break;
15056 case tok::minus: Opc = UO_Minus; break;
15057 case tok::tilde: Opc = UO_Not; break;
15058 case tok::exclaim: Opc = UO_LNot; break;
15059 case tok::kw___real: Opc = UO_Real; break;
15060 case tok::kw___imag: Opc = UO_Imag; break;
15061 case tok::kw___extension__: Opc = UO_Extension; break;
15062 }
15063 return Opc;
15064 }
15065
15066 const FieldDecl *
15067 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15068 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15069 // common for setters.
15070 // struct A {
15071 // int X;
15072 // -void setX(int X) { X = X; }
15073 // +void setX(int X) { this->X = X; }
15074 // };
15075
15076 // Only consider parameters for self assignment fixes.
15077 if (!isa<ParmVarDecl>(SelfAssigned))
15078 return nullptr;
15079 const auto *Method =
15080 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15081 if (!Method)
15082 return nullptr;
15083
15084 const CXXRecordDecl *Parent = Method->getParent();
15085 // In theory this is fixable if the lambda explicitly captures this, but
15086 // that's added complexity that's rarely going to be used.
15087 if (Parent->isLambda())
15088 return nullptr;
15089
15090 // FIXME: Use an actual Lookup operation instead of just traversing fields
15091 // in order to get base class fields.
15092 auto Field =
15093 llvm::find_if(Parent->fields(),
15094 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15095 return F->getDeclName() == Name;
15096 });
15097 return (Field != Parent->field_end()) ? *Field : nullptr;
15098 }
15099
15100 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15101 /// This warning suppressed in the event of macro expansions.
15102 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15103 SourceLocation OpLoc, bool IsBuiltin) {
15104 if (S.inTemplateInstantiation())
15105 return;
15106 if (S.isUnevaluatedContext())
15107 return;
15108 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15109 return;
15110 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15111 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15112 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15113 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15114 if (!LHSDeclRef || !RHSDeclRef ||
15115 LHSDeclRef->getLocation().isMacroID() ||
15116 RHSDeclRef->getLocation().isMacroID())
15117 return;
15118 const ValueDecl *LHSDecl =
15119 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15120 const ValueDecl *RHSDecl =
15121 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15122 if (LHSDecl != RHSDecl)
15123 return;
15124 if (LHSDecl->getType().isVolatileQualified())
15125 return;
15126 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15127 if (RefTy->getPointeeType().isVolatileQualified())
15128 return;
15129
15130 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15131 : diag::warn_self_assignment_overloaded)
15132 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15133 << RHSExpr->getSourceRange();
15134 if (const FieldDecl *SelfAssignField =
15135 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15136 Diag << 1 << SelfAssignField
15137 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15138 else
15139 Diag << 0;
15140 }
15141
15142 /// Check if a bitwise-& is performed on an Objective-C pointer. This
15143 /// is usually indicative of introspection within the Objective-C pointer.
15144 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15145 SourceLocation OpLoc) {
15146 if (!S.getLangOpts().ObjC)
15147 return;
15148
15149 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15150 const Expr *LHS = L.get();
15151 const Expr *RHS = R.get();
15152
15153 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15154 ObjCPointerExpr = LHS;
15155 OtherExpr = RHS;
15156 }
15157 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15158 ObjCPointerExpr = RHS;
15159 OtherExpr = LHS;
15160 }
15161
15162 // This warning is deliberately made very specific to reduce false
15163 // positives with logic that uses '&' for hashing. This logic mainly
15164 // looks for code trying to introspect into tagged pointers, which
15165 // code should generally never do.
15166 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15167 unsigned Diag = diag::warn_objc_pointer_masking;
15168 // Determine if we are introspecting the result of performSelectorXXX.
15169 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15170 // Special case messages to -performSelector and friends, which
15171 // can return non-pointer values boxed in a pointer value.
15172 // Some clients may wish to silence warnings in this subcase.
15173 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15174 Selector S = ME->getSelector();
15175 StringRef SelArg0 = S.getNameForSlot(0);
15176 if (SelArg0.starts_with("performSelector"))
15177 Diag = diag::warn_objc_pointer_masking_performSelector;
15178 }
15179
15180 S.Diag(OpLoc, Diag)
15181 << ObjCPointerExpr->getSourceRange();
15182 }
15183 }
15184
15185 // This helper function promotes a binary operator's operands (which are of a
15186 // half vector type) to a vector of floats and then truncates the result to
15187 // a vector of either half or short.
15188 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15189 BinaryOperatorKind Opc, QualType ResultTy,
15190 ExprValueKind VK, ExprObjectKind OK,
15191 bool IsCompAssign, SourceLocation OpLoc,
15192 FPOptionsOverride FPFeatures) {
15193 auto &Context = S.getASTContext();
15194 assert((isVector(ResultTy, Context.HalfTy) ||
15195 isVector(ResultTy, Context.ShortTy)) &&
15196 "Result must be a vector of half or short");
15197 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15198 isVector(RHS.get()->getType(), Context.HalfTy) &&
15199 "both operands expected to be a half vector");
15200
15201 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15202 QualType BinOpResTy = RHS.get()->getType();
15203
15204 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15205 // change BinOpResTy to a vector of ints.
15206 if (isVector(ResultTy, Context.ShortTy))
15207 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15208
15209 if (IsCompAssign)
15210 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15211 ResultTy, VK, OK, OpLoc, FPFeatures,
15212 BinOpResTy, BinOpResTy);
15213
15214 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15215 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15216 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15217 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15218 }
15219
15220 /// Returns true if conversion between vectors of halfs and vectors of floats
15221 /// is needed.
15222 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15223 Expr *E0, Expr *E1 = nullptr) {
15224 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15225 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15226 return false;
15227
15228 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15229 QualType Ty = E->IgnoreImplicit()->getType();
15230
15231 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15232 // to vectors of floats. Although the element type of the vectors is __fp16,
15233 // the vectors shouldn't be treated as storage-only types. See the
15234 // discussion here: https://reviews.llvm.org/rG825235c140e7
15235 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15236 if (VT->getVectorKind() == VectorKind::Neon)
15237 return false;
15238 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15239 }
15240 return false;
15241 };
15242
15243 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15244 }
15245
15246 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15247 BinaryOperatorKind Opc, Expr *LHSExpr,
15248 Expr *RHSExpr, bool ForFoldExpression) {
15249 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15250 // The syntax only allows initializer lists on the RHS of assignment,
15251 // so we don't need to worry about accepting invalid code for
15252 // non-assignment operators.
15253 // C++11 5.17p9:
15254 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15255 // of x = {} is x = T().
15256 InitializationKind Kind = InitializationKind::CreateDirectList(
15257 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15258 InitializedEntity Entity =
15259 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15260 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15261 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15262 if (Init.isInvalid())
15263 return Init;
15264 RHSExpr = Init.get();
15265 }
15266
15267 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15268 QualType ResultTy; // Result type of the binary operator.
15269 // The following two variables are used for compound assignment operators
15270 QualType CompLHSTy; // Type of LHS after promotions for computation
15271 QualType CompResultTy; // Type of computation result
15272 ExprValueKind VK = VK_PRValue;
15273 ExprObjectKind OK = OK_Ordinary;
15274 bool ConvertHalfVec = false;
15275
15276 if (!LHS.isUsable() || !RHS.isUsable())
15277 return ExprError();
15278
15279 if (getLangOpts().OpenCL) {
15280 QualType LHSTy = LHSExpr->getType();
15281 QualType RHSTy = RHSExpr->getType();
15282 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15283 // the ATOMIC_VAR_INIT macro.
15284 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15285 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15286 if (BO_Assign == Opc)
15287 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15288 else
15289 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15290 return ExprError();
15291 }
15292
15293 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15294 // only with a builtin functions and therefore should be disallowed here.
15295 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15296 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15297 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15298 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15299 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15300 return ExprError();
15301 }
15302 }
15303
15304 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15305 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15306
15307 switch (Opc) {
15308 case BO_Assign:
15309 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15310 if (getLangOpts().CPlusPlus &&
15311 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15312 VK = LHS.get()->getValueKind();
15313 OK = LHS.get()->getObjectKind();
15314 }
15315 if (!ResultTy.isNull()) {
15316 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15317 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15318
15319 // Avoid copying a block to the heap if the block is assigned to a local
15320 // auto variable that is declared in the same scope as the block. This
15321 // optimization is unsafe if the local variable is declared in an outer
15322 // scope. For example:
15323 //
15324 // BlockTy b;
15325 // {
15326 // b = ^{...};
15327 // }
15328 // // It is unsafe to invoke the block here if it wasn't copied to the
15329 // // heap.
15330 // b();
15331
15332 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15333 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15334 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15335 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15336 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15337
15338 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15339 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15340 NonTrivialCUnionContext::Assignment, NTCUK_Copy);
15341 }
15342 RecordModifiableNonNullParam(*this, LHS.get());
15343 break;
15344 case BO_PtrMemD:
15345 case BO_PtrMemI:
15346 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15347 Opc == BO_PtrMemI);
15348 break;
15349 case BO_Mul:
15350 case BO_Div:
15351 ConvertHalfVec = true;
15352 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15353 break;
15354 case BO_Rem:
15355 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15356 break;
15357 case BO_Add:
15358 ConvertHalfVec = true;
15359 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15360 break;
15361 case BO_Sub:
15362 ConvertHalfVec = true;
15363 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15364 break;
15365 case BO_Shl:
15366 case BO_Shr:
15367 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15368 break;
15369 case BO_LE:
15370 case BO_LT:
15371 case BO_GE:
15372 case BO_GT:
15373 ConvertHalfVec = true;
15374 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15375
15376 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15377 !ForFoldExpression && BI && BI->isComparisonOp())
15378 Diag(OpLoc, diag::warn_consecutive_comparison)
15379 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15380
15381 break;
15382 case BO_EQ:
15383 case BO_NE:
15384 ConvertHalfVec = true;
15385 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15386 break;
15387 case BO_Cmp:
15388 ConvertHalfVec = true;
15389 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15390 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15391 break;
15392 case BO_And:
15393 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15394 [[fallthrough]];
15395 case BO_Xor:
15396 case BO_Or:
15397 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15398 break;
15399 case BO_LAnd:
15400 case BO_LOr:
15401 ConvertHalfVec = true;
15402 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15403 break;
15404 case BO_MulAssign:
15405 case BO_DivAssign:
15406 ConvertHalfVec = true;
15407 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15408 CompLHSTy = CompResultTy;
15409 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15410 ResultTy =
15411 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15412 break;
15413 case BO_RemAssign:
15414 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15415 CompLHSTy = CompResultTy;
15416 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15417 ResultTy =
15418 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15419 break;
15420 case BO_AddAssign:
15421 ConvertHalfVec = true;
15422 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15423 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15424 ResultTy =
15425 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15426 break;
15427 case BO_SubAssign:
15428 ConvertHalfVec = true;
15429 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15430 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15431 ResultTy =
15432 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15433 break;
15434 case BO_ShlAssign:
15435 case BO_ShrAssign:
15436 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15437 CompLHSTy = CompResultTy;
15438 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15439 ResultTy =
15440 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15441 break;
15442 case BO_AndAssign:
15443 case BO_OrAssign: // fallthrough
15444 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15445 [[fallthrough]];
15446 case BO_XorAssign:
15447 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15448 CompLHSTy = CompResultTy;
15449 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15450 ResultTy =
15451 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15452 break;
15453 case BO_Comma:
15454 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15455 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15456 VK = RHS.get()->getValueKind();
15457 OK = RHS.get()->getObjectKind();
15458 }
15459 break;
15460 }
15461 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15462 return ExprError();
15463
15464 // Some of the binary operations require promoting operands of half vector to
15465 // float vectors and truncating the result back to half vector. For now, we do
15466 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15467 // arm64).
15468 assert(
15469 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15470 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15471 "both sides are half vectors or neither sides are");
15472 ConvertHalfVec =
15473 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15474
15475 // Check for array bounds violations for both sides of the BinaryOperator
15476 CheckArrayAccess(LHS.get());
15477 CheckArrayAccess(RHS.get());
15478
15479 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15480 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15481 &Context.Idents.get("object_setClass"),
15482 SourceLocation(), LookupOrdinaryName);
15483 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15484 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15485 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15486 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15487 "object_setClass(")
15488 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15489 ",")
15490 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15491 }
15492 else
15493 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15494 }
15495 else if (const ObjCIvarRefExpr *OIRE =
15496 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15497 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15498
15499 // Opc is not a compound assignment if CompResultTy is null.
15500 if (CompResultTy.isNull()) {
15501 if (ConvertHalfVec)
15502 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15503 OpLoc, CurFPFeatureOverrides());
15504 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15505 VK, OK, OpLoc, CurFPFeatureOverrides());
15506 }
15507
15508 // Handle compound assignments.
15509 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15510 OK_ObjCProperty) {
15511 VK = VK_LValue;
15512 OK = LHS.get()->getObjectKind();
15513 }
15514
15515 // The LHS is not converted to the result type for fixed-point compound
15516 // assignment as the common type is computed on demand. Reset the CompLHSTy
15517 // to the LHS type we would have gotten after unary conversions.
15518 if (CompResultTy->isFixedPointType())
15519 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15520
15521 if (ConvertHalfVec)
15522 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15523 OpLoc, CurFPFeatureOverrides());
15524
15525 return CompoundAssignOperator::Create(
15526 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15527 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15528 }
15529
15530 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15531 /// operators are mixed in a way that suggests that the programmer forgot that
15532 /// comparison operators have higher precedence. The most typical example of
15533 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15534 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15535 SourceLocation OpLoc, Expr *LHSExpr,
15536 Expr *RHSExpr) {
15537 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15538 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15539
15540 // Check that one of the sides is a comparison operator and the other isn't.
15541 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15542 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15543 if (isLeftComp == isRightComp)
15544 return;
15545
15546 // Bitwise operations are sometimes used as eager logical ops.
15547 // Don't diagnose this.
15548 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15549 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15550 if (isLeftBitwise || isRightBitwise)
15551 return;
15552
15553 SourceRange DiagRange = isLeftComp
15554 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15555 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15556 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15557 SourceRange ParensRange =
15558 isLeftComp
15559 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15560 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15561
15562 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15563 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15564 SuggestParentheses(Self, OpLoc,
15565 Self.PDiag(diag::note_precedence_silence) << OpStr,
15566 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15567 SuggestParentheses(Self, OpLoc,
15568 Self.PDiag(diag::note_precedence_bitwise_first)
15569 << BinaryOperator::getOpcodeStr(Opc),
15570 ParensRange);
15571 }
15572
15573 /// It accepts a '&&' expr that is inside a '||' one.
15574 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15575 /// in parentheses.
15576 static void
15577 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15578 BinaryOperator *Bop) {
15579 assert(Bop->getOpcode() == BO_LAnd);
15580 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15581 << Bop->getSourceRange() << OpLoc;
15582 SuggestParentheses(Self, Bop->getOperatorLoc(),
15583 Self.PDiag(diag::note_precedence_silence)
15584 << Bop->getOpcodeStr(),
15585 Bop->getSourceRange());
15586 }
15587
15588 /// Look for '&&' in the left hand of a '||' expr.
15589 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15590 Expr *LHSExpr, Expr *RHSExpr) {
15591 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15592 if (Bop->getOpcode() == BO_LAnd) {
15593 // If it's "string_literal && a || b" don't warn since the precedence
15594 // doesn't matter.
15595 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15596 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15597 } else if (Bop->getOpcode() == BO_LOr) {
15598 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15599 // If it's "a || b && string_literal || c" we didn't warn earlier for
15600 // "a || b && string_literal", but warn now.
15601 if (RBop->getOpcode() == BO_LAnd &&
15602 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15603 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15604 }
15605 }
15606 }
15607 }
15608
15609 /// Look for '&&' in the right hand of a '||' expr.
15610 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15611 Expr *LHSExpr, Expr *RHSExpr) {
15612 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15613 if (Bop->getOpcode() == BO_LAnd) {
15614 // If it's "a || b && string_literal" don't warn since the precedence
15615 // doesn't matter.
15616 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15617 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15618 }
15619 }
15620 }
15621
15622 /// Look for bitwise op in the left or right hand of a bitwise op with
15623 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15624 /// the '&' expression in parentheses.
15625 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15626 SourceLocation OpLoc, Expr *SubExpr) {
15627 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15628 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15629 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15630 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15631 << Bop->getSourceRange() << OpLoc;
15632 SuggestParentheses(S, Bop->getOperatorLoc(),
15633 S.PDiag(diag::note_precedence_silence)
15634 << Bop->getOpcodeStr(),
15635 Bop->getSourceRange());
15636 }
15637 }
15638 }
15639
15640 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15641 Expr *SubExpr, StringRef Shift) {
15642 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15643 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15644 StringRef Op = Bop->getOpcodeStr();
15645 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15646 << Bop->getSourceRange() << OpLoc << Shift << Op;
15647 SuggestParentheses(S, Bop->getOperatorLoc(),
15648 S.PDiag(diag::note_precedence_silence) << Op,
15649 Bop->getSourceRange());
15650 }
15651 }
15652 }
15653
15654 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15655 Expr *LHSExpr, Expr *RHSExpr) {
15656 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15657 if (!OCE)
15658 return;
15659
15660 FunctionDecl *FD = OCE->getDirectCallee();
15661 if (!FD || !FD->isOverloadedOperator())
15662 return;
15663
15664 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15665 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15666 return;
15667
15668 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15669 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15670 << (Kind == OO_LessLess);
15671 SuggestParentheses(S, OCE->getOperatorLoc(),
15672 S.PDiag(diag::note_precedence_silence)
15673 << (Kind == OO_LessLess ? "<<" : ">>"),
15674 OCE->getSourceRange());
15675 SuggestParentheses(
15676 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15677 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15678 }
15679
15680 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15681 /// precedence.
15682 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15683 SourceLocation OpLoc, Expr *LHSExpr,
15684 Expr *RHSExpr){
15685 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15686 if (BinaryOperator::isBitwiseOp(Opc))
15687 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15688
15689 // Diagnose "arg1 & arg2 | arg3"
15690 if ((Opc == BO_Or || Opc == BO_Xor) &&
15691 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15692 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15693 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15694 }
15695
15696 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15697 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15698 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15699 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15700 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15701 }
15702
15703 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15704 || Opc == BO_Shr) {
15705 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15706 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15707 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15708 }
15709
15710 // Warn on overloaded shift operators and comparisons, such as:
15711 // cout << 5 == 4;
15712 if (BinaryOperator::isComparisonOp(Opc))
15713 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15714 }
15715
15716 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15717 tok::TokenKind Kind,
15718 Expr *LHSExpr, Expr *RHSExpr) {
15719 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15720 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15721 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15722
15723 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15724 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15725
15726 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15727 ? BuiltinCountedByRefKind::Assignment
15728 : BuiltinCountedByRefKind::BinaryExpr;
15729
15730 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15731 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15732
15733 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15734 }
15735
15736 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15737 UnresolvedSetImpl &Functions) {
15738 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15739 if (OverOp != OO_None && OverOp != OO_Equal)
15740 LookupOverloadedOperatorName(OverOp, S, Functions);
15741
15742 // In C++20 onwards, we may have a second operator to look up.
15743 if (getLangOpts().CPlusPlus20) {
15744 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15745 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15746 }
15747 }
15748
15749 /// Build an overloaded binary operator expression in the given scope.
15750 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15751 BinaryOperatorKind Opc,
15752 Expr *LHS, Expr *RHS) {
15753 switch (Opc) {
15754 case BO_Assign:
15755 // In the non-overloaded case, we warn about self-assignment (x = x) for
15756 // both simple assignment and certain compound assignments where algebra
15757 // tells us the operation yields a constant result. When the operator is
15758 // overloaded, we can't do the latter because we don't want to assume that
15759 // those algebraic identities still apply; for example, a path-building
15760 // library might use operator/= to append paths. But it's still reasonable
15761 // to assume that simple assignment is just moving/copying values around
15762 // and so self-assignment is likely a bug.
15763 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15764 [[fallthrough]];
15765 case BO_DivAssign:
15766 case BO_RemAssign:
15767 case BO_SubAssign:
15768 case BO_AndAssign:
15769 case BO_OrAssign:
15770 case BO_XorAssign:
15771 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15772 break;
15773 default:
15774 break;
15775 }
15776
15777 // Find all of the overloaded operators visible from this point.
15778 UnresolvedSet<16> Functions;
15779 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15780
15781 // Build the (potentially-overloaded, potentially-dependent)
15782 // binary operation.
15783 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15784 }
15785
15786 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15787 BinaryOperatorKind Opc, Expr *LHSExpr,
15788 Expr *RHSExpr, bool ForFoldExpression) {
15789 if (!LHSExpr || !RHSExpr)
15790 return ExprError();
15791
15792 // We want to end up calling one of SemaPseudoObject::checkAssignment
15793 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15794 // both expressions are overloadable or either is type-dependent),
15795 // or CreateBuiltinBinOp (in any other case). We also want to get
15796 // any placeholder types out of the way.
15797
15798 // Handle pseudo-objects in the LHS.
15799 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15800 // Assignments with a pseudo-object l-value need special analysis.
15801 if (pty->getKind() == BuiltinType::PseudoObject &&
15802 BinaryOperator::isAssignmentOp(Opc))
15803 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15804
15805 // Don't resolve overloads if the other type is overloadable.
15806 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15807 // We can't actually test that if we still have a placeholder,
15808 // though. Fortunately, none of the exceptions we see in that
15809 // code below are valid when the LHS is an overload set. Note
15810 // that an overload set can be dependently-typed, but it never
15811 // instantiates to having an overloadable type.
15812 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15813 if (resolvedRHS.isInvalid()) return ExprError();
15814 RHSExpr = resolvedRHS.get();
15815
15816 if (RHSExpr->isTypeDependent() ||
15817 RHSExpr->getType()->isOverloadableType())
15818 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15819 }
15820
15821 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15822 // template, diagnose the missing 'template' keyword instead of diagnosing
15823 // an invalid use of a bound member function.
15824 //
15825 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15826 // to C++1z [over.over]/1.4, but we already checked for that case above.
15827 if (Opc == BO_LT && inTemplateInstantiation() &&
15828 (pty->getKind() == BuiltinType::BoundMember ||
15829 pty->getKind() == BuiltinType::Overload)) {
15830 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15831 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15832 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15833 return isa<FunctionTemplateDecl>(ND);
15834 })) {
15835 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15836 : OE->getNameLoc(),
15837 diag::err_template_kw_missing)
15838 << OE->getName().getAsIdentifierInfo();
15839 return ExprError();
15840 }
15841 }
15842
15843 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15844 if (LHS.isInvalid()) return ExprError();
15845 LHSExpr = LHS.get();
15846 }
15847
15848 // Handle pseudo-objects in the RHS.
15849 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15850 // An overload in the RHS can potentially be resolved by the type
15851 // being assigned to.
15852 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15853 if (getLangOpts().CPlusPlus &&
15854 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15855 LHSExpr->getType()->isOverloadableType()))
15856 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15857
15858 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15859 ForFoldExpression);
15860 }
15861
15862 // Don't resolve overloads if the other type is overloadable.
15863 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15864 LHSExpr->getType()->isOverloadableType())
15865 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15866
15867 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15868 if (!resolvedRHS.isUsable()) return ExprError();
15869 RHSExpr = resolvedRHS.get();
15870 }
15871
15872 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
15873 LHSExpr->getType()->isHLSLResourceRecordArray())) {
15874 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
15875 return ExprError();
15876 }
15877
15878 if (getLangOpts().CPlusPlus) {
15879 // Otherwise, build an overloaded op if either expression is type-dependent
15880 // or has an overloadable type.
15881 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15882 LHSExpr->getType()->isOverloadableType() ||
15883 RHSExpr->getType()->isOverloadableType())
15884 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15885 }
15886
15887 if (getLangOpts().RecoveryAST &&
15888 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15889 assert(!getLangOpts().CPlusPlus);
15890 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15891 "Should only occur in error-recovery path.");
15892 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15893 // C [6.15.16] p3:
15894 // An assignment expression has the value of the left operand after the
15895 // assignment, but is not an lvalue.
15896 return CompoundAssignOperator::Create(
15897 Context, LHSExpr, RHSExpr, Opc,
15898 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15899 OpLoc, CurFPFeatureOverrides());
15900 QualType ResultType;
15901 switch (Opc) {
15902 case BO_Assign:
15903 ResultType = LHSExpr->getType().getUnqualifiedType();
15904 break;
15905 case BO_LT:
15906 case BO_GT:
15907 case BO_LE:
15908 case BO_GE:
15909 case BO_EQ:
15910 case BO_NE:
15911 case BO_LAnd:
15912 case BO_LOr:
15913 // These operators have a fixed result type regardless of operands.
15914 ResultType = Context.IntTy;
15915 break;
15916 case BO_Comma:
15917 ResultType = RHSExpr->getType();
15918 break;
15919 default:
15920 ResultType = Context.DependentTy;
15921 break;
15922 }
15923 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15924 VK_PRValue, OK_Ordinary, OpLoc,
15925 CurFPFeatureOverrides());
15926 }
15927
15928 // Build a built-in binary operation.
15929 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15930 }
15931
15932 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15933 if (T.isNull() || T->isDependentType())
15934 return false;
15935
15936 if (!Ctx.isPromotableIntegerType(T))
15937 return true;
15938
15939 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15940 }
15941
15942 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15943 UnaryOperatorKind Opc, Expr *InputExpr,
15944 bool IsAfterAmp) {
15945 ExprResult Input = InputExpr;
15946 ExprValueKind VK = VK_PRValue;
15947 ExprObjectKind OK = OK_Ordinary;
15948 QualType resultType;
15949 bool CanOverflow = false;
15950
15951 bool ConvertHalfVec = false;
15952 if (getLangOpts().OpenCL) {
15953 QualType Ty = InputExpr->getType();
15954 // The only legal unary operation for atomics is '&'.
15955 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15956 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15957 // only with a builtin functions and therefore should be disallowed here.
15958 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15959 || Ty->isBlockPointerType())) {
15960 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15961 << InputExpr->getType()
15962 << Input.get()->getSourceRange());
15963 }
15964 }
15965
15966 if (getLangOpts().HLSL && OpLoc.isValid()) {
15967 if (Opc == UO_AddrOf)
15968 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15969 if (Opc == UO_Deref)
15970 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15971 }
15972
15973 if (InputExpr->isTypeDependent() &&
15974 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15975 resultType = Context.DependentTy;
15976 } else {
15977 switch (Opc) {
15978 case UO_PreInc:
15979 case UO_PreDec:
15980 case UO_PostInc:
15981 case UO_PostDec:
15982 resultType =
15983 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15984 Opc == UO_PreInc || Opc == UO_PostInc,
15985 Opc == UO_PreInc || Opc == UO_PreDec);
15986 CanOverflow = isOverflowingIntegerType(Context, resultType);
15987 break;
15988 case UO_AddrOf:
15989 resultType = CheckAddressOfOperand(Input, OpLoc);
15990 CheckAddressOfNoDeref(InputExpr);
15991 RecordModifiableNonNullParam(*this, InputExpr);
15992 break;
15993 case UO_Deref: {
15994 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15995 if (Input.isInvalid())
15996 return ExprError();
15997 resultType =
15998 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15999 break;
16000 }
16001 case UO_Plus:
16002 case UO_Minus:
16003 CanOverflow = Opc == UO_Minus &&
16004 isOverflowingIntegerType(Context, Input.get()->getType());
16005 Input = UsualUnaryConversions(Input.get());
16006 if (Input.isInvalid())
16007 return ExprError();
16008 // Unary plus and minus require promoting an operand of half vector to a
16009 // float vector and truncating the result back to a half vector. For now,
16010 // we do this only when HalfArgsAndReturns is set (that is, when the
16011 // target is arm or arm64).
16012 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16013
16014 // If the operand is a half vector, promote it to a float vector.
16015 if (ConvertHalfVec)
16016 Input = convertVector(Input.get(), Context.FloatTy, *this);
16017 resultType = Input.get()->getType();
16018 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16019 break;
16020 else if (resultType->isVectorType() &&
16021 // The z vector extensions don't allow + or - with bool vectors.
16022 (!Context.getLangOpts().ZVector ||
16023 resultType->castAs<VectorType>()->getVectorKind() !=
16024 VectorKind::AltiVecBool))
16025 break;
16026 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16027 break;
16028 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16029 Opc == UO_Plus && resultType->isPointerType())
16030 break;
16031
16032 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16033 << resultType << Input.get()->getSourceRange());
16034
16035 case UO_Not: // bitwise complement
16036 Input = UsualUnaryConversions(Input.get());
16037 if (Input.isInvalid())
16038 return ExprError();
16039 resultType = Input.get()->getType();
16040 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16041 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16042 // C99 does not support '~' for complex conjugation.
16043 Diag(OpLoc, diag::ext_integer_complement_complex)
16044 << resultType << Input.get()->getSourceRange();
16045 else if (resultType->hasIntegerRepresentation())
16046 break;
16047 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16048 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16049 // on vector float types.
16050 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16051 if (!T->isIntegerType())
16052 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16053 << resultType << Input.get()->getSourceRange());
16054 } else {
16055 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16056 << resultType << Input.get()->getSourceRange());
16057 }
16058 break;
16059
16060 case UO_LNot: // logical negation
16061 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16062 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16063 if (Input.isInvalid())
16064 return ExprError();
16065 resultType = Input.get()->getType();
16066
16067 // Though we still have to promote half FP to float...
16068 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16069 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16070 .get();
16071 resultType = Context.FloatTy;
16072 }
16073
16074 // WebAsembly tables can't be used in unary expressions.
16075 if (resultType->isPointerType() &&
16076 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16077 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16078 << resultType << Input.get()->getSourceRange());
16079 }
16080
16081 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16082 // C99 6.5.3.3p1: ok, fallthrough;
16083 if (Context.getLangOpts().CPlusPlus) {
16084 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16085 // operand contextually converted to bool.
16086 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16087 ScalarTypeToBooleanCastKind(resultType));
16088 } else if (Context.getLangOpts().OpenCL &&
16089 Context.getLangOpts().OpenCLVersion < 120) {
16090 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16091 // operate on scalar float types.
16092 if (!resultType->isIntegerType() && !resultType->isPointerType())
16093 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16094 << resultType << Input.get()->getSourceRange());
16095 }
16096 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16097 !resultType->hasBooleanRepresentation()) {
16098 // HLSL unary logical 'not' behaves like C++, which states that the
16099 // operand is converted to bool and the result is bool, however HLSL
16100 // extends this property to vectors.
16101 const VectorType *VTy = resultType->castAs<VectorType>();
16102 resultType =
16103 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16104
16105 Input = ImpCastExprToType(
16106 Input.get(), resultType,
16107 ScalarTypeToBooleanCastKind(VTy->getElementType()))
16108 .get();
16109 break;
16110 } else if (resultType->isExtVectorType()) {
16111 if (Context.getLangOpts().OpenCL &&
16112 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16113 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16114 // operate on vector float types.
16115 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16116 if (!T->isIntegerType())
16117 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16118 << resultType << Input.get()->getSourceRange());
16119 }
16120 // Vector logical not returns the signed variant of the operand type.
16121 resultType = GetSignedVectorType(resultType);
16122 break;
16123 } else if (Context.getLangOpts().CPlusPlus &&
16124 resultType->isVectorType()) {
16125 const VectorType *VTy = resultType->castAs<VectorType>();
16126 if (VTy->getVectorKind() != VectorKind::Generic)
16127 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16128 << resultType << Input.get()->getSourceRange());
16129
16130 // Vector logical not returns the signed variant of the operand type.
16131 resultType = GetSignedVectorType(resultType);
16132 break;
16133 } else {
16134 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16135 << resultType << Input.get()->getSourceRange());
16136 }
16137
16138 // LNot always has type int. C99 6.5.3.3p5.
16139 // In C++, it's bool. C++ 5.3.1p8
16140 resultType = Context.getLogicalOperationType();
16141 break;
16142 case UO_Real:
16143 case UO_Imag:
16144 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16145 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16146 // ordinary complex l-values to ordinary l-values and all other values to
16147 // r-values.
16148 if (Input.isInvalid())
16149 return ExprError();
16150 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16151 if (Input.get()->isGLValue() &&
16152 Input.get()->getObjectKind() == OK_Ordinary)
16153 VK = Input.get()->getValueKind();
16154 } else if (!getLangOpts().CPlusPlus) {
16155 // In C, a volatile scalar is read by __imag. In C++, it is not.
16156 Input = DefaultLvalueConversion(Input.get());
16157 }
16158 break;
16159 case UO_Extension:
16160 resultType = Input.get()->getType();
16161 VK = Input.get()->getValueKind();
16162 OK = Input.get()->getObjectKind();
16163 break;
16164 case UO_Coawait:
16165 // It's unnecessary to represent the pass-through operator co_await in the
16166 // AST; just return the input expression instead.
16167 assert(!Input.get()->getType()->isDependentType() &&
16168 "the co_await expression must be non-dependant before "
16169 "building operator co_await");
16170 return Input;
16171 }
16172 }
16173 if (resultType.isNull() || Input.isInvalid())
16174 return ExprError();
16175
16176 // Check for array bounds violations in the operand of the UnaryOperator,
16177 // except for the '*' and '&' operators that have to be handled specially
16178 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16179 // that are explicitly defined as valid by the standard).
16180 if (Opc != UO_AddrOf && Opc != UO_Deref)
16181 CheckArrayAccess(Input.get());
16182
16183 auto *UO =
16184 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16185 OpLoc, CanOverflow, CurFPFeatureOverrides());
16186
16187 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16188 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16189 !isUnevaluatedContext())
16190 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16191
16192 // Convert the result back to a half vector.
16193 if (ConvertHalfVec)
16194 return convertVector(UO, Context.HalfTy, *this);
16195 return UO;
16196 }
16197
16198 bool Sema::isQualifiedMemberAccess(Expr *E) {
16199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16200 if (!DRE->getQualifier())
16201 return false;
16202
16203 ValueDecl *VD = DRE->getDecl();
16204 if (!VD->isCXXClassMember())
16205 return false;
16206
16207 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16208 return true;
16209 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16210 return Method->isImplicitObjectMemberFunction();
16211
16212 return false;
16213 }
16214
16215 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16216 if (!ULE->getQualifier())
16217 return false;
16218
16219 for (NamedDecl *D : ULE->decls()) {
16220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16221 if (Method->isImplicitObjectMemberFunction())
16222 return true;
16223 } else {
16224 // Overload set does not contain methods.
16225 break;
16226 }
16227 }
16228
16229 return false;
16230 }
16231
16232 return false;
16233 }
16234
16235 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16236 UnaryOperatorKind Opc, Expr *Input,
16237 bool IsAfterAmp) {
16238 // First things first: handle placeholders so that the
16239 // overloaded-operator check considers the right type.
16240 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16241 // Increment and decrement of pseudo-object references.
16242 if (pty->getKind() == BuiltinType::PseudoObject &&
16243 UnaryOperator::isIncrementDecrementOp(Opc))
16244 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16245
16246 // extension is always a builtin operator.
16247 if (Opc == UO_Extension)
16248 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16249
16250 // & gets special logic for several kinds of placeholder.
16251 // The builtin code knows what to do.
16252 if (Opc == UO_AddrOf &&
16253 (pty->getKind() == BuiltinType::Overload ||
16254 pty->getKind() == BuiltinType::UnknownAny ||
16255 pty->getKind() == BuiltinType::BoundMember))
16256 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16257
16258 // Anything else needs to be handled now.
16259 ExprResult Result = CheckPlaceholderExpr(Input);
16260 if (Result.isInvalid()) return ExprError();
16261 Input = Result.get();
16262 }
16263
16264 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16265 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16266 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16267 // Find all of the overloaded operators visible from this point.
16268 UnresolvedSet<16> Functions;
16269 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16270 if (S && OverOp != OO_None)
16271 LookupOverloadedOperatorName(OverOp, S, Functions);
16272
16273 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16274 }
16275
16276 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16277 }
16278
16279 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16280 Expr *Input, bool IsAfterAmp) {
16281 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16282 IsAfterAmp);
16283 }
16284
16285 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16286 LabelDecl *TheDecl) {
16287 TheDecl->markUsed(Context);
16288 // Create the AST node. The address of a label always has type 'void*'.
16289 auto *Res = new (Context) AddrLabelExpr(
16290 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16291
16292 if (getCurFunction())
16293 getCurFunction()->AddrLabels.push_back(Res);
16294
16295 return Res;
16296 }
16297
16298 void Sema::ActOnStartStmtExpr() {
16299 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16300 // Make sure we diagnose jumping into a statement expression.
16301 setFunctionHasBranchProtectedScope();
16302 }
16303
16304 void Sema::ActOnStmtExprError() {
16305 // Note that function is also called by TreeTransform when leaving a
16306 // StmtExpr scope without rebuilding anything.
16307
16308 DiscardCleanupsInEvaluationContext();
16309 PopExpressionEvaluationContext();
16310 }
16311
16312 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16313 SourceLocation RPLoc) {
16314 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16315 }
16316
16317 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16318 SourceLocation RPLoc, unsigned TemplateDepth) {
16319 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16320 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16321
16322 if (hasAnyUnrecoverableErrorsInThisFunction())
16323 DiscardCleanupsInEvaluationContext();
16324 assert(!Cleanup.exprNeedsCleanups() &&
16325 "cleanups within StmtExpr not correctly bound!");
16326 PopExpressionEvaluationContext();
16327
16328 // FIXME: there are a variety of strange constraints to enforce here, for
16329 // example, it is not possible to goto into a stmt expression apparently.
16330 // More semantic analysis is needed.
16331
16332 // If there are sub-stmts in the compound stmt, take the type of the last one
16333 // as the type of the stmtexpr.
16334 QualType Ty = Context.VoidTy;
16335 bool StmtExprMayBindToTemp = false;
16336 if (!Compound->body_empty()) {
16337 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16338 if (const Expr *Value = LastStmt->getExprStmt()) {
16339 StmtExprMayBindToTemp = true;
16340 Ty = Value->getType();
16341 }
16342 }
16343 }
16344
16345 // FIXME: Check that expression type is complete/non-abstract; statement
16346 // expressions are not lvalues.
16347 Expr *ResStmtExpr =
16348 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16349 if (StmtExprMayBindToTemp)
16350 return MaybeBindToTemporary(ResStmtExpr);
16351 return ResStmtExpr;
16352 }
16353
16354 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16355 if (ER.isInvalid())
16356 return ExprError();
16357
16358 // Do function/array conversion on the last expression, but not
16359 // lvalue-to-rvalue. However, initialize an unqualified type.
16360 ER = DefaultFunctionArrayConversion(ER.get());
16361 if (ER.isInvalid())
16362 return ExprError();
16363 Expr *E = ER.get();
16364
16365 if (E->isTypeDependent())
16366 return E;
16367
16368 // In ARC, if the final expression ends in a consume, splice
16369 // the consume out and bind it later. In the alternate case
16370 // (when dealing with a retainable type), the result
16371 // initialization will create a produce. In both cases the
16372 // result will be +1, and we'll need to balance that out with
16373 // a bind.
16374 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16375 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16376 return Cast->getSubExpr();
16377
16378 // FIXME: Provide a better location for the initialization.
16379 return PerformCopyInitialization(
16380 InitializedEntity::InitializeStmtExprResult(
16381 E->getBeginLoc(), E->getType().getAtomicUnqualifiedType()),
16382 SourceLocation(), E);
16383 }
16384
16385 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16386 TypeSourceInfo *TInfo,
16387 ArrayRef<OffsetOfComponent> Components,
16388 SourceLocation RParenLoc) {
16389 QualType ArgTy = TInfo->getType();
16390 bool Dependent = ArgTy->isDependentType();
16391 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16392
16393 // We must have at least one component that refers to the type, and the first
16394 // one is known to be a field designator. Verify that the ArgTy represents
16395 // a struct/union/class.
16396 if (!Dependent && !ArgTy->isRecordType())
16397 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16398 << ArgTy << TypeRange);
16399
16400 // Type must be complete per C99 7.17p3 because a declaring a variable
16401 // with an incomplete type would be ill-formed.
16402 if (!Dependent
16403 && RequireCompleteType(BuiltinLoc, ArgTy,
16404 diag::err_offsetof_incomplete_type, TypeRange))
16405 return ExprError();
16406
16407 bool DidWarnAboutNonPOD = false;
16408 QualType CurrentType = ArgTy;
16409 SmallVector<OffsetOfNode, 4> Comps;
16410 SmallVector<Expr*, 4> Exprs;
16411 for (const OffsetOfComponent &OC : Components) {
16412 if (OC.isBrackets) {
16413 // Offset of an array sub-field. TODO: Should we allow vector elements?
16414 if (!CurrentType->isDependentType()) {
16415 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16416 if(!AT)
16417 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16418 << CurrentType);
16419 CurrentType = AT->getElementType();
16420 } else
16421 CurrentType = Context.DependentTy;
16422
16423 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16424 if (IdxRval.isInvalid())
16425 return ExprError();
16426 Expr *Idx = IdxRval.get();
16427
16428 // The expression must be an integral expression.
16429 // FIXME: An integral constant expression?
16430 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16431 !Idx->getType()->isIntegerType())
16432 return ExprError(
16433 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16434 << Idx->getSourceRange());
16435
16436 // Record this array index.
16437 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16438 Exprs.push_back(Idx);
16439 continue;
16440 }
16441
16442 // Offset of a field.
16443 if (CurrentType->isDependentType()) {
16444 // We have the offset of a field, but we can't look into the dependent
16445 // type. Just record the identifier of the field.
16446 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16447 CurrentType = Context.DependentTy;
16448 continue;
16449 }
16450
16451 // We need to have a complete type to look into.
16452 if (RequireCompleteType(OC.LocStart, CurrentType,
16453 diag::err_offsetof_incomplete_type))
16454 return ExprError();
16455
16456 // Look for the designated field.
16457 auto *RD = CurrentType->getAsRecordDecl();
16458 if (!RD)
16459 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16460 << CurrentType);
16461
16462 // C++ [lib.support.types]p5:
16463 // The macro offsetof accepts a restricted set of type arguments in this
16464 // International Standard. type shall be a POD structure or a POD union
16465 // (clause 9).
16466 // C++11 [support.types]p4:
16467 // If type is not a standard-layout class (Clause 9), the results are
16468 // undefined.
16469 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16470 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16471 unsigned DiagID =
16472 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16473 : diag::ext_offsetof_non_pod_type;
16474
16475 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16476 Diag(BuiltinLoc, DiagID)
16477 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16478 DidWarnAboutNonPOD = true;
16479 }
16480 }
16481
16482 // Look for the field.
16483 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16484 LookupQualifiedName(R, RD);
16485 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16486 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16487 if (!MemberDecl) {
16488 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16489 MemberDecl = IndirectMemberDecl->getAnonField();
16490 }
16491
16492 if (!MemberDecl) {
16493 // Lookup could be ambiguous when looking up a placeholder variable
16494 // __builtin_offsetof(S, _).
16495 // In that case we would already have emitted a diagnostic
16496 if (!R.isAmbiguous())
16497 Diag(BuiltinLoc, diag::err_no_member)
16498 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16499 return ExprError();
16500 }
16501
16502 // C99 7.17p3:
16503 // (If the specified member is a bit-field, the behavior is undefined.)
16504 //
16505 // We diagnose this as an error.
16506 if (MemberDecl->isBitField()) {
16507 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16508 << MemberDecl->getDeclName()
16509 << SourceRange(BuiltinLoc, RParenLoc);
16510 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16511 return ExprError();
16512 }
16513
16514 RecordDecl *Parent = MemberDecl->getParent();
16515 if (IndirectMemberDecl)
16516 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16517
16518 // If the member was found in a base class, introduce OffsetOfNodes for
16519 // the base class indirections.
16520 CXXBasePaths Paths;
16521 if (IsDerivedFrom(OC.LocStart, CurrentType,
16522 Context.getCanonicalTagType(Parent), Paths)) {
16523 if (Paths.getDetectedVirtual()) {
16524 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16525 << MemberDecl->getDeclName()
16526 << SourceRange(BuiltinLoc, RParenLoc);
16527 return ExprError();
16528 }
16529
16530 CXXBasePath &Path = Paths.front();
16531 for (const CXXBasePathElement &B : Path)
16532 Comps.push_back(OffsetOfNode(B.Base));
16533 }
16534
16535 if (IndirectMemberDecl) {
16536 for (auto *FI : IndirectMemberDecl->chain()) {
16537 assert(isa<FieldDecl>(FI));
16538 Comps.push_back(OffsetOfNode(OC.LocStart,
16539 cast<FieldDecl>(FI), OC.LocEnd));
16540 }
16541 } else
16542 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16543
16544 CurrentType = MemberDecl->getType().getNonReferenceType();
16545 }
16546
16547 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16548 Comps, Exprs, RParenLoc);
16549 }
16550
16551 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16552 SourceLocation BuiltinLoc,
16553 SourceLocation TypeLoc,
16554 ParsedType ParsedArgTy,
16555 ArrayRef<OffsetOfComponent> Components,
16556 SourceLocation RParenLoc) {
16557
16558 TypeSourceInfo *ArgTInfo;
16559 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16560 if (ArgTy.isNull())
16561 return ExprError();
16562
16563 if (!ArgTInfo)
16564 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16565
16566 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16567 }
16568
16569
16570 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16571 Expr *CondExpr,
16572 Expr *LHSExpr, Expr *RHSExpr,
16573 SourceLocation RPLoc) {
16574 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16575
16576 ExprValueKind VK = VK_PRValue;
16577 ExprObjectKind OK = OK_Ordinary;
16578 QualType resType;
16579 bool CondIsTrue = false;
16580 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16581 resType = Context.DependentTy;
16582 } else {
16583 // The conditional expression is required to be a constant expression.
16584 llvm::APSInt condEval(32);
16585 ExprResult CondICE = VerifyIntegerConstantExpression(
16586 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16587 if (CondICE.isInvalid())
16588 return ExprError();
16589 CondExpr = CondICE.get();
16590 CondIsTrue = condEval.getZExtValue();
16591
16592 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16593 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16594
16595 resType = ActiveExpr->getType();
16596 VK = ActiveExpr->getValueKind();
16597 OK = ActiveExpr->getObjectKind();
16598 }
16599
16600 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16601 resType, VK, OK, RPLoc, CondIsTrue);
16602 }
16603
16604 //===----------------------------------------------------------------------===//
16605 // Clang Extensions.
16606 //===----------------------------------------------------------------------===//
16607
16608 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16609 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16610
16611 if (LangOpts.CPlusPlus) {
16612 MangleNumberingContext *MCtx;
16613 Decl *ManglingContextDecl;
16614 std::tie(MCtx, ManglingContextDecl) =
16615 getCurrentMangleNumberContext(Block->getDeclContext());
16616 if (MCtx) {
16617 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16618 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16619 }
16620 }
16621
16622 PushBlockScope(CurScope, Block);
16623 CurContext->addDecl(Block);
16624 if (CurScope)
16625 PushDeclContext(CurScope, Block);
16626 else
16627 CurContext = Block;
16628
16629 getCurBlock()->HasImplicitReturnType = true;
16630
16631 // Enter a new evaluation context to insulate the block from any
16632 // cleanups from the enclosing full-expression.
16633 PushExpressionEvaluationContext(
16634 ExpressionEvaluationContext::PotentiallyEvaluated);
16635 }
16636
16637 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16638 Scope *CurScope) {
16639 assert(ParamInfo.getIdentifier() == nullptr &&
16640 "block-id should have no identifier!");
16641 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16642 BlockScopeInfo *CurBlock = getCurBlock();
16643
16644 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16645 QualType T = Sig->getType();
16646 DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block);
16647
16648 // GetTypeForDeclarator always produces a function type for a block
16649 // literal signature. Furthermore, it is always a FunctionProtoType
16650 // unless the function was written with a typedef.
16651 assert(T->isFunctionType() &&
16652 "GetTypeForDeclarator made a non-function block signature");
16653
16654 // Look for an explicit signature in that function type.
16655 FunctionProtoTypeLoc ExplicitSignature;
16656
16657 if ((ExplicitSignature = Sig->getTypeLoc()
16658 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16659
16660 // Check whether that explicit signature was synthesized by
16661 // GetTypeForDeclarator. If so, don't save that as part of the
16662 // written signature.
16663 if (ExplicitSignature.getLocalRangeBegin() ==
16664 ExplicitSignature.getLocalRangeEnd()) {
16665 // This would be much cheaper if we stored TypeLocs instead of
16666 // TypeSourceInfos.
16667 TypeLoc Result = ExplicitSignature.getReturnLoc();
16668 unsigned Size = Result.getFullDataSize();
16669 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16670 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16671
16672 ExplicitSignature = FunctionProtoTypeLoc();
16673 }
16674 }
16675
16676 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16677 CurBlock->FunctionType = T;
16678
16679 const auto *Fn = T->castAs<FunctionType>();
16680 QualType RetTy = Fn->getReturnType();
16681 bool isVariadic =
16682 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16683
16684 CurBlock->TheDecl->setIsVariadic(isVariadic);
16685
16686 // Context.DependentTy is used as a placeholder for a missing block
16687 // return type. TODO: what should we do with declarators like:
16688 // ^ * { ... }
16689 // If the answer is "apply template argument deduction"....
16690 if (RetTy != Context.DependentTy) {
16691 CurBlock->ReturnType = RetTy;
16692 CurBlock->TheDecl->setBlockMissingReturnType(false);
16693 CurBlock->HasImplicitReturnType = false;
16694 }
16695
16696 // Push block parameters from the declarator if we had them.
16697 SmallVector<ParmVarDecl*, 8> Params;
16698 if (ExplicitSignature) {
16699 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16700 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16701 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16702 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16703 // Diagnose this as an extension in C17 and earlier.
16704 if (!getLangOpts().C23)
16705 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16706 }
16707 Params.push_back(Param);
16708 }
16709
16710 // Fake up parameter variables if we have a typedef, like
16711 // ^ fntype { ... }
16712 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16713 for (const auto &I : Fn->param_types()) {
16714 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16715 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16716 Params.push_back(Param);
16717 }
16718 }
16719
16720 // Set the parameters on the block decl.
16721 if (!Params.empty()) {
16722 CurBlock->TheDecl->setParams(Params);
16723 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16724 /*CheckParameterNames=*/false);
16725 }
16726
16727 // Finally we can process decl attributes.
16728 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16729
16730 // Put the parameter variables in scope.
16731 for (auto *AI : CurBlock->TheDecl->parameters()) {
16732 AI->setOwningFunction(CurBlock->TheDecl);
16733
16734 // If this has an identifier, add it to the scope stack.
16735 if (AI->getIdentifier()) {
16736 CheckShadow(CurBlock->TheScope, AI);
16737
16738 PushOnScopeChains(AI, CurBlock->TheScope);
16739 }
16740
16741 if (AI->isInvalidDecl())
16742 CurBlock->TheDecl->setInvalidDecl();
16743 }
16744 }
16745
16746 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16747 // Leave the expression-evaluation context.
16748 DiscardCleanupsInEvaluationContext();
16749 PopExpressionEvaluationContext();
16750
16751 // Pop off CurBlock, handle nested blocks.
16752 PopDeclContext();
16753 PopFunctionScopeInfo();
16754 }
16755
16756 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16757 Stmt *Body, Scope *CurScope) {
16758 // If blocks are disabled, emit an error.
16759 if (!LangOpts.Blocks)
16760 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16761
16762 // Leave the expression-evaluation context.
16763 if (hasAnyUnrecoverableErrorsInThisFunction())
16764 DiscardCleanupsInEvaluationContext();
16765 assert(!Cleanup.exprNeedsCleanups() &&
16766 "cleanups within block not correctly bound!");
16767 PopExpressionEvaluationContext();
16768
16769 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16770 BlockDecl *BD = BSI->TheDecl;
16771
16772 maybeAddDeclWithEffects(BD);
16773
16774 if (BSI->HasImplicitReturnType)
16775 deduceClosureReturnType(*BSI);
16776
16777 QualType RetTy = Context.VoidTy;
16778 if (!BSI->ReturnType.isNull())
16779 RetTy = BSI->ReturnType;
16780
16781 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16782 QualType BlockTy;
16783
16784 // If the user wrote a function type in some form, try to use that.
16785 if (!BSI->FunctionType.isNull()) {
16786 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16787
16788 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16789 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16790
16791 // Turn protoless block types into nullary block types.
16792 if (isa<FunctionNoProtoType>(FTy)) {
16793 FunctionProtoType::ExtProtoInfo EPI;
16794 EPI.ExtInfo = Ext;
16795 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16796
16797 // Otherwise, if we don't need to change anything about the function type,
16798 // preserve its sugar structure.
16799 } else if (FTy->getReturnType() == RetTy &&
16800 (!NoReturn || FTy->getNoReturnAttr())) {
16801 BlockTy = BSI->FunctionType;
16802
16803 // Otherwise, make the minimal modifications to the function type.
16804 } else {
16805 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16806 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16807 EPI.TypeQuals = Qualifiers();
16808 EPI.ExtInfo = Ext;
16809 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16810 }
16811
16812 // If we don't have a function type, just build one from nothing.
16813 } else {
16814 FunctionProtoType::ExtProtoInfo EPI;
16815 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16816 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16817 }
16818
16819 DiagnoseUnusedParameters(BD->parameters());
16820 BlockTy = Context.getBlockPointerType(BlockTy);
16821
16822 // If needed, diagnose invalid gotos and switches in the block.
16823 if (getCurFunction()->NeedsScopeChecking() &&
16824 !PP.isCodeCompletionEnabled())
16825 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16826
16827 BD->setBody(cast<CompoundStmt>(Body));
16828
16829 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16830 DiagnoseUnguardedAvailabilityViolations(BD);
16831
16832 // Try to apply the named return value optimization. We have to check again
16833 // if we can do this, though, because blocks keep return statements around
16834 // to deduce an implicit return type.
16835 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16836 !BD->isDependentContext())
16837 computeNRVO(Body, BSI);
16838
16839 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16840 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16841 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(),
16842 NonTrivialCUnionContext::FunctionReturn,
16843 NTCUK_Destruct | NTCUK_Copy);
16844
16845 PopDeclContext();
16846
16847 // Set the captured variables on the block.
16848 SmallVector<BlockDecl::Capture, 4> Captures;
16849 for (Capture &Cap : BSI->Captures) {
16850 if (Cap.isInvalid() || Cap.isThisCapture())
16851 continue;
16852 // Cap.getVariable() is always a VarDecl because
16853 // blocks cannot capture structured bindings or other ValueDecl kinds.
16854 auto *Var = cast<VarDecl>(Cap.getVariable());
16855 Expr *CopyExpr = nullptr;
16856 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16857 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16858 // The capture logic needs the destructor, so make sure we mark it.
16859 // Usually this is unnecessary because most local variables have
16860 // their destructors marked at declaration time, but parameters are
16861 // an exception because it's technically only the call site that
16862 // actually requires the destructor.
16863 if (isa<ParmVarDecl>(Var))
16864 FinalizeVarWithDestructor(Var, Record);
16865
16866 // Enter a separate potentially-evaluated context while building block
16867 // initializers to isolate their cleanups from those of the block
16868 // itself.
16869 // FIXME: Is this appropriate even when the block itself occurs in an
16870 // unevaluated operand?
16871 EnterExpressionEvaluationContext EvalContext(
16872 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16873
16874 SourceLocation Loc = Cap.getLocation();
16875
16876 ExprResult Result = BuildDeclarationNameExpr(
16877 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16878
16879 // According to the blocks spec, the capture of a variable from
16880 // the stack requires a const copy constructor. This is not true
16881 // of the copy/move done to move a __block variable to the heap.
16882 if (!Result.isInvalid() &&
16883 !Result.get()->getType().isConstQualified()) {
16884 Result = ImpCastExprToType(Result.get(),
16885 Result.get()->getType().withConst(),
16886 CK_NoOp, VK_LValue);
16887 }
16888
16889 if (!Result.isInvalid()) {
16890 Result = PerformCopyInitialization(
16891 InitializedEntity::InitializeBlock(Var->getLocation(),
16892 Cap.getCaptureType()),
16893 Loc, Result.get());
16894 }
16895
16896 // Build a full-expression copy expression if initialization
16897 // succeeded and used a non-trivial constructor. Recover from
16898 // errors by pretending that the copy isn't necessary.
16899 if (!Result.isInvalid() &&
16900 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16901 ->isTrivial()) {
16902 Result = MaybeCreateExprWithCleanups(Result);
16903 CopyExpr = Result.get();
16904 }
16905 }
16906 }
16907
16908 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16909 CopyExpr);
16910 Captures.push_back(NewCap);
16911 }
16912 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16913
16914 // Pop the block scope now but keep it alive to the end of this function.
16915 AnalysisBasedWarnings::Policy WP =
16916 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
16917 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16918
16919 BlockExpr *Result = new (Context)
16920 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16921
16922 // If the block isn't obviously global, i.e. it captures anything at
16923 // all, then we need to do a few things in the surrounding context:
16924 if (Result->getBlockDecl()->hasCaptures()) {
16925 // First, this expression has a new cleanup object.
16926 ExprCleanupObjects.push_back(Result->getBlockDecl());
16927 Cleanup.setExprNeedsCleanups(true);
16928
16929 // It also gets a branch-protected scope if any of the captured
16930 // variables needs destruction.
16931 for (const auto &CI : Result->getBlockDecl()->captures()) {
16932 const VarDecl *var = CI.getVariable();
16933 if (var->getType().isDestructedType() != QualType::DK_none) {
16934 setFunctionHasBranchProtectedScope();
16935 break;
16936 }
16937 }
16938 }
16939
16940 if (getCurFunction())
16941 getCurFunction()->addBlock(BD);
16942
16943 // This can happen if the block's return type is deduced, but
16944 // the return expression is invalid.
16945 if (BD->isInvalidDecl())
16946 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16947 {Result}, Result->getType());
16948 return Result;
16949 }
16950
16951 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16952 SourceLocation RPLoc) {
16953 TypeSourceInfo *TInfo;
16954 GetTypeFromParser(Ty, &TInfo);
16955 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16956 }
16957
16958 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16959 Expr *E, TypeSourceInfo *TInfo,
16960 SourceLocation RPLoc) {
16961 Expr *OrigExpr = E;
16962 bool IsMS = false;
16963
16964 // CUDA device global function does not support varargs.
16965 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16966 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16967 CUDAFunctionTarget T = CUDA().IdentifyTarget(F);
16968 if (T == CUDAFunctionTarget::Global)
16969 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16970 }
16971 }
16972
16973 // NVPTX does not support va_arg expression.
16974 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16975 Context.getTargetInfo().getTriple().isNVPTX())
16976 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16977
16978 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16979 // as Microsoft ABI on an actual Microsoft platform, where
16980 // __builtin_ms_va_list and __builtin_va_list are the same.)
16981 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16982 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16983 QualType MSVaListType = Context.getBuiltinMSVaListType();
16984 if (Context.hasSameType(MSVaListType, E->getType())) {
16985 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16986 return ExprError();
16987 IsMS = true;
16988 }
16989 }
16990
16991 // Get the va_list type
16992 QualType VaListType = Context.getBuiltinVaListType();
16993 if (!IsMS) {
16994 if (VaListType->isArrayType()) {
16995 // Deal with implicit array decay; for example, on x86-64,
16996 // va_list is an array, but it's supposed to decay to
16997 // a pointer for va_arg.
16998 VaListType = Context.getArrayDecayedType(VaListType);
16999 // Make sure the input expression also decays appropriately.
17000 ExprResult Result = UsualUnaryConversions(E);
17001 if (Result.isInvalid())
17002 return ExprError();
17003 E = Result.get();
17004 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17005 // If va_list is a record type and we are compiling in C++ mode,
17006 // check the argument using reference binding.
17007 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17008 Context, Context.getLValueReferenceType(VaListType), false);
17009 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
17010 if (Init.isInvalid())
17011 return ExprError();
17012 E = Init.getAs<Expr>();
17013 } else {
17014 // Otherwise, the va_list argument must be an l-value because
17015 // it is modified by va_arg.
17016 if (!E->isTypeDependent() &&
17017 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17018 return ExprError();
17019 }
17020 }
17021
17022 if (!IsMS && !E->isTypeDependent() &&
17023 !Context.hasSameType(VaListType, E->getType()))
17024 return ExprError(
17025 Diag(E->getBeginLoc(),
17026 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17027 << OrigExpr->getType() << E->getSourceRange());
17028
17029 if (!TInfo->getType()->isDependentType()) {
17030 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17031 diag::err_second_parameter_to_va_arg_incomplete,
17032 TInfo->getTypeLoc()))
17033 return ExprError();
17034
17035 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17036 TInfo->getType(),
17037 diag::err_second_parameter_to_va_arg_abstract,
17038 TInfo->getTypeLoc()))
17039 return ExprError();
17040
17041 if (!TInfo->getType().isPODType(Context)) {
17042 Diag(TInfo->getTypeLoc().getBeginLoc(),
17043 TInfo->getType()->isObjCLifetimeType()
17044 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17045 : diag::warn_second_parameter_to_va_arg_not_pod)
17046 << TInfo->getType()
17047 << TInfo->getTypeLoc().getSourceRange();
17048 }
17049
17050 if (TInfo->getType()->isArrayType()) {
17051 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17052 PDiag(diag::warn_second_parameter_to_va_arg_array)
17053 << TInfo->getType()
17054 << TInfo->getTypeLoc().getSourceRange());
17055 }
17056
17057 // Check for va_arg where arguments of the given type will be promoted
17058 // (i.e. this va_arg is guaranteed to have undefined behavior).
17059 QualType PromoteType;
17060 if (Context.isPromotableIntegerType(TInfo->getType())) {
17061 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17062 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17063 // and C23 7.16.1.1p2 says, in part:
17064 // If type is not compatible with the type of the actual next argument
17065 // (as promoted according to the default argument promotions), the
17066 // behavior is undefined, except for the following cases:
17067 // - both types are pointers to qualified or unqualified versions of
17068 // compatible types;
17069 // - one type is compatible with a signed integer type, the other
17070 // type is compatible with the corresponding unsigned integer type,
17071 // and the value is representable in both types;
17072 // - one type is pointer to qualified or unqualified void and the
17073 // other is a pointer to a qualified or unqualified character type;
17074 // - or, the type of the next argument is nullptr_t and type is a
17075 // pointer type that has the same representation and alignment
17076 // requirements as a pointer to a character type.
17077 // Given that type compatibility is the primary requirement (ignoring
17078 // qualifications), you would think we could call typesAreCompatible()
17079 // directly to test this. However, in C++, that checks for *same type*,
17080 // which causes false positives when passing an enumeration type to
17081 // va_arg. Instead, get the underlying type of the enumeration and pass
17082 // that.
17083 QualType UnderlyingType = TInfo->getType();
17084 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17085 UnderlyingType = ED->getIntegerType();
17086 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17087 /*CompareUnqualified*/ true))
17088 PromoteType = QualType();
17089
17090 // If the types are still not compatible, we need to test whether the
17091 // promoted type and the underlying type are the same except for
17092 // signedness. Ask the AST for the correctly corresponding type and see
17093 // if that's compatible.
17094 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17095 PromoteType->isUnsignedIntegerType() !=
17096 UnderlyingType->isUnsignedIntegerType()) {
17097 UnderlyingType =
17098 UnderlyingType->isUnsignedIntegerType()
17099 ? Context.getCorrespondingSignedType(UnderlyingType)
17100 : Context.getCorrespondingUnsignedType(UnderlyingType);
17101 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17102 /*CompareUnqualified*/ true))
17103 PromoteType = QualType();
17104 }
17105 }
17106 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17107 PromoteType = Context.DoubleTy;
17108 if (!PromoteType.isNull())
17109 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17110 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17111 << TInfo->getType()
17112 << PromoteType
17113 << TInfo->getTypeLoc().getSourceRange());
17114 }
17115
17116 QualType T = TInfo->getType().getNonLValueExprType(Context);
17117 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17118 }
17119
17120 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17121 // The type of __null will be int or long, depending on the size of
17122 // pointers on the target.
17123 QualType Ty;
17124 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17125 if (pw == Context.getTargetInfo().getIntWidth())
17126 Ty = Context.IntTy;
17127 else if (pw == Context.getTargetInfo().getLongWidth())
17128 Ty = Context.LongTy;
17129 else if (pw == Context.getTargetInfo().getLongLongWidth())
17130 Ty = Context.LongLongTy;
17131 else {
17132 llvm_unreachable("I don't know size of pointer!");
17133 }
17134
17135 return new (Context) GNUNullExpr(Ty, TokenLoc);
17136 }
17137
17138 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17139 CXXRecordDecl *ImplDecl = nullptr;
17140
17141 // Fetch the std::source_location::__impl decl.
17142 if (NamespaceDecl *Std = S.getStdNamespace()) {
17143 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17144 Loc, Sema::LookupOrdinaryName);
17145 if (S.LookupQualifiedName(ResultSL, Std)) {
17146 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17147 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17148 Loc, Sema::LookupOrdinaryName);
17149 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17150 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17151 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17152 }
17153 }
17154 }
17155 }
17156
17157 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17158 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17159 return nullptr;
17160 }
17161
17162 // Verify that __impl is a trivial struct type, with no base classes, and with
17163 // only the four expected fields.
17164 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17165 ImplDecl->getNumBases() != 0) {
17166 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17167 return nullptr;
17168 }
17169
17170 unsigned Count = 0;
17171 for (FieldDecl *F : ImplDecl->fields()) {
17172 StringRef Name = F->getName();
17173
17174 if (Name == "_M_file_name") {
17175 if (F->getType() !=
17176 S.Context.getPointerType(S.Context.CharTy.withConst()))
17177 break;
17178 Count++;
17179 } else if (Name == "_M_function_name") {
17180 if (F->getType() !=
17181 S.Context.getPointerType(S.Context.CharTy.withConst()))
17182 break;
17183 Count++;
17184 } else if (Name == "_M_line") {
17185 if (!F->getType()->isIntegerType())
17186 break;
17187 Count++;
17188 } else if (Name == "_M_column") {
17189 if (!F->getType()->isIntegerType())
17190 break;
17191 Count++;
17192 } else {
17193 Count = 100; // invalid
17194 break;
17195 }
17196 }
17197 if (Count != 4) {
17198 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17199 return nullptr;
17200 }
17201
17202 return ImplDecl;
17203 }
17204
17205 ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17206 SourceLocation BuiltinLoc,
17207 SourceLocation RPLoc) {
17208 QualType ResultTy;
17209 switch (Kind) {
17210 case SourceLocIdentKind::File:
17211 case SourceLocIdentKind::FileName:
17212 case SourceLocIdentKind::Function:
17213 case SourceLocIdentKind::FuncSig: {
17214 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17215 ResultTy =
17216 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17217 break;
17218 }
17219 case SourceLocIdentKind::Line:
17220 case SourceLocIdentKind::Column:
17221 ResultTy = Context.UnsignedIntTy;
17222 break;
17223 case SourceLocIdentKind::SourceLocStruct:
17224 if (!StdSourceLocationImplDecl) {
17225 StdSourceLocationImplDecl =
17226 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17227 if (!StdSourceLocationImplDecl)
17228 return ExprError();
17229 }
17230 ResultTy = Context.getPointerType(
17231 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17232 break;
17233 }
17234
17235 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17236 }
17237
17238 ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17239 SourceLocation BuiltinLoc,
17240 SourceLocation RPLoc,
17241 DeclContext *ParentContext) {
17242 return new (Context)
17243 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17244 }
17245
17246 ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17247 StringLiteral *BinaryData, StringRef FileName) {
17248 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17249 Data->BinaryData = BinaryData;
17250 Data->FileName = FileName;
17251 return new (Context)
17252 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17253 Data->getDataElementCount());
17254 }
17255
17256 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17257 const Expr *SrcExpr) {
17258 if (!DstType->isFunctionPointerType() ||
17259 !SrcExpr->getType()->isFunctionType())
17260 return false;
17261
17262 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17263 if (!DRE)
17264 return false;
17265
17266 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17267 if (!FD)
17268 return false;
17269
17270 return !S.checkAddressOfFunctionIsAvailable(FD,
17271 /*Complain=*/true,
17272 SrcExpr->getBeginLoc());
17273 }
17274
17275 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17276 SourceLocation Loc,
17277 QualType DstType, QualType SrcType,
17278 Expr *SrcExpr, AssignmentAction Action,
17279 bool *Complained) {
17280 if (Complained)
17281 *Complained = false;
17282
17283 // Decode the result (notice that AST's are still created for extensions).
17284 bool CheckInferredResultType = false;
17285 bool isInvalid = false;
17286 unsigned DiagKind = 0;
17287 ConversionFixItGenerator ConvHints;
17288 bool MayHaveConvFixit = false;
17289 bool MayHaveFunctionDiff = false;
17290 const ObjCInterfaceDecl *IFace = nullptr;
17291 const ObjCProtocolDecl *PDecl = nullptr;
17292
17293 switch (ConvTy) {
17294 case AssignConvertType::Compatible:
17295 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17296 return false;
17297 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17298 // Still a valid conversion, but we may want to diagnose for C++
17299 // compatibility reasons.
17300 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17301 break;
17302 case AssignConvertType::PointerToInt:
17303 if (getLangOpts().CPlusPlus) {
17304 DiagKind = diag::err_typecheck_convert_pointer_int;
17305 isInvalid = true;
17306 } else {
17307 DiagKind = diag::ext_typecheck_convert_pointer_int;
17308 }
17309 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17310 MayHaveConvFixit = true;
17311 break;
17312 case AssignConvertType::IntToPointer:
17313 if (getLangOpts().CPlusPlus) {
17314 DiagKind = diag::err_typecheck_convert_int_pointer;
17315 isInvalid = true;
17316 } else {
17317 DiagKind = diag::ext_typecheck_convert_int_pointer;
17318 }
17319 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17320 MayHaveConvFixit = true;
17321 break;
17322 case AssignConvertType::IncompatibleFunctionPointerStrict:
17323 DiagKind =
17324 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17325 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17326 MayHaveConvFixit = true;
17327 break;
17328 case AssignConvertType::IncompatibleFunctionPointer:
17329 if (getLangOpts().CPlusPlus) {
17330 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17331 isInvalid = true;
17332 } else {
17333 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17334 }
17335 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17336 MayHaveConvFixit = true;
17337 break;
17338 case AssignConvertType::IncompatiblePointer:
17339 if (Action == AssignmentAction::Passing_CFAudited) {
17340 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17341 } else if (getLangOpts().CPlusPlus) {
17342 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17343 isInvalid = true;
17344 } else {
17345 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17346 }
17347 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17348 SrcType->isObjCObjectPointerType();
17349 if (CheckInferredResultType) {
17350 SrcType = SrcType.getUnqualifiedType();
17351 DstType = DstType.getUnqualifiedType();
17352 } else {
17353 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17354 }
17355 MayHaveConvFixit = true;
17356 break;
17357 case AssignConvertType::IncompatiblePointerSign:
17358 if (getLangOpts().CPlusPlus) {
17359 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17360 isInvalid = true;
17361 } else {
17362 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17363 }
17364 break;
17365 case AssignConvertType::FunctionVoidPointer:
17366 if (getLangOpts().CPlusPlus) {
17367 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17368 isInvalid = true;
17369 } else {
17370 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17371 }
17372 break;
17373 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17374 // Perform array-to-pointer decay if necessary.
17375 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17376
17377 isInvalid = true;
17378
17379 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17380 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17381 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17382 DiagKind = diag::err_typecheck_incompatible_address_space;
17383 break;
17384 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17385 DiagKind = diag::err_typecheck_incompatible_ownership;
17386 break;
17387 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17388 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17389 break;
17390 }
17391
17392 llvm_unreachable("unknown error case for discarding qualifiers!");
17393 // fallthrough
17394 }
17395 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17396 // If the qualifiers lost were because we were applying the
17397 // (deprecated) C++ conversion from a string literal to a char*
17398 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17399 // Ideally, this check would be performed in
17400 // checkPointerTypesForAssignment. However, that would require a
17401 // bit of refactoring (so that the second argument is an
17402 // expression, rather than a type), which should be done as part
17403 // of a larger effort to fix checkPointerTypesForAssignment for
17404 // C++ semantics.
17405 if (getLangOpts().CPlusPlus &&
17406 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17407 return false;
17408 if (getLangOpts().CPlusPlus) {
17409 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17410 isInvalid = true;
17411 } else {
17412 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17413 }
17414
17415 break;
17416 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17417 if (getLangOpts().CPlusPlus) {
17418 isInvalid = true;
17419 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17420 } else {
17421 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17422 }
17423 break;
17424 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17425 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17426 isInvalid = true;
17427 break;
17428 case AssignConvertType::IntToBlockPointer:
17429 DiagKind = diag::err_int_to_block_pointer;
17430 isInvalid = true;
17431 break;
17432 case AssignConvertType::IncompatibleBlockPointer:
17433 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17434 isInvalid = true;
17435 break;
17436 case AssignConvertType::IncompatibleObjCQualifiedId: {
17437 if (SrcType->isObjCQualifiedIdType()) {
17438 const ObjCObjectPointerType *srcOPT =
17439 SrcType->castAs<ObjCObjectPointerType>();
17440 for (auto *srcProto : srcOPT->quals()) {
17441 PDecl = srcProto;
17442 break;
17443 }
17444 if (const ObjCInterfaceType *IFaceT =
17445 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17446 IFace = IFaceT->getDecl();
17447 }
17448 else if (DstType->isObjCQualifiedIdType()) {
17449 const ObjCObjectPointerType *dstOPT =
17450 DstType->castAs<ObjCObjectPointerType>();
17451 for (auto *dstProto : dstOPT->quals()) {
17452 PDecl = dstProto;
17453 break;
17454 }
17455 if (const ObjCInterfaceType *IFaceT =
17456 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17457 IFace = IFaceT->getDecl();
17458 }
17459 if (getLangOpts().CPlusPlus) {
17460 DiagKind = diag::err_incompatible_qualified_id;
17461 isInvalid = true;
17462 } else {
17463 DiagKind = diag::warn_incompatible_qualified_id;
17464 }
17465 break;
17466 }
17467 case AssignConvertType::IncompatibleVectors:
17468 if (getLangOpts().CPlusPlus) {
17469 DiagKind = diag::err_incompatible_vectors;
17470 isInvalid = true;
17471 } else {
17472 DiagKind = diag::warn_incompatible_vectors;
17473 }
17474 break;
17475 case AssignConvertType::IncompatibleObjCWeakRef:
17476 DiagKind = diag::err_arc_weak_unavailable_assign;
17477 isInvalid = true;
17478 break;
17479 case AssignConvertType::Incompatible:
17480 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17481 if (Complained)
17482 *Complained = true;
17483 return true;
17484 }
17485
17486 DiagKind = diag::err_typecheck_convert_incompatible;
17487 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17488 MayHaveConvFixit = true;
17489 isInvalid = true;
17490 MayHaveFunctionDiff = true;
17491 break;
17492 }
17493
17494 QualType FirstType, SecondType;
17495 switch (Action) {
17496 case AssignmentAction::Assigning:
17497 case AssignmentAction::Initializing:
17498 // The destination type comes first.
17499 FirstType = DstType;
17500 SecondType = SrcType;
17501 break;
17502
17503 case AssignmentAction::Returning:
17504 case AssignmentAction::Passing:
17505 case AssignmentAction::Passing_CFAudited:
17506 case AssignmentAction::Converting:
17507 case AssignmentAction::Sending:
17508 case AssignmentAction::Casting:
17509 // The source type comes first.
17510 FirstType = SrcType;
17511 SecondType = DstType;
17512 break;
17513 }
17514
17515 PartialDiagnostic FDiag = PDiag(DiagKind);
17516 AssignmentAction ActionForDiag = Action;
17517 if (Action == AssignmentAction::Passing_CFAudited)
17518 ActionForDiag = AssignmentAction::Passing;
17519
17520 FDiag << FirstType << SecondType << ActionForDiag
17521 << SrcExpr->getSourceRange();
17522
17523 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17524 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17525 auto isPlainChar = [](const clang::Type *Type) {
17526 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17527 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17528 };
17529 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17530 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17531 }
17532
17533 // If we can fix the conversion, suggest the FixIts.
17534 if (!ConvHints.isNull()) {
17535 for (FixItHint &H : ConvHints.Hints)
17536 FDiag << H;
17537 }
17538
17539 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17540
17541 if (MayHaveFunctionDiff)
17542 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17543
17544 Diag(Loc, FDiag);
17545 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17546 DiagKind == diag::err_incompatible_qualified_id) &&
17547 PDecl && IFace && !IFace->hasDefinition())
17548 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17549 << IFace << PDecl;
17550
17551 if (SecondType == Context.OverloadTy)
17552 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17553 FirstType, /*TakingAddress=*/true);
17554
17555 if (CheckInferredResultType)
17556 ObjC().EmitRelatedResultTypeNote(SrcExpr);
17557
17558 if (Action == AssignmentAction::Returning &&
17559 ConvTy == AssignConvertType::IncompatiblePointer)
17560 ObjC().EmitRelatedResultTypeNoteForReturn(DstType);
17561
17562 if (Complained)
17563 *Complained = true;
17564 return isInvalid;
17565 }
17566
17567 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17568 llvm::APSInt *Result,
17569 AllowFoldKind CanFold) {
17570 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17571 public:
17572 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17573 QualType T) override {
17574 return S.Diag(Loc, diag::err_ice_not_integral)
17575 << T << S.LangOpts.CPlusPlus;
17576 }
17577 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17578 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17579 }
17580 } Diagnoser;
17581
17582 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17583 }
17584
17585 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17586 llvm::APSInt *Result,
17587 unsigned DiagID,
17588 AllowFoldKind CanFold) {
17589 class IDDiagnoser : public VerifyICEDiagnoser {
17590 unsigned DiagID;
17591
17592 public:
17593 IDDiagnoser(unsigned DiagID)
17594 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17595
17596 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17597 return S.Diag(Loc, DiagID);
17598 }
17599 } Diagnoser(DiagID);
17600
17601 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17602 }
17603
17604 Sema::SemaDiagnosticBuilder
17605 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17606 QualType T) {
17607 return diagnoseNotICE(S, Loc);
17608 }
17609
17610 Sema::SemaDiagnosticBuilder
17611 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17612 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17613 }
17614
17615 ExprResult
17616 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17617 VerifyICEDiagnoser &Diagnoser,
17618 AllowFoldKind CanFold) {
17619 SourceLocation DiagLoc = E->getBeginLoc();
17620
17621 if (getLangOpts().CPlusPlus11) {
17622 // C++11 [expr.const]p5:
17623 // If an expression of literal class type is used in a context where an
17624 // integral constant expression is required, then that class type shall
17625 // have a single non-explicit conversion function to an integral or
17626 // unscoped enumeration type
17627 ExprResult Converted;
17628 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17629 VerifyICEDiagnoser &BaseDiagnoser;
17630 public:
17631 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17632 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17633 BaseDiagnoser.Suppress, true),
17634 BaseDiagnoser(BaseDiagnoser) {}
17635
17636 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17637 QualType T) override {
17638 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17639 }
17640
17641 SemaDiagnosticBuilder diagnoseIncomplete(
17642 Sema &S, SourceLocation Loc, QualType T) override {
17643 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17644 }
17645
17646 SemaDiagnosticBuilder diagnoseExplicitConv(
17647 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17648 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17649 }
17650
17651 SemaDiagnosticBuilder noteExplicitConv(
17652 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17653 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17654 << ConvTy->isEnumeralType() << ConvTy;
17655 }
17656
17657 SemaDiagnosticBuilder diagnoseAmbiguous(
17658 Sema &S, SourceLocation Loc, QualType T) override {
17659 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17660 }
17661
17662 SemaDiagnosticBuilder noteAmbiguous(
17663 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17664 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17665 << ConvTy->isEnumeralType() << ConvTy;
17666 }
17667
17668 SemaDiagnosticBuilder diagnoseConversion(
17669 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17670 llvm_unreachable("conversion functions are permitted");
17671 }
17672 } ConvertDiagnoser(Diagnoser);
17673
17674 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17675 ConvertDiagnoser);
17676 if (Converted.isInvalid())
17677 return Converted;
17678 E = Converted.get();
17679 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17680 // don't try to evaluate it later. We also don't want to return the
17681 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17682 // this function will attempt to use 'Value'.
17683 if (isa<RecoveryExpr>(E))
17684 return ExprError();
17685 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17686 return ExprError();
17687 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17688 // An ICE must be of integral or unscoped enumeration type.
17689 if (!Diagnoser.Suppress)
17690 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17691 << E->getSourceRange();
17692 return ExprError();
17693 }
17694
17695 ExprResult RValueExpr = DefaultLvalueConversion(E);
17696 if (RValueExpr.isInvalid())
17697 return ExprError();
17698
17699 E = RValueExpr.get();
17700
17701 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17702 // in the non-ICE case.
17703 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17704 SmallVector<PartialDiagnosticAt, 8> Notes;
17705 if (Result)
17706 *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
17707 if (!isa<ConstantExpr>(E))
17708 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17709 : ConstantExpr::Create(Context, E);
17710
17711 if (Notes.empty())
17712 return E;
17713
17714 // If our only note is the usual "invalid subexpression" note, just point
17715 // the caret at its location rather than producing an essentially
17716 // redundant note.
17717 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17718 diag::note_invalid_subexpr_in_const_expr) {
17719 DiagLoc = Notes[0].first;
17720 Notes.clear();
17721 }
17722
17723 if (getLangOpts().CPlusPlus) {
17724 if (!Diagnoser.Suppress) {
17725 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17726 for (const PartialDiagnosticAt &Note : Notes)
17727 Diag(Note.first, Note.second);
17728 }
17729 return ExprError();
17730 }
17731
17732 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17733 for (const PartialDiagnosticAt &Note : Notes)
17734 Diag(Note.first, Note.second);
17735
17736 return E;
17737 }
17738
17739 Expr::EvalResult EvalResult;
17740 SmallVector<PartialDiagnosticAt, 8> Notes;
17741 EvalResult.Diag = &Notes;
17742
17743 // Try to evaluate the expression, and produce diagnostics explaining why it's
17744 // not a constant expression as a side-effect.
17745 bool Folded =
17746 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17747 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17748 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17749
17750 if (!isa<ConstantExpr>(E))
17751 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17752
17753 // In C++11, we can rely on diagnostics being produced for any expression
17754 // which is not a constant expression. If no diagnostics were produced, then
17755 // this is a constant expression.
17756 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17757 if (Result)
17758 *Result = EvalResult.Val.getInt();
17759 return E;
17760 }
17761
17762 // If our only note is the usual "invalid subexpression" note, just point
17763 // the caret at its location rather than producing an essentially
17764 // redundant note.
17765 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17766 diag::note_invalid_subexpr_in_const_expr) {
17767 DiagLoc = Notes[0].first;
17768 Notes.clear();
17769 }
17770
17771 if (!Folded || CanFold == AllowFoldKind::No) {
17772 if (!Diagnoser.Suppress) {
17773 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17774 for (const PartialDiagnosticAt &Note : Notes)
17775 Diag(Note.first, Note.second);
17776 }
17777
17778 return ExprError();
17779 }
17780
17781 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17782 for (const PartialDiagnosticAt &Note : Notes)
17783 Diag(Note.first, Note.second);
17784
17785 if (Result)
17786 *Result = EvalResult.Val.getInt();
17787 return E;
17788 }
17789
17790 namespace {
17791 // Handle the case where we conclude a expression which we speculatively
17792 // considered to be unevaluated is actually evaluated.
17793 class TransformToPE : public TreeTransform<TransformToPE> {
17794 typedef TreeTransform<TransformToPE> BaseTransform;
17795
17796 public:
17797 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17798
17799 // Make sure we redo semantic analysis
17800 bool AlwaysRebuild() { return true; }
17801 bool ReplacingOriginal() { return true; }
17802
17803 // We need to special-case DeclRefExprs referring to FieldDecls which
17804 // are not part of a member pointer formation; normal TreeTransforming
17805 // doesn't catch this case because of the way we represent them in the AST.
17806 // FIXME: This is a bit ugly; is it really the best way to handle this
17807 // case?
17808 //
17809 // Error on DeclRefExprs referring to FieldDecls.
17810 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17811 if (isa<FieldDecl>(E->getDecl()) &&
17812 !SemaRef.isUnevaluatedContext())
17813 return SemaRef.Diag(E->getLocation(),
17814 diag::err_invalid_non_static_member_use)
17815 << E->getDecl() << E->getSourceRange();
17816
17817 return BaseTransform::TransformDeclRefExpr(E);
17818 }
17819
17820 // Exception: filter out member pointer formation
17821 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17822 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17823 return E;
17824
17825 return BaseTransform::TransformUnaryOperator(E);
17826 }
17827
17828 // The body of a lambda-expression is in a separate expression evaluation
17829 // context so never needs to be transformed.
17830 // FIXME: Ideally we wouldn't transform the closure type either, and would
17831 // just recreate the capture expressions and lambda expression.
17832 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17833 return SkipLambdaBody(E, Body);
17834 }
17835 };
17836 }
17837
17838 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17839 assert(isUnevaluatedContext() &&
17840 "Should only transform unevaluated expressions");
17841 ExprEvalContexts.back().Context =
17842 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17843 if (isUnevaluatedContext())
17844 return E;
17845 return TransformToPE(*this).TransformExpr(E);
17846 }
17847
17848 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17849 assert(isUnevaluatedContext() &&
17850 "Should only transform unevaluated expressions");
17851 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
17852 if (isUnevaluatedContext())
17853 return TInfo;
17854 return TransformToPE(*this).TransformType(TInfo);
17855 }
17856
17857 void
17858 Sema::PushExpressionEvaluationContext(
17859 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17860 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17861 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17862 LambdaContextDecl, ExprContext);
17863
17864 // Discarded statements and immediate contexts nested in other
17865 // discarded statements or immediate context are themselves
17866 // a discarded statement or an immediate context, respectively.
17867 ExprEvalContexts.back().InDiscardedStatement =
17868 parentEvaluationContext().isDiscardedStatementContext();
17869
17870 // C++23 [expr.const]/p15
17871 // An expression or conversion is in an immediate function context if [...]
17872 // it is a subexpression of a manifestly constant-evaluated expression or
17873 // conversion.
17874 const auto &Prev = parentEvaluationContext();
17875 ExprEvalContexts.back().InImmediateFunctionContext =
17876 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17877
17878 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17879 Prev.InImmediateEscalatingFunctionContext;
17880
17881 Cleanup.reset();
17882 if (!MaybeODRUseExprs.empty())
17883 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17884 }
17885
17886 void
17887 Sema::PushExpressionEvaluationContext(
17888 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17889 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17890 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17891 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17892 }
17893
17894 void Sema::PushExpressionEvaluationContextForFunction(
17895 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17896 // [expr.const]/p14.1
17897 // An expression or conversion is in an immediate function context if it is
17898 // potentially evaluated and either: its innermost enclosing non-block scope
17899 // is a function parameter scope of an immediate function.
17900 PushExpressionEvaluationContext(
17901 FD && FD->isConsteval()
17902 ? ExpressionEvaluationContext::ImmediateFunctionContext
17903 : NewContext);
17904 const Sema::ExpressionEvaluationContextRecord &Parent =
17905 parentEvaluationContext();
17906 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
17907
17908 Current.InDiscardedStatement = false;
17909
17910 if (FD) {
17911
17912 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17913 // context is nested in an immediate function context, so smaller contexts
17914 // that appear inside immediate functions (like variable initializers) are
17915 // considered to be inside an immediate function context even though by
17916 // themselves they are not immediate function contexts. But when a new
17917 // function is entered, we need to reset this tracking, since the entered
17918 // function might be not an immediate function.
17919
17920 Current.InImmediateEscalatingFunctionContext =
17921 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17922
17923 if (isLambdaMethod(FD))
17924 Current.InImmediateFunctionContext =
17925 FD->isConsteval() ||
17926 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
17927 Parent.isImmediateFunctionContext()));
17928 else
17929 Current.InImmediateFunctionContext = FD->isConsteval();
17930 }
17931 }
17932
17933 namespace {
17934
17935 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17936 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17937 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17938 if (E->getOpcode() == UO_Deref)
17939 return CheckPossibleDeref(S, E->getSubExpr());
17940 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17941 return CheckPossibleDeref(S, E->getBase());
17942 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17943 return CheckPossibleDeref(S, E->getBase());
17944 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17945 QualType Inner;
17946 QualType Ty = E->getType();
17947 if (const auto *Ptr = Ty->getAs<PointerType>())
17948 Inner = Ptr->getPointeeType();
17949 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17950 Inner = Arr->getElementType();
17951 else
17952 return nullptr;
17953
17954 if (Inner->hasAttr(attr::NoDeref))
17955 return E;
17956 }
17957 return nullptr;
17958 }
17959
17960 } // namespace
17961
17962 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17963 for (const Expr *E : Rec.PossibleDerefs) {
17964 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17965 if (DeclRef) {
17966 const ValueDecl *Decl = DeclRef->getDecl();
17967 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17968 << Decl->getName() << E->getSourceRange();
17969 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17970 } else {
17971 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17972 << E->getSourceRange();
17973 }
17974 }
17975 Rec.PossibleDerefs.clear();
17976 }
17977
17978 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17979 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17980 return;
17981
17982 // Note: ignoring parens here is not justified by the standard rules, but
17983 // ignoring parentheses seems like a more reasonable approach, and this only
17984 // drives a deprecation warning so doesn't affect conformance.
17985 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17986 if (BO->getOpcode() == BO_Assign) {
17987 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17988 llvm::erase(LHSs, BO->getLHS());
17989 }
17990 }
17991 }
17992
17993 void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
17994 assert(getLangOpts().CPlusPlus20 &&
17995 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17996 "Cannot mark an immediate escalating expression outside of an "
17997 "immediate escalating context");
17998 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17999 Call && Call->getCallee()) {
18000 if (auto *DeclRef =
18001 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18002 DeclRef->setIsImmediateEscalating(true);
18003 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18004 Ctr->setIsImmediateEscalating(true);
18005 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18006 DeclRef->setIsImmediateEscalating(true);
18007 } else {
18008 assert(false && "expected an immediately escalating expression");
18009 }
18010 if (FunctionScopeInfo *FI = getCurFunction())
18011 FI->FoundImmediateEscalatingExpression = true;
18012 }
18013
18014 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18015 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18016 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18017 isCheckingDefaultArgumentOrInitializer() ||
18018 RebuildingImmediateInvocation || isImmediateFunctionContext())
18019 return E;
18020
18021 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18022 /// It's OK if this fails; we'll also remove this in
18023 /// HandleImmediateInvocations, but catching it here allows us to avoid
18024 /// walking the AST looking for it in simple cases.
18025 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18026 if (auto *DeclRef =
18027 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18028 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18029
18030 // C++23 [expr.const]/p16
18031 // An expression or conversion is immediate-escalating if it is not initially
18032 // in an immediate function context and it is [...] an immediate invocation
18033 // that is not a constant expression and is not a subexpression of an
18034 // immediate invocation.
18035 APValue Cached;
18036 auto CheckConstantExpressionAndKeepResult = [&]() {
18037 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18038 Expr::EvalResult Eval;
18039 Eval.Diag = &Notes;
18040 bool Res = E.get()->EvaluateAsConstantExpr(
18041 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18042 if (Res && Notes.empty()) {
18043 Cached = std::move(Eval.Val);
18044 return true;
18045 }
18046 return false;
18047 };
18048
18049 if (!E.get()->isValueDependent() &&
18050 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18051 !CheckConstantExpressionAndKeepResult()) {
18052 MarkExpressionAsImmediateEscalating(E.get());
18053 return E;
18054 }
18055
18056 if (Cleanup.exprNeedsCleanups()) {
18057 // Since an immediate invocation is a full expression itself - it requires
18058 // an additional ExprWithCleanups node, but it can participate to a bigger
18059 // full expression which actually requires cleanups to be run after so
18060 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18061 // may discard cleanups for outer expression too early.
18062
18063 // Note that ExprWithCleanups created here must always have empty cleanup
18064 // objects:
18065 // - compound literals do not create cleanup objects in C++ and immediate
18066 // invocations are C++-only.
18067 // - blocks are not allowed inside constant expressions and compiler will
18068 // issue an error if they appear there.
18069 //
18070 // Hence, in correct code any cleanup objects created inside current
18071 // evaluation context must be outside the immediate invocation.
18072 E = ExprWithCleanups::Create(getASTContext(), E.get(),
18073 Cleanup.cleanupsHaveSideEffects(), {});
18074 }
18075
18076 ConstantExpr *Res = ConstantExpr::Create(
18077 getASTContext(), E.get(),
18078 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18079 getASTContext()),
18080 /*IsImmediateInvocation*/ true);
18081 if (Cached.hasValue())
18082 Res->MoveIntoResult(Cached, getASTContext());
18083 /// Value-dependent constant expressions should not be immediately
18084 /// evaluated until they are instantiated.
18085 if (!Res->isValueDependent())
18086 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18087 return Res;
18088 }
18089
18090 static void EvaluateAndDiagnoseImmediateInvocation(
18091 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18092 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18093 Expr::EvalResult Eval;
18094 Eval.Diag = &Notes;
18095 ConstantExpr *CE = Candidate.getPointer();
18096 bool Result = CE->EvaluateAsConstantExpr(
18097 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18098 if (!Result || !Notes.empty()) {
18099 SemaRef.FailedImmediateInvocations.insert(CE);
18100 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18101 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18102 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18103 FunctionDecl *FD = nullptr;
18104 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18105 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18106 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18107 FD = Call->getConstructor();
18108 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18109 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18110
18111 assert(FD && FD->isImmediateFunction() &&
18112 "could not find an immediate function in this expression");
18113 if (FD->isInvalidDecl())
18114 return;
18115 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18116 << FD << FD->isConsteval();
18117 if (auto Context =
18118 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18119 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18120 << Context->Decl;
18121 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18122 }
18123 if (!FD->isConsteval())
18124 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18125 for (auto &Note : Notes)
18126 SemaRef.Diag(Note.first, Note.second);
18127 return;
18128 }
18129 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
18130 }
18131
18132 static void RemoveNestedImmediateInvocation(
18133 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18134 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18135 struct ComplexRemove : TreeTransform<ComplexRemove> {
18136 using Base = TreeTransform<ComplexRemove>;
18137 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18138 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18139 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18140 CurrentII;
18141 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18142 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18143 SmallVector<Sema::ImmediateInvocationCandidate,
18144 4>::reverse_iterator Current)
18145 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18146 void RemoveImmediateInvocation(ConstantExpr* E) {
18147 auto It = std::find_if(CurrentII, IISet.rend(),
18148 [E](Sema::ImmediateInvocationCandidate Elem) {
18149 return Elem.getPointer() == E;
18150 });
18151 // It is possible that some subexpression of the current immediate
18152 // invocation was handled from another expression evaluation context. Do
18153 // not handle the current immediate invocation if some of its
18154 // subexpressions failed before.
18155 if (It == IISet.rend()) {
18156 if (SemaRef.FailedImmediateInvocations.contains(E))
18157 CurrentII->setInt(1);
18158 } else {
18159 It->setInt(1); // Mark as deleted
18160 }
18161 }
18162 ExprResult TransformConstantExpr(ConstantExpr *E) {
18163 if (!E->isImmediateInvocation())
18164 return Base::TransformConstantExpr(E);
18165 RemoveImmediateInvocation(E);
18166 return Base::TransformExpr(E->getSubExpr());
18167 }
18168 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18169 /// we need to remove its DeclRefExpr from the DRSet.
18170 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18171 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18172 return Base::TransformCXXOperatorCallExpr(E);
18173 }
18174 /// Base::TransformUserDefinedLiteral doesn't preserve the
18175 /// UserDefinedLiteral node.
18176 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18177 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18178 /// here.
18179 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18180 if (!Init)
18181 return Init;
18182
18183 // We cannot use IgnoreImpCasts because we need to preserve
18184 // full expressions.
18185 while (true) {
18186 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18187 Init = ICE->getSubExpr();
18188 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18189 Init = ICE->getSubExpr();
18190 else
18191 break;
18192 }
18193 /// ConstantExprs are the first layer of implicit node to be removed so if
18194 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18195 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18196 CE && CE->isImmediateInvocation())
18197 RemoveImmediateInvocation(CE);
18198 return Base::TransformInitializer(Init, NotCopyInit);
18199 }
18200 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18201 DRSet.erase(E);
18202 return E;
18203 }
18204 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18205 // Do not rebuild lambdas to avoid creating a new type.
18206 // Lambdas have already been processed inside their eval contexts.
18207 return E;
18208 }
18209 bool AlwaysRebuild() { return false; }
18210 bool ReplacingOriginal() { return true; }
18211 bool AllowSkippingCXXConstructExpr() {
18212 bool Res = AllowSkippingFirstCXXConstructExpr;
18213 AllowSkippingFirstCXXConstructExpr = true;
18214 return Res;
18215 }
18216 bool AllowSkippingFirstCXXConstructExpr = true;
18217 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18218 Rec.ImmediateInvocationCandidates, It);
18219
18220 /// CXXConstructExpr with a single argument are getting skipped by
18221 /// TreeTransform in some situtation because they could be implicit. This
18222 /// can only occur for the top-level CXXConstructExpr because it is used
18223 /// nowhere in the expression being transformed therefore will not be rebuilt.
18224 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18225 /// skipping the first CXXConstructExpr.
18226 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18227 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18228
18229 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18230 // The result may not be usable in case of previous compilation errors.
18231 // In this case evaluation of the expression may result in crash so just
18232 // don't do anything further with the result.
18233 if (Res.isUsable()) {
18234 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18235 It->getPointer()->setSubExpr(Res.get());
18236 }
18237 }
18238
18239 static void
18240 HandleImmediateInvocations(Sema &SemaRef,
18241 Sema::ExpressionEvaluationContextRecord &Rec) {
18242 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18243 Rec.ReferenceToConsteval.size() == 0) ||
18244 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18245 return;
18246
18247 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18248 // [...]
18249 // - the initializer of a variable that is usable in constant expressions or
18250 // has constant initialization.
18251 if (SemaRef.getLangOpts().CPlusPlus23 &&
18252 Rec.ExprContext ==
18253 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18254 auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);
18255 if (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18256 VD->hasConstantInitialization()) {
18257 // An expression or conversion is in an 'immediate function context' if it
18258 // is potentially evaluated and either:
18259 // [...]
18260 // - it is a subexpression of a manifestly constant-evaluated expression
18261 // or conversion.
18262 return;
18263 }
18264 }
18265
18266 /// When we have more than 1 ImmediateInvocationCandidates or previously
18267 /// failed immediate invocations, we need to check for nested
18268 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18269 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18270 /// invocation.
18271 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18272 !SemaRef.FailedImmediateInvocations.empty()) {
18273
18274 /// Prevent sema calls during the tree transform from adding pointers that
18275 /// are already in the sets.
18276 llvm::SaveAndRestore DisableIITracking(
18277 SemaRef.RebuildingImmediateInvocation, true);
18278
18279 /// Prevent diagnostic during tree transfrom as they are duplicates
18280 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18281
18282 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18283 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18284 if (!It->getInt())
18285 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18286 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18287 Rec.ReferenceToConsteval.size()) {
18288 struct SimpleRemove : DynamicRecursiveASTVisitor {
18289 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18290 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18291 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18292 DRSet.erase(E);
18293 return DRSet.size();
18294 }
18295 } Visitor(Rec.ReferenceToConsteval);
18296 Visitor.TraverseStmt(
18297 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18298 }
18299 for (auto CE : Rec.ImmediateInvocationCandidates)
18300 if (!CE.getInt())
18301 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18302 for (auto *DR : Rec.ReferenceToConsteval) {
18303 // If the expression is immediate escalating, it is not an error;
18304 // The outer context itself becomes immediate and further errors,
18305 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18306 if (DR->isImmediateEscalating())
18307 continue;
18308 auto *FD = cast<FunctionDecl>(DR->getDecl());
18309 const NamedDecl *ND = FD;
18310 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18311 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18312 ND = MD->getParent();
18313
18314 // C++23 [expr.const]/p16
18315 // An expression or conversion is immediate-escalating if it is not
18316 // initially in an immediate function context and it is [...] a
18317 // potentially-evaluated id-expression that denotes an immediate function
18318 // that is not a subexpression of an immediate invocation.
18319 bool ImmediateEscalating = false;
18320 bool IsPotentiallyEvaluated =
18321 Rec.Context ==
18322 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18323 Rec.Context ==
18324 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18325 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18326 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18327
18328 if (!Rec.InImmediateEscalatingFunctionContext ||
18329 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18330 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18331 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18332 if (!FD->getBuiltinID())
18333 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18334 if (auto Context =
18335 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18336 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18337 << Context->Decl;
18338 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18339 }
18340 if (FD->isImmediateEscalating() && !FD->isConsteval())
18341 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18342
18343 } else {
18344 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18345 }
18346 }
18347 }
18348
18349 void Sema::PopExpressionEvaluationContext() {
18350 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18351 if (!Rec.Lambdas.empty()) {
18352 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18353 if (!getLangOpts().CPlusPlus20 &&
18354 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18355 Rec.isUnevaluated() ||
18356 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18357 unsigned D;
18358 if (Rec.isUnevaluated()) {
18359 // C++11 [expr.prim.lambda]p2:
18360 // A lambda-expression shall not appear in an unevaluated operand
18361 // (Clause 5).
18362 D = diag::err_lambda_unevaluated_operand;
18363 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18364 // C++1y [expr.const]p2:
18365 // A conditional-expression e is a core constant expression unless the
18366 // evaluation of e, following the rules of the abstract machine, would
18367 // evaluate [...] a lambda-expression.
18368 D = diag::err_lambda_in_constant_expression;
18369 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18370 // C++17 [expr.prim.lamda]p2:
18371 // A lambda-expression shall not appear [...] in a template-argument.
18372 D = diag::err_lambda_in_invalid_context;
18373 } else
18374 llvm_unreachable("Couldn't infer lambda error message.");
18375
18376 for (const auto *L : Rec.Lambdas)
18377 Diag(L->getBeginLoc(), D);
18378 }
18379 }
18380
18381 // Append the collected materialized temporaries into previous context before
18382 // exit if the previous also is a lifetime extending context.
18383 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18384 parentEvaluationContext().InLifetimeExtendingContext &&
18385 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18386 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18387 Rec.ForRangeLifetimeExtendTemps);
18388 }
18389
18390 WarnOnPendingNoDerefs(Rec);
18391 HandleImmediateInvocations(*this, Rec);
18392
18393 // Warn on any volatile-qualified simple-assignments that are not discarded-
18394 // value expressions nor unevaluated operands (those cases get removed from
18395 // this list by CheckUnusedVolatileAssignment).
18396 for (auto *BO : Rec.VolatileAssignmentLHSs)
18397 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18398 << BO->getType();
18399
18400 // When are coming out of an unevaluated context, clear out any
18401 // temporaries that we may have created as part of the evaluation of
18402 // the expression in that context: they aren't relevant because they
18403 // will never be constructed.
18404 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18405 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18406 ExprCleanupObjects.end());
18407 Cleanup = Rec.ParentCleanup;
18408 CleanupVarDeclMarking();
18409 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18410 // Otherwise, merge the contexts together.
18411 } else {
18412 Cleanup.mergeFrom(Rec.ParentCleanup);
18413 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18414 }
18415
18416 DiagnoseMisalignedMembers();
18417
18418 // Pop the current expression evaluation context off the stack.
18419 ExprEvalContexts.pop_back();
18420 }
18421
18422 void Sema::DiscardCleanupsInEvaluationContext() {
18423 ExprCleanupObjects.erase(
18424 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18425 ExprCleanupObjects.end());
18426 Cleanup.reset();
18427 MaybeODRUseExprs.clear();
18428 }
18429
18430 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18431 ExprResult Result = CheckPlaceholderExpr(E);
18432 if (Result.isInvalid())
18433 return ExprError();
18434 E = Result.get();
18435 if (!E->getType()->isVariablyModifiedType())
18436 return E;
18437 return TransformToPotentiallyEvaluated(E);
18438 }
18439
18440 /// Are we in a context that is potentially constant evaluated per C++20
18441 /// [expr.const]p12?
18442 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18443 /// C++2a [expr.const]p12:
18444 // An expression or conversion is potentially constant evaluated if it is
18445 switch (SemaRef.ExprEvalContexts.back().Context) {
18446 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18447 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18448
18449 // -- a manifestly constant-evaluated expression,
18450 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18451 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18452 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18453 // -- a potentially-evaluated expression,
18454 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18455 // -- an immediate subexpression of a braced-init-list,
18456
18457 // -- [FIXME] an expression of the form & cast-expression that occurs
18458 // within a templated entity
18459 // -- a subexpression of one of the above that is not a subexpression of
18460 // a nested unevaluated operand.
18461 return true;
18462
18463 case Sema::ExpressionEvaluationContext::Unevaluated:
18464 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18465 // Expressions in this context are never evaluated.
18466 return false;
18467 }
18468 llvm_unreachable("Invalid context");
18469 }
18470
18471 /// Return true if this function has a calling convention that requires mangling
18472 /// in the size of the parameter pack.
18473 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18474 // These manglings are only applicable for targets whcih use Microsoft
18475 // mangling scheme for C.
18476 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18477 return false;
18478
18479 // If this is C++ and this isn't an extern "C" function, parameters do not
18480 // need to be complete. In this case, C++ mangling will apply, which doesn't
18481 // use the size of the parameters.
18482 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18483 return false;
18484
18485 // Stdcall, fastcall, and vectorcall need this special treatment.
18486 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18487 switch (CC) {
18488 case CC_X86StdCall:
18489 case CC_X86FastCall:
18490 case CC_X86VectorCall:
18491 return true;
18492 default:
18493 break;
18494 }
18495 return false;
18496 }
18497
18498 /// Require that all of the parameter types of function be complete. Normally,
18499 /// parameter types are only required to be complete when a function is called
18500 /// or defined, but to mangle functions with certain calling conventions, the
18501 /// mangler needs to know the size of the parameter list. In this situation,
18502 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18503 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18504 /// result in a linker error. Clang doesn't implement this behavior, and instead
18505 /// attempts to error at compile time.
18506 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18507 SourceLocation Loc) {
18508 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18509 FunctionDecl *FD;
18510 ParmVarDecl *Param;
18511
18512 public:
18513 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18514 : FD(FD), Param(Param) {}
18515
18516 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18517 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18518 StringRef CCName;
18519 switch (CC) {
18520 case CC_X86StdCall:
18521 CCName = "stdcall";
18522 break;
18523 case CC_X86FastCall:
18524 CCName = "fastcall";
18525 break;
18526 case CC_X86VectorCall:
18527 CCName = "vectorcall";
18528 break;
18529 default:
18530 llvm_unreachable("CC does not need mangling");
18531 }
18532
18533 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18534 << Param->getDeclName() << FD->getDeclName() << CCName;
18535 }
18536 };
18537
18538 for (ParmVarDecl *Param : FD->parameters()) {
18539 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18540 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18541 }
18542 }
18543
18544 namespace {
18545 enum class OdrUseContext {
18546 /// Declarations in this context are not odr-used.
18547 None,
18548 /// Declarations in this context are formally odr-used, but this is a
18549 /// dependent context.
18550 Dependent,
18551 /// Declarations in this context are odr-used but not actually used (yet).
18552 FormallyOdrUsed,
18553 /// Declarations in this context are used.
18554 Used
18555 };
18556 }
18557
18558 /// Are we within a context in which references to resolved functions or to
18559 /// variables result in odr-use?
18560 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18561 const Sema::ExpressionEvaluationContextRecord &Context =
18562 SemaRef.currentEvaluationContext();
18563
18564 if (Context.isUnevaluated())
18565 return OdrUseContext::None;
18566
18567 if (SemaRef.CurContext->isDependentContext())
18568 return OdrUseContext::Dependent;
18569
18570 if (Context.isDiscardedStatementContext())
18571 return OdrUseContext::FormallyOdrUsed;
18572
18573 else if (Context.Context ==
18574 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18575 return OdrUseContext::FormallyOdrUsed;
18576
18577 return OdrUseContext::Used;
18578 }
18579
18580 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18581 if (!Func->isConstexpr())
18582 return false;
18583
18584 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18585 return true;
18586
18587 // Lambda conversion operators are never user provided.
18588 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18589 return isLambdaConversionOperator(Conv);
18590
18591 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18592 return CCD && CCD->getInheritedConstructor();
18593 }
18594
18595 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18596 bool MightBeOdrUse) {
18597 assert(Func && "No function?");
18598
18599 Func->setReferenced();
18600
18601 // Recursive functions aren't really used until they're used from some other
18602 // context.
18603 bool IsRecursiveCall = CurContext == Func;
18604
18605 // C++11 [basic.def.odr]p3:
18606 // A function whose name appears as a potentially-evaluated expression is
18607 // odr-used if it is the unique lookup result or the selected member of a
18608 // set of overloaded functions [...].
18609 //
18610 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18611 // can just check that here.
18612 OdrUseContext OdrUse =
18613 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18614 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18615 OdrUse = OdrUseContext::FormallyOdrUsed;
18616
18617 // Trivial default constructors and destructors are never actually used.
18618 // FIXME: What about other special members?
18619 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18620 OdrUse == OdrUseContext::Used) {
18621 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18622 if (Constructor->isDefaultConstructor())
18623 OdrUse = OdrUseContext::FormallyOdrUsed;
18624 if (isa<CXXDestructorDecl>(Func))
18625 OdrUse = OdrUseContext::FormallyOdrUsed;
18626 }
18627
18628 // C++20 [expr.const]p12:
18629 // A function [...] is needed for constant evaluation if it is [...] a
18630 // constexpr function that is named by an expression that is potentially
18631 // constant evaluated
18632 bool NeededForConstantEvaluation =
18633 isPotentiallyConstantEvaluatedContext(*this) &&
18634 isImplicitlyDefinableConstexprFunction(Func);
18635
18636 // Determine whether we require a function definition to exist, per
18637 // C++11 [temp.inst]p3:
18638 // Unless a function template specialization has been explicitly
18639 // instantiated or explicitly specialized, the function template
18640 // specialization is implicitly instantiated when the specialization is
18641 // referenced in a context that requires a function definition to exist.
18642 // C++20 [temp.inst]p7:
18643 // The existence of a definition of a [...] function is considered to
18644 // affect the semantics of the program if the [...] function is needed for
18645 // constant evaluation by an expression
18646 // C++20 [basic.def.odr]p10:
18647 // Every program shall contain exactly one definition of every non-inline
18648 // function or variable that is odr-used in that program outside of a
18649 // discarded statement
18650 // C++20 [special]p1:
18651 // The implementation will implicitly define [defaulted special members]
18652 // if they are odr-used or needed for constant evaluation.
18653 //
18654 // Note that we skip the implicit instantiation of templates that are only
18655 // used in unused default arguments or by recursive calls to themselves.
18656 // This is formally non-conforming, but seems reasonable in practice.
18657 bool NeedDefinition =
18658 !IsRecursiveCall &&
18659 (OdrUse == OdrUseContext::Used ||
18660 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18661
18662 // C++14 [temp.expl.spec]p6:
18663 // If a template [...] is explicitly specialized then that specialization
18664 // shall be declared before the first use of that specialization that would
18665 // cause an implicit instantiation to take place, in every translation unit
18666 // in which such a use occurs
18667 if (NeedDefinition &&
18668 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18669 Func->getMemberSpecializationInfo()))
18670 checkSpecializationReachability(Loc, Func);
18671
18672 if (getLangOpts().CUDA)
18673 CUDA().CheckCall(Loc, Func);
18674
18675 // If we need a definition, try to create one.
18676 if (NeedDefinition && !Func->getBody()) {
18677 runWithSufficientStackSpace(Loc, [&] {
18678 if (CXXConstructorDecl *Constructor =
18679 dyn_cast<CXXConstructorDecl>(Func)) {
18680 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18681 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18682 if (Constructor->isDefaultConstructor()) {
18683 if (Constructor->isTrivial() &&
18684 !Constructor->hasAttr<DLLExportAttr>())
18685 return;
18686 DefineImplicitDefaultConstructor(Loc, Constructor);
18687 } else if (Constructor->isCopyConstructor()) {
18688 DefineImplicitCopyConstructor(Loc, Constructor);
18689 } else if (Constructor->isMoveConstructor()) {
18690 DefineImplicitMoveConstructor(Loc, Constructor);
18691 }
18692 } else if (Constructor->getInheritedConstructor()) {
18693 DefineInheritingConstructor(Loc, Constructor);
18694 }
18695 } else if (CXXDestructorDecl *Destructor =
18696 dyn_cast<CXXDestructorDecl>(Func)) {
18697 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18698 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18699 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18700 return;
18701 DefineImplicitDestructor(Loc, Destructor);
18702 }
18703 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18704 MarkVTableUsed(Loc, Destructor->getParent());
18705 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18706 if (MethodDecl->isOverloadedOperator() &&
18707 MethodDecl->getOverloadedOperator() == OO_Equal) {
18708 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18709 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18710 if (MethodDecl->isCopyAssignmentOperator())
18711 DefineImplicitCopyAssignment(Loc, MethodDecl);
18712 else if (MethodDecl->isMoveAssignmentOperator())
18713 DefineImplicitMoveAssignment(Loc, MethodDecl);
18714 }
18715 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18716 MethodDecl->getParent()->isLambda()) {
18717 CXXConversionDecl *Conversion =
18718 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18719 if (Conversion->isLambdaToBlockPointerConversion())
18720 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18721 else
18722 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18723 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18724 MarkVTableUsed(Loc, MethodDecl->getParent());
18725 }
18726
18727 if (Func->isDefaulted() && !Func->isDeleted()) {
18728 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18729 if (DCK != DefaultedComparisonKind::None)
18730 DefineDefaultedComparison(Loc, Func, DCK);
18731 }
18732
18733 // Implicit instantiation of function templates and member functions of
18734 // class templates.
18735 if (Func->isImplicitlyInstantiable()) {
18736 TemplateSpecializationKind TSK =
18737 Func->getTemplateSpecializationKindForInstantiation();
18738 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18739 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18740 if (FirstInstantiation) {
18741 PointOfInstantiation = Loc;
18742 if (auto *MSI = Func->getMemberSpecializationInfo())
18743 MSI->setPointOfInstantiation(Loc);
18744 // FIXME: Notify listener.
18745 else
18746 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18747 } else if (TSK != TSK_ImplicitInstantiation) {
18748 // Use the point of use as the point of instantiation, instead of the
18749 // point of explicit instantiation (which we track as the actual point
18750 // of instantiation). This gives better backtraces in diagnostics.
18751 PointOfInstantiation = Loc;
18752 }
18753
18754 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18755 Func->isConstexpr()) {
18756 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18757 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18758 CodeSynthesisContexts.size())
18759 PendingLocalImplicitInstantiations.push_back(
18760 std::make_pair(Func, PointOfInstantiation));
18761 else if (Func->isConstexpr())
18762 // Do not defer instantiations of constexpr functions, to avoid the
18763 // expression evaluator needing to call back into Sema if it sees a
18764 // call to such a function.
18765 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18766 else {
18767 Func->setInstantiationIsPending(true);
18768 PendingInstantiations.push_back(
18769 std::make_pair(Func, PointOfInstantiation));
18770 if (llvm::isTimeTraceVerbose()) {
18771 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18772 std::string Name;
18773 llvm::raw_string_ostream OS(Name);
18774 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18775 /*Qualified=*/true);
18776 return Name;
18777 });
18778 }
18779 // Notify the consumer that a function was implicitly instantiated.
18780 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18781 }
18782 }
18783 } else {
18784 // Walk redefinitions, as some of them may be instantiable.
18785 for (auto *i : Func->redecls()) {
18786 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18787 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18788 }
18789 }
18790 });
18791 }
18792
18793 // If a constructor was defined in the context of a default parameter
18794 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18795 // context), its initializers may not be referenced yet.
18796 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18797 EnterExpressionEvaluationContext EvalContext(
18798 *this,
18799 Constructor->isImmediateFunction()
18800 ? ExpressionEvaluationContext::ImmediateFunctionContext
18801 : ExpressionEvaluationContext::PotentiallyEvaluated,
18802 Constructor);
18803 for (CXXCtorInitializer *Init : Constructor->inits()) {
18804 if (Init->isInClassMemberInitializer())
18805 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18806 MarkDeclarationsReferencedInExpr(Init->getInit());
18807 });
18808 }
18809 }
18810
18811 // C++14 [except.spec]p17:
18812 // An exception-specification is considered to be needed when:
18813 // - the function is odr-used or, if it appears in an unevaluated operand,
18814 // would be odr-used if the expression were potentially-evaluated;
18815 //
18816 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18817 // function is a pure virtual function we're calling, and in that case the
18818 // function was selected by overload resolution and we need to resolve its
18819 // exception specification for a different reason.
18820 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18821 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18822 ResolveExceptionSpec(Loc, FPT);
18823
18824 // A callee could be called by a host function then by a device function.
18825 // If we only try recording once, we will miss recording the use on device
18826 // side. Therefore keep trying until it is recorded.
18827 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18828 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18829 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func);
18830
18831 // If this is the first "real" use, act on that.
18832 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18833 // Keep track of used but undefined functions.
18834 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18835 if (mightHaveNonExternalLinkage(Func))
18836 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18837 else if (Func->getMostRecentDecl()->isInlined() &&
18838 !LangOpts.GNUInline &&
18839 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18840 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18841 else if (isExternalWithNoLinkageType(Func))
18842 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18843 }
18844
18845 // Some x86 Windows calling conventions mangle the size of the parameter
18846 // pack into the name. Computing the size of the parameters requires the
18847 // parameter types to be complete. Check that now.
18848 if (funcHasParameterSizeMangling(*this, Func))
18849 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18850
18851 // In the MS C++ ABI, the compiler emits destructor variants where they are
18852 // used. If the destructor is used here but defined elsewhere, mark the
18853 // virtual base destructors referenced. If those virtual base destructors
18854 // are inline, this will ensure they are defined when emitting the complete
18855 // destructor variant. This checking may be redundant if the destructor is
18856 // provided later in this TU.
18857 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18858 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18859 CXXRecordDecl *Parent = Dtor->getParent();
18860 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18861 CheckCompleteDestructorVariant(Loc, Dtor);
18862 }
18863 }
18864
18865 Func->markUsed(Context);
18866 }
18867 }
18868
18869 /// Directly mark a variable odr-used. Given a choice, prefer to use
18870 /// MarkVariableReferenced since it does additional checks and then
18871 /// calls MarkVarDeclODRUsed.
18872 /// If the variable must be captured:
18873 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18874 /// - else capture it in the DeclContext that maps to the
18875 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18876 static void
18877 MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18878 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18879 // Keep track of used but undefined variables.
18880 // FIXME: We shouldn't suppress this warning for static data members.
18881 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18882 assert(Var && "expected a capturable variable");
18883
18884 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18885 (!Var->isExternallyVisible() || Var->isInline() ||
18886 SemaRef.isExternalWithNoLinkageType(Var)) &&
18887 !(Var->isStaticDataMember() && Var->hasInit())) {
18888 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18889 if (old.isInvalid())
18890 old = Loc;
18891 }
18892 QualType CaptureType, DeclRefType;
18893 if (SemaRef.LangOpts.OpenMP)
18894 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
18895 SemaRef.tryCaptureVariable(V, Loc, TryCaptureKind::Implicit,
18896 /*EllipsisLoc*/ SourceLocation(),
18897 /*BuildAndDiagnose*/ true, CaptureType,
18898 DeclRefType, FunctionScopeIndexToStopAt);
18899
18900 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18901 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18902 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18903 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18904 if (VarTarget == SemaCUDA::CVT_Host &&
18905 (UserTarget == CUDAFunctionTarget::Device ||
18906 UserTarget == CUDAFunctionTarget::HostDevice ||
18907 UserTarget == CUDAFunctionTarget::Global)) {
18908 // Diagnose ODR-use of host global variables in device functions.
18909 // Reference of device global variables in host functions is allowed
18910 // through shadow variables therefore it is not diagnosed.
18911 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18912 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18913 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18914 SemaRef.targetDiag(Var->getLocation(),
18915 Var->getType().isConstQualified()
18916 ? diag::note_cuda_const_var_unpromoted
18917 : diag::note_cuda_host_var);
18918 }
18919 } else if (VarTarget == SemaCUDA::CVT_Device &&
18920 !Var->hasAttr<CUDASharedAttr>() &&
18921 (UserTarget == CUDAFunctionTarget::Host ||
18922 UserTarget == CUDAFunctionTarget::HostDevice)) {
18923 // Record a CUDA/HIP device side variable if it is ODR-used
18924 // by host code. This is done conservatively, when the variable is
18925 // referenced in any of the following contexts:
18926 // - a non-function context
18927 // - a host function
18928 // - a host device function
18929 // This makes the ODR-use of the device side variable by host code to
18930 // be visible in the device compilation for the compiler to be able to
18931 // emit template variables instantiated by host code only and to
18932 // externalize the static device side variable ODR-used by host code.
18933 if (!Var->hasExternalStorage())
18934 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18935 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18936 (!FD || (!FD->getDescribedFunctionTemplate() &&
18937 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
18938 GVA_StrongExternal)))
18939 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18940 }
18941 }
18942
18943 V->markUsed(SemaRef.Context);
18944 }
18945
18946 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18947 SourceLocation Loc,
18948 unsigned CapturingScopeIndex) {
18949 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18950 }
18951
18952 static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
18953 SourceLocation loc,
18954 ValueDecl *var) {
18955 DeclContext *VarDC = var->getDeclContext();
18956
18957 // If the parameter still belongs to the translation unit, then
18958 // we're actually just using one parameter in the declaration of
18959 // the next.
18960 if (isa<ParmVarDecl>(var) &&
18961 isa<TranslationUnitDecl>(VarDC))
18962 return;
18963
18964 // For C code, don't diagnose about capture if we're not actually in code
18965 // right now; it's impossible to write a non-constant expression outside of
18966 // function context, so we'll get other (more useful) diagnostics later.
18967 //
18968 // For C++, things get a bit more nasty... it would be nice to suppress this
18969 // diagnostic for certain cases like using a local variable in an array bound
18970 // for a member of a local class, but the correct predicate is not obvious.
18971 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18972 return;
18973
18974 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18975 unsigned ContextKind = 3; // unknown
18976 if (isa<CXXMethodDecl>(VarDC) &&
18977 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18978 ContextKind = 2;
18979 } else if (isa<FunctionDecl>(VarDC)) {
18980 ContextKind = 0;
18981 } else if (isa<BlockDecl>(VarDC)) {
18982 ContextKind = 1;
18983 }
18984
18985 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18986 << var << ValueKind << ContextKind << VarDC;
18987 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18988 << var;
18989
18990 // FIXME: Add additional diagnostic info about class etc. which prevents
18991 // capture.
18992 }
18993
18994 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18995 ValueDecl *Var,
18996 bool &SubCapturesAreNested,
18997 QualType &CaptureType,
18998 QualType &DeclRefType) {
18999 // Check whether we've already captured it.
19000 if (CSI->CaptureMap.count(Var)) {
19001 // If we found a capture, any subcaptures are nested.
19002 SubCapturesAreNested = true;
19003
19004 // Retrieve the capture type for this variable.
19005 CaptureType = CSI->getCapture(Var).getCaptureType();
19006
19007 // Compute the type of an expression that refers to this variable.
19008 DeclRefType = CaptureType.getNonReferenceType();
19009
19010 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19011 // are mutable in the sense that user can change their value - they are
19012 // private instances of the captured declarations.
19013 const Capture &Cap = CSI->getCapture(Var);
19014 // C++ [expr.prim.lambda]p10:
19015 // The type of such a data member is [...] an lvalue reference to the
19016 // referenced function type if the entity is a reference to a function.
19017 // [...]
19018 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19019 !(isa<LambdaScopeInfo>(CSI) &&
19020 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19021 !(isa<CapturedRegionScopeInfo>(CSI) &&
19022 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19023 DeclRefType.addConst();
19024 return true;
19025 }
19026 return false;
19027 }
19028
19029 // Only block literals, captured statements, and lambda expressions can
19030 // capture; other scopes don't work.
19031 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19032 ValueDecl *Var,
19033 SourceLocation Loc,
19034 const bool Diagnose,
19035 Sema &S) {
19036 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
19037 return getLambdaAwareParentOfDeclContext(DC);
19038
19039 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19040 if (Underlying) {
19041 if (Underlying->hasLocalStorage() && Diagnose)
19042 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19043 }
19044 return nullptr;
19045 }
19046
19047 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19048 // certain types of variables (unnamed, variably modified types etc.)
19049 // so check for eligibility.
19050 static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19051 SourceLocation Loc, const bool Diagnose,
19052 Sema &S) {
19053
19054 assert((isa<VarDecl, BindingDecl>(Var)) &&
19055 "Only variables and structured bindings can be captured");
19056
19057 bool IsBlock = isa<BlockScopeInfo>(CSI);
19058 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19059
19060 // Lambdas are not allowed to capture unnamed variables
19061 // (e.g. anonymous unions).
19062 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19063 // assuming that's the intent.
19064 if (IsLambda && !Var->getDeclName()) {
19065 if (Diagnose) {
19066 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19067 S.Diag(Var->getLocation(), diag::note_declared_at);
19068 }
19069 return false;
19070 }
19071
19072 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19073 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19074 if (Diagnose) {
19075 S.Diag(Loc, diag::err_ref_vm_type);
19076 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19077 }
19078 return false;
19079 }
19080 // Prohibit structs with flexible array members too.
19081 // We cannot capture what is in the tail end of the struct.
19082 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19083 VTD && VTD->hasFlexibleArrayMember()) {
19084 if (Diagnose) {
19085 if (IsBlock)
19086 S.Diag(Loc, diag::err_ref_flexarray_type);
19087 else
19088 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19089 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19090 }
19091 return false;
19092 }
19093 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19094 // Lambdas and captured statements are not allowed to capture __block
19095 // variables; they don't support the expected semantics.
19096 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19097 if (Diagnose) {
19098 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19099 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19100 }
19101 return false;
19102 }
19103 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19104 if (S.getLangOpts().OpenCL && IsBlock &&
19105 Var->getType()->isBlockPointerType()) {
19106 if (Diagnose)
19107 S.Diag(Loc, diag::err_opencl_block_ref_block);
19108 return false;
19109 }
19110
19111 if (isa<BindingDecl>(Var)) {
19112 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19113 if (Diagnose)
19114 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19115 return false;
19116 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19117 S.Diag(Loc, S.LangOpts.CPlusPlus20
19118 ? diag::warn_cxx17_compat_capture_binding
19119 : diag::ext_capture_binding)
19120 << Var;
19121 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19122 }
19123 }
19124
19125 return true;
19126 }
19127
19128 // Returns true if the capture by block was successful.
19129 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19130 SourceLocation Loc, const bool BuildAndDiagnose,
19131 QualType &CaptureType, QualType &DeclRefType,
19132 const bool Nested, Sema &S, bool Invalid) {
19133 bool ByRef = false;
19134
19135 // Blocks are not allowed to capture arrays, excepting OpenCL.
19136 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19137 // (decayed to pointers).
19138 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19139 if (BuildAndDiagnose) {
19140 S.Diag(Loc, diag::err_ref_array_type);
19141 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19142 Invalid = true;
19143 } else {
19144 return false;
19145 }
19146 }
19147
19148 // Forbid the block-capture of autoreleasing variables.
19149 if (!Invalid &&
19150 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19151 if (BuildAndDiagnose) {
19152 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19153 << /*block*/ 0;
19154 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19155 Invalid = true;
19156 } else {
19157 return false;
19158 }
19159 }
19160
19161 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19162 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19163 QualType PointeeTy = PT->getPointeeType();
19164
19165 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19166 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19167 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19168 if (BuildAndDiagnose) {
19169 SourceLocation VarLoc = Var->getLocation();
19170 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19171 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19172 }
19173 }
19174 }
19175
19176 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19177 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19178 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19179 // Block capture by reference does not change the capture or
19180 // declaration reference types.
19181 ByRef = true;
19182 } else {
19183 // Block capture by copy introduces 'const'.
19184 CaptureType = CaptureType.getNonReferenceType().withConst();
19185 DeclRefType = CaptureType;
19186 }
19187
19188 // Actually capture the variable.
19189 if (BuildAndDiagnose)
19190 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19191 CaptureType, Invalid);
19192
19193 return !Invalid;
19194 }
19195
19196 /// Capture the given variable in the captured region.
19197 static bool captureInCapturedRegion(
19198 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19199 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19200 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19201 Sema &S, bool Invalid) {
19202 // By default, capture variables by reference.
19203 bool ByRef = true;
19204 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19205 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19206 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19207 // Using an LValue reference type is consistent with Lambdas (see below).
19208 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19209 bool HasConst = DeclRefType.isConstQualified();
19210 DeclRefType = DeclRefType.getUnqualifiedType();
19211 // Don't lose diagnostics about assignments to const.
19212 if (HasConst)
19213 DeclRefType.addConst();
19214 }
19215 // Do not capture firstprivates in tasks.
19216 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19217 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19218 return true;
19219 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19220 RSI->OpenMPCaptureLevel);
19221 }
19222
19223 if (ByRef)
19224 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19225 else
19226 CaptureType = DeclRefType;
19227
19228 // Actually capture the variable.
19229 if (BuildAndDiagnose)
19230 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19231 Loc, SourceLocation(), CaptureType, Invalid);
19232
19233 return !Invalid;
19234 }
19235
19236 /// Capture the given variable in the lambda.
19237 static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19238 SourceLocation Loc, const bool BuildAndDiagnose,
19239 QualType &CaptureType, QualType &DeclRefType,
19240 const bool RefersToCapturedVariable,
19241 const TryCaptureKind Kind,
19242 SourceLocation EllipsisLoc, const bool IsTopScope,
19243 Sema &S, bool Invalid) {
19244 // Determine whether we are capturing by reference or by value.
19245 bool ByRef = false;
19246 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19247 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19248 } else {
19249 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19250 }
19251
19252 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19253 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19254 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19255 Invalid = true;
19256 }
19257
19258 // Compute the type of the field that will capture this variable.
19259 if (ByRef) {
19260 // C++11 [expr.prim.lambda]p15:
19261 // An entity is captured by reference if it is implicitly or
19262 // explicitly captured but not captured by copy. It is
19263 // unspecified whether additional unnamed non-static data
19264 // members are declared in the closure type for entities
19265 // captured by reference.
19266 //
19267 // FIXME: It is not clear whether we want to build an lvalue reference
19268 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19269 // to do the former, while EDG does the latter. Core issue 1249 will
19270 // clarify, but for now we follow GCC because it's a more permissive and
19271 // easily defensible position.
19272 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19273 } else {
19274 // C++11 [expr.prim.lambda]p14:
19275 // For each entity captured by copy, an unnamed non-static
19276 // data member is declared in the closure type. The
19277 // declaration order of these members is unspecified. The type
19278 // of such a data member is the type of the corresponding
19279 // captured entity if the entity is not a reference to an
19280 // object, or the referenced type otherwise. [Note: If the
19281 // captured entity is a reference to a function, the
19282 // corresponding data member is also a reference to a
19283 // function. - end note ]
19284 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19285 if (!RefType->getPointeeType()->isFunctionType())
19286 CaptureType = RefType->getPointeeType();
19287 }
19288
19289 // Forbid the lambda copy-capture of autoreleasing variables.
19290 if (!Invalid &&
19291 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19292 if (BuildAndDiagnose) {
19293 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19294 S.Diag(Var->getLocation(), diag::note_previous_decl)
19295 << Var->getDeclName();
19296 Invalid = true;
19297 } else {
19298 return false;
19299 }
19300 }
19301
19302 // Make sure that by-copy captures are of a complete and non-abstract type.
19303 if (!Invalid && BuildAndDiagnose) {
19304 if (!CaptureType->isDependentType() &&
19305 S.RequireCompleteSizedType(
19306 Loc, CaptureType,
19307 diag::err_capture_of_incomplete_or_sizeless_type,
19308 Var->getDeclName()))
19309 Invalid = true;
19310 else if (S.RequireNonAbstractType(Loc, CaptureType,
19311 diag::err_capture_of_abstract_type))
19312 Invalid = true;
19313 }
19314 }
19315
19316 // Compute the type of a reference to this captured variable.
19317 if (ByRef)
19318 DeclRefType = CaptureType.getNonReferenceType();
19319 else {
19320 // C++ [expr.prim.lambda]p5:
19321 // The closure type for a lambda-expression has a public inline
19322 // function call operator [...]. This function call operator is
19323 // declared const (9.3.1) if and only if the lambda-expression's
19324 // parameter-declaration-clause is not followed by mutable.
19325 DeclRefType = CaptureType.getNonReferenceType();
19326 bool Const = LSI->lambdaCaptureShouldBeConst();
19327 // C++ [expr.prim.lambda]p10:
19328 // The type of such a data member is [...] an lvalue reference to the
19329 // referenced function type if the entity is a reference to a function.
19330 // [...]
19331 if (Const && !CaptureType->isReferenceType() &&
19332 !DeclRefType->isFunctionType())
19333 DeclRefType.addConst();
19334 }
19335
19336 // Add the capture.
19337 if (BuildAndDiagnose)
19338 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19339 Loc, EllipsisLoc, CaptureType, Invalid);
19340
19341 return !Invalid;
19342 }
19343
19344 static bool canCaptureVariableByCopy(ValueDecl *Var,
19345 const ASTContext &Context) {
19346 // Offer a Copy fix even if the type is dependent.
19347 if (Var->getType()->isDependentType())
19348 return true;
19349 QualType T = Var->getType().getNonReferenceType();
19350 if (T.isTriviallyCopyableType(Context))
19351 return true;
19352 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19353
19354 if (!(RD = RD->getDefinition()))
19355 return false;
19356 if (RD->hasSimpleCopyConstructor())
19357 return true;
19358 if (RD->hasUserDeclaredCopyConstructor())
19359 for (CXXConstructorDecl *Ctor : RD->ctors())
19360 if (Ctor->isCopyConstructor())
19361 return !Ctor->isDeleted();
19362 }
19363 return false;
19364 }
19365
19366 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19367 /// default capture. Fixes may be omitted if they aren't allowed by the
19368 /// standard, for example we can't emit a default copy capture fix-it if we
19369 /// already explicitly copy capture capture another variable.
19370 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19371 ValueDecl *Var) {
19372 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19373 // Don't offer Capture by copy of default capture by copy fixes if Var is
19374 // known not to be copy constructible.
19375 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19376
19377 SmallString<32> FixBuffer;
19378 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19379 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19380 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19381 if (ShouldOfferCopyFix) {
19382 // Offer fixes to insert an explicit capture for the variable.
19383 // [] -> [VarName]
19384 // [OtherCapture] -> [OtherCapture, VarName]
19385 FixBuffer.assign({Separator, Var->getName()});
19386 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19387 << Var << /*value*/ 0
19388 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19389 }
19390 // As above but capture by reference.
19391 FixBuffer.assign({Separator, "&", Var->getName()});
19392 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19393 << Var << /*reference*/ 1
19394 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19395 }
19396
19397 // Only try to offer default capture if there are no captures excluding this
19398 // and init captures.
19399 // [this]: OK.
19400 // [X = Y]: OK.
19401 // [&A, &B]: Don't offer.
19402 // [A, B]: Don't offer.
19403 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19404 return !C.isThisCapture() && !C.isInitCapture();
19405 }))
19406 return;
19407
19408 // The default capture specifiers, '=' or '&', must appear first in the
19409 // capture body.
19410 SourceLocation DefaultInsertLoc =
19411 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19412
19413 if (ShouldOfferCopyFix) {
19414 bool CanDefaultCopyCapture = true;
19415 // [=, *this] OK since c++17
19416 // [=, this] OK since c++20
19417 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19418 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19419 ? LSI->getCXXThisCapture().isCopyCapture()
19420 : false;
19421 // We can't use default capture by copy if any captures already specified
19422 // capture by copy.
19423 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19424 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19425 })) {
19426 FixBuffer.assign({"=", Separator});
19427 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19428 << /*value*/ 0
19429 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19430 }
19431 }
19432
19433 // We can't use default capture by reference if any captures already specified
19434 // capture by reference.
19435 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19436 return !C.isInitCapture() && C.isReferenceCapture() &&
19437 !C.isThisCapture();
19438 })) {
19439 FixBuffer.assign({"&", Separator});
19440 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19441 << /*reference*/ 1
19442 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19443 }
19444 }
19445
19446 bool Sema::tryCaptureVariable(
19447 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19448 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19449 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19450 // An init-capture is notionally from the context surrounding its
19451 // declaration, but its parent DC is the lambda class.
19452 DeclContext *VarDC = Var->getDeclContext();
19453 DeclContext *DC = CurContext;
19454
19455 // Skip past RequiresExprBodys because they don't constitute function scopes.
19456 while (DC->isRequiresExprBody())
19457 DC = DC->getParent();
19458
19459 // tryCaptureVariable is called every time a DeclRef is formed,
19460 // it can therefore have non-negigible impact on performances.
19461 // For local variables and when there is no capturing scope,
19462 // we can bailout early.
19463 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19464 return true;
19465
19466 // Exception: Function parameters are not tied to the function's DeclContext
19467 // until we enter the function definition. Capturing them anyway would result
19468 // in an out-of-bounds error while traversing DC and its parents.
19469 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19470 return true;
19471
19472 const auto *VD = dyn_cast<VarDecl>(Var);
19473 if (VD) {
19474 if (VD->isInitCapture())
19475 VarDC = VarDC->getParent();
19476 } else {
19477 VD = Var->getPotentiallyDecomposedVarDecl();
19478 }
19479 assert(VD && "Cannot capture a null variable");
19480
19481 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19482 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19483 // We need to sync up the Declaration Context with the
19484 // FunctionScopeIndexToStopAt
19485 if (FunctionScopeIndexToStopAt) {
19486 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19487 unsigned FSIndex = FunctionScopes.size() - 1;
19488 // When we're parsing the lambda parameter list, the current DeclContext is
19489 // NOT the lambda but its parent. So move away the current LSI before
19490 // aligning DC and FunctionScopeIndexToStopAt.
19491 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19492 FSIndex && LSI && !LSI->AfterParameterList)
19493 --FSIndex;
19494 assert(MaxFunctionScopesIndex <= FSIndex &&
19495 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19496 "FunctionScopes.");
19497 while (FSIndex != MaxFunctionScopesIndex) {
19498 DC = getLambdaAwareParentOfDeclContext(DC);
19499 --FSIndex;
19500 }
19501 }
19502
19503 // Capture global variables if it is required to use private copy of this
19504 // variable.
19505 bool IsGlobal = !VD->hasLocalStorage();
19506 if (IsGlobal && !(LangOpts.OpenMP &&
19507 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19508 MaxFunctionScopesIndex)))
19509 return true;
19510
19511 if (isa<VarDecl>(Var))
19512 Var = cast<VarDecl>(Var->getCanonicalDecl());
19513
19514 // Walk up the stack to determine whether we can capture the variable,
19515 // performing the "simple" checks that don't depend on type. We stop when
19516 // we've either hit the declared scope of the variable or find an existing
19517 // capture of that variable. We start from the innermost capturing-entity
19518 // (the DC) and ensure that all intervening capturing-entities
19519 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19520 // declcontext can either capture the variable or have already captured
19521 // the variable.
19522 CaptureType = Var->getType();
19523 DeclRefType = CaptureType.getNonReferenceType();
19524 bool Nested = false;
19525 bool Explicit = (Kind != TryCaptureKind::Implicit);
19526 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19527 do {
19528
19529 LambdaScopeInfo *LSI = nullptr;
19530 if (!FunctionScopes.empty())
19531 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19532 FunctionScopes[FunctionScopesIndex]);
19533
19534 bool IsInScopeDeclarationContext =
19535 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19536
19537 if (LSI && !LSI->AfterParameterList) {
19538 // This allows capturing parameters from a default value which does not
19539 // seems correct
19540 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19541 return true;
19542 }
19543 // If the variable is declared in the current context, there is no need to
19544 // capture it.
19545 if (IsInScopeDeclarationContext &&
19546 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19547 return true;
19548
19549 // Only block literals, captured statements, and lambda expressions can
19550 // capture; other scopes don't work.
19551 DeclContext *ParentDC =
19552 !IsInScopeDeclarationContext
19553 ? DC->getParent()
19554 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19555 BuildAndDiagnose, *this);
19556 // We need to check for the parent *first* because, if we *have*
19557 // private-captured a global variable, we need to recursively capture it in
19558 // intermediate blocks, lambdas, etc.
19559 if (!ParentDC) {
19560 if (IsGlobal) {
19561 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19562 break;
19563 }
19564 return true;
19565 }
19566
19567 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19568 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19569
19570 // Check whether we've already captured it.
19571 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19572 DeclRefType)) {
19573 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19574 break;
19575 }
19576
19577 // When evaluating some attributes (like enable_if) we might refer to a
19578 // function parameter appertaining to the same declaration as that
19579 // attribute.
19580 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19581 Parm && Parm->getDeclContext() == DC)
19582 return true;
19583
19584 // If we are instantiating a generic lambda call operator body,
19585 // we do not want to capture new variables. What was captured
19586 // during either a lambdas transformation or initial parsing
19587 // should be used.
19588 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19589 if (BuildAndDiagnose) {
19590 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19591 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19592 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19593 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19594 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19595 buildLambdaCaptureFixit(*this, LSI, Var);
19596 } else
19597 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19598 }
19599 return true;
19600 }
19601
19602 // Try to capture variable-length arrays types.
19603 if (Var->getType()->isVariablyModifiedType()) {
19604 // We're going to walk down into the type and look for VLA
19605 // expressions.
19606 QualType QTy = Var->getType();
19607 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19608 QTy = PVD->getOriginalType();
19609 captureVariablyModifiedType(Context, QTy, CSI);
19610 }
19611
19612 if (getLangOpts().OpenMP) {
19613 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19614 // OpenMP private variables should not be captured in outer scope, so
19615 // just break here. Similarly, global variables that are captured in a
19616 // target region should not be captured outside the scope of the region.
19617 if (RSI->CapRegionKind == CR_OpenMP) {
19618 // FIXME: We should support capturing structured bindings in OpenMP.
19619 if (isa<BindingDecl>(Var)) {
19620 if (BuildAndDiagnose) {
19621 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19622 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19623 }
19624 return true;
19625 }
19626 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19627 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19628 // If the variable is private (i.e. not captured) and has variably
19629 // modified type, we still need to capture the type for correct
19630 // codegen in all regions, associated with the construct. Currently,
19631 // it is captured in the innermost captured region only.
19632 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19633 Var->getType()->isVariablyModifiedType()) {
19634 QualType QTy = Var->getType();
19635 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19636 QTy = PVD->getOriginalType();
19637 for (int I = 1,
19638 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19639 I < E; ++I) {
19640 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19641 FunctionScopes[FunctionScopesIndex - I]);
19642 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19643 "Wrong number of captured regions associated with the "
19644 "OpenMP construct.");
19645 captureVariablyModifiedType(Context, QTy, OuterRSI);
19646 }
19647 }
19648 bool IsTargetCap =
19649 IsOpenMPPrivateDecl != OMPC_private &&
19650 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19651 RSI->OpenMPCaptureLevel);
19652 // Do not capture global if it is not privatized in outer regions.
19653 bool IsGlobalCap =
19654 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19655 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19656
19657 // When we detect target captures we are looking from inside the
19658 // target region, therefore we need to propagate the capture from the
19659 // enclosing region. Therefore, the capture is not initially nested.
19660 if (IsTargetCap)
19661 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19662 RSI->OpenMPLevel);
19663
19664 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19665 (IsGlobal && !IsGlobalCap)) {
19666 Nested = !IsTargetCap;
19667 bool HasConst = DeclRefType.isConstQualified();
19668 DeclRefType = DeclRefType.getUnqualifiedType();
19669 // Don't lose diagnostics about assignments to const.
19670 if (HasConst)
19671 DeclRefType.addConst();
19672 CaptureType = Context.getLValueReferenceType(DeclRefType);
19673 break;
19674 }
19675 }
19676 }
19677 }
19678 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19679 // No capture-default, and this is not an explicit capture
19680 // so cannot capture this variable.
19681 if (BuildAndDiagnose) {
19682 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19683 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19684 auto *LSI = cast<LambdaScopeInfo>(CSI);
19685 if (LSI->Lambda) {
19686 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19687 buildLambdaCaptureFixit(*this, LSI, Var);
19688 }
19689 // FIXME: If we error out because an outer lambda can not implicitly
19690 // capture a variable that an inner lambda explicitly captures, we
19691 // should have the inner lambda do the explicit capture - because
19692 // it makes for cleaner diagnostics later. This would purely be done
19693 // so that the diagnostic does not misleadingly claim that a variable
19694 // can not be captured by a lambda implicitly even though it is captured
19695 // explicitly. Suggestion:
19696 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19697 // at the function head
19698 // - cache the StartingDeclContext - this must be a lambda
19699 // - captureInLambda in the innermost lambda the variable.
19700 }
19701 return true;
19702 }
19703 Explicit = false;
19704 FunctionScopesIndex--;
19705 if (IsInScopeDeclarationContext)
19706 DC = ParentDC;
19707 } while (!VarDC->Equals(DC));
19708
19709 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19710 // computing the type of the capture at each step, checking type-specific
19711 // requirements, and adding captures if requested.
19712 // If the variable had already been captured previously, we start capturing
19713 // at the lambda nested within that one.
19714 bool Invalid = false;
19715 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19716 ++I) {
19717 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19718
19719 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19720 // certain types of variables (unnamed, variably modified types etc.)
19721 // so check for eligibility.
19722 if (!Invalid)
19723 Invalid =
19724 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19725
19726 // After encountering an error, if we're actually supposed to capture, keep
19727 // capturing in nested contexts to suppress any follow-on diagnostics.
19728 if (Invalid && !BuildAndDiagnose)
19729 return true;
19730
19731 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19732 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19733 DeclRefType, Nested, *this, Invalid);
19734 Nested = true;
19735 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19736 Invalid = !captureInCapturedRegion(
19737 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19738 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19739 Nested = true;
19740 } else {
19741 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19742 Invalid =
19743 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19744 DeclRefType, Nested, Kind, EllipsisLoc,
19745 /*IsTopScope*/ I == N - 1, *this, Invalid);
19746 Nested = true;
19747 }
19748
19749 if (Invalid && !BuildAndDiagnose)
19750 return true;
19751 }
19752 return Invalid;
19753 }
19754
19755 bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19756 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19757 QualType CaptureType;
19758 QualType DeclRefType;
19759 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19760 /*BuildAndDiagnose=*/true, CaptureType,
19761 DeclRefType, nullptr);
19762 }
19763
19764 bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19765 QualType CaptureType;
19766 QualType DeclRefType;
19767 return !tryCaptureVariable(
19768 Var, Loc, TryCaptureKind::Implicit, SourceLocation(),
19769 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19770 }
19771
19772 QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19773 assert(Var && "Null value cannot be captured");
19774
19775 QualType CaptureType;
19776 QualType DeclRefType;
19777
19778 // Determine whether we can capture this variable.
19779 if (tryCaptureVariable(Var, Loc, TryCaptureKind::Implicit, SourceLocation(),
19780 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19781 nullptr))
19782 return QualType();
19783
19784 return DeclRefType;
19785 }
19786
19787 namespace {
19788 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19789 // The produced TemplateArgumentListInfo* points to data stored within this
19790 // object, so should only be used in contexts where the pointer will not be
19791 // used after the CopiedTemplateArgs object is destroyed.
19792 class CopiedTemplateArgs {
19793 bool HasArgs;
19794 TemplateArgumentListInfo TemplateArgStorage;
19795 public:
19796 template<typename RefExpr>
19797 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19798 if (HasArgs)
19799 E->copyTemplateArgumentsInto(TemplateArgStorage);
19800 }
19801 operator TemplateArgumentListInfo*()
19802 #ifdef __has_cpp_attribute
19803 #if __has_cpp_attribute(clang::lifetimebound)
19804 [[clang::lifetimebound]]
19805 #endif
19806 #endif
19807 {
19808 return HasArgs ? &TemplateArgStorage : nullptr;
19809 }
19810 };
19811 }
19812
19813 /// Walk the set of potential results of an expression and mark them all as
19814 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19815 ///
19816 /// \return A new expression if we found any potential results, ExprEmpty() if
19817 /// not, and ExprError() if we diagnosed an error.
19818 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19819 NonOdrUseReason NOUR) {
19820 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19821 // an object that satisfies the requirements for appearing in a
19822 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19823 // is immediately applied." This function handles the lvalue-to-rvalue
19824 // conversion part.
19825 //
19826 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19827 // transform it into the relevant kind of non-odr-use node and rebuild the
19828 // tree of nodes leading to it.
19829 //
19830 // This is a mini-TreeTransform that only transforms a restricted subset of
19831 // nodes (and only certain operands of them).
19832
19833 // Rebuild a subexpression.
19834 auto Rebuild = [&](Expr *Sub) {
19835 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19836 };
19837
19838 // Check whether a potential result satisfies the requirements of NOUR.
19839 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19840 // Any entity other than a VarDecl is always odr-used whenever it's named
19841 // in a potentially-evaluated expression.
19842 auto *VD = dyn_cast<VarDecl>(D);
19843 if (!VD)
19844 return true;
19845
19846 // C++2a [basic.def.odr]p4:
19847 // A variable x whose name appears as a potentially-evalauted expression
19848 // e is odr-used by e unless
19849 // -- x is a reference that is usable in constant expressions, or
19850 // -- x is a variable of non-reference type that is usable in constant
19851 // expressions and has no mutable subobjects, and e is an element of
19852 // the set of potential results of an expression of
19853 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19854 // conversion is applied, or
19855 // -- x is a variable of non-reference type, and e is an element of the
19856 // set of potential results of a discarded-value expression to which
19857 // the lvalue-to-rvalue conversion is not applied
19858 //
19859 // We check the first bullet and the "potentially-evaluated" condition in
19860 // BuildDeclRefExpr. We check the type requirements in the second bullet
19861 // in CheckLValueToRValueConversionOperand below.
19862 switch (NOUR) {
19863 case NOUR_None:
19864 case NOUR_Unevaluated:
19865 llvm_unreachable("unexpected non-odr-use-reason");
19866
19867 case NOUR_Constant:
19868 // Constant references were handled when they were built.
19869 if (VD->getType()->isReferenceType())
19870 return true;
19871 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19872 if (RD->hasDefinition() && RD->hasMutableFields())
19873 return true;
19874 if (!VD->isUsableInConstantExpressions(S.Context))
19875 return true;
19876 break;
19877
19878 case NOUR_Discarded:
19879 if (VD->getType()->isReferenceType())
19880 return true;
19881 break;
19882 }
19883 return false;
19884 };
19885
19886 // Check whether this expression may be odr-used in CUDA/HIP.
19887 auto MaybeCUDAODRUsed = [&]() -> bool {
19888 if (!S.LangOpts.CUDA)
19889 return false;
19890 LambdaScopeInfo *LSI = S.getCurLambda();
19891 if (!LSI)
19892 return false;
19893 auto *DRE = dyn_cast<DeclRefExpr>(E);
19894 if (!DRE)
19895 return false;
19896 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
19897 if (!VD)
19898 return false;
19899 return LSI->CUDAPotentialODRUsedVars.count(VD);
19900 };
19901
19902 // Mark that this expression does not constitute an odr-use.
19903 auto MarkNotOdrUsed = [&] {
19904 if (!MaybeCUDAODRUsed()) {
19905 S.MaybeODRUseExprs.remove(E);
19906 if (LambdaScopeInfo *LSI = S.getCurLambda())
19907 LSI->markVariableExprAsNonODRUsed(E);
19908 }
19909 };
19910
19911 // C++2a [basic.def.odr]p2:
19912 // The set of potential results of an expression e is defined as follows:
19913 switch (E->getStmtClass()) {
19914 // -- If e is an id-expression, ...
19915 case Expr::DeclRefExprClass: {
19916 auto *DRE = cast<DeclRefExpr>(E);
19917 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19918 break;
19919
19920 // Rebuild as a non-odr-use DeclRefExpr.
19921 MarkNotOdrUsed();
19922 return DeclRefExpr::Create(
19923 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19924 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19925 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19926 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19927 }
19928
19929 case Expr::FunctionParmPackExprClass: {
19930 auto *FPPE = cast<FunctionParmPackExpr>(E);
19931 // If any of the declarations in the pack is odr-used, then the expression
19932 // as a whole constitutes an odr-use.
19933 for (ValueDecl *D : *FPPE)
19934 if (IsPotentialResultOdrUsed(D))
19935 return ExprEmpty();
19936
19937 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19938 // nothing cares about whether we marked this as an odr-use, but it might
19939 // be useful for non-compiler tools.
19940 MarkNotOdrUsed();
19941 break;
19942 }
19943
19944 // -- If e is a subscripting operation with an array operand...
19945 case Expr::ArraySubscriptExprClass: {
19946 auto *ASE = cast<ArraySubscriptExpr>(E);
19947 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19948 if (!OldBase->getType()->isArrayType())
19949 break;
19950 ExprResult Base = Rebuild(OldBase);
19951 if (!Base.isUsable())
19952 return Base;
19953 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19954 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19955 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19956 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19957 ASE->getRBracketLoc());
19958 }
19959
19960 case Expr::MemberExprClass: {
19961 auto *ME = cast<MemberExpr>(E);
19962 // -- If e is a class member access expression [...] naming a non-static
19963 // data member...
19964 if (isa<FieldDecl>(ME->getMemberDecl())) {
19965 ExprResult Base = Rebuild(ME->getBase());
19966 if (!Base.isUsable())
19967 return Base;
19968 return MemberExpr::Create(
19969 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19970 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19971 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19972 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19973 ME->getObjectKind(), ME->isNonOdrUse());
19974 }
19975
19976 if (ME->getMemberDecl()->isCXXInstanceMember())
19977 break;
19978
19979 // -- If e is a class member access expression naming a static data member,
19980 // ...
19981 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19982 break;
19983
19984 // Rebuild as a non-odr-use MemberExpr.
19985 MarkNotOdrUsed();
19986 return MemberExpr::Create(
19987 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19988 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19989 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19990 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19991 }
19992
19993 case Expr::BinaryOperatorClass: {
19994 auto *BO = cast<BinaryOperator>(E);
19995 Expr *LHS = BO->getLHS();
19996 Expr *RHS = BO->getRHS();
19997 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19998 if (BO->getOpcode() == BO_PtrMemD) {
19999 ExprResult Sub = Rebuild(LHS);
20000 if (!Sub.isUsable())
20001 return Sub;
20002 BO->setLHS(Sub.get());
20003 // -- If e is a comma expression, ...
20004 } else if (BO->getOpcode() == BO_Comma) {
20005 ExprResult Sub = Rebuild(RHS);
20006 if (!Sub.isUsable())
20007 return Sub;
20008 BO->setRHS(Sub.get());
20009 } else {
20010 break;
20011 }
20012 return ExprResult(BO);
20013 }
20014
20015 // -- If e has the form (e1)...
20016 case Expr::ParenExprClass: {
20017 auto *PE = cast<ParenExpr>(E);
20018 ExprResult Sub = Rebuild(PE->getSubExpr());
20019 if (!Sub.isUsable())
20020 return Sub;
20021 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20022 }
20023
20024 // -- If e is a glvalue conditional expression, ...
20025 // We don't apply this to a binary conditional operator. FIXME: Should we?
20026 case Expr::ConditionalOperatorClass: {
20027 auto *CO = cast<ConditionalOperator>(E);
20028 ExprResult LHS = Rebuild(CO->getLHS());
20029 if (LHS.isInvalid())
20030 return ExprError();
20031 ExprResult RHS = Rebuild(CO->getRHS());
20032 if (RHS.isInvalid())
20033 return ExprError();
20034 if (!LHS.isUsable() && !RHS.isUsable())
20035 return ExprEmpty();
20036 if (!LHS.isUsable())
20037 LHS = CO->getLHS();
20038 if (!RHS.isUsable())
20039 RHS = CO->getRHS();
20040 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20041 CO->getCond(), LHS.get(), RHS.get());
20042 }
20043
20044 // [Clang extension]
20045 // -- If e has the form __extension__ e1...
20046 case Expr::UnaryOperatorClass: {
20047 auto *UO = cast<UnaryOperator>(E);
20048 if (UO->getOpcode() != UO_Extension)
20049 break;
20050 ExprResult Sub = Rebuild(UO->getSubExpr());
20051 if (!Sub.isUsable())
20052 return Sub;
20053 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20054 Sub.get());
20055 }
20056
20057 // [Clang extension]
20058 // -- If e has the form _Generic(...), the set of potential results is the
20059 // union of the sets of potential results of the associated expressions.
20060 case Expr::GenericSelectionExprClass: {
20061 auto *GSE = cast<GenericSelectionExpr>(E);
20062
20063 SmallVector<Expr *, 4> AssocExprs;
20064 bool AnyChanged = false;
20065 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20066 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20067 if (AssocExpr.isInvalid())
20068 return ExprError();
20069 if (AssocExpr.isUsable()) {
20070 AssocExprs.push_back(AssocExpr.get());
20071 AnyChanged = true;
20072 } else {
20073 AssocExprs.push_back(OrigAssocExpr);
20074 }
20075 }
20076
20077 void *ExOrTy = nullptr;
20078 bool IsExpr = GSE->isExprPredicate();
20079 if (IsExpr)
20080 ExOrTy = GSE->getControllingExpr();
20081 else
20082 ExOrTy = GSE->getControllingType();
20083 return AnyChanged ? S.CreateGenericSelectionExpr(
20084 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20085 GSE->getRParenLoc(), IsExpr, ExOrTy,
20086 GSE->getAssocTypeSourceInfos(), AssocExprs)
20087 : ExprEmpty();
20088 }
20089
20090 // [Clang extension]
20091 // -- If e has the form __builtin_choose_expr(...), the set of potential
20092 // results is the union of the sets of potential results of the
20093 // second and third subexpressions.
20094 case Expr::ChooseExprClass: {
20095 auto *CE = cast<ChooseExpr>(E);
20096
20097 ExprResult LHS = Rebuild(CE->getLHS());
20098 if (LHS.isInvalid())
20099 return ExprError();
20100
20101 ExprResult RHS = Rebuild(CE->getLHS());
20102 if (RHS.isInvalid())
20103 return ExprError();
20104
20105 if (!LHS.get() && !RHS.get())
20106 return ExprEmpty();
20107 if (!LHS.isUsable())
20108 LHS = CE->getLHS();
20109 if (!RHS.isUsable())
20110 RHS = CE->getRHS();
20111
20112 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20113 RHS.get(), CE->getRParenLoc());
20114 }
20115
20116 // Step through non-syntactic nodes.
20117 case Expr::ConstantExprClass: {
20118 auto *CE = cast<ConstantExpr>(E);
20119 ExprResult Sub = Rebuild(CE->getSubExpr());
20120 if (!Sub.isUsable())
20121 return Sub;
20122 return ConstantExpr::Create(S.Context, Sub.get());
20123 }
20124
20125 // We could mostly rely on the recursive rebuilding to rebuild implicit
20126 // casts, but not at the top level, so rebuild them here.
20127 case Expr::ImplicitCastExprClass: {
20128 auto *ICE = cast<ImplicitCastExpr>(E);
20129 // Only step through the narrow set of cast kinds we expect to encounter.
20130 // Anything else suggests we've left the region in which potential results
20131 // can be found.
20132 switch (ICE->getCastKind()) {
20133 case CK_NoOp:
20134 case CK_DerivedToBase:
20135 case CK_UncheckedDerivedToBase: {
20136 ExprResult Sub = Rebuild(ICE->getSubExpr());
20137 if (!Sub.isUsable())
20138 return Sub;
20139 CXXCastPath Path(ICE->path());
20140 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20141 ICE->getValueKind(), &Path);
20142 }
20143
20144 default:
20145 break;
20146 }
20147 break;
20148 }
20149
20150 default:
20151 break;
20152 }
20153
20154 // Can't traverse through this node. Nothing to do.
20155 return ExprEmpty();
20156 }
20157
20158 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20159 // Check whether the operand is or contains an object of non-trivial C union
20160 // type.
20161 if (E->getType().isVolatileQualified() &&
20162 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20163 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20164 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
20165 NonTrivialCUnionContext::LValueToRValueVolatile,
20166 NTCUK_Destruct | NTCUK_Copy);
20167
20168 // C++2a [basic.def.odr]p4:
20169 // [...] an expression of non-volatile-qualified non-class type to which
20170 // the lvalue-to-rvalue conversion is applied [...]
20171 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20172 return E;
20173
20174 ExprResult Result =
20175 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
20176 if (Result.isInvalid())
20177 return ExprError();
20178 return Result.get() ? Result : E;
20179 }
20180
20181 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20182 if (!Res.isUsable())
20183 return Res;
20184
20185 // If a constant-expression is a reference to a variable where we delay
20186 // deciding whether it is an odr-use, just assume we will apply the
20187 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20188 // (a non-type template argument), we have special handling anyway.
20189 return CheckLValueToRValueConversionOperand(Res.get());
20190 }
20191
20192 void Sema::CleanupVarDeclMarking() {
20193 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20194 // call.
20195 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20196 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20197
20198 for (Expr *E : LocalMaybeODRUseExprs) {
20199 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20200 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20201 DRE->getLocation(), *this);
20202 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20203 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20204 *this);
20205 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20206 for (ValueDecl *VD : *FP)
20207 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20208 } else {
20209 llvm_unreachable("Unexpected expression");
20210 }
20211 }
20212
20213 assert(MaybeODRUseExprs.empty() &&
20214 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20215 }
20216
20217 static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20218 ValueDecl *Var, Expr *E) {
20219 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20220 if (!VD)
20221 return;
20222
20223 const bool RefersToEnclosingScope =
20224 (SemaRef.CurContext != VD->getDeclContext() &&
20225 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20226 if (RefersToEnclosingScope) {
20227 LambdaScopeInfo *const LSI =
20228 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20229 if (LSI && (!LSI->CallOperator ||
20230 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20231 // If a variable could potentially be odr-used, defer marking it so
20232 // until we finish analyzing the full expression for any
20233 // lvalue-to-rvalue
20234 // or discarded value conversions that would obviate odr-use.
20235 // Add it to the list of potential captures that will be analyzed
20236 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20237 // unless the variable is a reference that was initialized by a constant
20238 // expression (this will never need to be captured or odr-used).
20239 //
20240 // FIXME: We can simplify this a lot after implementing P0588R1.
20241 assert(E && "Capture variable should be used in an expression.");
20242 if (!Var->getType()->isReferenceType() ||
20243 !VD->isUsableInConstantExpressions(SemaRef.Context))
20244 LSI->addPotentialCapture(E->IgnoreParens());
20245 }
20246 }
20247 }
20248
20249 static void DoMarkVarDeclReferenced(
20250 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20251 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20252 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20253 isa<FunctionParmPackExpr>(E)) &&
20254 "Invalid Expr argument to DoMarkVarDeclReferenced");
20255 Var->setReferenced();
20256
20257 if (Var->isInvalidDecl())
20258 return;
20259
20260 auto *MSI = Var->getMemberSpecializationInfo();
20261 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20262 : Var->getTemplateSpecializationKind();
20263
20264 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20265 bool UsableInConstantExpr =
20266 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
20267
20268 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20269 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20270 }
20271
20272 // C++20 [expr.const]p12:
20273 // A variable [...] is needed for constant evaluation if it is [...] a
20274 // variable whose name appears as a potentially constant evaluated
20275 // expression that is either a contexpr variable or is of non-volatile
20276 // const-qualified integral type or of reference type
20277 bool NeededForConstantEvaluation =
20278 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20279
20280 bool NeedDefinition =
20281 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20282 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20283 Var->getType()->isUndeducedType());
20284
20285 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20286 "Can't instantiate a partial template specialization.");
20287
20288 // If this might be a member specialization of a static data member, check
20289 // the specialization is visible. We already did the checks for variable
20290 // template specializations when we created them.
20291 if (NeedDefinition && TSK != TSK_Undeclared &&
20292 !isa<VarTemplateSpecializationDecl>(Var))
20293 SemaRef.checkSpecializationVisibility(Loc, Var);
20294
20295 // Perform implicit instantiation of static data members, static data member
20296 // templates of class templates, and variable template specializations. Delay
20297 // instantiations of variable templates, except for those that could be used
20298 // in a constant expression.
20299 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20300 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20301 // instantiation declaration if a variable is usable in a constant
20302 // expression (among other cases).
20303 bool TryInstantiating =
20304 TSK == TSK_ImplicitInstantiation ||
20305 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20306
20307 if (TryInstantiating) {
20308 SourceLocation PointOfInstantiation =
20309 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20310 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20311 if (FirstInstantiation) {
20312 PointOfInstantiation = Loc;
20313 if (MSI)
20314 MSI->setPointOfInstantiation(PointOfInstantiation);
20315 // FIXME: Notify listener.
20316 else
20317 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20318 }
20319
20320 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20321 // Do not defer instantiations of variables that could be used in a
20322 // constant expression.
20323 // The type deduction also needs a complete initializer.
20324 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20325 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20326 });
20327
20328 // The size of an incomplete array type can be updated by
20329 // instantiating the initializer. The DeclRefExpr's type should be
20330 // updated accordingly too, or users of it would be confused!
20331 if (E)
20332 SemaRef.getCompletedType(E);
20333
20334 // Re-set the member to trigger a recomputation of the dependence bits
20335 // for the expression.
20336 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20337 DRE->setDecl(DRE->getDecl());
20338 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20339 ME->setMemberDecl(ME->getMemberDecl());
20340 } else if (FirstInstantiation) {
20341 SemaRef.PendingInstantiations
20342 .push_back(std::make_pair(Var, PointOfInstantiation));
20343 } else {
20344 bool Inserted = false;
20345 for (auto &I : SemaRef.SavedPendingInstantiations) {
20346 auto Iter = llvm::find_if(
20347 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20348 return P.first == Var;
20349 });
20350 if (Iter != I.end()) {
20351 SemaRef.PendingInstantiations.push_back(*Iter);
20352 I.erase(Iter);
20353 Inserted = true;
20354 break;
20355 }
20356 }
20357
20358 // FIXME: For a specialization of a variable template, we don't
20359 // distinguish between "declaration and type implicitly instantiated"
20360 // and "implicit instantiation of definition requested", so we have
20361 // no direct way to avoid enqueueing the pending instantiation
20362 // multiple times.
20363 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20364 SemaRef.PendingInstantiations
20365 .push_back(std::make_pair(Var, PointOfInstantiation));
20366 }
20367 }
20368 }
20369
20370 // C++2a [basic.def.odr]p4:
20371 // A variable x whose name appears as a potentially-evaluated expression e
20372 // is odr-used by e unless
20373 // -- x is a reference that is usable in constant expressions
20374 // -- x is a variable of non-reference type that is usable in constant
20375 // expressions and has no mutable subobjects [FIXME], and e is an
20376 // element of the set of potential results of an expression of
20377 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20378 // conversion is applied
20379 // -- x is a variable of non-reference type, and e is an element of the set
20380 // of potential results of a discarded-value expression to which the
20381 // lvalue-to-rvalue conversion is not applied [FIXME]
20382 //
20383 // We check the first part of the second bullet here, and
20384 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20385 // FIXME: To get the third bullet right, we need to delay this even for
20386 // variables that are not usable in constant expressions.
20387
20388 // If we already know this isn't an odr-use, there's nothing more to do.
20389 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20390 if (DRE->isNonOdrUse())
20391 return;
20392 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20393 if (ME->isNonOdrUse())
20394 return;
20395
20396 switch (OdrUse) {
20397 case OdrUseContext::None:
20398 // In some cases, a variable may not have been marked unevaluated, if it
20399 // appears in a defaukt initializer.
20400 assert((!E || isa<FunctionParmPackExpr>(E) ||
20401 SemaRef.isUnevaluatedContext()) &&
20402 "missing non-odr-use marking for unevaluated decl ref");
20403 break;
20404
20405 case OdrUseContext::FormallyOdrUsed:
20406 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20407 // behavior.
20408 break;
20409
20410 case OdrUseContext::Used:
20411 // If we might later find that this expression isn't actually an odr-use,
20412 // delay the marking.
20413 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20414 SemaRef.MaybeODRUseExprs.insert(E);
20415 else
20416 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20417 break;
20418
20419 case OdrUseContext::Dependent:
20420 // If this is a dependent context, we don't need to mark variables as
20421 // odr-used, but we may still need to track them for lambda capture.
20422 // FIXME: Do we also need to do this inside dependent typeid expressions
20423 // (which are modeled as unevaluated at this point)?
20424 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20425 break;
20426 }
20427 }
20428
20429 static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20430 BindingDecl *BD, Expr *E) {
20431 BD->setReferenced();
20432
20433 if (BD->isInvalidDecl())
20434 return;
20435
20436 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20437 if (OdrUse == OdrUseContext::Used) {
20438 QualType CaptureType, DeclRefType;
20439 SemaRef.tryCaptureVariable(BD, Loc, TryCaptureKind::Implicit,
20440 /*EllipsisLoc*/ SourceLocation(),
20441 /*BuildAndDiagnose*/ true, CaptureType,
20442 DeclRefType,
20443 /*FunctionScopeIndexToStopAt*/ nullptr);
20444 } else if (OdrUse == OdrUseContext::Dependent) {
20445 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20446 }
20447 }
20448
20449 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20450 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20451 }
20452
20453 // C++ [temp.dep.expr]p3:
20454 // An id-expression is type-dependent if it contains:
20455 // - an identifier associated by name lookup with an entity captured by copy
20456 // in a lambda-expression that has an explicit object parameter whose type
20457 // is dependent ([dcl.fct]),
20458 static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20459 Sema &SemaRef, ValueDecl *D, Expr *E) {
20460 auto *ID = dyn_cast<DeclRefExpr>(E);
20461 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20462 return;
20463
20464 // If any enclosing lambda with a dependent explicit object parameter either
20465 // explicitly captures the variable by value, or has a capture default of '='
20466 // and does not capture the variable by reference, then the type of the DRE
20467 // is dependent on the type of that lambda's explicit object parameter.
20468 auto IsDependent = [&]() {
20469 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20470 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20471 if (!LSI)
20472 continue;
20473
20474 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20475 LSI->AfterParameterList)
20476 return false;
20477
20478 const auto *MD = LSI->CallOperator;
20479 if (MD->getType().isNull())
20480 continue;
20481
20482 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20483 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20484 !Ty->getParamType(0)->isDependentType())
20485 continue;
20486
20487 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20488 if (C->isCopyCapture())
20489 return true;
20490 continue;
20491 }
20492
20493 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20494 return true;
20495 }
20496 return false;
20497 }();
20498
20499 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20500 IsDependent, SemaRef.getASTContext());
20501 }
20502
20503 static void
20504 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20505 bool MightBeOdrUse,
20506 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20507 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20508 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20509
20510 if (SemaRef.getLangOpts().OpenACC)
20511 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20512
20513 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20514 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20515 if (SemaRef.getLangOpts().CPlusPlus)
20516 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20517 Var, E);
20518 return;
20519 }
20520
20521 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20522 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20523 if (SemaRef.getLangOpts().CPlusPlus)
20524 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20525 Decl, E);
20526 return;
20527 }
20528 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20529
20530 // If this is a call to a method via a cast, also mark the method in the
20531 // derived class used in case codegen can devirtualize the call.
20532 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20533 if (!ME)
20534 return;
20535 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20536 if (!MD)
20537 return;
20538 // Only attempt to devirtualize if this is truly a virtual call.
20539 bool IsVirtualCall = MD->isVirtual() &&
20540 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20541 if (!IsVirtualCall)
20542 return;
20543
20544 // If it's possible to devirtualize the call, mark the called function
20545 // referenced.
20546 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20547 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20548 if (DM)
20549 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20550 }
20551
20552 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20553 // [basic.def.odr] (CWG 1614)
20554 // A function is named by an expression or conversion [...]
20555 // unless it is a pure virtual function and either the expression is not an
20556 // id-expression naming the function with an explicitly qualified name or
20557 // the expression forms a pointer to member
20558 bool OdrUse = true;
20559 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20560 if (Method->isVirtual() &&
20561 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20562 OdrUse = false;
20563
20564 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20565 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20566 !isImmediateFunctionContext() &&
20567 !isCheckingDefaultArgumentOrInitializer() &&
20568 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20569 !FD->isDependentContext())
20570 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20571 }
20572 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20573 RefsMinusAssignments);
20574 }
20575
20576 void Sema::MarkMemberReferenced(MemberExpr *E) {
20577 // C++11 [basic.def.odr]p2:
20578 // A non-overloaded function whose name appears as a potentially-evaluated
20579 // expression or a member of a set of candidate functions, if selected by
20580 // overload resolution when referred to from a potentially-evaluated
20581 // expression, is odr-used, unless it is a pure virtual function and its
20582 // name is not explicitly qualified.
20583 bool MightBeOdrUse = true;
20584 if (E->performsVirtualDispatch(getLangOpts())) {
20585 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20586 if (Method->isPureVirtual())
20587 MightBeOdrUse = false;
20588 }
20589 SourceLocation Loc =
20590 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20591 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20592 RefsMinusAssignments);
20593 }
20594
20595 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20596 for (ValueDecl *VD : *E)
20597 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20598 RefsMinusAssignments);
20599 }
20600
20601 /// Perform marking for a reference to an arbitrary declaration. It
20602 /// marks the declaration referenced, and performs odr-use checking for
20603 /// functions and variables. This method should not be used when building a
20604 /// normal expression which refers to a variable.
20605 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20606 bool MightBeOdrUse) {
20607 if (MightBeOdrUse) {
20608 if (auto *VD = dyn_cast<VarDecl>(D)) {
20609 MarkVariableReferenced(Loc, VD);
20610 return;
20611 }
20612 }
20613 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20614 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20615 return;
20616 }
20617 D->setReferenced();
20618 }
20619
20620 namespace {
20621 // Mark all of the declarations used by a type as referenced.
20622 // FIXME: Not fully implemented yet! We need to have a better understanding
20623 // of when we're entering a context we should not recurse into.
20624 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20625 // TreeTransforms rebuilding the type in a new context. Rather than
20626 // duplicating the TreeTransform logic, we should consider reusing it here.
20627 // Currently that causes problems when rebuilding LambdaExprs.
20628 class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20629 Sema &S;
20630 SourceLocation Loc;
20631
20632 public:
20633 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20634
20635 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20636 };
20637 }
20638
20639 bool MarkReferencedDecls::TraverseTemplateArgument(
20640 const TemplateArgument &Arg) {
20641 {
20642 // A non-type template argument is a constant-evaluated context.
20643 EnterExpressionEvaluationContext Evaluated(
20644 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20645 if (Arg.getKind() == TemplateArgument::Declaration) {
20646 if (Decl *D = Arg.getAsDecl())
20647 S.MarkAnyDeclReferenced(Loc, D, true);
20648 } else if (Arg.getKind() == TemplateArgument::Expression) {
20649 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20650 }
20651 }
20652
20653 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20654 }
20655
20656 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20657 MarkReferencedDecls Marker(*this, Loc);
20658 Marker.TraverseType(T);
20659 }
20660
20661 namespace {
20662 /// Helper class that marks all of the declarations referenced by
20663 /// potentially-evaluated subexpressions as "referenced".
20664 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20665 public:
20666 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20667 bool SkipLocalVariables;
20668 ArrayRef<const Expr *> StopAt;
20669
20670 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20671 ArrayRef<const Expr *> StopAt)
20672 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20673
20674 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20675 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20676 }
20677
20678 void Visit(Expr *E) {
20679 if (llvm::is_contained(StopAt, E))
20680 return;
20681 Inherited::Visit(E);
20682 }
20683
20684 void VisitConstantExpr(ConstantExpr *E) {
20685 // Don't mark declarations within a ConstantExpression, as this expression
20686 // will be evaluated and folded to a value.
20687 }
20688
20689 void VisitDeclRefExpr(DeclRefExpr *E) {
20690 // If we were asked not to visit local variables, don't.
20691 if (SkipLocalVariables) {
20692 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20693 if (VD->hasLocalStorage())
20694 return;
20695 }
20696
20697 // FIXME: This can trigger the instantiation of the initializer of a
20698 // variable, which can cause the expression to become value-dependent
20699 // or error-dependent. Do we need to propagate the new dependence bits?
20700 S.MarkDeclRefReferenced(E);
20701 }
20702
20703 void VisitMemberExpr(MemberExpr *E) {
20704 S.MarkMemberReferenced(E);
20705 Visit(E->getBase());
20706 }
20707 };
20708 } // namespace
20709
20710 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20711 bool SkipLocalVariables,
20712 ArrayRef<const Expr*> StopAt) {
20713 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20714 }
20715
20716 /// Emit a diagnostic when statements are reachable.
20717 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20718 const PartialDiagnostic &PD) {
20719 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20720 // The initializer of a constexpr variable or of the first declaration of a
20721 // static data member is not syntactically a constant evaluated constant,
20722 // but nonetheless is always required to be a constant expression, so we
20723 // can skip diagnosing.
20724 if (Decl &&
20725 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20726 Decl->isFirstDecl() && !Decl->isInline())))
20727 return false;
20728
20729 if (Stmts.empty()) {
20730 Diag(Loc, PD);
20731 return true;
20732 }
20733
20734 if (getCurFunction()) {
20735 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20736 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20737 return true;
20738 }
20739
20740 // For non-constexpr file-scope variables with reachability context (non-empty
20741 // Stmts), build a CFG for the initializer and check whether the context in
20742 // question is reachable.
20743 if (Decl && Decl->isFileVarDecl()) {
20744 AnalysisWarnings.registerVarDeclWarning(
20745 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20746 return true;
20747 }
20748
20749 Diag(Loc, PD);
20750 return true;
20751 }
20752
20753 /// Emit a diagnostic that describes an effect on the run-time behavior
20754 /// of the program being compiled.
20755 ///
20756 /// This routine emits the given diagnostic when the code currently being
20757 /// type-checked is "potentially evaluated", meaning that there is a
20758 /// possibility that the code will actually be executable. Code in sizeof()
20759 /// expressions, code used only during overload resolution, etc., are not
20760 /// potentially evaluated. This routine will suppress such diagnostics or,
20761 /// in the absolutely nutty case of potentially potentially evaluated
20762 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20763 /// later.
20764 ///
20765 /// This routine should be used for all diagnostics that describe the run-time
20766 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20767 /// Failure to do so will likely result in spurious diagnostics or failures
20768 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20769 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20770 const PartialDiagnostic &PD) {
20771
20772 if (ExprEvalContexts.back().isDiscardedStatementContext())
20773 return false;
20774
20775 switch (ExprEvalContexts.back().Context) {
20776 case ExpressionEvaluationContext::Unevaluated:
20777 case ExpressionEvaluationContext::UnevaluatedList:
20778 case ExpressionEvaluationContext::UnevaluatedAbstract:
20779 case ExpressionEvaluationContext::DiscardedStatement:
20780 // The argument will never be evaluated, so don't complain.
20781 break;
20782
20783 case ExpressionEvaluationContext::ConstantEvaluated:
20784 case ExpressionEvaluationContext::ImmediateFunctionContext:
20785 // Relevant diagnostics should be produced by constant evaluation.
20786 break;
20787
20788 case ExpressionEvaluationContext::PotentiallyEvaluated:
20789 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20790 return DiagIfReachable(Loc, Stmts, PD);
20791 }
20792
20793 return false;
20794 }
20795
20796 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20797 const PartialDiagnostic &PD) {
20798 return DiagRuntimeBehavior(
20799 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20800 PD);
20801 }
20802
20803 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20804 CallExpr *CE, FunctionDecl *FD) {
20805 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20806 return false;
20807
20808 // If we're inside a decltype's expression, don't check for a valid return
20809 // type or construct temporaries until we know whether this is the last call.
20810 if (ExprEvalContexts.back().ExprContext ==
20811 ExpressionEvaluationContextRecord::EK_Decltype) {
20812 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20813 return false;
20814 }
20815
20816 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20817 FunctionDecl *FD;
20818 CallExpr *CE;
20819
20820 public:
20821 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20822 : FD(FD), CE(CE) { }
20823
20824 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20825 if (!FD) {
20826 S.Diag(Loc, diag::err_call_incomplete_return)
20827 << T << CE->getSourceRange();
20828 return;
20829 }
20830
20831 S.Diag(Loc, diag::err_call_function_incomplete_return)
20832 << CE->getSourceRange() << FD << T;
20833 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20834 << FD->getDeclName();
20835 }
20836 } Diagnoser(FD, CE);
20837
20838 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20839 return true;
20840
20841 return false;
20842 }
20843
20844 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20845 // will prevent this condition from triggering, which is what we want.
20846 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20847 SourceLocation Loc;
20848
20849 unsigned diagnostic = diag::warn_condition_is_assignment;
20850 bool IsOrAssign = false;
20851
20852 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20853 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20854 return;
20855
20856 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20857
20858 // Greylist some idioms by putting them into a warning subcategory.
20859 if (ObjCMessageExpr *ME
20860 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20861 Selector Sel = ME->getSelector();
20862
20863 // self = [<foo> init...]
20864 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20865 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20866
20867 // <foo> = [<bar> nextObject]
20868 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20869 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20870 }
20871
20872 Loc = Op->getOperatorLoc();
20873 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20874 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20875 return;
20876
20877 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20878 Loc = Op->getOperatorLoc();
20879 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20880 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20881 else {
20882 // Not an assignment.
20883 return;
20884 }
20885
20886 Diag(Loc, diagnostic) << E->getSourceRange();
20887
20888 SourceLocation Open = E->getBeginLoc();
20889 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20890 Diag(Loc, diag::note_condition_assign_silence)
20891 << FixItHint::CreateInsertion(Open, "(")
20892 << FixItHint::CreateInsertion(Close, ")");
20893
20894 if (IsOrAssign)
20895 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20896 << FixItHint::CreateReplacement(Loc, "!=");
20897 else
20898 Diag(Loc, diag::note_condition_assign_to_comparison)
20899 << FixItHint::CreateReplacement(Loc, "==");
20900 }
20901
20902 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20903 // Don't warn if the parens came from a macro.
20904 SourceLocation parenLoc = ParenE->getBeginLoc();
20905 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20906 return;
20907 // Don't warn for dependent expressions.
20908 if (ParenE->isTypeDependent())
20909 return;
20910
20911 Expr *E = ParenE->IgnoreParens();
20912 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20913 return;
20914
20915 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20916 if (opE->getOpcode() == BO_EQ &&
20917 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20918 == Expr::MLV_Valid) {
20919 SourceLocation Loc = opE->getOperatorLoc();
20920
20921 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20922 SourceRange ParenERange = ParenE->getSourceRange();
20923 Diag(Loc, diag::note_equality_comparison_silence)
20924 << FixItHint::CreateRemoval(ParenERange.getBegin())
20925 << FixItHint::CreateRemoval(ParenERange.getEnd());
20926 Diag(Loc, diag::note_equality_comparison_to_assign)
20927 << FixItHint::CreateReplacement(Loc, "=");
20928 }
20929 }
20930
20931 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20932 bool IsConstexpr) {
20933 DiagnoseAssignmentAsCondition(E);
20934 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20935 DiagnoseEqualityWithExtraParens(parenE);
20936
20937 ExprResult result = CheckPlaceholderExpr(E);
20938 if (result.isInvalid()) return ExprError();
20939 E = result.get();
20940
20941 if (!E->isTypeDependent()) {
20942 if (getLangOpts().CPlusPlus)
20943 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20944
20945 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20946 if (ERes.isInvalid())
20947 return ExprError();
20948 E = ERes.get();
20949
20950 QualType T = E->getType();
20951 if (!T->isScalarType()) { // C99 6.8.4.1p1
20952 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20953 << T << E->getSourceRange();
20954 return ExprError();
20955 }
20956 CheckBoolLikeConversion(E, Loc);
20957 }
20958
20959 return E;
20960 }
20961
20962 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20963 Expr *SubExpr, ConditionKind CK,
20964 bool MissingOK) {
20965 // MissingOK indicates whether having no condition expression is valid
20966 // (for loop) or invalid (e.g. while loop).
20967 if (!SubExpr)
20968 return MissingOK ? ConditionResult() : ConditionError();
20969
20970 ExprResult Cond;
20971 switch (CK) {
20972 case ConditionKind::Boolean:
20973 Cond = CheckBooleanCondition(Loc, SubExpr);
20974 break;
20975
20976 case ConditionKind::ConstexprIf:
20977 // Note: this might produce a FullExpr
20978 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20979 break;
20980
20981 case ConditionKind::Switch:
20982 Cond = CheckSwitchCondition(Loc, SubExpr);
20983 break;
20984 }
20985 if (Cond.isInvalid()) {
20986 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20987 {SubExpr}, PreferredConditionType(CK));
20988 if (!Cond.get())
20989 return ConditionError();
20990 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
20991 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
20992
20993 if (!Cond.isUsable())
20994 return ConditionError();
20995
20996 return ConditionResult(*this, nullptr, Cond,
20997 CK == ConditionKind::ConstexprIf);
20998 }
20999
21000 namespace {
21001 /// A visitor for rebuilding a call to an __unknown_any expression
21002 /// to have an appropriate type.
21003 struct RebuildUnknownAnyFunction
21004 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21005
21006 Sema &S;
21007
21008 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21009
21010 ExprResult VisitStmt(Stmt *S) {
21011 llvm_unreachable("unexpected statement!");
21012 }
21013
21014 ExprResult VisitExpr(Expr *E) {
21015 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21016 << E->getSourceRange();
21017 return ExprError();
21018 }
21019
21020 /// Rebuild an expression which simply semantically wraps another
21021 /// expression which it shares the type and value kind of.
21022 template <class T> ExprResult rebuildSugarExpr(T *E) {
21023 ExprResult SubResult = Visit(E->getSubExpr());
21024 if (SubResult.isInvalid()) return ExprError();
21025
21026 Expr *SubExpr = SubResult.get();
21027 E->setSubExpr(SubExpr);
21028 E->setType(SubExpr->getType());
21029 E->setValueKind(SubExpr->getValueKind());
21030 assert(E->getObjectKind() == OK_Ordinary);
21031 return E;
21032 }
21033
21034 ExprResult VisitParenExpr(ParenExpr *E) {
21035 return rebuildSugarExpr(E);
21036 }
21037
21038 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21039 return rebuildSugarExpr(E);
21040 }
21041
21042 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21043 ExprResult SubResult = Visit(E->getSubExpr());
21044 if (SubResult.isInvalid()) return ExprError();
21045
21046 Expr *SubExpr = SubResult.get();
21047 E->setSubExpr(SubExpr);
21048 E->setType(S.Context.getPointerType(SubExpr->getType()));
21049 assert(E->isPRValue());
21050 assert(E->getObjectKind() == OK_Ordinary);
21051 return E;
21052 }
21053
21054 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21055 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21056
21057 E->setType(VD->getType());
21058
21059 assert(E->isPRValue());
21060 if (S.getLangOpts().CPlusPlus &&
21061 !(isa<CXXMethodDecl>(VD) &&
21062 cast<CXXMethodDecl>(VD)->isInstance()))
21063 E->setValueKind(VK_LValue);
21064
21065 return E;
21066 }
21067
21068 ExprResult VisitMemberExpr(MemberExpr *E) {
21069 return resolveDecl(E, E->getMemberDecl());
21070 }
21071
21072 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21073 return resolveDecl(E, E->getDecl());
21074 }
21075 };
21076 }
21077
21078 /// Given a function expression of unknown-any type, try to rebuild it
21079 /// to have a function type.
21080 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21081 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21082 if (Result.isInvalid()) return ExprError();
21083 return S.DefaultFunctionArrayConversion(Result.get());
21084 }
21085
21086 namespace {
21087 /// A visitor for rebuilding an expression of type __unknown_anytype
21088 /// into one which resolves the type directly on the referring
21089 /// expression. Strict preservation of the original source
21090 /// structure is not a goal.
21091 struct RebuildUnknownAnyExpr
21092 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21093
21094 Sema &S;
21095
21096 /// The current destination type.
21097 QualType DestType;
21098
21099 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21100 : S(S), DestType(CastType) {}
21101
21102 ExprResult VisitStmt(Stmt *S) {
21103 llvm_unreachable("unexpected statement!");
21104 }
21105
21106 ExprResult VisitExpr(Expr *E) {
21107 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21108 << E->getSourceRange();
21109 return ExprError();
21110 }
21111
21112 ExprResult VisitCallExpr(CallExpr *E);
21113 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21114
21115 /// Rebuild an expression which simply semantically wraps another
21116 /// expression which it shares the type and value kind of.
21117 template <class T> ExprResult rebuildSugarExpr(T *E) {
21118 ExprResult SubResult = Visit(E->getSubExpr());
21119 if (SubResult.isInvalid()) return ExprError();
21120 Expr *SubExpr = SubResult.get();
21121 E->setSubExpr(SubExpr);
21122 E->setType(SubExpr->getType());
21123 E->setValueKind(SubExpr->getValueKind());
21124 assert(E->getObjectKind() == OK_Ordinary);
21125 return E;
21126 }
21127
21128 ExprResult VisitParenExpr(ParenExpr *E) {
21129 return rebuildSugarExpr(E);
21130 }
21131
21132 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21133 return rebuildSugarExpr(E);
21134 }
21135
21136 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21137 const PointerType *Ptr = DestType->getAs<PointerType>();
21138 if (!Ptr) {
21139 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21140 << E->getSourceRange();
21141 return ExprError();
21142 }
21143
21144 if (isa<CallExpr>(E->getSubExpr())) {
21145 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21146 << E->getSourceRange();
21147 return ExprError();
21148 }
21149
21150 assert(E->isPRValue());
21151 assert(E->getObjectKind() == OK_Ordinary);
21152 E->setType(DestType);
21153
21154 // Build the sub-expression as if it were an object of the pointee type.
21155 DestType = Ptr->getPointeeType();
21156 ExprResult SubResult = Visit(E->getSubExpr());
21157 if (SubResult.isInvalid()) return ExprError();
21158 E->setSubExpr(SubResult.get());
21159 return E;
21160 }
21161
21162 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21163
21164 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21165
21166 ExprResult VisitMemberExpr(MemberExpr *E) {
21167 return resolveDecl(E, E->getMemberDecl());
21168 }
21169
21170 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21171 return resolveDecl(E, E->getDecl());
21172 }
21173 };
21174 }
21175
21176 /// Rebuilds a call expression which yielded __unknown_anytype.
21177 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21178 Expr *CalleeExpr = E->getCallee();
21179
21180 enum FnKind {
21181 FK_MemberFunction,
21182 FK_FunctionPointer,
21183 FK_BlockPointer
21184 };
21185
21186 FnKind Kind;
21187 QualType CalleeType = CalleeExpr->getType();
21188 if (CalleeType == S.Context.BoundMemberTy) {
21189 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21190 Kind = FK_MemberFunction;
21191 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21192 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21193 CalleeType = Ptr->getPointeeType();
21194 Kind = FK_FunctionPointer;
21195 } else {
21196 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21197 Kind = FK_BlockPointer;
21198 }
21199 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21200
21201 // Verify that this is a legal result type of a function.
21202 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21203 DestType->isFunctionType()) {
21204 unsigned diagID = diag::err_func_returning_array_function;
21205 if (Kind == FK_BlockPointer)
21206 diagID = diag::err_block_returning_array_function;
21207
21208 S.Diag(E->getExprLoc(), diagID)
21209 << DestType->isFunctionType() << DestType;
21210 return ExprError();
21211 }
21212
21213 // Otherwise, go ahead and set DestType as the call's result.
21214 E->setType(DestType.getNonLValueExprType(S.Context));
21215 E->setValueKind(Expr::getValueKindForType(DestType));
21216 assert(E->getObjectKind() == OK_Ordinary);
21217
21218 // Rebuild the function type, replacing the result type with DestType.
21219 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21220 if (Proto) {
21221 // __unknown_anytype(...) is a special case used by the debugger when
21222 // it has no idea what a function's signature is.
21223 //
21224 // We want to build this call essentially under the K&R
21225 // unprototyped rules, but making a FunctionNoProtoType in C++
21226 // would foul up all sorts of assumptions. However, we cannot
21227 // simply pass all arguments as variadic arguments, nor can we
21228 // portably just call the function under a non-variadic type; see
21229 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21230 // However, it turns out that in practice it is generally safe to
21231 // call a function declared as "A foo(B,C,D);" under the prototype
21232 // "A foo(B,C,D,...);". The only known exception is with the
21233 // Windows ABI, where any variadic function is implicitly cdecl
21234 // regardless of its normal CC. Therefore we change the parameter
21235 // types to match the types of the arguments.
21236 //
21237 // This is a hack, but it is far superior to moving the
21238 // corresponding target-specific code from IR-gen to Sema/AST.
21239
21240 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21241 SmallVector<QualType, 8> ArgTypes;
21242 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21243 ArgTypes.reserve(E->getNumArgs());
21244 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21245 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21246 }
21247 ParamTypes = ArgTypes;
21248 }
21249 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21250 Proto->getExtProtoInfo());
21251 } else {
21252 DestType = S.Context.getFunctionNoProtoType(DestType,
21253 FnType->getExtInfo());
21254 }
21255
21256 // Rebuild the appropriate pointer-to-function type.
21257 switch (Kind) {
21258 case FK_MemberFunction:
21259 // Nothing to do.
21260 break;
21261
21262 case FK_FunctionPointer:
21263 DestType = S.Context.getPointerType(DestType);
21264 break;
21265
21266 case FK_BlockPointer:
21267 DestType = S.Context.getBlockPointerType(DestType);
21268 break;
21269 }
21270
21271 // Finally, we can recurse.
21272 ExprResult CalleeResult = Visit(CalleeExpr);
21273 if (!CalleeResult.isUsable()) return ExprError();
21274 E->setCallee(CalleeResult.get());
21275
21276 // Bind a temporary if necessary.
21277 return S.MaybeBindToTemporary(E);
21278 }
21279
21280 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21281 // Verify that this is a legal result type of a call.
21282 if (DestType->isArrayType() || DestType->isFunctionType()) {
21283 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21284 << DestType->isFunctionType() << DestType;
21285 return ExprError();
21286 }
21287
21288 // Rewrite the method result type if available.
21289 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21290 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21291 Method->setReturnType(DestType);
21292 }
21293
21294 // Change the type of the message.
21295 E->setType(DestType.getNonReferenceType());
21296 E->setValueKind(Expr::getValueKindForType(DestType));
21297
21298 return S.MaybeBindToTemporary(E);
21299 }
21300
21301 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21302 // The only case we should ever see here is a function-to-pointer decay.
21303 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21304 assert(E->isPRValue());
21305 assert(E->getObjectKind() == OK_Ordinary);
21306
21307 E->setType(DestType);
21308
21309 // Rebuild the sub-expression as the pointee (function) type.
21310 DestType = DestType->castAs<PointerType>()->getPointeeType();
21311
21312 ExprResult Result = Visit(E->getSubExpr());
21313 if (!Result.isUsable()) return ExprError();
21314
21315 E->setSubExpr(Result.get());
21316 return E;
21317 } else if (E->getCastKind() == CK_LValueToRValue) {
21318 assert(E->isPRValue());
21319 assert(E->getObjectKind() == OK_Ordinary);
21320
21321 assert(isa<BlockPointerType>(E->getType()));
21322
21323 E->setType(DestType);
21324
21325 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21326 DestType = S.Context.getLValueReferenceType(DestType);
21327
21328 ExprResult Result = Visit(E->getSubExpr());
21329 if (!Result.isUsable()) return ExprError();
21330
21331 E->setSubExpr(Result.get());
21332 return E;
21333 } else {
21334 llvm_unreachable("Unhandled cast type!");
21335 }
21336 }
21337
21338 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21339 ExprValueKind ValueKind = VK_LValue;
21340 QualType Type = DestType;
21341
21342 // We know how to make this work for certain kinds of decls:
21343
21344 // - functions
21345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21346 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21347 DestType = Ptr->getPointeeType();
21348 ExprResult Result = resolveDecl(E, VD);
21349 if (Result.isInvalid()) return ExprError();
21350 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21351 VK_PRValue);
21352 }
21353
21354 if (!Type->isFunctionType()) {
21355 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21356 << VD << E->getSourceRange();
21357 return ExprError();
21358 }
21359 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21360 // We must match the FunctionDecl's type to the hack introduced in
21361 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21362 // type. See the lengthy commentary in that routine.
21363 QualType FDT = FD->getType();
21364 const FunctionType *FnType = FDT->castAs<FunctionType>();
21365 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21366 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21367 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21368 SourceLocation Loc = FD->getLocation();
21369 FunctionDecl *NewFD = FunctionDecl::Create(
21370 S.Context, FD->getDeclContext(), Loc, Loc,
21371 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21372 SC_None, S.getCurFPFeatures().isFPConstrained(),
21373 false /*isInlineSpecified*/, FD->hasPrototype(),
21374 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21375
21376 if (FD->getQualifier())
21377 NewFD->setQualifierInfo(FD->getQualifierLoc());
21378
21379 SmallVector<ParmVarDecl*, 16> Params;
21380 for (const auto &AI : FT->param_types()) {
21381 ParmVarDecl *Param =
21382 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21383 Param->setScopeInfo(0, Params.size());
21384 Params.push_back(Param);
21385 }
21386 NewFD->setParams(Params);
21387 DRE->setDecl(NewFD);
21388 VD = DRE->getDecl();
21389 }
21390 }
21391
21392 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21393 if (MD->isInstance()) {
21394 ValueKind = VK_PRValue;
21395 Type = S.Context.BoundMemberTy;
21396 }
21397
21398 // Function references aren't l-values in C.
21399 if (!S.getLangOpts().CPlusPlus)
21400 ValueKind = VK_PRValue;
21401
21402 // - variables
21403 } else if (isa<VarDecl>(VD)) {
21404 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21405 Type = RefTy->getPointeeType();
21406 } else if (Type->isFunctionType()) {
21407 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21408 << VD << E->getSourceRange();
21409 return ExprError();
21410 }
21411
21412 // - nothing else
21413 } else {
21414 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21415 << VD << E->getSourceRange();
21416 return ExprError();
21417 }
21418
21419 // Modifying the declaration like this is friendly to IR-gen but
21420 // also really dangerous.
21421 VD->setType(DestType);
21422 E->setType(Type);
21423 E->setValueKind(ValueKind);
21424 return E;
21425 }
21426
21427 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21428 Expr *CastExpr, CastKind &CastKind,
21429 ExprValueKind &VK, CXXCastPath &Path) {
21430 // The type we're casting to must be either void or complete.
21431 if (!CastType->isVoidType() &&
21432 RequireCompleteType(TypeRange.getBegin(), CastType,
21433 diag::err_typecheck_cast_to_incomplete))
21434 return ExprError();
21435
21436 // Rewrite the casted expression from scratch.
21437 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21438 if (!result.isUsable()) return ExprError();
21439
21440 CastExpr = result.get();
21441 VK = CastExpr->getValueKind();
21442 CastKind = CK_NoOp;
21443
21444 return CastExpr;
21445 }
21446
21447 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21448 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21449 }
21450
21451 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21452 Expr *arg, QualType &paramType) {
21453 // If the syntactic form of the argument is not an explicit cast of
21454 // any sort, just do default argument promotion.
21455 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21456 if (!castArg) {
21457 ExprResult result = DefaultArgumentPromotion(arg);
21458 if (result.isInvalid()) return ExprError();
21459 paramType = result.get()->getType();
21460 return result;
21461 }
21462
21463 // Otherwise, use the type that was written in the explicit cast.
21464 assert(!arg->hasPlaceholderType());
21465 paramType = castArg->getTypeAsWritten();
21466
21467 // Copy-initialize a parameter of that type.
21468 InitializedEntity entity =
21469 InitializedEntity::InitializeParameter(Context, paramType,
21470 /*consumed*/ false);
21471 return PerformCopyInitialization(entity, callLoc, arg);
21472 }
21473
21474 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21475 Expr *orig = E;
21476 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21477 while (true) {
21478 E = E->IgnoreParenImpCasts();
21479 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21480 E = call->getCallee();
21481 diagID = diag::err_uncasted_call_of_unknown_any;
21482 } else {
21483 break;
21484 }
21485 }
21486
21487 SourceLocation loc;
21488 NamedDecl *d;
21489 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21490 loc = ref->getLocation();
21491 d = ref->getDecl();
21492 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21493 loc = mem->getMemberLoc();
21494 d = mem->getMemberDecl();
21495 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21496 diagID = diag::err_uncasted_call_of_unknown_any;
21497 loc = msg->getSelectorStartLoc();
21498 d = msg->getMethodDecl();
21499 if (!d) {
21500 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21501 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21502 << orig->getSourceRange();
21503 return ExprError();
21504 }
21505 } else {
21506 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21507 << E->getSourceRange();
21508 return ExprError();
21509 }
21510
21511 S.Diag(loc, diagID) << d << orig->getSourceRange();
21512
21513 // Never recoverable.
21514 return ExprError();
21515 }
21516
21517 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21518 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21519 if (!placeholderType) return E;
21520
21521 switch (placeholderType->getKind()) {
21522 case BuiltinType::UnresolvedTemplate: {
21523 auto *ULE = cast<UnresolvedLookupExpr>(E);
21524 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21525 // There's only one FoundDecl for UnresolvedTemplate type. See
21526 // BuildTemplateIdExpr.
21527 NamedDecl *Temp = *ULE->decls_begin();
21528 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21529
21530 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21531 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21532 // as it models only the unqualified-id case, where this case can clearly be
21533 // qualified. Thus we can't just qualify an assumed template.
21534 TemplateName TN;
21535 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21536 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21537 TemplateName(TD));
21538 else
21539 TN = Context.getAssumedTemplateName(NameInfo.getName());
21540
21541 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21542 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21543 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21544 << IsTypeAliasTemplateDecl;
21545
21546 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21547 bool HasAnyDependentTA = false;
21548 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21549 HasAnyDependentTA |= Arg.getArgument().isDependent();
21550 TAL.addArgument(Arg);
21551 }
21552
21553 QualType TST;
21554 {
21555 SFINAETrap Trap(*this);
21556 TST = CheckTemplateIdType(
21557 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21558 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21559 }
21560 if (TST.isNull())
21561 TST = Context.getTemplateSpecializationType(
21562 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21563 /*CanonicalArgs=*/{},
21564 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21565 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21566 TST);
21567 }
21568
21569 // Overloaded expressions.
21570 case BuiltinType::Overload: {
21571 // Try to resolve a single function template specialization.
21572 // This is obligatory.
21573 ExprResult Result = E;
21574 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21575 return Result;
21576
21577 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21578 // leaves Result unchanged on failure.
21579 Result = E;
21580 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21581 return Result;
21582
21583 // If that failed, try to recover with a call.
21584 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21585 /*complain*/ true);
21586 return Result;
21587 }
21588
21589 // Bound member functions.
21590 case BuiltinType::BoundMember: {
21591 ExprResult result = E;
21592 const Expr *BME = E->IgnoreParens();
21593 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21594 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21595 if (isa<CXXPseudoDestructorExpr>(BME)) {
21596 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21597 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21598 if (ME->getMemberNameInfo().getName().getNameKind() ==
21599 DeclarationName::CXXDestructorName)
21600 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21601 }
21602 tryToRecoverWithCall(result, PD,
21603 /*complain*/ true);
21604 return result;
21605 }
21606
21607 // ARC unbridged casts.
21608 case BuiltinType::ARCUnbridgedCast: {
21609 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21610 ObjC().diagnoseARCUnbridgedCast(realCast);
21611 return realCast;
21612 }
21613
21614 // Expressions of unknown type.
21615 case BuiltinType::UnknownAny:
21616 return diagnoseUnknownAnyExpr(*this, E);
21617
21618 // Pseudo-objects.
21619 case BuiltinType::PseudoObject:
21620 return PseudoObject().checkRValue(E);
21621
21622 case BuiltinType::BuiltinFn: {
21623 // Accept __noop without parens by implicitly converting it to a call expr.
21624 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21625 if (DRE) {
21626 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21627 unsigned BuiltinID = FD->getBuiltinID();
21628 if (BuiltinID == Builtin::BI__noop) {
21629 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21630 CK_BuiltinFnToFnPtr)
21631 .get();
21632 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21633 VK_PRValue, SourceLocation(),
21634 FPOptionsOverride());
21635 }
21636
21637 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21638 // Any use of these other than a direct call is ill-formed as of C++20,
21639 // because they are not addressable functions. In earlier language
21640 // modes, warn and force an instantiation of the real body.
21641 Diag(E->getBeginLoc(),
21642 getLangOpts().CPlusPlus20
21643 ? diag::err_use_of_unaddressable_function
21644 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21645 if (FD->isImplicitlyInstantiable()) {
21646 // Require a definition here because a normal attempt at
21647 // instantiation for a builtin will be ignored, and we won't try
21648 // again later. We assume that the definition of the template
21649 // precedes this use.
21650 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21651 /*Recursive=*/false,
21652 /*DefinitionRequired=*/true,
21653 /*AtEndOfTU=*/false);
21654 }
21655 // Produce a properly-typed reference to the function.
21656 CXXScopeSpec SS;
21657 SS.Adopt(DRE->getQualifierLoc());
21658 TemplateArgumentListInfo TemplateArgs;
21659 DRE->copyTemplateArgumentsInto(TemplateArgs);
21660 return BuildDeclRefExpr(
21661 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21662 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21663 DRE->getTemplateKeywordLoc(),
21664 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21665 }
21666 }
21667
21668 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21669 return ExprError();
21670 }
21671
21672 case BuiltinType::IncompleteMatrixIdx: {
21673 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21674 // At this point, we know there was no second [] to complete the operator.
21675 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21676 if (getLangOpts().HLSL) {
21677 return CreateBuiltinMatrixSingleSubscriptExpr(
21678 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21679 }
21680 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21681 return ExprError();
21682 }
21683
21684 // Expressions of unknown type.
21685 case BuiltinType::ArraySection:
21686 // If we've already diagnosed something on the array section type, we
21687 // shouldn't need to do any further diagnostic here.
21688 if (!E->containsErrors())
21689 Diag(E->getBeginLoc(), diag::err_array_section_use)
21690 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21691 return ExprError();
21692
21693 // Expressions of unknown type.
21694 case BuiltinType::OMPArrayShaping:
21695 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21696
21697 case BuiltinType::OMPIterator:
21698 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21699
21700 // Everything else should be impossible.
21701 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21702 case BuiltinType::Id:
21703 #include "clang/Basic/OpenCLImageTypes.def"
21704 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21705 case BuiltinType::Id:
21706 #include "clang/Basic/OpenCLExtensionTypes.def"
21707 #define SVE_TYPE(Name, Id, SingletonId) \
21708 case BuiltinType::Id:
21709 #include "clang/Basic/AArch64ACLETypes.def"
21710 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21711 case BuiltinType::Id:
21712 #include "clang/Basic/PPCTypes.def"
21713 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21714 #include "clang/Basic/RISCVVTypes.def"
21715 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21716 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21717 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21718 #include "clang/Basic/AMDGPUTypes.def"
21719 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21720 #include "clang/Basic/HLSLIntangibleTypes.def"
21721 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21722 #define PLACEHOLDER_TYPE(Id, SingletonId)
21723 #include "clang/AST/BuiltinTypes.def"
21724 break;
21725 }
21726
21727 llvm_unreachable("invalid placeholder type!");
21728 }
21729
21730 bool Sema::CheckCaseExpression(Expr *E) {
21731 if (E->isTypeDependent())
21732 return true;
21733 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21734 return E->getType()->isIntegralOrEnumerationType();
21735 return false;
21736 }
21737
21738 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21739 ArrayRef<Expr *> SubExprs, QualType T) {
21740 if (!Context.getLangOpts().RecoveryAST)
21741 return ExprError();
21742
21743 if (isSFINAEContext())
21744 return ExprError();
21745
21746 if (T.isNull() || T->isUndeducedType() ||
21747 !Context.getLangOpts().RecoveryASTType)
21748 // We don't know the concrete type, fallback to dependent type.
21749 T = Context.DependentTy;
21750
21751 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21752 }